Sfoglia il codice sorgente

fix(video): 原子保留取消意图并精确回收新旧底流

Kazerin 3 settimane fa
parent
commit
3969e49981
27 ha cambiato i file con 2591 aggiunte e 301 eliminazioni
  1. 11 0
      video-service/src/main/java/com/ruoyi/wvp/gb28181/service/IPlayService.java
  2. 8 1
      video-service/src/main/java/com/ruoyi/wvp/gb28181/service/impl/InviteStreamServiceImpl.java
  3. 390 1
      video-service/src/main/java/com/ruoyi/wvp/gb28181/service/impl/PlayServiceImpl.java
  4. 58 1
      video-service/src/main/java/com/ruoyi/wvp/gb28181/session/SipInviteSessionManager.java
  5. 34 5
      video-service/src/main/java/com/ruoyi/wvp/gb28181/transmit/cmd/impl/SIPCommander.java
  6. 22 6
      video-service/src/main/java/com/ruoyi/wvp/media/event/hook/Hook.java
  7. 50 24
      video-service/src/main/java/com/ruoyi/wvp/media/event/hook/HookSubscribe.java
  8. 10 0
      video-service/src/main/java/com/ruoyi/wvp/service/IReceiveRtpServerService.java
  9. 235 8
      video-service/src/main/java/com/ruoyi/wvp/service/impl/RtpServerServiceImpl.java
  10. 9 1
      video-service/src/main/java/com/zksy/video/ManualVideoController.java
  11. 100 20
      video-service/src/main/java/com/zksy/video/ManualVideoService.java
  12. 104 49
      video-service/src/main/java/com/zksy/video/lifecycle/Gb28181LifecycleMedia.java
  13. 66 35
      video-service/src/main/java/com/zksy/video/lifecycle/ManualLifecycleMedia.java
  14. 29 28
      video-service/src/main/java/com/zksy/video/lifecycle/RedisVideoLifecycleStore.java
  15. 38 2
      video-service/src/main/java/com/zksy/video/lifecycle/VideoLifecycleMedia.java
  16. 11 0
      video-service/src/main/java/com/zksy/video/lifecycle/VideoLifecycleRecord.java
  17. 156 99
      video-service/src/main/java/com/zksy/video/lifecycle/VideoLifecycleService.java
  18. 3 7
      video-service/src/main/java/com/zksy/video/lifecycle/VideoLifecycleStore.java
  19. 202 0
      video-service/src/test/java/com/zksy/video/lifecycle/AdoptedGbDeepSeamTest.java
  20. 178 0
      video-service/src/test/java/com/zksy/video/lifecycle/Gb28181LifecycleMediaTest.java
  21. 306 0
      video-service/src/test/java/com/zksy/video/lifecycle/ManagedGbDeepSeamTest.java
  22. 57 0
      video-service/src/test/java/com/zksy/video/lifecycle/ManagedHookIsolationTest.java
  23. 42 0
      video-service/src/test/java/com/zksy/video/lifecycle/ManagedInviteRetentionTest.java
  24. 84 0
      video-service/src/test/java/com/zksy/video/lifecycle/ManualLegacyHandleTest.java
  25. 243 0
      video-service/src/test/java/com/zksy/video/lifecycle/ManualLifecycleMediaTest.java
  26. 136 0
      video-service/src/test/java/com/zksy/video/lifecycle/VideoLifecycleRaceTest.java
  27. 9 14
      video-service/src/test/java/com/zksy/video/lifecycle/VideoLifecycleServiceTest.java

+ 11 - 0
video-service/src/main/java/com/ruoyi/wvp/gb28181/service/IPlayService.java

@@ -19,6 +19,17 @@ import com.ruoyi.wvp.common.InviteInfo;
  */
  */
 public interface IPlayService {
 public interface IPlayService {
 
 
+    SSRCInfo playManaged(MediaServer mediaServer, String deviceId, String channelId, String stream, ErrorCallback<StreamInfo> callback);
+
+    /** True only after both SIP termination and exact RTP close are confirmed. */
+    boolean stopManaged(MediaServer mediaServer, Device device, DeviceChannel channel, String stream);
+
+    /** Capture/revalidate an observed legacy dialog; never allocates or replaces media. */
+    String adoptStream(MediaServer node, Device device, DeviceChannel channel, String stream, String handle);
+
+    /** An opaque adoption handle binds node/device/channel/stream and Call-ID/SSRC/allocation token. */
+    boolean stopAdopted(MediaServer node, Device device, DeviceChannel channel, String stream, String handle);
+
     SSRCInfo play(MediaServer mediaServerItem, String deviceId, String channelId, String ssrc, ErrorCallback<StreamInfo> callback);
     SSRCInfo play(MediaServer mediaServerItem, String deviceId, String channelId, String ssrc, ErrorCallback<StreamInfo> callback);
 
 
     StreamInfo onPublishHandlerForPlay(MediaServer mediaServerItem, MediaInfo mediaInfo, Device device, DeviceChannel channel);
     StreamInfo onPublishHandlerForPlay(MediaServer mediaServerItem, MediaInfo mediaInfo, Device device, DeviceChannel channel);

+ 8 - 1
video-service/src/main/java/com/ruoyi/wvp/gb28181/service/impl/InviteStreamServiceImpl.java

@@ -53,6 +53,8 @@ public class InviteStreamServiceImpl implements IInviteStreamService {
     @Async("taskExecutor")
     @Async("taskExecutor")
     @EventListener
     @EventListener
     public void onApplicationEvent(MediaDepartureEvent event) {
     public void onApplicationEvent(MediaDepartureEvent event) {
+        // Managed teardown owns this exact Invite until SIP/RTP termination is confirmed.
+        if (isManaged(event.getStream())) return;
         if ("rtsp".equals(event.getSchema()) && "rtp".equals(event.getApp())) {
         if ("rtsp".equals(event.getSchema()) && "rtp".equals(event.getApp())) {
             InviteInfo inviteInfo = getInviteInfoByStream(null, event.getStream());
             InviteInfo inviteInfo = getInviteInfoByStream(null, event.getStream());
             if (inviteInfo != null && (inviteInfo.getType() == InviteSessionType.PLAY || inviteInfo.getType() == InviteSessionType.PLAYBACK)) {
             if (inviteInfo != null && (inviteInfo.getType() == InviteSessionType.PLAY || inviteInfo.getType() == InviteSessionType.PLAYBACK)) {
@@ -209,6 +211,7 @@ public class InviteStreamServiceImpl implements IInviteStreamService {
             return;
             return;
         }
         }
         InviteInfo inviteInfo = getInviteInfo(type, channelId, stream);
         InviteInfo inviteInfo = getInviteInfo(type, channelId, stream);
+        if (stream == null && inviteInfo != null && isManaged(inviteInfo.getStream())) return;
         if (inviteInfo != null) {
         if (inviteInfo != null) {
             String objectKey = inviteInfo.getType() +
             String objectKey = inviteInfo.getType() +
                     ":" + inviteInfo.getChannelId() +
                     ":" + inviteInfo.getChannelId() +
@@ -334,6 +337,10 @@ public class InviteStreamServiceImpl implements IInviteStreamService {
         return inviteInfoInDb;
         return inviteInfoInDb;
     }
     }
 
 
+    private static boolean isManaged(String stream) {
+        return stream != null && stream.matches("managed_[0-9a-f]{32}");
+    }
+
     @Scheduled(fixedRate = 10000)   //定时检测,清理错误的redis数据,防止因为错误数据导致的点播不可用
     @Scheduled(fixedRate = 10000)   //定时检测,清理错误的redis数据,防止因为错误数据导致的点播不可用
     public void execute(){
     public void execute(){
         String key = VideoManagerConstants.INVITE_PREFIX;
         String key = VideoManagerConstants.INVITE_PREFIX;
@@ -343,7 +350,7 @@ public class InviteStreamServiceImpl implements IInviteStreamService {
         List<Object> values = redisTemplate.opsForHash().values(key);
         List<Object> values = redisTemplate.opsForHash().values(key);
         for (Object value : values) {
         for (Object value : values) {
             InviteInfo inviteInfo = (InviteInfo)value;
             InviteInfo inviteInfo = (InviteInfo)value;
-            if (inviteInfo.getStreamInfo() != null) {
+            if (isManaged(inviteInfo.getStream()) || inviteInfo.getStreamInfo() != null) {
                 continue;
                 continue;
             }
             }
             if (inviteInfo.getCreateTime() == null || inviteInfo.getExpirationTime() == 0) {
             if (inviteInfo.getCreateTime() == null || inviteInfo.getExpirationTime() == 0) {

+ 390 - 1
video-service/src/main/java/com/ruoyi/wvp/gb28181/service/impl/PlayServiceImpl.java

@@ -109,7 +109,12 @@ public class PlayServiceImpl implements IPlayService {
     @EventListener
     @EventListener
     public void onApplicationEvent(MediaDepartureEvent event) {
     public void onApplicationEvent(MediaDepartureEvent event) {
         if (!"rtp".equals(event.getApp())) return;
         if (!"rtp".equals(event.getApp())) return;
+        // The adapter owns adopted teardown; a departure hook must not enter channel-wide legacy stop.
+        SsrcTransaction departing = sessionManager.getSsrcTransactionByStream("rtp", event.getStream());
+        if (sessionManager.isAdopted(departing)) return;
         InviteInfo info = inviteStreamService.getInviteInfoByStream(null, event.getStream());
         InviteInfo info = inviteStreamService.getInviteInfoByStream(null, event.getStream());
+        if (info != null && info.getStream() != null && info.getStream().startsWith("managed_")
+                && (event.getMediaServer() == null || !java.util.Objects.equals(info.getMediaServerId(), event.getMediaServer().getId()))) return;
         if (info != null && info.getStatus() == InviteSessionStatus.ok
         if (info != null && info.getStatus() == InviteSessionStatus.ok
                 && info.getStreamInfo() != null && info.getSsrcInfo() != null) stop(info);
                 && info.getStreamInfo() != null && info.getSsrcInfo() != null) stop(info);
     }
     }
@@ -123,6 +128,8 @@ public class PlayServiceImpl implements IPlayService {
         if (!"rtp".equals(event.getApp())) {
         if (!"rtp".equals(event.getApp())) {
             return;
             return;
         }
         }
+        // The managed namespace is never a legacy device/channel identifier.
+        if (event.getStream() == null || event.getStream().startsWith("managed_")) return;
         if (videoLifecycleStore != null && videoLifecycleStore.isStreamCancelled(event.getStream())) {
         if (videoLifecycleStore != null && videoLifecycleStore.isStreamCancelled(event.getStream())) {
             log.info("[ZLM HOOK] 该流已被取消,不自动点播:{}", event.getStream());
             log.info("[ZLM HOOK] 该流已被取消,不自动点播:{}", event.getStream());
             return;
             return;
@@ -164,6 +171,361 @@ public class PlayServiceImpl implements IPlayService {
     }
     }
 
 
 
 
+    /** Retains termination evidence independently of the legacy channel cache/ready TTL. */
+    private final java.util.Map<String, ManagedPlay> managedPlays = new java.util.concurrent.ConcurrentHashMap<>();
+
+    private static final class ManagedPlay {
+        private final MediaServer node;
+        private final Device device;
+        private final DeviceChannel channel;
+        private final String stream;
+        private SSRCInfo ssrc;
+        private boolean inviteSent;
+        private boolean byeConfirmed;
+        private String confirmedCallId;
+        private boolean stopped;
+        private boolean answered;
+        private ManagedPlay(MediaServer node, Device device, DeviceChannel channel, String stream) {
+            this.node = node; this.device = device; this.channel = channel; this.stream = stream;
+        }
+    }
+
+    private boolean managedCancelled(String stream) {
+        return videoLifecycleStore == null || videoLifecycleStore.isStreamCancelled(stream);
+    }
+
+    private boolean managedMatches(ManagedPlay play, MediaServer node, Device device, DeviceChannel channel) {
+        return java.util.Objects.equals(play.node.getId(), node.getId())
+                && java.util.Objects.equals(play.device.getDeviceId(), device.getDeviceId())
+                && java.util.Objects.equals(play.channel.getId(), channel.getId());
+    }
+
+    @Override
+    public synchronized SSRCInfo playManaged(MediaServer node, String deviceId, String channelId, String stream,
+                                              ErrorCallback<StreamInfo> callback) {
+        if (node == null || node.getId() == null || !node.isRtpEnable() || stream == null
+                || !stream.matches("managed_[0-9a-fA-F]{32}") || managedCancelled(stream)) {
+            if (callback != null) callback.run(InviteErrorCode.FAIL.getCode(), "Managed generation cancelled or unsupported node/stream", null);
+            return null;
+        }
+        Device device = redisCatchStorage.getDevice(deviceId);
+        DeviceChannel channel = deviceChannelService.getOneForSource(deviceId, channelId);
+        if (device == null || channel == null) {
+            if (callback != null) callback.run(InviteErrorCode.FAIL.getCode(), "Managed device/channel missing", null);
+            return null;
+        }
+        // Never take over or stop a different stream, even when its media list is empty.
+        for (InviteInfo existing : inviteStreamService.getAllInviteInfo()) {
+            if (existing.getType() == InviteSessionType.PLAY && java.util.Objects.equals(channel.getId(), existing.getChannelId())
+                    && !stream.equals(existing.getStream())) {
+                if (callback != null) callback.run(InviteErrorCode.FAIL.getCode(), "Channel already belongs to another stream", null);
+                return null;
+            }
+        }
+        InviteInfo existing = inviteStreamService.getInviteInfo(InviteSessionType.PLAY, channel.getId(), stream);
+        if (existing != null) {
+            if (!node.getId().equals(existing.getMediaServerId()) || !deviceId.equals(existing.getDeviceId())) return null;
+            ManagedPlay retained = managedPlays.get(stream);
+            if (retained == null) {
+                retained = new ManagedPlay(node, device, channel, stream); retained.ssrc = existing.getSsrcInfo();
+                retained.inviteSent = true; managedPlays.put(stream, retained);
+            }
+            if (managedCancelled(stream)) return null;
+            if (existing.getStreamInfo() != null) {
+                if (callback != null) callback.run(InviteErrorCode.SUCCESS.getCode(), InviteErrorCode.SUCCESS.getMsg(), existing.getStreamInfo());
+            } else if (callback != null) {
+                inviteStreamService.once(InviteSessionType.PLAY, channel.getId(), stream, callback);
+            }
+            return existing.getSsrcInfo();
+        }
+        // Same UUID is single-use even after a failure or a cache eviction.
+        if (managedPlays.containsKey(stream)) return null;
+        ManagedPlay play = new ManagedPlay(node, device, channel, stream);
+        managedPlays.put(stream, play);
+        RTPServerParam param = new RTPServerParam(); param.setMediaServerItem(node); param.setStreamId(stream);
+        param.setSsrcCheck(device.isSsrcCheck()); param.setDisableAudio(!channel.isHasAudio());
+        param.setTcpMode("TCP-ACTIVE".equalsIgnoreCase(device.getStreamMode()) ? 2 : "TCP-PASSIVE".equalsIgnoreCase(device.getStreamMode()) ? 1 : 0);
+        try {
+            if (managedCancelled(stream)) return null;
+            play.ssrc = receiveRtpServerService.openRTPServer(param, (code, msg, result) -> managedArrival(play, callback, code, msg, result));
+            if (play.ssrc == null || play.ssrc.getPort() <= 0 || managedCancelled(stream)) {
+                failManaged(play, callback, InviteErrorCode.FAIL.getCode(), "Managed allocation failed/cancelled");
+                return null;
+            }
+            InviteInfo invite = InviteInfo.getInviteInfo(deviceId, channel.getId(), stream, play.ssrc, node.getId(), node.getSdpIp(),
+                    play.ssrc.getPort(), device.getStreamMode(), InviteSessionType.PLAY, InviteSessionStatus.ready, userSetting.getRecordSip());
+            inviteStreamService.updateInviteInfo(invite);
+            if (managedCancelled(stream)) {
+                failManaged(play, callback, InviteErrorCode.FAIL.getCode(), "Managed generation cancelled");
+                return null;
+            }
+            // Set BEFORE dispatch: timeout/throw does not prove that no INVITE left the process.
+            play.inviteSent = true;
+            cmder.playStreamCmd(node, play.ssrc, device, channel,
+                    event -> managedInviteOk(play, callback, event),
+                    event -> failManaged(play, callback, event.statusCode, event.msg), userSetting.getPlayTimeout().longValue());
+            return play.ssrc;
+        } catch (InvalidArgumentException | SipException | ParseException | RuntimeException ex) {
+            failManaged(play, callback, InviteErrorCode.ERROR_FOR_SIP_SENDING_FAILED.getCode(), ex.getMessage());
+            return null;
+        }
+    }
+
+    private synchronized void managedArrival(ManagedPlay play, ErrorCallback<StreamInfo> callback,
+                                             int code, String msg, OpenRTPServerResult result) {
+        if (result != null && result.getSsrcInfo() != null
+                && play.stream.equals(result.getSsrcInfo().getStream()) && "rtp".equals(result.getSsrcInfo().getApp())) {
+            play.ssrc = result.getSsrcInfo();
+        }
+        if (managedCancelled(play.stream) || code != InviteErrorCode.SUCCESS.getCode()) {
+            failManaged(play, callback, code == InviteErrorCode.SUCCESS.getCode() ? InviteErrorCode.FAIL.getCode() : code, msg);
+            return;
+        }
+        if (result == null || result.getHookData() == null || result.getHookData().getMediaServer() == null
+                || !play.node.getId().equals(result.getHookData().getMediaServer().getId())
+                || !play.stream.equals(result.getHookData().getStream())
+                || result.getHookData().getMediaInfo() == null
+                || !play.stream.equals(result.getHookData().getMediaInfo().getStream())
+                || !"rtp".equals(result.getHookData().getMediaInfo().getApp())) return;
+        StreamInfo info = onPublishHandlerForPlay(play.node, result.getHookData().getMediaInfo(), play.device, play.channel);
+        if (info == null || managedCancelled(play.stream)) {
+            failManaged(play, callback, InviteErrorCode.FAIL.getCode(), "Managed arrival no longer owned");
+            return;
+        }
+        if (!play.answered) {
+            play.answered = true;
+            try { if (callback != null) callback.run(InviteErrorCode.SUCCESS.getCode(), InviteErrorCode.SUCCESS.getMsg(), info); }
+            finally { inviteStreamService.call(InviteSessionType.PLAY, play.channel.getId(), play.stream,
+                    InviteErrorCode.SUCCESS.getCode(), InviteErrorCode.SUCCESS.getMsg(), info); }
+        }
+    }
+
+    private synchronized void managedInviteOk(ManagedPlay play, ErrorCallback<StreamInfo> callback, SipSubscribe.EventResult event) {
+        // SIPCommander has retained the exact late dialog for ACK/BYE, but never republishes it.
+        if (managedCancelled(play.stream)) {
+            stopManaged(play.node, play.device, play.channel, play.stream);
+            return;
+        }
+        InviteInfo invite = inviteStreamService.getInviteInfo(InviteSessionType.PLAY, play.channel.getId(), play.stream);
+        if (invite == null || !play.node.getId().equals(invite.getMediaServerId())) {
+            failManaged(play, callback, InviteErrorCode.FAIL.getCode(), "Managed invite no longer owned");
+            return;
+        }
+        try {
+            ResponseEvent response = (ResponseEvent) event.event;
+            String sdp = new String(response.getResponse().getRawContent(), java.nio.charset.StandardCharsets.UTF_8);
+            String responseSsrc = SipUtils.getSsrcFromSdp(sdp);
+            if (responseSsrc != null && !responseSsrc.equals(play.ssrc.getSsrc()) && play.device.isSsrcCheck()) {
+                if (!Boolean.TRUE.equals(mediaServerService.updateRtpServerSSRC(play.node, play.stream, responseSsrc))) {
+                    failManaged(play, callback, InviteErrorCode.ERROR_FOR_RESET_SSRC.getCode(), "Managed SSRC update failed");
+                    return;
+                }
+            }
+            if (managedCancelled(play.stream)) { stopManaged(play.node, play.device, play.channel, play.stream); return; }
+            if ("TCP-ACTIVE".equalsIgnoreCase(play.device.getStreamMode())) {
+                String body = sdp.contains("y=") ? sdp.substring(0, sdp.indexOf("y=")) : sdp;
+                SessionDescription description = SdpFactory.getInstance().createSessionDescription(body);
+                int port = -1;
+                for (Object value : description.getMediaDescriptions(true)) {
+                    Media media = ((MediaDescription)value).getMedia();
+                    if (media.getMediaFormats(false).contains("96")) { port = media.getMediaPort(); break; }
+                }
+                if (port <= 0 || !Boolean.TRUE.equals(mediaServerService.connectRtpServer(play.node, description.getConnection().getAddress(), port, play.stream))) {
+                    failManaged(play, callback, InviteErrorCode.FAIL.getCode(), "Managed TCP connect failed"); return;
+                }
+            }
+            if (managedCancelled(play.stream)) { stopManaged(play.node, play.device, play.channel, play.stream); return; }
+            // Arrival, not SIP 200, publishes StreamInfo. Only this precise Invite can be updated.
+            invite.setStatus(InviteSessionStatus.ok); inviteStreamService.updateInviteInfo(invite);
+        } catch (SdpException | RuntimeException ex) {
+            failManaged(play, callback, InviteErrorCode.ERROR_FOR_SDP_PARSING_EXCEPTIONS.getCode(), ex.getMessage());
+        }
+    }
+
+    private synchronized void failManaged(ManagedPlay play, ErrorCallback<StreamInfo> callback, int code, String msg) {
+        try { stopManaged(play.node, play.device, play.channel, play.stream); }
+        finally {
+            if (!play.answered) {
+                play.answered = true;
+                try { if (callback != null) callback.run(code, msg, null); }
+                finally { inviteStreamService.call(InviteSessionType.PLAY, play.channel.getId(), play.stream, code, msg, null); }
+            }
+        }
+    }
+
+    @Override
+    public synchronized boolean stopManaged(MediaServer node, Device device, DeviceChannel channel, String stream) {
+        if (node == null || node.getId() == null || device == null || channel == null || stream == null
+                || !stream.matches("managed_[0-9a-fA-F]{32}")) return false;
+        ManagedPlay play = managedPlays.get(stream);
+        InviteInfo invite = inviteStreamService.getInviteInfo(InviteSessionType.PLAY, channel.getId(), stream);
+        SsrcTransaction transaction = sessionManager.getSsrcTransactionByStream("rtp", stream);
+        if ((play != null && !managedMatches(play, node, device, channel))
+                || (invite != null && (!node.getId().equals(invite.getMediaServerId()) || !device.getDeviceId().equals(invite.getDeviceId())))
+                || (transaction != null && (!node.getId().equals(transaction.getMediaServerId())
+                || !device.getDeviceId().equals(transaction.getDeviceId()) || !java.util.Objects.equals(channel.getId(), transaction.getChannelId())))) return false;
+        if (videoLifecycleStore == null) return false;
+        videoLifecycleStore.markStreamCancelled(stream);
+        try {
+            inviteStreamService.call(InviteSessionType.PLAY, channel.getId(), stream,
+                    InviteErrorCode.FAIL.getCode(), "Managed generation cancelled", null);
+        } catch (RuntimeException ex) {
+            log.warn("[Managed callback close] {}: {}", stream, ex.getMessage());
+        }
+        if (play == null) {
+            // Missing transaction is NOT evidence that an INVITE was never sent.
+            if (invite == null && transaction == null) return false;
+            play = new ManagedPlay(node, device, channel, stream); play.inviteSent = true;
+            play.ssrc = invite == null ? new SSRCInfo(0, transaction.getSsrc(), "rtp", stream, null) : invite.getSsrcInfo();
+            managedPlays.put(stream, play);
+        }
+        if (play.stopped && transaction == null) return true;
+        final ManagedPlay owned = play;
+        if (transaction != null && owned.byeConfirmed && !java.util.Objects.equals(owned.confirmedCallId, transaction.getCallId())) {
+            owned.byeConfirmed = false;
+            owned.stopped = false;
+        }
+        boolean rtpClosed = false;
+        try {
+            if (transaction != null && !owned.byeConfirmed) {
+                String callId = transaction.getCallId();
+                cmder.streamByeCmd(device, channel.getDeviceId(), "rtp", stream, callId, event -> {
+                    synchronized (PlayServiceImpl.this) {
+                        if (event.statusCode >= 200 && event.statusCode < 300
+                                && (event.callId == null || java.util.Objects.equals(callId, event.callId))) {
+                            owned.byeConfirmed = true;
+                            owned.confirmedCallId = callId;
+                            sessionManager.removeManagedIfSame(transaction);
+                        }
+                    }
+                });
+            }
+        } catch (InvalidArgumentException | SipException | ParseException | SsrcTransactionNotFoundException | RuntimeException ex) {
+            log.warn("[Managed BYE] {}/{} remains pending: {}", node.getId(), stream, ex.getMessage());
+        } finally {
+            try {
+                SSRCInfo info = owned.ssrc == null ? new SSRCInfo(0, null, "rtp", stream, null) : owned.ssrc;
+                rtpClosed = receiveRtpServerService.closeManagedRTPServer(node, info);
+            } catch (RuntimeException ex) {
+                log.warn("[Managed close] {}/{} remains pending: {}", node.getId(), stream, ex.getMessage());
+            }
+        }
+        if (rtpClosed && (!owned.inviteSent || owned.byeConfirmed)) {
+            if (transaction != null && java.util.Objects.equals(owned.confirmedCallId, transaction.getCallId())) {
+                sessionManager.removeManagedIfSame(transaction);
+            }
+            inviteStreamService.removeInviteInfo(InviteSessionType.PLAY, channel.getId(), stream);
+            owned.stopped = true;
+            return true;
+        }
+        return false;
+    }
+
+    /** Adoption is a capability for one observed dialog, NOT a reusable legacy stream name. */
+    private final java.util.Map<String, AdoptedPlay> adoptedPlays = new java.util.concurrent.ConcurrentHashMap<>();
+
+    private static final class AdoptedPlay {
+        private final SsrcTransaction dialog;
+        private final SSRCInfo info;
+        private final String channelCode;
+        private boolean byeConfirmed;
+        private boolean cancelled;
+        private AdoptedPlay(SsrcTransaction current, SSRCInfo ssrc, String channelCode) {
+            this.channelCode = channelCode;
+            info = new SSRCInfo(ssrc.getPort(), ssrc.getSsrc(), ssrc.getApp(), ssrc.getStream(), ssrc.getTimeOutTaskKey());
+            dialog = new SsrcTransaction();
+            dialog.setApp(current.getApp()); dialog.setStream(current.getStream()); dialog.setCallId(current.getCallId());
+            dialog.setSsrc(current.getSsrc()); dialog.setMediaServerId(current.getMediaServerId());
+            dialog.setDeviceId(current.getDeviceId()); dialog.setChannelId(current.getChannelId()); dialog.setType(current.getType());
+            SipTransactionInfo sip = new SipTransactionInfo(), source = current.getSipTransactionInfo();
+            sip.setCallId(source.getCallId()); sip.setFromTag(source.getFromTag()); sip.setToTag(source.getToTag());
+            sip.setViaBranch(source.getViaBranch()); sip.setAsSender(source.isAsSender()); dialog.setSipTransactionInfo(sip);
+        }
+    }
+
+    private static boolean nonblank(String value) { return value != null && !value.isBlank(); }
+
+    private boolean adoptedIdentity(AdoptedPlay owned, MediaServer node, Device device, DeviceChannel channel, String stream) {
+        return owned != null && node != null && device != null && channel != null
+                && java.util.Objects.equals(owned.dialog.getMediaServerId(), node.getId())
+                && java.util.Objects.equals(owned.dialog.getDeviceId(), device.getDeviceId())
+                && java.util.Objects.equals(owned.dialog.getChannelId(), channel.getId())
+                && java.util.Objects.equals(owned.channelCode, channel.getDeviceId())
+                && java.util.Objects.equals(owned.dialog.getStream(), stream);
+    }
+
+    private boolean adoptedInvite(AdoptedPlay owned, InviteInfo invite) {
+        return invite != null && invite.getSsrcInfo() != null && invite.getType() == InviteSessionType.PLAY
+                && java.util.Objects.equals(owned.dialog.getMediaServerId(), invite.getMediaServerId())
+                && java.util.Objects.equals(owned.dialog.getDeviceId(), invite.getDeviceId())
+                && java.util.Objects.equals(owned.dialog.getChannelId(), invite.getChannelId())
+                && java.util.Objects.equals(owned.dialog.getStream(), invite.getStream())
+                && owned.info.equals(invite.getSsrcInfo());
+    }
+
+    @Override
+    public synchronized String adoptStream(MediaServer node, Device device, DeviceChannel channel, String stream, String handle) {
+        if (node == null || !nonblank(node.getId()) || !node.isRtpEnable() || device == null || channel == null
+                || !nonblank(stream) || stream.startsWith("managed_")) return null;
+        InviteInfo invite = inviteStreamService.getInviteInfo(InviteSessionType.PLAY, channel.getId(), stream);
+        SsrcTransaction current = sessionManager.getSsrcTransactionByStream("rtp", stream);
+        if (handle != null) {
+            AdoptedPlay owned = adoptedPlays.get(handle);
+            return adoptedIdentity(owned, node, device, channel, stream) && !owned.cancelled
+                    && adoptedInvite(owned, invite) && SipInviteSessionManager.sameDialog(owned.dialog, current)
+                    ? handle : null;
+        }
+        if (invite == null || invite.getSsrcInfo() == null || current == null || current.getType() != InviteSessionType.PLAY
+                || !nonblank(current.getCallId()) || !nonblank(current.getSsrc()) || !"rtp".equals(current.getApp())
+                || current.getSipTransactionInfo() == null
+                || !current.getCallId().equals(current.getSipTransactionInfo().getCallId())
+                || !nonblank(current.getSipTransactionInfo().getFromTag()) || !nonblank(current.getSipTransactionInfo().getToTag())
+                || !nonblank(invite.getSsrcInfo().getTimeOutTaskKey())
+                || !"rtp".equals(invite.getSsrcInfo().getApp()) || !stream.equals(invite.getSsrcInfo().getStream())
+                || !current.getSsrc().equals(invite.getSsrcInfo().getSsrc())) return null;
+        AdoptedPlay owned = new AdoptedPlay(current, invite.getSsrcInfo(), channel.getDeviceId());
+        if (!adoptedIdentity(owned, node, device, channel, stream) || !adoptedInvite(owned, invite)
+                || !sessionManager.retainAdopted(owned.dialog, owned.info)) return null;
+        String token = java.util.UUID.randomUUID().toString(); adoptedPlays.put(token, owned); return token;
+    }
+
+    @Override
+    public synchronized boolean stopAdopted(MediaServer node, Device device, DeviceChannel channel, String stream, String handle) {
+        AdoptedPlay owned = handle == null ? null : adoptedPlays.get(handle);
+        if (!adoptedIdentity(owned, node, device, channel, stream)) return false;
+        InviteInfo invite = inviteStreamService.getInviteInfo(InviteSessionType.PLAY, channel.getId(), stream);
+        SsrcTransaction current = sessionManager.getSsrcTransactionByStream("rtp", stream);
+        if ((invite != null && !adoptedInvite(owned, invite))
+                || (current != null && !SipInviteSessionManager.sameDialog(owned.dialog, current))
+                || (current == null && !owned.byeConfirmed)) return false;
+        owned.cancelled = true;
+        try {
+            if (!owned.byeConfirmed) {
+                // Explicit dialog overload: never invokes the legacy remove-before-send path.
+                cmder.streamByeCmd(device, owned.channelCode, owned.dialog.getSipTransactionInfo(), event -> {
+                    synchronized (PlayServiceImpl.this) {
+                        if (event.statusCode >= 200 && event.statusCode < 300
+                                && owned.dialog.getCallId().equals(event.callId)) {
+                            owned.byeConfirmed = true;
+                            sessionManager.removeAdoptedIfSame(owned.dialog);
+                        }
+                    }
+                });
+            }
+        } catch (InvalidArgumentException | SipException | ParseException | SsrcTransactionNotFoundException | RuntimeException ex) {
+            log.warn("[Adopted BYE] {}/{} remains pending: {}", node.getId(), stream, ex.getMessage());
+        }
+        // A retained receipt can survive departure/Invite eviction; a different allocation cannot.
+        boolean closed = receiveRtpServerService.closeAdoptedRTPServer(node, owned.info, owned.dialog.getCallId());
+        current = sessionManager.getSsrcTransactionByStream("rtp", stream);
+        invite = inviteStreamService.getInviteInfo(InviteSessionType.PLAY, channel.getId(), stream);
+        if (!closed || !owned.byeConfirmed || (current != null && !SipInviteSessionManager.sameDialog(owned.dialog, current))
+                || (invite != null && !adoptedInvite(owned, invite))) return false;
+        sessionManager.removeAdoptedIfSame(owned.dialog);
+        if (invite != null) inviteStreamService.removeInviteInfo(InviteSessionType.PLAY, channel.getId(), stream);
+        return true;
+    }
+
     @Override
     @Override
     public SSRCInfo play(MediaServer mediaServerItem, String deviceId, String channelId, String ssrc, ErrorCallback<StreamInfo> callback) {
     public SSRCInfo play(MediaServer mediaServerItem, String deviceId, String channelId, String ssrc, ErrorCallback<StreamInfo> callback) {
         if (mediaServerItem == null) {
         if (mediaServerItem == null) {
@@ -405,7 +767,23 @@ public class PlayServiceImpl implements IPlayService {
         }
         }
     }
     }
 
 
-    public StreamInfo onPublishHandlerForPlay(MediaServer mediaServerItem, MediaInfo mediaInfo, Device device, DeviceChannel channel) {
+    public synchronized StreamInfo onPublishHandlerForPlay(MediaServer mediaServerItem, MediaInfo mediaInfo, Device device, DeviceChannel channel) {
+        if (mediaInfo != null && mediaInfo.getStream() != null && mediaInfo.getStream().startsWith("managed_")) {
+            String stream = mediaInfo.getStream();
+            if (managedCancelled(stream) || mediaServerItem == null || !"rtp".equals(mediaInfo.getApp())
+                    || (mediaInfo.getMediaServer() != null && !java.util.Objects.equals(mediaServerItem.getId(), mediaInfo.getMediaServer().getId()))) return null;
+            InviteInfo exact = inviteStreamService.getInviteInfo(InviteSessionType.PLAY, channel.getId(), stream);
+            if (exact == null || !java.util.Objects.equals(exact.getMediaServerId(), mediaServerItem.getId())
+                    || !java.util.Objects.equals(exact.getDeviceId(), device.getDeviceId())) return null;
+            StreamInfo info = mediaServerService.getStreamInfoByAppAndStream(mediaServerItem, "rtp", stream, mediaInfo, null);
+            if (info == null || !stream.equals(info.getStream()) || info.getMediaServer() == null
+                    || !mediaServerItem.getId().equals(info.getMediaServer().getId()) || managedCancelled(stream)) return null;
+            info.setDeviceId(device.getDeviceId()); info.setChannelId(channel.getId());
+            exact.setStatus(InviteSessionStatus.ok); exact.setStreamInfo(info);
+            inviteStreamService.updateInviteInfo(exact);
+            // Deliberately no channel-wide startPlay/stopPlay: the managed stream owns only its exact Invite.
+            return managedCancelled(stream) ? null : info;
+        }
         StreamInfo streamInfo = null;
         StreamInfo streamInfo = null;
         streamInfo = onPublishHandler(mediaServerItem, mediaInfo, device, channel);
         streamInfo = onPublishHandler(mediaServerItem, mediaInfo, device, channel);
         if (streamInfo != null) {
         if (streamInfo != null) {
@@ -975,6 +1353,13 @@ public class PlayServiceImpl implements IPlayService {
 
 
     @Override
     @Override
     public void stop(InviteSessionType type, Device device, DeviceChannel channel, String stream) {
     public void stop(InviteSessionType type, Device device, DeviceChannel channel, String stream) {
+        if (stream != null && stream.startsWith("managed_")) {
+            InviteInfo exact = inviteStreamService.getInviteInfo(type, channel.getId(), stream);
+            ManagedPlay retained = managedPlays.get(stream);
+            MediaServer node = retained != null ? retained.node : exact == null ? null : mediaServerService.getOne(exact.getMediaServerId());
+            stopManaged(node, device, channel, stream);
+            return;
+        }
         InviteInfo inviteInfo = inviteStreamService.getInviteInfo(type, channel.getId(), stream);
         InviteInfo inviteInfo = inviteStreamService.getInviteInfo(type, channel.getId(), stream);
         if (inviteInfo == null) {
         if (inviteInfo == null) {
             if (type == InviteSessionType.PLAY) {
             if (type == InviteSessionType.PLAY) {
@@ -1019,6 +1404,10 @@ public class PlayServiceImpl implements IPlayService {
             log.warn("[停止点播] 发现设备不存在");
             log.warn("[停止点播] 发现设备不存在");
             return;
             return;
         }
         }
+        if (inviteInfo.getStream() != null && inviteInfo.getStream().startsWith("managed_")) {
+            stopManaged(mediaServerService.getOne(inviteInfo.getMediaServerId()), device, channel, inviteInfo.getStream());
+            return;
+        }
         inviteStreamService.removeInviteInfo(inviteInfo);
         inviteStreamService.removeInviteInfo(inviteInfo);
         if (InviteSessionStatus.ok == inviteInfo.getStatus()) {
         if (InviteSessionStatus.ok == inviteInfo.getStatus()) {
             try {
             try {

+ 58 - 1
video-service/src/main/java/com/ruoyi/wvp/gb28181/session/SipInviteSessionManager.java

@@ -25,7 +25,7 @@ public class SipInviteSessionManager {
 	/**
 	/**
 	 * 添加一个点播/回放的事务信息
 	 * 添加一个点播/回放的事务信息
 	 */
 	 */
-	public void put(SsrcTransaction ssrcTransaction){
+	public synchronized void put(SsrcTransaction ssrcTransaction){
 		redisTemplate.opsForHash().put(VideoManagerConstants.SIP_INVITE_SESSION_STREAM + userSetting.getServerId()
 		redisTemplate.opsForHash().put(VideoManagerConstants.SIP_INVITE_SESSION_STREAM + userSetting.getServerId()
 				, ssrcTransaction.getApp() + ssrcTransaction.getStream(), ssrcTransaction);
 				, ssrcTransaction.getApp() + ssrcTransaction.getStream(), ssrcTransaction);
 
 
@@ -67,6 +67,63 @@ public class SipInviteSessionManager {
 		}
 		}
 	}
 	}
 
 
+    private final java.util.Map<String, SsrcTransaction> adoptedDialogs = new java.util.concurrent.ConcurrentHashMap<>();
+    private final java.util.Map<String, com.ruoyi.wvp.service.bean.SSRCInfo> adoptedAllocations = new java.util.concurrent.ConcurrentHashMap<>();
+
+    /** Bind an observed legacy dialog before any cancellation can remove its retry handle. */
+    public synchronized boolean retainAdopted(SsrcTransaction owned, com.ruoyi.wvp.service.bean.SSRCInfo info) {
+        if (owned == null || info == null || !sameDialog(owned, getSsrcTransactionByStream(owned.getApp(), owned.getStream()))
+                || !sameDialog(owned, getSsrcTransactionByCallId(owned.getCallId()))) return false;
+        adoptedDialogs.put(owned.getCallId(), owned);
+        adoptedAllocations.put(owned.getCallId(), new com.ruoyi.wvp.service.bean.SSRCInfo(info.getPort(), info.getSsrc(), info.getApp(), info.getStream(), info.getTimeOutTaskKey()));
+        return true;
+    }
+
+    public boolean isAdopted(SsrcTransaction owned) {
+        return owned != null && owned.getCallId() != null && sameDialog(owned, adoptedDialogs.get(owned.getCallId()));
+    }
+
+    public boolean isAdoptedRtp(String nodeId, String callId, com.ruoyi.wvp.service.bean.SSRCInfo info) {
+        SsrcTransaction owned = callId == null ? null : adoptedDialogs.get(callId);
+        return owned != null && java.util.Objects.equals(nodeId, owned.getMediaServerId())
+                && info != null && info.equals(adoptedAllocations.get(callId));
+    }
+
+    public static boolean sameDialog(SsrcTransaction expected, SsrcTransaction current) {
+        return expected != null && current != null
+                && java.util.Objects.equals(expected.getCallId(), current.getCallId())
+                && java.util.Objects.equals(expected.getSsrc(), current.getSsrc())
+                && java.util.Objects.equals(expected.getApp(), current.getApp())
+                && java.util.Objects.equals(expected.getStream(), current.getStream())
+                && java.util.Objects.equals(expected.getMediaServerId(), current.getMediaServerId())
+                && java.util.Objects.equals(expected.getDeviceId(), current.getDeviceId())
+                && java.util.Objects.equals(expected.getChannelId(), current.getChannelId())
+                && expected.getType() == current.getType()
+                && expected.getSipTransactionInfo() != null && current.getSipTransactionInfo() != null
+                && java.util.Objects.equals(expected.getSipTransactionInfo().getCallId(), current.getSipTransactionInfo().getCallId())
+                && java.util.Objects.equals(expected.getSipTransactionInfo().getFromTag(), current.getSipTransactionInfo().getFromTag())
+                && java.util.Objects.equals(expected.getSipTransactionInfo().getToTag(), current.getSipTransactionInfo().getToTag());
+    }
+
+    public synchronized boolean removeAdoptedIfSame(SsrcTransaction owned) {
+        if (!isAdopted(owned) || !sameDialog(owned, getSsrcTransactionByStream(owned.getApp(), owned.getStream()))
+                || !sameDialog(owned, getSsrcTransactionByCallId(owned.getCallId()))) return false;
+        redisTemplate.opsForHash().delete(VideoManagerConstants.SIP_INVITE_SESSION_STREAM + userSetting.getServerId(), owned.getApp() + owned.getStream());
+        redisTemplate.opsForHash().delete(VideoManagerConstants.SIP_INVITE_SESSION_CALL_ID + userSetting.getServerId(), owned.getCallId());
+        return true;
+    }
+
+    /** A late BYE acknowledgement may remove only the dialog it actually terminated. */
+    public synchronized boolean removeManagedIfSame(SsrcTransaction owned) {
+        if (owned == null || owned.getStream() == null || !owned.getStream().startsWith("managed_")) return false;
+        SsrcTransaction current = getSsrcTransactionByStream(owned.getApp(), owned.getStream());
+        if (current == null || !java.util.Objects.equals(current.getCallId(), owned.getCallId())
+                || !java.util.Objects.equals(current.getMediaServerId(), owned.getMediaServerId())) return false;
+        redisTemplate.opsForHash().delete(VideoManagerConstants.SIP_INVITE_SESSION_STREAM + userSetting.getServerId(), owned.getApp() + owned.getStream());
+        redisTemplate.opsForHash().delete(VideoManagerConstants.SIP_INVITE_SESSION_CALL_ID + userSetting.getServerId(), owned.getCallId());
+        return true;
+    }
+
 	public void removeByCallId(String callId) {
 	public void removeByCallId(String callId) {
 		SsrcTransaction ssrcTransaction = getSsrcTransactionByCallId(callId);
 		SsrcTransaction ssrcTransaction = getSsrcTransactionByCallId(callId);
 		if (ssrcTransaction == null ) {
 		if (ssrcTransaction == null ) {

+ 34 - 5
video-service/src/main/java/com/ruoyi/wvp/gb28181/transmit/cmd/impl/SIPCommander.java

@@ -46,6 +46,14 @@ import java.text.ParseException;
 @Slf4j
 @Slf4j
 public class SIPCommander implements ISIPCommander {
 public class SIPCommander implements ISIPCommander {
 
 
+    @Autowired
+    private com.zksy.video.lifecycle.VideoLifecycleStore videoLifecycleStore;
+
+    private boolean managedCancelled(String stream) {
+        return stream != null && stream.startsWith("managed_")
+                && (videoLifecycleStore == null || videoLifecycleStore.isStreamCancelled(stream));
+    }
+
     @Autowired
     @Autowired
     private SipConfig sipConfig;
     private SipConfig sipConfig;
 
 
@@ -255,6 +263,7 @@ public class SIPCommander implements ISIPCommander {
     public void playStreamCmd(MediaServer mediaServerItem, SSRCInfo ssrcInfo, Device device, DeviceChannel channel,
     public void playStreamCmd(MediaServer mediaServerItem, SSRCInfo ssrcInfo, Device device, DeviceChannel channel,
                               SipSubscribe.Event okEvent, SipSubscribe.Event errorEvent, Long timeout) throws InvalidArgumentException, SipException, ParseException {
                               SipSubscribe.Event okEvent, SipSubscribe.Event errorEvent, Long timeout) throws InvalidArgumentException, SipException, ParseException {
         String stream = ssrcInfo.getStream();
         String stream = ssrcInfo.getStream();
+        if (managedCancelled(stream)) throw new SipException("Managed generation cancelled before INVITE");
 
 
         if (device == null) {
         if (device == null) {
             return;
             return;
@@ -327,9 +336,13 @@ public class SIPCommander implements ISIPCommander {
 //			content.append("f=v/2/5/25/1/4000a/1/8/1" + "\r\n"); // 未发现支持此特性的设备
 //			content.append("f=v/2/5/25/1/4000a/1/8/1" + "\r\n"); // 未发现支持此特性的设备
 
 
         Request request = headerProvider.createInviteRequest(device, channel.getDeviceId(), content.toString(), SipUtils.getNewViaTag(), SipUtils.getNewFromTag(), null, ssrcInfo.getSsrc(),sipSender.getNewCallIdHeader(sipLayer.getLocalIp(device.getLocalIp()),device.getTransport()));
         Request request = headerProvider.createInviteRequest(device, channel.getDeviceId(), content.toString(), SipUtils.getNewViaTag(), SipUtils.getNewFromTag(), null, ssrcInfo.getSsrc(),sipSender.getNewCallIdHeader(sipLayer.getLocalIp(device.getLocalIp()),device.getTransport()));
+        if (managedCancelled(stream)) throw new SipException("Managed generation cancelled before INVITE dispatch");
         sipSender.transmitRequest(sipLayer.getLocalIp(device.getLocalIp()), request, (e -> {
         sipSender.transmitRequest(sipLayer.getLocalIp(device.getLocalIp()), request, (e -> {
-            sessionManager.removeByStream(ssrcInfo.getApp(), ssrcInfo.getStream());
-            mediaServerService.releaseSsrc(mediaServerItem.getId(), ssrcInfo.getSsrc());
+            if (!stream.startsWith("managed_")) {
+                sessionManager.removeByStream(ssrcInfo.getApp(), ssrcInfo.getStream());
+                mediaServerService.releaseSsrc(mediaServerItem.getId(), ssrcInfo.getSsrc());
+            }
+            // A managed timeout/error cannot destroy a dialog retained for BYE retry.
             errorEvent.response(e);
             errorEvent.response(e);
         }), e -> {
         }), e -> {
             ResponseEvent responseEvent = (ResponseEvent) e.event;
             ResponseEvent responseEvent = (ResponseEvent) e.event;
@@ -338,6 +351,9 @@ public class SIPCommander implements ISIPCommander {
             SsrcTransaction ssrcTransaction = SsrcTransaction.buildForDevice(device.getDeviceId(), channel.getId(),
             SsrcTransaction ssrcTransaction = SsrcTransaction.buildForDevice(device.getDeviceId(), channel.getId(),
                     callId,ssrcInfo.getApp(), ssrcInfo.getStream(), ssrcInfo.getSsrc(), mediaServerItem.getId(), response,
                     callId,ssrcInfo.getApp(), ssrcInfo.getStream(), ssrcInfo.getSsrc(), mediaServerItem.getId(), response,
                     InviteSessionType.PLAY);
                     InviteSessionType.PLAY);
+            if (managedCancelled(stream)) {
+                log.info("[Managed INVITE] late 200 retained for ACK/BYE only: {}", stream);
+            }
             sessionManager.put(ssrcTransaction);
             sessionManager.put(ssrcTransaction);
             okEvent.response(e);
             okEvent.response(e);
         }, timeout);
         }, timeout);
@@ -554,9 +570,22 @@ public class SIPCommander implements ISIPCommander {
         }
         }
 
 
         log.info("[发送BYE] 设备: device: {}, channel: {}, callId: {}", device.getDeviceId(), channelId, ssrcTransaction.getCallId());
         log.info("[发送BYE] 设备: device: {}, channel: {}, callId: {}", device.getDeviceId(), channelId, ssrcTransaction.getCallId());
-        sessionManager.removeByCallId(ssrcTransaction.getCallId());
-        Request byteRequest = headerProvider.createByteRequest(device, channelId, ssrcTransaction.getSipTransactionInfo());
-        sipSender.transmitRequest(sipLayer.getLocalIp(device.getLocalIp()), byteRequest, null, okEvent);
+        final SsrcTransaction owned = ssrcTransaction;
+        boolean managed = owned.getStream() != null && owned.getStream().startsWith("managed_");
+        boolean adopted = sessionManager.isAdopted(owned);
+        if (!managed && !adopted) sessionManager.removeByCallId(owned.getCallId());
+        Request byteRequest = headerProvider.createByteRequest(device, channelId, owned.getSipTransactionInfo());
+        SipSubscribe.Event response = !managed && !adopted ? okEvent : event -> {
+            if (event.statusCode >= 200 && event.statusCode < 300
+                    && (adopted ? owned.getCallId().equals(event.callId)
+                    : event.callId == null || owned.getCallId().equals(event.callId))) {
+                if (adopted) sessionManager.removeAdoptedIfSame(owned);
+                else sessionManager.removeManagedIfSame(owned);
+            }
+            if (okEvent != null) okEvent.response(event);
+        };
+        // Managed transport errors leave the actual dialog available for retry.
+        sipSender.transmitRequest(sipLayer.getLocalIp(device.getLocalIp()), byteRequest, null, response);
     }
     }
 
 
     @Override
     @Override

+ 22 - 6
video-service/src/main/java/com/ruoyi/wvp/media/event/hook/Hook.java

@@ -1,6 +1,7 @@
 package com.ruoyi.wvp.media.event.hook;
 package com.ruoyi.wvp.media.event.hook;
 
 
 import lombok.Data;
 import lombok.Data;
+import java.util.Objects;
 
 
 /**
 /**
  * zlm hook事件的参数
  * zlm hook事件的参数
@@ -15,6 +16,9 @@ public class Hook {
 
 
     private String stream;
     private String stream;
 
 
+    /** null preserves the historical all-node subscription. */
+    private String mediaServerId;
+
     private Long expireTime;
     private Long expireTime;
 
 
 
 
@@ -28,24 +32,36 @@ public class Hook {
     }
     }
 
 
     public static Hook getInstance(HookType hookType, String app, String stream, String mediaServer) {
     public static Hook getInstance(HookType hookType, String app, String stream, String mediaServer) {
-        // TODO 后续修改所有方法
-        return Hook.getInstance(hookType, app, stream);
+        Hook hook = Hook.getInstance(hookType, app, stream);
+        hook.setMediaServerId(mediaServer);
+        return hook;
     }
     }
 
 
     @Override
     @Override
     public boolean equals(Object obj) {
     public boolean equals(Object obj) {
         if (obj instanceof Hook) {
         if (obj instanceof Hook) {
             Hook param = (Hook) obj;
             Hook param = (Hook) obj;
-            return param.getHookType().equals(this.hookType)
-                    && param.getApp().equals(this.app)
-                    && param.getStream().equals(this.stream);
+            return Objects.equals(param.getHookType(), this.hookType)
+                    && Objects.equals(param.getApp(), this.app)
+                    && Objects.equals(param.getStream(), this.stream)
+                    && Objects.equals(param.getMediaServerId(), this.mediaServerId);
         }else {
         }else {
             return false;
             return false;
         }
         }
     }
     }
 
 
+    @Override
+    public int hashCode() {
+        return Objects.hash(hookType, app, stream, mediaServerId);
+    }
+
     @Override
     @Override
     public String toString() {
     public String toString() {
-        return this.getHookType() + this.getApp() + this.getStream();
+        // Length framing prevents app/stream/node boundary collisions.
+        return hookType + ":" + part(app) + part(stream) + part(mediaServerId);
+    }
+
+    private static String part(String value) {
+        return value == null ? "-1:" : value.length() + ":" + value;
     }
     }
 }
 }

+ 50 - 24
video-service/src/main/java/com/ruoyi/wvp/media/event/hook/HookSubscribe.java

@@ -69,46 +69,72 @@ public class HookSubscribe {
         sendNotify(HookType.on_record_mp4, event);
         sendNotify(HookType.on_record_mp4, event);
     }
     }
 
 
-    private final Map<String, Event> allSubscribes = new ConcurrentHashMap<>();
-    private final Map<String, Hook> allHook = new ConcurrentHashMap<>();
+    /** Opaque owner identity; expiry and removal compare this exact registration. */
+    public static final class Subscription {
+        private final String key;
+        private final Hook hook;
+        private final Event event;
+        private final long expires;
+
+        private Subscription(Hook hook, Event event, long expires) {
+            this.key = hook.toString();
+            this.hook = hook;
+            this.event = event;
+            this.expires = expires;
+        }
+    }
+
+    private final Map<String, Subscription> allSubscribes = new ConcurrentHashMap<>();
 
 
     private void sendNotify(HookType hookType, MediaEvent event) {
     private void sendNotify(HookType hookType, MediaEvent event) {
-        Hook paramHook = Hook.getInstance(hookType, event.getApp(), event.getStream());
-        Event hookSubscribeEvent = allSubscribes.get(paramHook.toString());
-        if (hookSubscribeEvent != null) {
-            HookData data = HookData.getInstance(event);
-            hookSubscribeEvent.response(data);
+        String node = event.getMediaServer() == null ? null : event.getMediaServer().getId();
+        Subscription exact = node == null ? null : allSubscribes.get(
+                Hook.getInstance(hookType, event.getApp(), event.getStream(), node).toString());
+        Subscription wildcard = allSubscribes.get(Hook.getInstance(hookType, event.getApp(), event.getStream()).toString());
+        HookData data = HookData.getInstance(event);
+        notifyOwner(exact, data);
+        notifyOwner(wildcard, data);
+    }
+
+    private void notifyOwner(Subscription owner, HookData data) {
+        if (owner == null || allSubscribes.get(owner.key) != owner) return;
+        if (owner.expires < System.currentTimeMillis()) {
+            removeOwnedSubscribe(owner);
+            return;
         }
         }
+        owner.event.response(data);
     }
     }
 
 
     public void addSubscribe(Hook hook, Event event) {
     public void addSubscribe(Hook hook, Event event) {
-        if (hook.getExpireTime() == null) {
-            hook.setExpireTime(System.currentTimeMillis() + subscribeExpire);
-        }
-        allSubscribes.put(hook.toString(), event);
-        allHook.put(hook.toString(), hook);
+        addOwnedSubscribe(hook, event);
+    }
+
+    public Subscription addOwnedSubscribe(Hook hook, Event event) {
+        long expires = hook.getExpireTime() == null ? System.currentTimeMillis() + subscribeExpire : hook.getExpireTime();
+        Subscription owner = new Subscription(hook, event, expires);
+        allSubscribes.put(owner.key, owner);
+        return owner;
+    }
+
+    public boolean removeOwnedSubscribe(Subscription owner) {
+        return owner != null && allSubscribes.remove(owner.key, owner);
     }
     }
 
 
     public void removeSubscribe(Hook hook) {
     public void removeSubscribe(Hook hook) {
         allSubscribes.remove(hook.toString());
         allSubscribes.remove(hook.toString());
-        allHook.remove(hook.toString());
     }
     }
 
 
-    /**
-     * 对订阅数据进行过期清理
-     */
-    @Scheduled(fixedRate=subscribeExpire)   //每5分钟执行一次
+    @Scheduled(fixedRate=subscribeExpire)
     public void execute(){
     public void execute(){
-        long expireTime = System.currentTimeMillis();
-        for (Hook hook : allHook.values()) {
-            if (hook.getExpireTime() < expireTime) {
-                allSubscribes.remove(hook.toString());
-                allHook.remove(hook.toString());
-            }
+        long now = System.currentTimeMillis();
+        for (Subscription owner : allSubscribes.values()) {
+            if (owner.expires < now) removeOwnedSubscribe(owner);
         }
         }
     }
     }
 
 
     public List<Hook> getAll() {
     public List<Hook> getAll() {
-        return new ArrayList<>(allHook.values());
+        List<Hook> result = new ArrayList<>();
+        for (Subscription owner : allSubscribes.values()) result.add(owner.hook);
+        return result;
     }
     }
 }
 }

+ 10 - 0
video-service/src/main/java/com/ruoyi/wvp/service/IReceiveRtpServerService.java

@@ -10,4 +10,14 @@ public interface IReceiveRtpServerService {
     SSRCInfo openRTPServer(RTPServerParam rtpServerParam, ErrorCallback<OpenRTPServerResult> callback);
     SSRCInfo openRTPServer(RTPServerParam rtpServerParam, ErrorCallback<OpenRTPServerResult> callback);
 
 
     void closeRTPServer(MediaServer mediaServer, SSRCInfo ssrcInfo);
     void closeRTPServer(MediaServer mediaServer, SSRCInfo ssrcInfo);
+
+    /** Legacy names are reusable: close evidence belongs to this allocation and dialog, never the name. */
+    default boolean closeAdoptedRTPServer(MediaServer node, SSRCInfo info, String callId) {
+        return false;
+    }
+
+    /** A void close or an empty media list is not positive close evidence. */
+    default boolean closeManagedRTPServer(MediaServer mediaServer, SSRCInfo ssrcInfo) {
+        return false;
+    }
 }
 }

+ 235 - 8
video-service/src/main/java/com/ruoyi/wvp/service/impl/RtpServerServiceImpl.java

@@ -65,8 +65,215 @@ public class RtpServerServiceImpl implements IReceiveRtpServerService {
 
 
     }
     }
 
 
+    @Autowired
+    private com.zksy.video.lifecycle.VideoLifecycleStore videoLifecycleStore;
+
+    private final java.util.concurrent.ConcurrentMap<String, ManagedRtp> 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 final java.util.concurrent.atomic.AtomicBoolean released = new java.util.concurrent.atomic.AtomicBoolean();
+        private volatile boolean closed;
+        private volatile boolean opening = true;
+        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 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<OpenRTPServerResult> 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;
+        }
+        ManagedRtp entry = new ManagedRtp(new SSRCInfo(0, null, "rtp", stream, java.util.UUID.randomUUID().toString()));
+        if (managedRtp.putIfAbsent(managedKey(node, stream), entry) != null) {
+            callback.run(InviteErrorCode.FAIL.getCode(), "Managed RTP generation already allocated", null);
+            return null;
+        }
+        try {
+            if (cancelled(stream)) {
+                entry.opening = false; entry.closed = true;
+                return null;
+            }
+            entry.info.setSsrc(ssrcFactory.getPlaySsrc(node.getId()));
+            if (cancelled(stream)) {
+                entry.opening = false;
+                entry.closed = true;
+                releaseManagedSsrc(node, entry);
+                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);
+            entry.opening = false;
+            // A close response obtained while create was in-flight cannot prove the newly returned allocation closed.
+            entry.closed = false;
+            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) {
+            entry.opening = false;
+            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 && entry.released.compareAndSet(false, true)) {
+            ssrcFactory.releaseSsrc(node.getId(), entry.info.getSsrc());
+        }
+    }
+
+    @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;
+        ManagedRtp entry = managedRtp.computeIfAbsent(managedKey(node, info.getStream()), key -> {
+            ManagedRtp adopted = new ManagedRtp(info); adopted.opening = false; return adopted;
+        });
+        entry.terminal.set(true);
+        // Remove local ownership even when the remote close throws or never answers.
+        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);
+        }
+        if (entry.closed) return true;
+        try {
+            mediaServerService.closeRTPServer(node, info.getStream(), closed -> {
+                if (Boolean.TRUE.equals(closed) && !entry.opening) {
+                    entry.closed = true;
+                    releaseManagedSsrc(node, entry);
+                }
+            });
+        } catch (RuntimeException ex) {
+            log.warn("[Managed RTP close] {}/{} remains uncertain: {}", node.getId(), info.getStream(), ex.getMessage());
+        }
+        return entry.closed;
+    }
+
+    /** Unlike managed UUIDs, legacy names can be allocated again. Keep the allocation token, not a name receipt. */
+    private final java.util.Map<String, LegacyRtp> 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 final java.util.concurrent.atomic.AtomicBoolean released = new java.util.concurrent.atomic.AtomicBoolean();
+        private String callId;
+        private boolean closing;
+        private volatile boolean closed;
+        private volatile boolean opening = true;
+        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 || !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.opening
+                || (entry.callId != null && !entry.callId.equals(callId)))) return false;
+        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;
+        if (entry == null) {
+            // Only Play's already observed Invite/dialog supplies this handle, never media-list guesses.
+            entry = new LegacyRtp(info); entry.opening = false; legacyRtp.put(key, entry);
+        }
+        entry.callId = callId;
+        final LegacyRtp owned = entry;
+        owned.terminal.set(true);
+        try { dynamicTask.stop(info.getTimeOutTaskKey()); }
+        catch (RuntimeException ex) { log.warn("[Adopted timer close] {}: {}", info.getStream(), ex.getMessage()); }
+        finally { subscribe.removeOwnedSubscribe(owned.owner); }
+        if (owned.closed) return true;
+        if (owned.closing) return false; // Never leave a second name-based close in flight across reallocation.
+        owned.closing = true;
+        try {
+            mediaServerService.closeRTPServer(node, info.getStream(), closed -> {
+                synchronized (RtpServerServiceImpl.this) {
+                    if (Boolean.TRUE.equals(closed) && legacyRtp.get(key) == owned && !owned.opening) {
+                        if (owned.released.compareAndSet(false, true)) ssrcFactory.releaseSsrc(node.getId(), info.getSsrc());
+                        owned.closed = true;
+                    }
+                    owned.closing = false;
+                }
+            });
+        } catch (RuntimeException ex) {
+            // Dispatch may already have escaped; without a response keep the allocation fenced.
+            log.warn("[Adopted RTP close] {}/{} remains uncertain: {}", node.getId(), info.getStream(), ex.getMessage());
+        }
+        return owned.closed;
+    }
+
     @Override
     @Override
     public SSRCInfo openRTPServer(RTPServerParam rtpServerParam, ErrorCallback<OpenRTPServerResult> callback) {
     public SSRCInfo openRTPServer(RTPServerParam rtpServerParam, ErrorCallback<OpenRTPServerResult> callback) {
+        if (rtpServerParam.getStreamId() != null && rtpServerParam.getStreamId().startsWith("managed_")) {
+            return openManagedRtp(rtpServerParam, callback);
+        }
+        return openLegacyRtp(rtpServerParam, callback);
+    }
+
+    private synchronized SSRCInfo openLegacyRtp(RTPServerParam rtpServerParam, ErrorCallback<OpenRTPServerResult> callback) {
         if (callback == null) {
         if (callback == null) {
             log.warn("[开启RTP收流] 失败,回调为NULL");
             log.warn("[开启RTP收流] 失败,回调为NULL");
             return null;
             return null;
@@ -97,6 +304,18 @@ public class RtpServerServiceImpl implements IReceiveRtpServerService {
             // 目前zlm不支持 tcp模式更新ssrc,暂时关闭ssrc校验
             // 目前zlm不支持 tcp模式更新ssrc,暂时关闭ssrc校验
             log.warn("[openRTPServer] 平台对接时下级可能自定义ssrc,但是tcp模式zlm收流目前无法更新ssrc,可能收流超时,此时请使用udp收流或者关闭ssrc校验");
             log.warn("[openRTPServer] 平台对接时下级可能自定义ssrc,但是tcp模式zlm收流目前无法更新ssrc,可能收流超时,此时请使用udp收流或者关闭ssrc校验");
         }
         }
+        // Register BEFORE create: even an in-flight replacement invalidates the previous close receipt.
+        String timeOutTaskKey = UUID.randomUUID().toString();
+        SSRCInfo ssrcInfo = new SSRCInfo(0, ssrc, "rtp", streamId, timeOutTaskKey);
+        LegacyRtp entry = new LegacyRtp(ssrcInfo);
+        String allocationKey = managedKey(rtpServerParam.getMediaServerItem(), streamId);
+        LegacyRtp previous = legacyRtp.get(allocationKey);
+        if (previous != null && previous.callId != null && !previous.closed) {
+            if (rtpServerParam.getPresetSsrc() == null) ssrcFactory.releaseSsrc(rtpServerParam.getMediaServerItem().getId(), ssrc);
+            callback.run(InviteErrorCode.FAIL.getCode(), "Adopted RTP close is still pending", null);
+            return null;
+        }
+        legacyRtp.put(allocationKey, entry);
         int rtpServerPort;
         int rtpServerPort;
         if (rtpServerParam.getMediaServerItem().isRtpEnable()) {
         if (rtpServerParam.getMediaServerItem().isRtpEnable()) {
             rtpServerPort = mediaServerService.createRTPServer(rtpServerParam.getMediaServerItem(), streamId,
             rtpServerPort = mediaServerService.createRTPServer(rtpServerParam.getMediaServerItem(), streamId,
@@ -105,6 +324,8 @@ public class RtpServerServiceImpl implements IReceiveRtpServerService {
         } else {
         } else {
             rtpServerPort = rtpServerParam.getMediaServerItem().getRtpProxyPort();
             rtpServerPort = rtpServerParam.getMediaServerItem().getRtpProxyPort();
         }
         }
+        ssrcInfo.setPort(rtpServerPort);
+        entry.opening = false;
         if (rtpServerPort == 0) {
         if (rtpServerPort == 0) {
             callback.run(InviteErrorCode.ERROR_FOR_RESOURCE_EXHAUSTION.getCode(), "开启RTPServer失败", null);
             callback.run(InviteErrorCode.ERROR_FOR_RESOURCE_EXHAUSTION.getCode(), "开启RTPServer失败", null);
             // 释放ssrc
             // 释放ssrc
@@ -114,15 +335,12 @@ public class RtpServerServiceImpl implements IReceiveRtpServerService {
             return null;
             return null;
         }
         }
 
 
-        // 设置流超时的定时任务
-        String timeOutTaskKey = UUID.randomUUID().toString();
-
-        SSRCInfo ssrcInfo = new SSRCInfo(rtpServerPort, ssrc, "rtp", streamId, timeOutTaskKey);
         OpenRTPServerResult openRTPServerResult = new OpenRTPServerResult();
         OpenRTPServerResult openRTPServerResult = new OpenRTPServerResult();
         openRTPServerResult.setSsrcInfo(ssrcInfo);
         openRTPServerResult.setSsrcInfo(ssrcInfo);
 
 
         Hook rtpHook = Hook.getInstance(HookType.on_media_arrival, ssrcInfo.getApp(), streamId, rtpServerParam.getMediaServerItem().getId());
         Hook rtpHook = Hook.getInstance(HookType.on_media_arrival, ssrcInfo.getApp(), streamId, rtpServerParam.getMediaServerItem().getId());
         dynamicTask.startDelay(timeOutTaskKey, () -> {
         dynamicTask.startDelay(timeOutTaskKey, () -> {
+            if (legacyRtp.get(allocationKey) != entry || !entry.terminal.compareAndSet(false, true)) return;
             // 收流超时
             // 收流超时
             // 释放ssrc
             // 释放ssrc
             if (rtpServerParam.getPresetSsrc() == null) {
             if (rtpServerParam.getPresetSsrc() == null) {
@@ -130,23 +348,32 @@ public class RtpServerServiceImpl implements IReceiveRtpServerService {
             }
             }
             // 关闭收流端口
             // 关闭收流端口
             mediaServerService.closeRTPServer(rtpServerParam.getMediaServerItem(), streamId);
             mediaServerService.closeRTPServer(rtpServerParam.getMediaServerItem(), streamId);
-            subscribe.removeSubscribe(rtpHook);
+            subscribe.removeOwnedSubscribe(entry.owner);
             callback.run(InviteErrorCode.ERROR_FOR_STREAM_TIMEOUT.getCode(), InviteErrorCode.ERROR_FOR_STREAM_TIMEOUT.getMsg(), openRTPServerResult);
             callback.run(InviteErrorCode.ERROR_FOR_STREAM_TIMEOUT.getCode(), InviteErrorCode.ERROR_FOR_STREAM_TIMEOUT.getMsg(), openRTPServerResult);
         }, userSetting.getPlayTimeout());
         }, userSetting.getPlayTimeout());
         // 开启流到来的监听
         // 开启流到来的监听
-        subscribe.addSubscribe(rtpHook, (hookData) -> {
+        entry.owner = subscribe.addOwnedSubscribe(rtpHook, (hookData) -> {
+            if (legacyRtp.get(allocationKey) != entry || !entry.terminal.compareAndSet(false, true)) return;
             dynamicTask.stop(timeOutTaskKey);
             dynamicTask.stop(timeOutTaskKey);
             // hook响应
             // hook响应
             openRTPServerResult.setHookData(hookData);
             openRTPServerResult.setHookData(hookData);
-            callback.run(InviteErrorCode.SUCCESS.getCode(), InviteErrorCode.SUCCESS.getMsg(), openRTPServerResult);
-            subscribe.removeSubscribe(rtpHook);
+            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;
         return ssrcInfo;
     }
     }
 
 
     @Override
     @Override
     public void closeRTPServer(MediaServer mediaServer, SSRCInfo ssrcInfo) {
     public void closeRTPServer(MediaServer mediaServer, SSRCInfo ssrcInfo) {
+        if (ssrcInfo != null && ssrcInfo.getStream() != null && ssrcInfo.getStream().startsWith("managed_")) {
+            closeManagedRTPServer(mediaServer, ssrcInfo);
+            return;
+        }
         if (mediaServer == null) {
         if (mediaServer == null) {
             return;
             return;
         }
         }

+ 9 - 1
video-service/src/main/java/com/zksy/video/ManualVideoController.java

@@ -10,5 +10,13 @@ public class ManualVideoController {
     private final ManualVideoService service;
     private final ManualVideoService service;
     public ManualVideoController(ManualVideoService service) {this.service=service;}
     public ManualVideoController(ManualVideoService service) {this.service=service;}
     @PostMapping("/start") public AjaxResult start(@RequestBody Map<String,String> input) {return AjaxResult.success(service.start(input.get("id"),input.get("url")));}
     @PostMapping("/start") public AjaxResult start(@RequestBody Map<String,String> input) {return AjaxResult.success(service.start(input.get("id"),input.get("url")));}
-    @PostMapping("/stop") public AjaxResult stop(@RequestBody Map<String,String> input) {service.stop(input.get("key"));return AjaxResult.success();}
+    @PostMapping("/stop") public AjaxResult stop(@RequestBody Map<String,String> input) {
+        if (input.containsKey("mediaServerId")) {
+            return service.stop(input.get("mediaServerId"), input.get("key"))
+                    ? AjaxResult.success() : AjaxResult.error("代理节点未知或尚未确认回收");
+        }
+        // Key-only compatibility is limited to handles this process actually received; no default-node guess.
+        try { service.stop(input.get("key")); return AjaxResult.success(); }
+        catch (IllegalStateException unknown) { return AjaxResult.error(unknown.getMessage()); }
+    }
 }
 }

+ 100 - 20
video-service/src/main/java/com/zksy/video/ManualVideoService.java

@@ -9,6 +9,9 @@ import com.ruoyi.wvp.media.zlm.ZLMRESTfulUtils;
 import com.ruoyi.wvp.media.service.IMediaServerService;
 import com.ruoyi.wvp.media.service.IMediaServerService;
 import com.ruoyi.wvp.vmanager.bean.StreamContent;
 import com.ruoyi.wvp.vmanager.bean.StreamContent;
 import com.fasterxml.jackson.databind.ObjectMapper;
 import com.fasterxml.jackson.databind.ObjectMapper;
+import com.ruoyi.wvp.common.StreamInfo;
+import com.ruoyi.wvp.media.bean.MediaInfo;
+import com.zksy.video.lifecycle.VideoLifecycleMedia;
 
 
 @Service
 @Service
 public class ManualVideoService {
 public class ManualVideoService {
@@ -16,28 +19,105 @@ public class ManualVideoService {
     private final ZLMRESTfulUtils zlm;
     private final ZLMRESTfulUtils zlm;
     private final ObjectMapper json;
     private final ObjectMapper json;
     public ManualVideoService(IMediaServerService servers,ZLMRESTfulUtils zlm,ObjectMapper json) {this.servers=servers;this.zlm=zlm;this.json=json;}
     public ManualVideoService(IMediaServerService servers,ZLMRESTfulUtils zlm,ObjectMapper json) {this.servers=servers;this.zlm=zlm;this.json=json;}
-    public synchronized Map<String,Object> start(String id,String url) { return start(id,url,"manual_"+id); }
-    /** 受管代次入口:stream 由调用方按观看代次生成,同一设备不同代次不复用物理流。 */
+    /** 旧入口仅记本进程亲自收到的 actual key -> 节点;重启后未知 key 拒绝猜测。 */
+    private final Map<String, String> legacyNodes = new java.util.concurrent.ConcurrentHashMap<>();
+    private final Map<String, LegacyProxy> legacyProxies = new java.util.concurrent.ConcurrentHashMap<>();
+    private static final class LegacyProxy {
+        private final String id, url, stream, node, key;
+        private LegacyProxy(String id, String url, String stream, String node, String key) {
+            this.id = id; this.url = url; this.stream = stream; this.node = node; this.key = key;
+        }
+    }
+    public synchronized Map<String, Object> start(String id, String url) { return start(id, url, "manual_" + id); }
+
+    public synchronized Map<String, Object> start(String id, String url, String stream) {
+        LegacyProxy confirmed = legacyProxies.get(stream);
+        String node = confirmed == null ? selectMediaServer() : confirmed.node;
+        Map<String, Object> result = new LinkedHashMap<>();
+        result.put("stream", stream); result.put("mediaServerId", node);
+        if (confirmed != null && (!Objects.equals(id, confirmed.id) || !Objects.equals(url, confirmed.url))) {
+            result.put("status", "CLEANUP_PENDING");
+            return result;
+        }
+        String key = confirmed == null ? start(node, id, url, stream) : confirmed.key;
+        if (key != null) {
+            result.put("proxyKey", key); legacyNodes.put(key, node);
+            legacyProxies.put(stream, new LegacyProxy(id, url, stream, node, key));
+        }
+        try {
+            Map<String, Object> media = key == null ? null : status(node, stream, url);
+            if (media != null) result.putAll(media);
+            result.put("status", key == null ? "CLEANUP_PENDING" : media == null ? "STARTING" : "ACTIVE");
+        } catch (RuntimeException unknown) { result.put("status", "CLEANUP_PENDING"); }
+        return result;
+    }
+
+    /** 受管入口:节点和流已持久化;只返回 add 的真实 key,绝不拼接代理句柄。 */
+    public String start(String mediaServerId, String id, String url, String stream) {
+        if (id == null || !id.matches("[A-Za-z0-9_-]{1,64}")) throw new IllegalArgumentException("视频设备编号无效");
+        if (stream == null || !stream.matches("[A-Za-z0-9_-]{1,64}")) throw new IllegalArgumentException("拉流名称无效");
+        URI uri = URI.create(url);
+        if (uri.getHost() == null || !Set.of("rtsp", "rtsps", "rtmp", "rtmps").contains(uri.getScheme().toLowerCase(Locale.ROOT)))
+            throw new IllegalArgumentException("拉流地址必须使用 RTSP 或 RTMP");
+        MediaServer server = recordedServer(mediaServerId);
+        if (VideoLifecycleMedia.findMedia(zlm, server, "city_video", stream) != null) return null;
+        JSONObject response = zlm.addStreamProxy(server, "city_video", stream, url, true, false, "0", 15);
+        if (response == null || !Integer.valueOf(0).equals(response.getInteger("code")))
+            throw new IllegalStateException("手动拉流结果未知或失败");
+        JSONObject data = response.getJSONObject("data");
+        String key = data == null ? null : data.getString("key");
+        return key == null || key.isBlank() ? null : key;
+    }
+    public String selectMediaServer() {
+        MediaServer server = servers.getDefaultMediaServer();
+        if (server == null || server.getId() == null || !server.isStatus() || !"zlm".equals(server.getType()))
+            throw new IllegalArgumentException("媒体节点未上线");
+        return server.getId();
+    }
+
+    /** 只定位持久化节点;这里绝不选择默认节点。 */
+    public MediaServer recordedServer(String mediaServerId) {
+        MediaServer server = mediaServerId == null ? null : servers.getOne(mediaServerId);
+        if (server == null || !mediaServerId.equals(server.getId()) || !server.isStatus()
+                || !"zlm".equals(server.getType())) throw new IllegalStateException("记录的媒体节点不可用");
+        return server;
+    }
+
     @SuppressWarnings("unchecked")
     @SuppressWarnings("unchecked")
-    public synchronized Map<String,Object> start(String id,String url,String stream) {
-        if(id==null || !id.matches("[A-Za-z0-9_-]{1,64}")) throw new IllegalArgumentException("视频设备编号无效");
-        if(stream==null || !stream.matches("[A-Za-z0-9_-]{1,64}")) throw new IllegalArgumentException("拉流名称无效");
-        URI uri=URI.create(url);
-        if(uri.getHost()==null || !Set.of("rtsp","rtsps","rtmp","rtmps").contains(uri.getScheme())) throw new IllegalArgumentException("拉流地址必须使用 RTSP 或 RTMP");
-        MediaServer server=servers.getDefaultMediaServer();
-        if(server==null) throw new IllegalArgumentException("媒体节点未上线");
-        String key="__defaultVhost__/city_video/"+stream;
-        if(servers.getStreamInfoByAppAndStreamWithCheck("city_video",stream,server.getId(),false)==null) {
-            JSONObject result=zlm.addStreamProxy(server,"city_video",stream,url,true,false,"0",15);
-            if(result==null || result.getIntValue("code")!=0) throw new IllegalArgumentException("手动设备拉流失败,请检查视频地址与设备网络");
-            JSONObject data=result.getJSONObject("data"); if(data!=null && data.getString("key")!=null) key=data.getString("key");
+    public Map<String, Object> status(String mediaServerId, String stream, String url) {
+        MediaServer server = recordedServer(mediaServerId);
+        JSONObject live = VideoLifecycleMedia.findMedia(zlm, server, "city_video", stream);
+        if (live == null) return null;
+        if (!Integer.valueOf(4).equals(live.getInteger("originType")) || !url.equals(live.getString("originUrl")))
+            throw new IllegalStateException("实际媒体与手动拉流来源不匹配");
+        StreamInfo info = servers.getStreamInfoByAppAndStream(server, "city_video", stream,
+                MediaInfo.getInstance(live, server, null), null);
+        if (info == null) throw new IllegalStateException("无法生成已确认媒体的播放信息");
+        Map<String, Object> result = json.convertValue(new StreamContent(info), Map.class);
+        result.put("app", "city_video"); result.put("stream", stream); result.put("mediaServerId", mediaServerId);
+        return result;
+    }
+
+    /** 只能用真实 add 响应的 key,在已记录节点上确认删除成功。 */
+    public synchronized boolean stop(String mediaServerId, String key) {
+        if (mediaServerId == null || mediaServerId.isBlank() || key == null || key.isBlank()) return false;
+        try {
+            MediaServer server = recordedServer(mediaServerId);
+            JSONObject result = zlm.delStreamProxy(server, key);
+            if (result == null || !Integer.valueOf(0).equals(result.getInteger("code"))) return false;
+            JSONObject data = result.getJSONObject("data");
+            if (data != null && Boolean.FALSE.equals(data.getBoolean("flag"))) return false;
+            legacyNodes.remove(key, mediaServerId);
+            legacyProxies.entrySet().removeIf(entry -> mediaServerId.equals(entry.getValue().node) && key.equals(entry.getValue().key));
+            return true;
+        } catch (RuntimeException unavailable) {
+            return false;
         }
         }
-        Map<String,Object> result=json.convertValue(new StreamContent(servers.getStreamInfoByAppAndStream(server,"city_video",stream,null,null)),Map.class);
-        result.put("proxyKey",key);return result;
     }
     }
-    public void stop(String key) {
-        if(key==null || !key.startsWith("__defaultVhost__/city_video/manual_")) throw new IllegalArgumentException("无效拉流会话");
-        MediaServer server=servers.getDefaultMediaServer();
-        if(server!=null) zlm.delStreamProxy(server,key);
+
+    public synchronized void stop(String key) {
+        String node = key == null ? null : legacyNodes.get(key);
+        if (node == null || !stop(node, key)) throw new IllegalStateException("代理节点未知或尚未确认回收");
+        legacyNodes.remove(key, node);
     }
     }
 }
 }

+ 104 - 49
video-service/src/main/java/com/zksy/video/lifecycle/Gb28181LifecycleMedia.java

@@ -2,98 +2,153 @@ package com.zksy.video.lifecycle;
 
 
 import java.util.LinkedHashMap;
 import java.util.LinkedHashMap;
 import java.util.Map;
 import java.util.Map;
+import java.util.UUID;
 import org.springframework.stereotype.Component;
 import org.springframework.stereotype.Component;
+import com.alibaba.fastjson2.JSONObject;
 import com.fasterxml.jackson.databind.ObjectMapper;
 import com.fasterxml.jackson.databind.ObjectMapper;
-import com.ruoyi.wvp.common.InviteSessionType;
 import com.ruoyi.wvp.common.StreamInfo;
 import com.ruoyi.wvp.common.StreamInfo;
 import com.ruoyi.wvp.gb28181.bean.Device;
 import com.ruoyi.wvp.gb28181.bean.Device;
 import com.ruoyi.wvp.gb28181.bean.DeviceChannel;
 import com.ruoyi.wvp.gb28181.bean.DeviceChannel;
 import com.ruoyi.wvp.gb28181.service.IDeviceChannelService;
 import com.ruoyi.wvp.gb28181.service.IDeviceChannelService;
 import com.ruoyi.wvp.gb28181.service.IDeviceService;
 import com.ruoyi.wvp.gb28181.service.IDeviceService;
 import com.ruoyi.wvp.gb28181.service.IPlayService;
 import com.ruoyi.wvp.gb28181.service.IPlayService;
+import com.ruoyi.wvp.media.bean.MediaInfo;
 import com.ruoyi.wvp.media.bean.MediaServer;
 import com.ruoyi.wvp.media.bean.MediaServer;
 import com.ruoyi.wvp.media.service.IMediaServerService;
 import com.ruoyi.wvp.media.service.IMediaServerService;
+import com.ruoyi.wvp.media.zlm.ZLMRESTfulUtils;
+import com.ruoyi.wvp.service.bean.SSRCInfo;
 import com.ruoyi.wvp.vmanager.bean.StreamContent;
 import com.ruoyi.wvp.vmanager.bean.StreamContent;
 
 
-/**
- * GB28181 源:复用既有 INVITE 点播与停止链路。
- *
- * 已知边界:物理流名由 {@link IPlayService} 固定为 {@code 设备ID_通道ID},同一摄像机天然共享一条流;
- * 本适配器不修改该命名(改动会牵动 SIP 事务、ZLM hook 与既有管理端播放链)。
- * 因此“不同代次唯一物理流”在 GB28181 侧尚未成立,代次隔离只保证本服务不再为已取消代次发起点播。
- */
+/** GB28181 adapter 只管理记录节点上的本代次流;SIP/RTP 的精确启动和回收由 managed 接口负责。 */
 @Component
 @Component
 public class Gb28181LifecycleMedia implements VideoLifecycleMedia {
 public class Gb28181LifecycleMedia implements VideoLifecycleMedia {
     private static final String APP = "rtp";
     private static final String APP = "rtp";
-
     private final IDeviceService devices;
     private final IDeviceService devices;
     private final IDeviceChannelService channels;
     private final IDeviceChannelService channels;
     private final IPlayService play;
     private final IPlayService play;
     private final IMediaServerService servers;
     private final IMediaServerService servers;
+    private final ZLMRESTfulUtils zlm;
     private final ObjectMapper json;
     private final ObjectMapper json;
 
 
     public Gb28181LifecycleMedia(IDeviceService devices, IDeviceChannelService channels, IPlayService play,
     public Gb28181LifecycleMedia(IDeviceService devices, IDeviceChannelService channels, IPlayService play,
-            IMediaServerService servers, ObjectMapper json) {
-        this.devices = devices; this.channels = channels; this.play = play; this.servers = servers; this.json = json;
+            IMediaServerService servers, ZLMRESTfulUtils zlm, ObjectMapper json) {
+        this.devices = devices; this.channels = channels; this.play = play;
+        this.servers = servers; this.zlm = zlm; this.json = json;
     }
     }
 
 
     @Override public boolean supports(String sourceType) { return "GB28181".equals(sourceType); }
     @Override public boolean supports(String sourceType) { return "GB28181".equals(sourceType); }
 
 
     @Override public String intendedStream(VideoLifecycleRecord record) {
     @Override public String intendedStream(VideoLifecycleRecord record) {
-        return record.getDeviceId() == null || record.getChannelId() == null ? null
-                : streamName(record.getDeviceId(), record.getChannelId());
+        return "managed_" + UUID.fromString(record.getGeneration()).toString().replace("-", "");
+    }
+
+    @Override public void prepare(VideoLifecycleRecord record) {
+        if (record.isCancelled()) return;
+        Device device = device(record);
+        channel(record);
+        if (record.getStream() == null) {
+            MediaServer server = play.getNewMediaServerItem(device);
+            if (server == null || server.getId() == null || !server.isStatus() || !"zlm".equals(server.getType()))
+                throw new IllegalArgumentException("媒体节点未上线");
+            record.setStream(intendedStream(record));
+            record.setMediaServerId(server.getId());
+        } else {
+            // adoption 只允许保留原 stream + 原节点;实际存在性在 start/status 确认。
+            recordedServer(record);
+        }
     }
     }
 
 
     @Override public Map<String, Object> start(VideoLifecycleRecord record) {
     @Override public Map<String, Object> start(VideoLifecycleRecord record) {
-        String deviceId = record.getDeviceId(), channelId = record.getChannelId();
-        if (deviceId == null || channelId == null) throw new IllegalArgumentException("国标设备与通道不能为空");
-        Device device = devices.getDeviceByDeviceId(deviceId);
-        if (device == null) throw new IllegalArgumentException("设备未注册或离线");
-        DeviceChannel channel = channels.getOne(deviceId, channelId);
-        if (channel == null) throw new IllegalArgumentException("通道不存在");
-        MediaServer server = play.getNewMediaServerItem(device);
-        if (server == null) throw new IllegalArgumentException("媒体节点未上线");
-        String stream = streamName(deviceId, channelId);
-        if (servers.getStreamInfoByAppAndStream(server, APP, stream, null, null) == null) {
-            // 回调结果由 status 轮询确认;此处只发起,不谎报 ACTIVE。
-            play.play(server, deviceId, channelId, null, (code, msg, data) -> { });
+        if (record.isCancelled()) return cancel(record);
+        try {
+            MediaServer server = recordedServer(record);
+            device(record); channel(record);
+            if (!intendedStream(record).equals(record.getStream())) return status(record);
+            JSONObject live = VideoLifecycleMedia.findMedia(zlm, server, APP, record.getStream());
+            if (live != null) return outcome(record, "ACTIVE", media(server, record, live));
+            SSRCInfo handle = play.playManaged(server, record.getDeviceId(), record.getChannelId(), record.getStream(),
+                    (code, message, info) -> { }); // 异步回调不改记录;只认后续真实媒体探测。
+            if (handle == null || !APP.equals(handle.getApp()) || !record.getStream().equals(handle.getStream()))
+                return outcome(record, "CLEANUP_PENDING", null);
+            return outcome(record, "STARTING", null);
+        } catch (RuntimeException unknown) {
+            return outcome(record, "CLEANUP_PENDING", null);
         }
         }
-        return outcome("STARTING", null, stream);
     }
     }
 
 
     @Override public Map<String, Object> status(VideoLifecycleRecord record) {
     @Override public Map<String, Object> status(VideoLifecycleRecord record) {
-        MediaServer server = servers.getDefaultMediaServer();
-        StreamInfo info = server == null || record.getStream() == null ? null
-                : servers.getStreamInfoByAppAndStream(server, APP, record.getStream(), null, null);
-        if (info == null) return outcome("STARTING", null, record.getStream());
-        return outcome("ACTIVE", media(info), record.getStream());
+        if (record.isCancelled()) return cancel(record);
+        try {
+            MediaServer server = recordedServer(record);
+            JSONObject live = VideoLifecycleMedia.findMedia(zlm, server, APP, record.getStream());
+            if (live == null) return outcome(record,
+                    intendedStream(record).equals(record.getStream()) ? "STARTING" : "CLEANUP_PENDING", null);
+            Map<String, Object> actual = media(server, record, live);
+            if (!intendedStream(record).equals(record.getStream())) {
+                String handle = play.adoptStream(server, device(record), channel(record), record.getStream(), record.getAdoptedHandle());
+                if (handle == null) return outcome(record, "CLEANUP_PENDING", null);
+                record.setAdoptedHandle(handle);
+            }
+            return outcome(record, "ACTIVE", actual);
+        } catch (RuntimeException unknown) {
+            return outcome(record, "CLEANUP_PENDING", null);
+        }
     }
     }
 
 
     @Override public Map<String, Object> cancel(VideoLifecycleRecord record) {
     @Override public Map<String, Object> cancel(VideoLifecycleRecord record) {
-        String deviceId = record.getDeviceId(), channelId = record.getChannelId();
-        if (deviceId == null || channelId == null || record.getStream() == null)
-            throw new IllegalArgumentException("缺少可精确回收的国标句柄");
-        Device device = devices.getDeviceByDeviceId(deviceId);
-        DeviceChannel channel = channels.getOne(deviceId, channelId);
-        if (device == null || channel == null) throw new IllegalStateException("设备或通道不可用,无法确认停止");
-        play.stop(InviteSessionType.PLAY, device, channel, record.getStream());
-        MediaServer server = servers.getDefaultMediaServer();
-        StreamInfo still = server == null ? null
-                : servers.getStreamInfoByAppAndStream(server, APP, record.getStream(), null, null);
-        // 只有流确实不在才算停成;否则留给主服务继续等回收。
-        return still == null ? outcome("STOPPED", null, record.getStream()) : outcome("CLEANUP_PENDING", null, record.getStream());
+        try {
+            MediaServer server = recordedServer(record);
+            if (record.getStream() == null || record.getStream().isBlank()) return outcome(record, "CLEANUP_PENDING", null);
+            boolean stopped = intendedStream(record).equals(record.getStream())
+                    ? play.stopManaged(server, device(record), channel(record), record.getStream())
+                    : play.stopAdopted(server, device(record), channel(record), record.getStream(), record.getAdoptedHandle());
+            if (!stopped || record.isStartInFlight()) return outcome(record, "CLEANUP_PENDING", null);
+            JSONObject still = VideoLifecycleMedia.findMedia(zlm, server, APP, record.getStream());
+            return outcome(record, still == null ? "STOPPED" : "CLEANUP_PENDING", null);
+        } catch (RuntimeException unknown) {
+            return outcome(record, "CLEANUP_PENDING", null);
+        }
     }
     }
 
 
-    static String streamName(String deviceId, String channelId) { return deviceId + "_" + channelId; }
+    private MediaServer recordedServer(VideoLifecycleRecord record) {
+        String id = record.getMediaServerId();
+        MediaServer server = id == null ? null : servers.getOne(id);
+        if (server == null || !id.equals(server.getId()) || !server.isStatus() || !"zlm".equals(server.getType()))
+            throw new IllegalStateException("记录的媒体节点不可用");
+        return server;
+    }
+
+    private Device device(VideoLifecycleRecord record) {
+        if (record.getDeviceId() == null || record.getDeviceId().isBlank()) throw new IllegalArgumentException("国标设备不能为空");
+        Device device = devices.getDeviceByDeviceId(record.getDeviceId());
+        if (device == null) throw new IllegalArgumentException("设备未注册或离线");
+        return device;
+    }
+
+    private DeviceChannel channel(VideoLifecycleRecord record) {
+        if (record.getChannelId() == null || record.getChannelId().isBlank()) throw new IllegalArgumentException("国标通道不能为空");
+        DeviceChannel channel = channels.getOne(record.getDeviceId(), record.getChannelId());
+        if (channel == null) throw new IllegalArgumentException("通道不存在");
+        return channel;
+    }
 
 
     @SuppressWarnings("unchecked")
     @SuppressWarnings("unchecked")
-    private Map<String, Object> media(StreamInfo info) { return json.convertValue(new StreamContent(info), Map.class); }
+    private Map<String, Object> media(MediaServer server, VideoLifecycleRecord record, JSONObject live) {
+        if (!Integer.valueOf(3).equals(live.getInteger("originType"))) throw new IllegalStateException("实际媒体不是国标 RTP 流");
+        StreamInfo info = servers.getStreamInfoByAppAndStream(server, APP, record.getStream(),
+                MediaInfo.getInstance(live, server, null), null);
+        if (info == null) throw new IllegalStateException("无法生成已确认媒体的播放信息");
+        Map<String, Object> result = json.convertValue(new StreamContent(info), Map.class);
+        result.put("app", APP); result.put("stream", record.getStream()); result.put("mediaServerId", server.getId());
+        return result;
+    }
 
 
-    private static Map<String, Object> outcome(String status, Map<String, Object> media, String stream) {
-        Map<String, Object> result = new LinkedHashMap<>();
-        result.put("status", status);
+    private static Map<String, Object> outcome(VideoLifecycleRecord record, String status, Map<String, Object> media) {
+        Map<String, Object> result = new LinkedHashMap<>(); result.put("status", status);
+        record.setMedia(media);
         if (media != null) result.put("media", media);
         if (media != null) result.put("media", media);
-        if (stream != null) result.put("stream", stream);
+        if (record.getStream() != null) result.put("stream", record.getStream());
+        if (record.getMediaServerId() != null) result.put("mediaServerId", record.getMediaServerId());
         return result;
         return result;
     }
     }
 }
 }

+ 66 - 35
video-service/src/main/java/com/zksy/video/lifecycle/ManualLifecycleMedia.java

@@ -1,74 +1,105 @@
 package com.zksy.video.lifecycle;
 package com.zksy.video.lifecycle;
 
 
 import java.net.URI;
 import java.net.URI;
-import java.util.LinkedHashMap;
 import java.util.Locale;
 import java.util.Locale;
 import java.util.Map;
 import java.util.Map;
 import java.util.Set;
 import java.util.Set;
 import org.springframework.stereotype.Component;
 import org.springframework.stereotype.Component;
 import com.zksy.video.ManualVideoService;
 import com.zksy.video.ManualVideoService;
 
 
-/**
- * MANUAL 源:RTSP/RTMP 走真实拉流代理并按代次取唯一 stream;
- * http(s) 原生地址不经过媒体节点,直接作为 ACTIVE 媒体返回。
- */
+/** MANUAL 原生地址不创建媒体资源;代理始终绑定代次流名、实际 key 和记录节点。 */
 @Component
 @Component
 public class ManualLifecycleMedia implements VideoLifecycleMedia {
 public class ManualLifecycleMedia implements VideoLifecycleMedia {
     private static final Set<String> PROXY_SCHEMES = Set.of("rtsp", "rtsps", "rtmp", "rtmps");
     private static final Set<String> PROXY_SCHEMES = Set.of("rtsp", "rtsps", "rtmp", "rtmps");
-
     private final ManualVideoService manual;
     private final ManualVideoService manual;
 
 
     public ManualLifecycleMedia(ManualVideoService manual) { this.manual = manual; }
     public ManualLifecycleMedia(ManualVideoService manual) { this.manual = manual; }
-
     @Override public boolean supports(String sourceType) { return "MANUAL".equals(sourceType); }
     @Override public boolean supports(String sourceType) { return "MANUAL".equals(sourceType); }
 
 
-    @Override public String intendedStream(VideoLifecycleRecord record) {
+    private static boolean proxy(VideoLifecycleRecord record) {
         String url = record.getUrl();
         String url = record.getUrl();
-        if (url == null || url.isBlank()) return null;
+        if (url == null || url.isBlank()) throw new IllegalArgumentException("手动视频地址缺失");
         URI uri = URI.create(url);
         URI uri = URI.create(url);
-        return uri.getHost() != null && PROXY_SCHEMES.contains(String.valueOf(uri.getScheme()).toLowerCase(Locale.ROOT))
-                ? managedStream(record) : null;
+        String scheme = String.valueOf(uri.getScheme()).toLowerCase(Locale.ROOT);
+        if (uri.getHost() == null || !(PROXY_SCHEMES.contains(scheme) || Set.of("http", "https").contains(scheme)))
+            throw new IllegalArgumentException("不支持的手动视频地址");
+        return PROXY_SCHEMES.contains(scheme);
+    }
+
+    @Override public String intendedStream(VideoLifecycleRecord record) {
+        return proxy(record) ? managedStream(record) : null;
+    }
+
+    @Override public void prepare(VideoLifecycleRecord record) {
+        if (record.isCancelled()) return;
+        if (!proxy(record)) {
+            if (record.getStream() != null || record.getProxyKey() != null)
+                throw new IllegalArgumentException("原生地址不能接管媒体代理");
+            return;
+        }
+        if (record.getStream() == null) {
+            record.setStream(managedStream(record));
+            record.setMediaServerId(manual.selectMediaServer());
+        } else {
+            // 已有流绝不迁移到默认节点,也不另起一个新流。
+            manual.recordedServer(record.getMediaServerId());
+        }
     }
     }
 
 
     @Override public Map<String, Object> start(VideoLifecycleRecord record) {
     @Override public Map<String, Object> start(VideoLifecycleRecord record) {
-        String url = record.getUrl();
-        if (url == null || url.isBlank()) throw new IllegalArgumentException("手动视频地址缺失");
-        URI uri = URI.create(url);
-        if (uri.getHost() != null && PROXY_SCHEMES.contains(String.valueOf(uri.getScheme()).toLowerCase(Locale.ROOT))) {
-            String stream = managedStream(record);
-            Map<String, Object> media = manual.start(record.getVideoId(), url, stream);
-            Object key = media.get("proxyKey");
-            return outcome("ACTIVE", media, stream, key instanceof String ? (String) key : null);
+        if (record.isCancelled()) return cancel(record);
+        if (!proxy(record)) return outcome(record, "ACTIVE", Map.of("native", true, "url", record.getUrl()));
+        if (record.getStream() == null) return outcome(record, "CLEANUP_PENDING", null);
+        if (!record.getStream().equals(managedStream(record)) || record.getProxyKey() != null) return status(record);
+        try {
+            String key = manual.start(record.getMediaServerId(), record.getVideoId(), record.getUrl(), record.getStream());
+            record.setProxyKey(key); // 在后续探测可能失败之前保留实际 add 响应。
+            if (key == null) return outcome(record, "CLEANUP_PENDING", null);
+            return status(record);
+        } catch (RuntimeException unknown) {
+            return outcome(record, "CLEANUP_PENDING", null);
+        }
+    }
+
+    @Override public Map<String, Object> status(VideoLifecycleRecord record) {
+        if (record.isCancelled()) return cancel(record);
+        try {
+            if (!proxy(record)) return outcome(record, "ACTIVE", Map.of("native", true, "url", record.getUrl()));
+            Map<String, Object> media = manual.status(record.getMediaServerId(), record.getStream(), record.getUrl());
+            if (record.getProxyKey() == null || record.getProxyKey().isBlank()) return outcome(record, "CLEANUP_PENDING", null);
+            if (media == null && !record.getStream().equals(managedStream(record)))
+                return outcome(record, "CLEANUP_PENDING", null);
+            if (media != null) media.put("proxyKey", record.getProxyKey());
+            return outcome(record, media == null ? "STARTING" : "ACTIVE", media);
+        } catch (RuntimeException unknown) {
+            return outcome(record, "CLEANUP_PENDING", null);
         }
         }
-        return outcome("ACTIVE", Map.of("native", true, "url", uri.toString()), null, null);
     }
     }
 
 
     @Override public Map<String, Object> cancel(VideoLifecycleRecord record) {
     @Override public Map<String, Object> cancel(VideoLifecycleRecord record) {
         String key = record.getProxyKey();
         String key = record.getProxyKey();
         if (key != null && !key.isBlank()) {
         if (key != null && !key.isBlank()) {
-            manual.stop(key);
-            return outcome("STOPPED", null, record.getStream(), key);
+            boolean stopped = manual.stop(record.getMediaServerId(), key);
+            return outcome(record, stopped && !record.isStartInFlight() ? "STOPPED" : "CLEANUP_PENDING", null);
         }
         }
-        // 没有真实代理句柄:只可能是原生地址或尚未创建代理,均无媒体需要回收。
-        return outcome("STOPPED", null, record.getStream(), null);
+        // 原生地址确实没有外部资源;代理缺 actual key 永远不能假报已回收。
+        boolean nativeOnly = false;
+        try { nativeOnly = !proxy(record) && record.getStream() == null; } catch (RuntimeException unknown) { /* 未知来源 */ }
+        return outcome(record, nativeOnly && !record.isStartInFlight() ? "STOPPED" : "CLEANUP_PENDING", null);
     }
     }
 
 
-    /** 唯一物理流名:低于 64 字符且保持既有 manual_ 前缀,避免与旧停止校验冲突。 */
     static String managedStream(VideoLifecycleRecord record) {
     static String managedStream(VideoLifecycleRecord record) {
-        String id = String.valueOf(record.getVideoId()).replaceAll("[^A-Za-z0-9_-]", "");
-        if (id.isEmpty()) id = "device";
-        if (id.length() > 40) id = id.substring(0, 40);
-        String suffix = String.valueOf(record.getGeneration()).replaceAll("[^A-Za-z0-9]", "");
-        if (suffix.length() > 8) suffix = suffix.substring(0, 8);
-        return "manual_" + id + "_" + suffix;
+        return "manual_" + java.util.UUID.fromString(record.getGeneration()).toString().replace("-", "");
     }
     }
 
 
-    private static Map<String, Object> outcome(String status, Map<String, Object> media, String stream, String proxyKey) {
-        Map<String, Object> result = new LinkedHashMap<>();
+    private static Map<String, Object> outcome(VideoLifecycleRecord record, String status, Map<String, Object> media) {
+        Map<String, Object> result = new java.util.LinkedHashMap<>();
         result.put("status", status);
         result.put("status", status);
+        record.setMedia(media);
         if (media != null) result.put("media", media);
         if (media != null) result.put("media", media);
-        if (stream != null) result.put("stream", stream);
-        if (proxyKey != null) result.put("proxyKey", proxyKey);
+        if (record.getStream() != null) result.put("stream", record.getStream());
+        if (record.getProxyKey() != null) result.put("proxyKey", record.getProxyKey());
+        if (record.getMediaServerId() != null) result.put("mediaServerId", record.getMediaServerId());
         return result;
         return result;
     }
     }
 }
 }

+ 29 - 28
video-service/src/main/java/com/zksy/video/lifecycle/RedisVideoLifecycleStore.java

@@ -1,45 +1,46 @@
 package com.zksy.video.lifecycle;
 package com.zksy.video.lifecycle;
 
 
-import java.time.Duration;
-import java.util.regex.Pattern;
-import org.springframework.data.redis.core.RedisTemplate;
+import com.alibaba.fastjson2.JSON;
+import org.springframework.data.redis.core.StringRedisTemplate;
+import org.springframework.data.redis.core.script.DefaultRedisScript;
 import org.springframework.stereotype.Component;
 import org.springframework.stereotype.Component;
+import java.util.List;
 
 
-/**
- * 用既有 RedisTemplate 保存代次意图。TTL 略长于主服务的观看回收窗口,
- * 让取消墓碑在迟到 start 到达时仍然可见。
- */
+/** Atomic Redis journal. Unconfirmed resources and cancellation tombstones must not expire silently. */
 @Component
 @Component
 public class RedisVideoLifecycleStore implements VideoLifecycleStore {
 public class RedisVideoLifecycleStore implements VideoLifecycleStore {
     private static final String PREFIX = "CITY_VIDEO_LIFECYCLE:";
     private static final String PREFIX = "CITY_VIDEO_LIFECYCLE:";
     private static final String CANCELLED_PREFIX = "CITY_VIDEO_LIFECYCLE_CANCELLED_STREAM:";
     private static final String CANCELLED_PREFIX = "CITY_VIDEO_LIFECYCLE_CANCELLED_STREAM:";
-    private static final Pattern STREAM = Pattern.compile("[A-Za-z0-9_-]{1,200}");
-    private static final Duration TTL = Duration.ofMinutes(30);
-    private static final Pattern GENERATION = Pattern.compile("[A-Za-z0-9_-]{1,64}");
-
-    private final RedisTemplate<Object, Object> redis;
-
-    public RedisVideoLifecycleStore(RedisTemplate<Object, Object> redis) { this.redis = redis; }
+    private static final DefaultRedisScript<Long> CAS = new DefaultRedisScript<>(
+            "local old=redis.call('GET',KEYS[1]); "
+            + "if ARGV[1]=='-1' then if old then return 0 end "
+            + "else if not old then return 0 end; "
+            + "if tonumber(cjson.decode(old).revision or 0)~=tonumber(ARGV[1]) then return 0 end end; "
+            + "redis.call('SET',KEYS[1],ARGV[2]); return 1", Long.class);
+    private final StringRedisTemplate redis;
+    public RedisVideoLifecycleStore(StringRedisTemplate redis) { this.redis = redis; }
 
 
     @Override public VideoLifecycleRecord find(String generation) {
     @Override public VideoLifecycleRecord find(String generation) {
-        if (!valid(generation)) return null;
-        Object value = redis.opsForValue().get(PREFIX + generation);
-        return value instanceof VideoLifecycleRecord ? (VideoLifecycleRecord) value : null;
+        validate(generation);
+        return JSON.parseObject(redis.opsForValue().get(PREFIX + generation), VideoLifecycleRecord.class);
     }
     }
-
-    @Override public void save(VideoLifecycleRecord record) {
-        if (record == null || !valid(record.getGeneration())) throw new IllegalArgumentException("观看代次标识无效");
-        redis.opsForValue().set(PREFIX + record.getGeneration(), record, TTL);
+    @Override public boolean compareAndSet(VideoLifecycleRecord expected, VideoLifecycleRecord update) {
+        validate(update.getGeneration());
+        long revision = expected == null ? -1 : expected.getRevision();
+        if (expected != null && !expected.getGeneration().equals(update.getGeneration()))
+            throw new IllegalArgumentException("观看代次不可改变");
+        update.setRevision(revision + 1);
+        return Long.valueOf(1).equals(redis.execute(CAS, List.of(PREFIX + update.getGeneration()),
+                Long.toString(revision), JSON.toJSONString(update)));
     }
     }
-
-    private static boolean valid(String generation) { return generation != null && GENERATION.matcher(generation).matches(); }
-
     @Override public void markStreamCancelled(String stream) {
     @Override public void markStreamCancelled(String stream) {
-        if (stream != null && STREAM.matcher(stream).matches())
-            redis.opsForValue().set(CANCELLED_PREFIX + stream, Boolean.TRUE, TTL);
+        if (stream != null && stream.matches("[A-Za-z0-9_-]{1,200}"))
+            redis.opsForValue().set(CANCELLED_PREFIX + stream, "true");
     }
     }
-
     @Override public boolean isStreamCancelled(String stream) {
     @Override public boolean isStreamCancelled(String stream) {
-        return stream != null && Boolean.TRUE.equals(redis.opsForValue().get(CANCELLED_PREFIX + stream));
+        return stream != null && "true".equals(redis.opsForValue().get(CANCELLED_PREFIX + stream));
+    }
+    private static void validate(String id) {
+        if (id == null || !id.matches("[A-Za-z0-9_-]{1,64}")) throw new IllegalArgumentException("观看代次标识无效");
     }
     }
 }
 }

+ 38 - 2
video-service/src/main/java/com/zksy/video/lifecycle/VideoLifecycleMedia.java

@@ -1,6 +1,10 @@
 package com.zksy.video.lifecycle;
 package com.zksy.video.lifecycle;
 
 
 import java.util.Map;
 import java.util.Map;
+import com.alibaba.fastjson2.JSONArray;
+import com.alibaba.fastjson2.JSONObject;
+import com.ruoyi.wvp.media.bean.MediaServer;
+import com.ruoyi.wvp.media.zlm.ZLMRESTfulUtils;
 
 
 /**
 /**
  * 媒体侧适配接缝。实现只负责“这一个代次的真实媒体句柄”,
  * 媒体侧适配接缝。实现只负责“这一个代次的真实媒体句柄”,
@@ -10,6 +14,14 @@ public interface VideoLifecycleMedia {
 
 
     boolean supports(String sourceType);
     boolean supports(String sourceType);
 
 
+    /**
+     * 仅校验来源、选择媒体节点并预分配 stream,不创建代理、SIP 或 RTP 资源。
+     * 协调层必须先持久化修改后的 record,再调用 start。
+     */
+    default void prepare(VideoLifecycleRecord record) {
+        if (record.getStream() == null) record.setStream(intendedStream(record));
+    }
+
     /**
     /**
      * 为该代次启动媒体。返回 {@code status} 与(仅 ACTIVE 时的){@code media}、{@code stream}/{@code proxyKey}。
      * 为该代次启动媒体。返回 {@code status} 与(仅 ACTIVE 时的){@code media}、{@code stream}/{@code proxyKey}。
      * 不得在已取消的代次上创建任何媒体资源。
      * 不得在已取消的代次上创建任何媒体资源。
@@ -17,8 +29,8 @@ public interface VideoLifecycleMedia {
     Map<String, Object> start(VideoLifecycleRecord record);
     Map<String, Object> start(VideoLifecycleRecord record);
 
 
     /**
     /**
-     * 本代次将会使用的媒体句柄(不调用媒体即可算出)。
-     * 先落库它,取消才能在“启动结果未知”时仍有精确回收目标。
+     * 本代次的预分配流名;不是媒体代理的真实 proxyKey。
+     * 无法恢复 add 响应的 actual proxyKey 时必须保留 CLEANUP_PENDING。
      */
      */
     default String intendedStream(VideoLifecycleRecord record) { return null; }
     default String intendedStream(VideoLifecycleRecord record) { return null; }
 
 
@@ -28,9 +40,33 @@ public interface VideoLifecycleMedia {
     default Map<String, Object> status(VideoLifecycleRecord record) {
     default Map<String, Object> status(VideoLifecycleRecord record) {
         java.util.Map<String, Object> result = new java.util.LinkedHashMap<>();
         java.util.Map<String, Object> result = new java.util.LinkedHashMap<>();
         result.put("status", record.getStatus());
         result.put("status", record.getStatus());
+        if ("ACTIVE".equals(record.getStatus()) && record.getMedia() != null)
+            result.put("media", record.getMedia());
         return result;
         return result;
     }
     }
 
 
+    /** 原始 ZLM 成功响应才是存在性证据;错误/畸形响应不能折叠成“不存在”。 */
+    static JSONObject findMedia(ZLMRESTfulUtils zlm, MediaServer server, String app, String stream) {
+        if (server == null || !server.isStatus() || !"zlm".equals(server.getType())
+                || stream == null || stream.isBlank()) throw new IllegalStateException("记录的媒体节点或流不可用");
+        JSONObject response = zlm.getMediaList(server, app, stream);
+        if (response == null || !Integer.valueOf(0).equals(response.getInteger("code")))
+            throw new IllegalStateException("媒体存在性查询失败");
+        Object data = response.get("data");
+        if (data == null) return null; // ZLM code=0 的空列表可省略 data。
+        if (!(data instanceof JSONArray)) throw new IllegalStateException("媒体列表格式无效");
+        JSONObject found = null;
+        for (Object item : (JSONArray) data) {
+            if (!(item instanceof JSONObject)) throw new IllegalStateException("媒体条目格式无效");
+            JSONObject row = (JSONObject) item;
+            if (row.getString("app") == null || row.getString("stream") == null || row.getString("vhost") == null)
+                throw new IllegalStateException("媒体条目身份缺失");
+            if (app.equals(row.getString("app")) && stream.equals(row.getString("stream"))
+                    && "__defaultVhost__".equals(row.getString("vhost"))) found = row;
+        }
+        return found;
+    }
+
     /** 用已记录的真实句柄精确回收该代次;无法证明回收完成时返回 CLEANUP_PENDING。 */
     /** 用已记录的真实句柄精确回收该代次;无法证明回收完成时返回 CLEANUP_PENDING。 */
     Map<String, Object> cancel(VideoLifecycleRecord record);
     Map<String, Object> cancel(VideoLifecycleRecord record);
 }
 }

+ 11 - 0
video-service/src/main/java/com/zksy/video/lifecycle/VideoLifecycleRecord.java

@@ -1,6 +1,7 @@
 package com.zksy.video.lifecycle;
 package com.zksy.video.lifecycle;
 
 
 import lombok.Data;
 import lombok.Data;
+import java.util.Map;
 
 
 /**
 /**
  * 单个观看代次的持久意图。cancel 先到会留下 {@link #cancelled} 墓碑,
  * 单个观看代次的持久意图。cancel 先到会留下 {@link #cancelled} 墓碑,
@@ -22,6 +23,16 @@ public class VideoLifecycleRecord {
     /** 本次代次实际使用的媒体 stream;MANUAL 代理另记 proxyKey。 */
     /** 本次代次实际使用的媒体 stream;MANUAL 代理另记 proxyKey。 */
     private String stream;
     private String stream;
     private String proxyKey;
     private String proxyKey;
+    /** 旧 GB 流接管时观察到的精确对话凭据;进程重启后未知 token 不得重新猜测。 */
+    private String adoptedHandle;
+    /** prepare 选择并持久化的节点;查询和回收禁止重新选择默认节点。 */
+    private String mediaServerId;
+    /** 最近一次真实探测确认可播放的媒体描述。 */
+    private Map<String, Object> media;
+    /** 协调层持久化的乐观锁版本。 */
+    private long revision;
+    /** 外部启动请求尚未完成;即使当前流未出现也不能证明已经回收。 */
+    private boolean startInFlight;
     /** 取消意图先落库;置位后任何后续 start 都不得创建媒体。 */
     /** 取消意图先落库;置位后任何后续 start 都不得创建媒体。 */
     private boolean cancelled;
     private boolean cancelled;
     /** 启动截止时间(epoch millis)。 */
     /** 启动截止时间(epoch millis)。 */

+ 156 - 99
video-service/src/main/java/com/zksy/video/lifecycle/VideoLifecycleService.java

@@ -1,138 +1,195 @@
 package com.zksy.video.lifecycle;
 package com.zksy.video.lifecycle;
 
 
-import java.util.LinkedHashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
+import org.springframework.beans.BeanUtils;
+import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.stereotype.Service;
 import org.springframework.stereotype.Service;
+import java.time.Clock;
+import java.util.*;
+import java.util.function.Consumer;
 
 
-/**
- * 观看代次协调:意图先落库,媒体调用在后;cancel 是墓碑,永远优先于迟到的 start。
- * 本类不复制主服务的观看归属/共享计数,只对“这一个代次的真实媒体句柄”负责。
- */
+/** Durable generation intent. Each transition is CAS; no persistence lock spans a media operation. */
 @Service
 @Service
 public class VideoLifecycleService {
 public class VideoLifecycleService {
     private static final Set<String> TERMINAL = Set.of("STOPPED", "FAILED");
     private static final Set<String> TERMINAL = Set.of("STOPPED", "FAILED");
     private static final Set<String> STATES = Set.of("STARTING", "ACTIVE", "CLEANUP_PENDING", "STOPPED", "FAILED");
     private static final Set<String> STATES = Set.of("STARTING", "ACTIVE", "CLEANUP_PENDING", "STOPPED", "FAILED");
-
     private final VideoLifecycleStore store;
     private final VideoLifecycleStore store;
     private final List<VideoLifecycleMedia> adapters;
     private final List<VideoLifecycleMedia> adapters;
+    private final Clock clock;
 
 
-    public VideoLifecycleService(VideoLifecycleStore store, List<VideoLifecycleMedia> adapters) {
-        this.store = store; this.adapters = adapters;
+    @Autowired public VideoLifecycleService(VideoLifecycleStore store, List<VideoLifecycleMedia> adapters) {
+        this(store, adapters, Clock.systemUTC());
+    }
+    public VideoLifecycleService(VideoLifecycleStore store, List<VideoLifecycleMedia> adapters, Clock clock) {
+        this.store = store; this.adapters = adapters; this.clock = clock;
     }
     }
 
 
-    public Map<String, Object> start(Map<String, Object> body) {
-        VideoLifecycleRecord record = parse(body);
-        VideoLifecycleRecord stored = store.find(record.getGeneration());
-        if (stored != null && stored.isCancelled()) return result(stored, "STOPPED", null);
-        VideoLifecycleMedia media;
-        try {
-            media = adapter(record);
-        } catch (IllegalArgumentException unsupported) {
-            return settle(stored != null ? stored : record, "FAILED");
+    public Map<String,Object> start(Map<String,Object> body) {
+        VideoLifecycleRecord request = parse(body), current = store.find(request.getGeneration());
+        if (current != null) {
+            sameSource(current, request);
+            if (current.isCancelled() || TERMINAL.contains(current.getStatus()) || current.isStartInFlight()) return result(current);
+            return status(body); // A repeated start observes, it never issues a second allocation.
         }
         }
-        if (stored == null) {
-            String intended = media.intendedStream(record);
-            if (intended != null && record.getStream() == null) record.setStream(intended);
-            record.setStatus("STARTING");
-            store.save(record);                       // 意图先于任何媒体调用落库
+        VideoLifecycleRecord initial = copy(request);
+        if (expired(request)) {
+            initial.setCancelled(true); initial.setStatus("FAILED");
         } else {
         } else {
-            if (TERMINAL.contains(stored.getStatus())) return result(stored, stored.getStatus(), null);
-            record = stored;
+            VideoLifecycleMedia media = adapter(initial);
+            try {
+                media.prepare(initial); // Validation/node selection cannot allocate resources.
+                initial.setStatus("STARTING"); initial.setStartInFlight(true);
+            } catch (RuntimeException notDispatched) {
+                initial.setCancelled(true);
+                initial.setStatus(request.getStream() == null && request.getProxyKey() == null ? "FAILED" : "CLEANUP_PENDING");
+            }
         }
         }
-        try {
-            return merge(record, media.start(record));
-        } catch (IllegalArgumentException invalid) {
-            return settle(record, "FAILED");          // 校验失败:确认未创建任何媒体
-        } catch (RuntimeException unknown) {
-            return settle(record, "CLEANUP_PENDING"); // 结果未知:既不谎报成功也不谎报已停
+        if (!store.compareAndSet(null, initial)) return start(body);
+        if (TERMINAL.contains(initial.getStatus()) || !initial.isStartInFlight()) return result(initial);
+        // Cancellation may have won after allocation intent was persisted, but before dispatch.
+        current = store.find(initial.getGeneration());
+        if (current.isCancelled() || expired(current)) {
+            return result(transition(request, row -> {
+                row.setStartInFlight(false); row.setCancelled(true);
+                row.setStatus(request.getStream() == null ? "STOPPED" : "CLEANUP_PENDING"); row.setMedia(null);
+            }));
         }
         }
+        Map<String,Object> outcome;
+        try { outcome = adapter(initial).start(initial); }
+        catch (RuntimeException unknown) { outcome = Map.of("status", "CLEANUP_PENDING"); }
+        current = merge(request, initial, outcome, true, false);
+        if (current.isCancelled() && !TERMINAL.contains(current.getStatus())) return cleanup(request, current);
+        return result(current);
     }
     }
 
 
-    public Map<String, Object> status(Map<String, Object> body) {
-        VideoLifecycleRecord record = store.find(parse(body).getGeneration());
-        if (record == null) return result(parse(body), "CLEANUP_PENDING", null);
-        if (TERMINAL.contains(record.getStatus())) return result(record, record.getStatus(), null);
-        try {
-            // 已取消的代次只确认回收,不再启动;未取消的代次只查询。
-            return merge(record, record.isCancelled() ? adapter(record).cancel(record) : adapter(record).status(record));
-        } catch (RuntimeException unknown) {
-            return result(record, "CLEANUP_PENDING", null);
-        }
+    public Map<String,Object> status(Map<String,Object> body) {
+        VideoLifecycleRecord request = parse(body), row = store.find(request.getGeneration());
+        if (row == null) return pending(request);
+        sameSource(row, request);
+        if (TERMINAL.contains(row.getStatus())) return result(row);
+        if (row.isCancelled() || ("STARTING".equals(row.getStatus()) && expired(row))) return cancel(body);
+        if (row.isStartInFlight()) return result(row);
+        Map<String,Object> outcome;
+        try { outcome = adapter(row).status(row); }
+        catch (RuntimeException unknown) { outcome = Map.of("status", "CLEANUP_PENDING"); }
+        return result(merge(request, row, outcome, false, false));
     }
     }
 
 
-    public Map<String, Object> cancel(Map<String, Object> body) {
-        VideoLifecycleRecord request = parse(body);
-        VideoLifecycleRecord record = store.find(request.getGeneration());
-        if (record == null) {
-            // 未知代次:留终止墓碑,并如实等待——没有句柄就无法证明已回收。
-            request.setCancelled(true); request.setStatus("CLEANUP_PENDING"); store.save(request);
-            if (request.getStream() != null) store.markStreamCancelled(request.getStream());
-            return result(request, "CLEANUP_PENDING", null);
-        }
-        if (TERMINAL.contains(record.getStatus())) return result(record, record.getStatus(), null);
-        record.setCancelled(true); record.setStatus("CLEANUP_PENDING");
-        store.save(record);                            // 墓碑先行,之后任何 start 都不得复活
-        if (record.getStream() != null) store.markStreamCancelled(record.getStream());
-        try {
-            return merge(record, adapter(record).cancel(record));
-        } catch (RuntimeException unknown) {
-            return result(record, "CLEANUP_PENDING", null);
+    public Map<String,Object> cancel(Map<String,Object> body) {
+        VideoLifecycleRecord request = parse(body), row = store.find(request.getGeneration());
+        if (row == null) {
+            VideoLifecycleRecord tombstone = copy(request);
+            tombstone.setCancelled(true); tombstone.setStatus("CLEANUP_PENDING");
+            if (!store.compareAndSet(null, tombstone)) return cancel(body);
+            // No dispatch evidence: do not guess a physical handle or claim completion.
+            return result(tombstone);
         }
         }
+        sameSource(row, request);
+        if (TERMINAL.contains(row.getStatus())) return result(row);
+        row = transition(request, value -> {
+            if (!TERMINAL.contains(value.getStatus())) {
+                value.setCancelled(true); value.setStatus("CLEANUP_PENDING"); value.setMedia(null);
+            }
+        });
+        if (row.getStream() != null) store.markStreamCancelled(row.getStream());
+        return cleanup(request, row);
     }
     }
 
 
-    private Map<String, Object> merge(VideoLifecycleRecord record, Map<String, Object> outcome) {
-        String state = text(outcome.get("status"));
-        if (STATE_OK(state)) record.setStatus(state);
-        if (outcome.get("stream") instanceof String) record.setStream((String) outcome.get("stream"));
-        if (outcome.get("proxyKey") instanceof String) record.setProxyKey((String) outcome.get("proxyKey"));
-        if (record.isCancelled() && !TERMINAL.contains(record.getStatus())) record.setStatus("CLEANUP_PENDING");
-        store.save(record);
-        return result(record, record.getStatus(), outcome.get("media"));
+    private Map<String,Object> cleanup(VideoLifecycleRecord request, VideoLifecycleRecord row) {
+        Map<String,Object> outcome;
+        try { outcome = adapter(row).cancel(row); }
+        catch (RuntimeException unknown) { outcome = Map.of("status", "CLEANUP_PENDING"); }
+        return result(merge(request, row, outcome, false, true));
     }
     }
 
 
-    private Map<String, Object> settle(VideoLifecycleRecord record, String state) {
-        record.setStatus(state); store.save(record); return result(record, state, null);
+    /** Merge returned handles, but cancellation and terminal state always beat a stale snapshot. */
+    private VideoLifecycleRecord merge(VideoLifecycleRecord request, VideoLifecycleRecord attempt,
+            Map<String,Object> outcome, boolean completedStart, boolean cleanup) {
+        return transition(request, row -> {
+            if (TERMINAL.contains(row.getStatus())) return;
+            if (completedStart) {
+                row.setStartInFlight(false);
+                if (expired(row)) row.setCancelled(true);
+            }
+            String state = outcome != null && outcome.get("status") != null && STATES.contains(outcome.get("status")) ? (String) outcome.get("status") : "CLEANUP_PENDING";
+            if (row.getMediaServerId() == null) row.setMediaServerId(attempt.getMediaServerId());
+            if (row.getStream() == null) row.setStream(attempt.getStream());
+            if (row.getProxyKey() == null) row.setProxyKey(attempt.getProxyKey());
+            if (row.getAdoptedHandle() == null) row.setAdoptedHandle(attempt.getAdoptedHandle());
+            if (outcome != null) {
+                if (outcome.get("stream") instanceof String) {
+                    String returned = (String) outcome.get("stream");
+                    if (row.getStream() != null && !row.getStream().equals(returned)) state = "CLEANUP_PENDING";
+                    else row.setStream(returned);
+                }
+                if (outcome.get("proxyKey") instanceof String) row.setProxyKey((String) outcome.get("proxyKey"));
+            }
+            if (row.isCancelled()) {
+                row.setStatus(cleanup && !attempt.isStartInFlight() && !row.isStartInFlight() && TERMINAL.contains(state) ? state : "CLEANUP_PENDING");
+                row.setMedia(null);
+            } else if ("CLEANUP_PENDING".equals(state)) {
+                row.setStatus(state); row.setCancelled(true); row.setMedia(null);
+            } else if ("ACTIVE".equals(state)) {
+                if (outcome.get("media") instanceof Map) {
+                    row.setMedia(new LinkedHashMap<>(cast(outcome.get("media")))); row.setStatus(state);
+                } else { row.setStatus("CLEANUP_PENDING"); row.setCancelled(true); row.setMedia(null); }
+            } else {
+                row.setStatus(state); row.setMedia(null);
+            }
+        });
     }
     }
 
 
-    private VideoLifecycleMedia adapter(VideoLifecycleRecord record) {
-        return adapters.stream().filter(item -> item.supports(record.getSourceType())).findFirst()
+    private VideoLifecycleRecord transition(VideoLifecycleRecord request, Consumer<VideoLifecycleRecord> change) {
+        for (int retry = 0; retry < 32; retry++) {
+            VideoLifecycleRecord before = store.find(request.getGeneration());
+            if (before == null) throw new IllegalStateException("观看代次记录丢失,结果未确认");
+            sameSource(before, request);
+            VideoLifecycleRecord after = copy(before); change.accept(after);
+            if (store.compareAndSet(before, after)) return after;
+        }
+        throw new IllegalStateException("观看代次状态变更繁忙,结果未确认");
+    }
+    private boolean expired(VideoLifecycleRecord row) { return row.getDeadline() <= clock.millis(); }
+    private VideoLifecycleMedia adapter(VideoLifecycleRecord row) {
+        return adapters.stream().filter(item -> item.supports(row.getSourceType())).findFirst()
                 .orElseThrow(() -> new IllegalArgumentException("不支持的视频来源类型"));
                 .orElseThrow(() -> new IllegalArgumentException("不支持的视频来源类型"));
     }
     }
-
-    private static boolean STATE_OK(String state) { return state != null && STATES.contains(state); }
-
-    @SuppressWarnings("unchecked")
-    private static VideoLifecycleRecord parse(Map<String, Object> body) {
+    private static void sameSource(VideoLifecycleRecord saved, VideoLifecycleRecord request) {
+        if (!Objects.equals(saved.getSourceType(), request.getSourceType()) || !Objects.equals(saved.getVideoId(), request.getVideoId())
+                || !Objects.equals(saved.getDeviceId(), request.getDeviceId()) || !Objects.equals(saved.getChannelId(), request.getChannelId())
+                || !Objects.equals(saved.getUrl(), request.getUrl()) || !Objects.equals(saved.getDeadline(), request.getDeadline()))
+            throw new IllegalArgumentException("观看代次的来源与截止时间不可改变");
+    }
+    private static VideoLifecycleRecord parse(Map<String,Object> body) {
         if (body == null) throw new IllegalArgumentException("请求体缺失");
         if (body == null) throw new IllegalArgumentException("请求体缺失");
-        VideoLifecycleRecord record = new VideoLifecycleRecord();
-        record.setGeneration(text(body.get("generation")));
-        if (record.getGeneration() == null || !record.getGeneration().matches("[A-Za-z0-9_-]{1,64}"))
-            throw new IllegalArgumentException("观看代次标识无效");
+        VideoLifecycleRecord row = new VideoLifecycleRecord();
+        row.setGeneration(text(body.get("generation")));
+        if (row.getGeneration() == null || !row.getGeneration().matches("[A-Za-z0-9_-]{1,64}")) throw new IllegalArgumentException("观看代次标识无效");
         if (!(body.get("source") instanceof Map)) throw new IllegalArgumentException("视频来源缺失");
         if (!(body.get("source") instanceof Map)) throw new IllegalArgumentException("视频来源缺失");
-        Map<String, Object> source = (Map<String, Object>) body.get("source");
-        record.setSourceType(text(source.get("type")));
-        record.setVideoId(text(source.get("videoId")));
-        record.setDeviceId(text(source.get("deviceId")));
-        record.setChannelId(text(source.get("channelId")));
-        record.setUrl(text(source.get("url")));
-        if (body.get("startDeadline") instanceof Number) record.setDeadline(((Number) body.get("startDeadline")).longValue());
+        Map<String,Object> source = cast(body.get("source"));
+        row.setSourceType(text(source.get("type"))); row.setVideoId(text(source.get("videoId")));
+        row.setDeviceId(text(source.get("deviceId"))); row.setChannelId(text(source.get("channelId"))); row.setUrl(text(source.get("url")));
+        if (row.getVideoId() == null || row.getSourceType() == null || !Set.of("GB28181", "MANUAL").contains(row.getSourceType())) throw new IllegalArgumentException("视频来源无效");
+        if (!(body.get("startDeadline") instanceof Number)) throw new IllegalArgumentException("启动截止时间缺失");
+        row.setDeadline(((Number) body.get("startDeadline")).longValue());
+        if (row.getDeadline() <= 0) throw new IllegalArgumentException("启动截止时间无效");
         if (body.get("existingMedia") instanceof Map) {
         if (body.get("existingMedia") instanceof Map) {
-            Map<String, Object> existing = (Map<String, Object>) body.get("existingMedia");
-            record.setStream(text(existing.get("stream")));
-            record.setProxyKey(text(existing.get("proxyKey")));
+            Map<String,Object> existing = cast(body.get("existingMedia"));
+            row.setStream(text(existing.get("stream"))); row.setProxyKey(text(existing.get("proxyKey")));
+            row.setMediaServerId(text(existing.get("mediaServerId")));
         }
         }
-        return record;
+        return row;
     }
     }
-
+    private static VideoLifecycleRecord copy(VideoLifecycleRecord row) {
+        VideoLifecycleRecord copy = new VideoLifecycleRecord(); BeanUtils.copyProperties(row, copy); return copy;
+    }
+    @SuppressWarnings("unchecked") private static Map<String,Object> cast(Object value) { return (Map<String,Object>) value; }
     private static String text(Object value) { return value instanceof String && !((String) value).isBlank() ? (String) value : null; }
     private static String text(Object value) { return value instanceof String && !((String) value).isBlank() ? (String) value : null; }
-
-    private static Map<String, Object> result(VideoLifecycleRecord record, String status, Object media) {
-        Map<String, Object> result = new LinkedHashMap<>();
-        result.put("generation", record.getGeneration());
-        result.put("status", status);
-        if (media != null) result.put("media", media);
+    private static Map<String,Object> pending(VideoLifecycleRecord row) {
+        return Map.of("generation", row.getGeneration(), "status", "CLEANUP_PENDING");
+    }
+    private static Map<String,Object> result(VideoLifecycleRecord row) {
+        Map<String,Object> result = new LinkedHashMap<>(); result.put("generation", row.getGeneration()); result.put("status", row.getStatus());
+        if (!row.isCancelled() && "ACTIVE".equals(row.getStatus()) && row.getMedia() != null) result.put("media", row.getMedia());
         return result;
         return result;
     }
     }
 }
 }

+ 3 - 7
video-service/src/main/java/com/zksy/video/lifecycle/VideoLifecycleStore.java

@@ -1,14 +1,10 @@
 package com.zksy.video.lifecycle;
 package com.zksy.video.lifecycle;
 
 
-/** 代次意图的持久存储:取消墓碑必须先于任何媒体调用落库。 */
+/** Persistence seam: mutations compare independent snapshots, never blindly overwrite cancellation. */
 public interface VideoLifecycleStore {
 public interface VideoLifecycleStore {
-
     VideoLifecycleRecord find(String generation);
     VideoLifecycleRecord find(String generation);
-
-    void save(VideoLifecycleRecord record);
-
-    /** 记下被取消的 stream,供 ZLM 钩子拦住“流未找到就自动点播”的复活路径。 */
+    /** expected == null means insert-only; otherwise require the observed revision. */
+    boolean compareAndSet(VideoLifecycleRecord expected, VideoLifecycleRecord update);
     void markStreamCancelled(String stream);
     void markStreamCancelled(String stream);
-
     boolean isStreamCancelled(String stream);
     boolean isStreamCancelled(String stream);
 }
 }

+ 202 - 0
video-service/src/test/java/com/zksy/video/lifecycle/AdoptedGbDeepSeamTest.java

@@ -0,0 +1,202 @@
+package com.zksy.video.lifecycle;
+
+import com.alibaba.fastjson2.JSONObject;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.ruoyi.wvp.common.*;
+import com.ruoyi.wvp.common.InviteInfo;
+import com.ruoyi.wvp.gb28181.SipLayer;
+import com.ruoyi.wvp.gb28181.bean.*;
+import com.ruoyi.wvp.gb28181.event.SipSubscribe;
+import com.ruoyi.wvp.gb28181.service.*;
+import com.ruoyi.wvp.gb28181.transmit.SIPSender;
+import com.ruoyi.wvp.gb28181.transmit.cmd.SIPRequestHeaderProvider;
+import com.ruoyi.wvp.gb28181.transmit.cmd.impl.SIPCommander;
+import com.ruoyi.wvp.media.zlm.ZLMRESTfulUtils;
+import com.ruoyi.wvp.service.bean.*;
+import org.junit.jupiter.api.Test;
+import javax.sip.SipException;
+import javax.sip.message.Request;
+import java.util.*;
+import static org.junit.jupiter.api.Assertions.*;
+import static org.mockito.Mockito.*;
+
+/** Real adapter -> Play -> RTP/Hook/Invite/Session/Commander; only external I/O is replaced. */
+class AdoptedGbDeepSeamTest {
+    private static final String STREAM = "device_channel";
+
+    @Test void lastStopRequiresExactBye2xxAndPositiveRtpCloseThenConverges() throws Exception {
+        Fixture f = new Fixture(); f.legacy("call-first", true);
+        VideoLifecycleRecord record = f.record();
+        f.adapter.prepare(record);
+        assertEquals("ACTIVE", f.adapter.start(record).get("status"));
+        assertNotNull(record.getAdoptedHandle());
+        record.setCancelled(true);
+        assertEquals("CLEANUP_PENDING", f.adapter.cancel(record).get("status"));
+        assertNotNull(f.sessions.getSsrcTransactionByStream("rtp", STREAM));
+        assertFalse(f.open.contains(STREAM)); assertTrue(f.hooks.getAll().isEmpty());
+        f.ack(0, "wrong-call", 200);
+        assertEquals("CLEANUP_PENDING", f.adapter.cancel(record).get("status"));
+        f.ack(0, "call-first", 200);
+        assertNull(f.sessions.getSsrcTransactionByStream("rtp", STREAM));
+        assertEquals("STOPPED", f.adapter.cancel(record).get("status"));
+        assertNull(f.invites.getInviteInfoByStream(InviteSessionType.PLAY, STREAM));
+        verify(f.media, never()).getDefaultMediaServer();
+    }
+
+    @Test void sameNameNewDialogAndAllocationCannotReuseOldCloseReceipt() throws Exception {
+        Fixture f = new Fixture(); f.legacy("call-first", true);
+        VideoLifecycleRecord old = f.record(); assertEquals("ACTIVE", f.adapter.start(old).get("status"));
+        assertEquals("CLEANUP_PENDING", f.adapter.cancel(old).get("status"));
+        f.ack(0, "call-first", 200);
+        assertEquals("STOPPED", f.adapter.cancel(old).get("status"));
+        f.legacy("call-second", true);
+        assertEquals("CLEANUP_PENDING", f.adapter.cancel(old).get("status"));
+        assertTrue(f.open.contains(STREAM));
+        assertEquals("call-second", f.sessions.getSsrcTransactionByStream("rtp", STREAM).getCallId());
+        VideoLifecycleRecord next = f.record(); next.setGeneration("22222222-2222-2222-2222-222222222222");
+        assertEquals("ACTIVE", f.adapter.start(next).get("status"));
+        assertNotEquals(old.getAdoptedHandle(), next.getAdoptedHandle());
+        f.closeAcknowledged = false;
+        assertEquals("CLEANUP_PENDING", f.adapter.cancel(next).get("status"));
+        f.ack(0, "call-first", 200); // a late duplicate cannot terminate the new dialog
+        assertNotNull(f.sessions.getSsrcTransactionByStream("rtp", STREAM));
+        f.ack(1, "call-second", 200);
+        assertEquals("CLEANUP_PENDING", f.adapter.cancel(next).get("status"));
+        assertTrue(f.open.contains(STREAM));
+        f.closeAcknowledged = true;
+        assertEquals("STOPPED", f.adapter.cancel(next).get("status"));
+    }
+
+    @Test void transportFailureRetainsAdoptedDialogAndOnlyClosesExactRtp() throws Exception {
+        Fixture f = new Fixture(); f.legacy("call-first", false);
+        VideoLifecycleRecord record = f.record(); assertEquals("ACTIVE", f.adapter.start(record).get("status"));
+        doThrow(new SipException("offline")).when(f.sender).transmitRequest(any(), any(), any(), any());
+        assertEquals("CLEANUP_PENDING", f.adapter.cancel(record).get("status"));
+        assertNotNull(f.sessions.getSsrcTransactionByStream("rtp", STREAM));
+        assertNotNull(f.invites.getInviteInfoByStream(InviteSessionType.PLAY, STREAM));
+        assertTrue(f.hooks.getAll().isEmpty()); assertFalse(f.open.contains(STREAM));
+    }
+
+    @Test void missingOrMismatchedDialogNeverGrantsAdoptionOrBlindStops() throws Exception {
+        Fixture f = new Fixture(); SSRCInfo info = f.legacy("call-first", false);
+        f.sessions.removeByStream("rtp", STREAM);
+        VideoLifecycleRecord record = f.record();
+        assertEquals("CLEANUP_PENDING", f.adapter.start(record).get("status"));
+        assertEquals("CLEANUP_PENDING", f.adapter.cancel(record).get("status"));
+        assertTrue(f.open.contains(STREAM)); assertTrue(f.acks.isEmpty());
+        SsrcTransaction tx = f.dialog(STREAM); tx.setSsrc(info.getSsrc()); tx.setMediaServerId("node-b"); f.sessions.put(tx);
+        assertEquals("CLEANUP_PENDING", f.adapter.start(record).get("status"));
+        assertTrue(f.open.contains(STREAM));
+    }
+
+    @Test void replacementBeforeLateByeAckSurvivesAndOldRecordNeverAdoptsAgain() throws Exception {
+        Fixture f = new Fixture(); SSRCInfo first = f.legacy("call-first", true);
+        VideoLifecycleRecord old = f.record(); assertEquals("ACTIVE", f.adapter.start(old).get("status"));
+        assertEquals("CLEANUP_PENDING", f.adapter.cancel(old).get("status"));
+        f.legacy("call-second", false);
+        f.ack(0, "call-first", 200);
+        assertEquals("CLEANUP_PENDING", f.adapter.cancel(old).get("status"));
+        assertEquals("CLEANUP_PENDING", f.adapter.status(old).get("status"));
+        assertTrue(f.open.contains(STREAM)); assertEquals(1, f.hooks.getAll().size());
+        assertEquals("call-second", f.sessions.getSsrcTransactionByStream("rtp", STREAM).getCallId());
+        assertFalse(f.rtp.closeAdoptedRTPServer(f.node, first, "call-first"));
+        assertTrue(f.open.contains(STREAM));
+    }
+
+    @Test void changedNodeSsrcOrSipTagsCannotUseAnObservedHandle() throws Exception {
+        Fixture f = new Fixture(); f.legacy("call-first", true);
+        VideoLifecycleRecord record = f.record(); assertEquals("ACTIVE", f.adapter.start(record).get("status"));
+        SsrcTransaction current = f.sessions.getSsrcTransactionByStream("rtp", STREAM);
+        current.getSipTransactionInfo().setToTag("different-dialog"); f.sessions.put(current);
+        assertEquals("CLEANUP_PENDING", f.adapter.cancel(record).get("status"));
+        current.getSipTransactionInfo().setToTag("to"); current.setSsrc("9999999999"); f.sessions.put(current);
+        assertEquals("CLEANUP_PENDING", f.adapter.cancel(record).get("status"));
+        assertTrue(f.open.contains(STREAM)); assertTrue(f.acks.isEmpty());
+        record.setAdoptedHandle("unknown-after-process-restart");
+        assertEquals("CLEANUP_PENDING", f.adapter.cancel(record).get("status"));
+        assertTrue(f.open.contains(STREAM));
+    }
+
+    @Test void pendingRtpResponseCannotQueueAnotherNameCloseOrAllowReallocation() throws Exception {
+        Fixture f = new Fixture(); f.legacy("call-first", true);
+        VideoLifecycleRecord record = f.record(); assertEquals("ACTIVE", f.adapter.start(record).get("status"));
+        f.delayClose = true;
+        assertEquals("CLEANUP_PENDING", f.adapter.cancel(record).get("status"));
+        f.ack(0, "call-first", 200);
+        assertEquals("CLEANUP_PENDING", f.adapter.cancel(record).get("status"));
+        assertEquals(1, f.pendingCloses.size());
+        RTPServerParam next = new RTPServerParam(); next.setMediaServerItem(f.node); next.setStreamId(STREAM);
+        assertNull(f.rtp.openRTPServer(next, (code, msg, result) -> { }));
+        f.pendingCloses.get(0).run();
+        assertEquals("STOPPED", f.adapter.cancel(record).get("status"));
+        assertEquals(1, f.pendingCloses.size());
+    }
+
+    private static class Fixture extends ManagedGbDeepSeamTest.Fixture {
+        final SIPSender sender = mock(SIPSender.class);
+        final List<SipSubscribe.Event> acks = new ArrayList<>();
+        final List<Runnable> pendingCloses = new ArrayList<>();
+        boolean delayClose;
+        final Gb28181LifecycleMedia adapter;
+        Fixture() throws Exception {
+            node.setType("zlm"); node.setStatus(true);
+            SIPCommander commander = new SIPCommander();
+            SIPRequestHeaderProvider headers = mock(SIPRequestHeaderProvider.class);
+            SipLayer layer = mock(SipLayer.class);
+            wire(commander, "sessionManager", sessions); wire(commander, "sipSender", sender);
+            wire(commander, "headerProvider", headers); wire(commander, "sipLayer", layer);
+            wire(play, "cmder", commander);
+            when(headers.createByteRequest(any(), anyString(), any())).thenReturn(mock(Request.class));
+            when(layer.getLocalIp(any())).thenReturn("127.0.0.1");
+            doAnswer(i -> { acks.add(i.getArgument(3)); return null; }).when(sender).transmitRequest(any(), any(), any(), any());
+            IDeviceService devices = mock(IDeviceService.class);
+            IDeviceChannelService channels = mock(IDeviceChannelService.class);
+            when(devices.getDeviceByDeviceId("device")).thenReturn(device);
+            when(channels.getOne("device", "channel")).thenReturn(channel);
+            ZLMRESTfulUtils zlm = mock(ZLMRESTfulUtils.class);
+            com.ruoyi.wvp.media.zlm.ZLMServerFactory factory = new com.ruoyi.wvp.media.zlm.ZLMServerFactory();
+            wire(factory, "zlmresTfulUtils", zlm);
+            // Exercise the real code=0/hit=1 -> boolean mapping rather than fabricating stop=true.
+            doAnswer(i -> {
+                Map<String, Object> params = i.getArgument(1);
+                String stream = (String) params.get("stream_id");
+                ZLMRESTfulUtils.RequestCallback callback = i.getArgument(2);
+                Runnable response = () -> {
+                    boolean hit = closeAcknowledged && open.remove(stream);
+                    callback.run(JSONObject.parseObject(hit
+                            ? "{\"code\":0,\"hit\":1}" : "{\"code\":0,\"hit\":0}"));
+                };
+                if (delayClose) pendingCloses.add(response); else response.run();
+                return null;
+            }).when(zlm).closeRtpServer(eq(node), anyMap(), any());
+            doAnswer(i -> { factory.closeRtpServer(i.getArgument(0), i.getArgument(1), i.getArgument(2)); return null; })
+                    .when(media).closeRTPServer(any(), anyString(), any());
+            when(zlm.getMediaList(node, "rtp", STREAM)).thenAnswer(i -> JSONObject.parseObject(open.contains(STREAM)
+                    ? "{\"code\":0,\"data\":[{\"app\":\"rtp\",\"stream\":\"device_channel\",\"vhost\":\"__defaultVhost__\",\"originType\":3}]}"
+                    : "{\"code\":0,\"data\":[]}"));
+            adapter = new Gb28181LifecycleMedia(devices, channels, play, media, zlm, new ObjectMapper());
+        }
+        SSRCInfo legacy(String callId, boolean arrival) {
+            RTPServerParam param = new RTPServerParam(); param.setMediaServerItem(node); param.setStreamId(STREAM);
+            param.setPort(0); param.setTcpMode(0);
+            SSRCInfo info = rtp.openRTPServer(param, (code, msg, result) -> { }); assertNotNull(info);
+            InviteInfo invite = InviteInfo.getInviteInfo("device", 7, STREAM, info, "node-a", "127.0.0.1", 30000,
+                    "UDP", InviteSessionType.PLAY, InviteSessionStatus.ready, false);
+            invites.updateInviteInfo(invite);
+            SsrcTransaction tx = dialog(STREAM); tx.setCallId(callId); tx.setSsrc(info.getSsrc()); tx.setType(InviteSessionType.PLAY);
+            tx.getSipTransactionInfo().setCallId(callId); tx.getSipTransactionInfo().setFromTag("from"); tx.getSipTransactionInfo().setToTag("to");
+            sessions.put(tx);
+            if (arrival) hooks.onApplicationEvent(arrival(STREAM, node));
+            return info;
+        }
+        VideoLifecycleRecord record() {
+            VideoLifecycleRecord record = new VideoLifecycleRecord(); record.setGeneration("11111111-1111-1111-1111-111111111111");
+            record.setSourceType("GB28181"); record.setVideoId("cam"); record.setDeviceId("device"); record.setChannelId("channel");
+            record.setStream(STREAM); record.setMediaServerId("node-a"); return record;
+        }
+        void ack(int index, String callId, int code) {
+            SipSubscribe.EventResult<?> event = new SipSubscribe.EventResult<>(); event.callId = callId; event.statusCode = code;
+            acks.get(index).response(event);
+        }
+    }
+}

+ 178 - 0
video-service/src/test/java/com/zksy/video/lifecycle/Gb28181LifecycleMediaTest.java

@@ -0,0 +1,178 @@
+package com.zksy.video.lifecycle;
+
+import com.alibaba.fastjson2.JSONObject;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.ruoyi.wvp.common.StreamInfo;
+import com.ruoyi.wvp.gb28181.bean.Device;
+import com.ruoyi.wvp.gb28181.bean.DeviceChannel;
+import com.ruoyi.wvp.gb28181.service.IDeviceService;
+import com.ruoyi.wvp.gb28181.service.IDeviceChannelService;
+import com.ruoyi.wvp.gb28181.service.IPlayService;
+import com.ruoyi.wvp.media.bean.MediaServer;
+import com.ruoyi.wvp.media.service.IMediaServerService;
+import com.ruoyi.wvp.media.zlm.ZLMRESTfulUtils;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.NullSource;
+import org.junit.jupiter.params.provider.ValueSource;
+import com.ruoyi.wvp.service.bean.SSRCInfo;
+import java.util.Map;
+import static org.junit.jupiter.api.Assertions.*;
+import static org.mockito.Mockito.*;
+
+/** Real lifecycle adapter; only device registry, SIP/RTP and ZLM I/O boundaries are substituted. */
+class Gb28181LifecycleMediaTest {
+    private final IDeviceService devices = mock(IDeviceService.class);
+    private final IDeviceChannelService channels = mock(IDeviceChannelService.class);
+    private final IPlayService play = mock(IPlayService.class);
+    private final IMediaServerService servers = mock(IMediaServerService.class);
+    private final ZLMRESTfulUtils zlm = mock(ZLMRESTfulUtils.class);
+    private final Gb28181LifecycleMedia adapter = new Gb28181LifecycleMedia(devices, channels, play, servers, zlm, new ObjectMapper());
+    private final Device device = new Device();
+    private final DeviceChannel channel = new DeviceChannel();
+
+    private VideoLifecycleRecord record() {
+        VideoLifecycleRecord record = new VideoLifecycleRecord();
+        record.setGeneration("b43b54f9-9d20-4440-b26c-97cbe7264901");
+        record.setSourceType("GB28181"); record.setVideoId("cam-1");
+        record.setDeviceId("device-1"); record.setChannelId("channel-1");
+        record.setStream("managed_b43b54f99d204440b26c97cbe7264901"); record.setMediaServerId("node-a");
+        record.setStatus("STARTING");
+        when(devices.getDeviceByDeviceId("device-1")).thenReturn(device);
+        when(channels.getOne("device-1", "channel-1")).thenReturn(channel);
+        return record;
+    }
+
+    private MediaServer onlineNode() {
+        MediaServer node = new MediaServer(); node.setId("node-a"); node.setType("zlm"); node.setStatus(true);
+        when(servers.getOne("node-a")).thenReturn(node);
+        return node;
+    }
+
+    @Test void prepareAllocatesGenerationSpecificStreamAndNodeWithoutStartingMedia() {
+        VideoLifecycleRecord first = record(); first.setStream(null); first.setMediaServerId(null);
+        VideoLifecycleRecord second = record(); second.setStream(null); second.setMediaServerId(null);
+        second.setGeneration("b43b54f9-9d20-4440-b26c-97cbe7264902");
+        MediaServer node = onlineNode(); when(play.getNewMediaServerItem(device)).thenReturn(node);
+        adapter.prepare(first); adapter.prepare(second);
+        assertEquals("managed_b43b54f99d204440b26c97cbe7264901", first.getStream());
+        assertNotEquals(first.getStream(), second.getStream());
+        assertEquals("node-a", first.getMediaServerId());
+        verifyNoInteractions(zlm);
+    }
+
+    @Test void mediaQueryFailureIsUnknownNotAnAbsentStream() {
+        VideoLifecycleRecord record = record(); MediaServer node = onlineNode();
+        when(zlm.getMediaList(node, "rtp", record.getStream())).thenReturn(JSONObject.parseObject("{\"code\":-1}"));
+        assertEquals("CLEANUP_PENDING", adapter.status(record).get("status"));
+        verify(servers, never()).getDefaultMediaServer();
+    }
+
+    @Test void managedStartUsesPreparedNodeAndExactGenerationStream() {
+        VideoLifecycleRecord record = record(); MediaServer node = onlineNode();
+        absent(node, record);
+        when(play.playManaged(eq(node), eq("device-1"), eq("channel-1"), eq(record.getStream()), any()))
+                .thenReturn(new SSRCInfo(30000, "1234567890", "rtp", record.getStream(), "timeout"));
+        Map<String, Object> result = adapter.start(record);
+        assertEquals("STARTING", result.get("status"));
+        assertEquals(record.getStream(), result.get("stream"));
+        assertEquals("node-a", result.get("mediaServerId"));
+        verify(play).playManaged(eq(node), eq("device-1"), eq("channel-1"), eq(record.getStream()), any());
+        verify(play, never()).getNewMediaServerItem(any());
+        verify(play, never()).play(any(), anyString(), anyString(), any(), any());
+        verify(servers, never()).getDefaultMediaServer();
+    }
+
+    @Test void mismatchedReturnedManagedHandleIsNotAValidStart() {
+        VideoLifecycleRecord record = record(); MediaServer node = onlineNode(); absent(node, record);
+        when(play.playManaged(eq(node), anyString(), anyString(), eq(record.getStream()), any()))
+                .thenReturn(new SSRCInfo(30000, "1234567890", "rtp", "wrong-stream", "timeout"));
+        assertEquals("CLEANUP_PENDING", adapter.start(record).get("status"));
+        assertEquals("managed_b43b54f99d204440b26c97cbe7264901", record.getStream());
+    }
+
+    @Test void adoptionUsesOnlyMatchingLiveOldStreamAndNeverInvitesNewStream() {
+        VideoLifecycleRecord record = record(); record.setStream("device-1_channel-1"); MediaServer node = onlineNode();
+        live(node, record, 3);
+        when(play.adoptStream(node, device, channel, record.getStream(), null)).thenReturn("observed-dialog-token");
+        adapter.prepare(record);
+        Map<String, Object> result = adapter.start(record);
+        assertEquals("ACTIVE", result.get("status"));
+        Map<?, ?> media = (Map<?, ?>) result.get("media");
+        assertEquals("device-1_channel-1", media.get("stream")); assertEquals("node-a", media.get("mediaServerId"));
+        assertEquals("observed-dialog-token", record.getAdoptedHandle());
+        verify(play).adoptStream(node, device, channel, record.getStream(), null);
+        verifyNoMoreInteractions(play);
+    }
+
+    @Test void absentOldStreamAndWrongActualOriginNeverStartReplacement() {
+        VideoLifecycleRecord record = record(); record.setStream("device-1_channel-1"); MediaServer node = onlineNode();
+        absent(node, record);
+        assertEquals("CLEANUP_PENDING", adapter.start(record).get("status"));
+        live(node, record, 4);
+        assertEquals("CLEANUP_PENDING", adapter.start(record).get("status"));
+        verifyNoInteractions(play);
+    }
+
+    @Test void booleanStopProofAndNoLateStartAreBothRequired() {
+        VideoLifecycleRecord record = record(); MediaServer node = onlineNode(); absent(node, record);
+        when(play.stopManaged(node, device, channel, record.getStream())).thenReturn(false, true, true);
+        assertEquals("CLEANUP_PENDING", adapter.cancel(record).get("status"));
+        record.setStartInFlight(true);
+        assertEquals("CLEANUP_PENDING", adapter.cancel(record).get("status"));
+        record.setStartInFlight(false);
+        assertEquals("STOPPED", adapter.cancel(record).get("status"));
+        verify(play, times(3)).stopManaged(node, device, channel, record.getStream());
+        verify(servers, never()).getDefaultMediaServer();
+    }
+
+    @ParameterizedTest @NullSource
+    @ValueSource(strings = {"{}", "{\"code\":-1}", "{\"code\":0,\"data\":{}}", "{\"code\":0,\"data\":[{}]}"})
+    void rawErrorsNeverBecomeStoppedEvenAfterAcceptedStop(String response) {
+        VideoLifecycleRecord record = record(); MediaServer node = onlineNode();
+        when(play.stopManaged(node, device, channel, record.getStream())).thenReturn(true);
+        when(zlm.getMediaList(node, "rtp", record.getStream())).thenReturn(JSONObject.parseObject(response));
+        assertEquals("CLEANUP_PENDING", adapter.cancel(record).get("status"));
+        assertEquals("CLEANUP_PENDING", adapter.status(record).get("status"));
+    }
+
+    @Test void liveMediaAfterStopStillNeedsCleanup() {
+        VideoLifecycleRecord record = record(); MediaServer node = onlineNode(); live(node, record, 3);
+        when(play.stopManaged(node, device, channel, record.getStream())).thenReturn(true);
+        assertEquals("CLEANUP_PENDING", adapter.cancel(record).get("status"));
+    }
+
+    @Test void cancelledStartNeverInvitesAndMissingDeviceCannotConfirmCleanup() {
+        VideoLifecycleRecord record = record(); record.setCancelled(true); MediaServer node = onlineNode();
+        when(devices.getDeviceByDeviceId("device-1")).thenReturn(null);
+        assertEquals("CLEANUP_PENDING", adapter.start(record).get("status"));
+        verifyNoInteractions(play, zlm);
+    }
+
+    @Test void actualEmptyStatusDoesNotBuildPlaybackUrls() {
+        VideoLifecycleRecord record = record(); MediaServer node = onlineNode(); absent(node, record);
+        assertEquals("STARTING", adapter.status(record).get("status"));
+        verify(servers, never()).getStreamInfoByAppAndStream(any(), anyString(), anyString(), any(), any());
+    }
+
+    private void absent(MediaServer node, VideoLifecycleRecord record) {
+        when(zlm.getMediaList(node, "rtp", record.getStream())).thenReturn(JSONObject.parseObject("{\"code\":0,\"data\":[]}"));
+    }
+
+    private void live(MediaServer node, VideoLifecycleRecord record, int originType) {
+        JSONObject row = new JSONObject(); row.put("app", "rtp"); row.put("stream", record.getStream());
+        row.put("vhost", "__defaultVhost__"); row.put("originType", originType);
+        JSONObject response = new JSONObject(); response.put("code", 0);
+        response.put("data", new com.alibaba.fastjson2.JSONArray(java.util.List.of(row)));
+        when(zlm.getMediaList(node, "rtp", record.getStream())).thenReturn(response);
+        StreamInfo info = new StreamInfo(); info.setApp("rtp"); info.setStream(record.getStream()); info.setMediaServer(node);
+        when(servers.getStreamInfoByAppAndStream(eq(node), eq("rtp"), eq(record.getStream()), any(), isNull())).thenReturn(info);
+    }
+
+    @Test void missingRecordedNodeCannotConfirmStopped() {
+        VideoLifecycleRecord record = record();
+        assertEquals("CLEANUP_PENDING", adapter.cancel(record).get("status"));
+        verify(servers, never()).getDefaultMediaServer();
+        verifyNoInteractions(play, zlm);
+    }
+}

+ 306 - 0
video-service/src/test/java/com/zksy/video/lifecycle/ManagedGbDeepSeamTest.java

@@ -0,0 +1,306 @@
+package com.zksy.video.lifecycle;
+
+import com.ruoyi.wvp.common.*;
+import com.ruoyi.wvp.common.InviteInfo;
+import com.ruoyi.wvp.conf.DynamicTask;
+import com.ruoyi.wvp.conf.UserSetting;
+import com.ruoyi.wvp.gb28181.bean.*;
+import com.ruoyi.wvp.gb28181.event.SipSubscribe;
+import com.ruoyi.wvp.gb28181.service.IDeviceChannelService;
+import com.ruoyi.wvp.gb28181.service.impl.InviteStreamServiceImpl;
+import com.ruoyi.wvp.gb28181.service.impl.PlayServiceImpl;
+import com.ruoyi.wvp.gb28181.session.SSRCFactory;
+import com.ruoyi.wvp.gb28181.session.SipInviteSessionManager;
+import com.ruoyi.wvp.gb28181.transmit.cmd.ISIPCommander;
+import com.ruoyi.wvp.media.bean.MediaInfo;
+import com.ruoyi.wvp.media.bean.MediaServer;
+import com.ruoyi.wvp.media.event.hook.HookSubscribe;
+import com.ruoyi.wvp.media.event.media.MediaArrivalEvent;
+import com.ruoyi.wvp.media.service.IMediaServerService;
+import com.ruoyi.wvp.service.bean.*;
+import com.ruoyi.wvp.service.impl.RtpServerServiceImpl;
+import com.ruoyi.wvp.storager.IRedisCatchStorage;
+import org.junit.jupiter.api.Test;
+import org.springframework.data.redis.core.*;
+import org.springframework.test.util.ReflectionTestUtils;
+import javax.sip.SipException;
+import java.util.*;
+import java.util.concurrent.atomic.AtomicInteger;
+import static org.junit.jupiter.api.Assertions.*;
+import static org.mockito.ArgumentMatchers.*;
+import static org.mockito.Mockito.*;
+
+/** Real Play + RTP + Hook + Invite + SIP session registry; substitutes only I/O and the clock. */
+class ManagedGbDeepSeamTest {
+    private static final String OLD = "managed_11111111111111111111111111111111";
+    private static final String NEXT = "managed_22222222222222222222222222222222";
+
+    @Test void readyWithoutDialogClosesLocalResourcesButRemainsPending() throws Exception {
+        Fixture f = new Fixture();
+        SSRCInfo info = f.start(OLD);
+        assertNotNull(info);
+        assertFalse(f.play.stopManaged(f.node, f.device, f.channel, OLD));
+        assertNotNull(f.invites.getInviteInfoByStream(InviteSessionType.PLAY, OLD));
+        assertTrue(f.hooks.getAll().isEmpty());
+        assertFalse(f.open.contains(OLD));
+        assertTrue(f.cancelled.contains(OLD));
+        assertNull(f.sessions.getSsrcTransactionByStream("rtp", OLD));
+    }
+
+    @Test void byeFailureFinallyClosesOnlyOldRtpAndRetainsDialogForRetry() throws Exception {
+        Fixture f = new Fixture(); f.start(OLD); SsrcTransaction dialog = f.dialog(OLD);
+        doThrow(new SipException("transport down")).when(f.sip).streamByeCmd(any(), anyString(), eq("rtp"), eq(OLD), any(), any());
+        assertFalse(f.play.stopManaged(f.node, f.device, f.channel, OLD));
+        assertSame(dialog, f.sessions.getSsrcTransactionByStream("rtp", OLD));
+        assertNotNull(f.invites.getInviteInfoByStream(InviteSessionType.PLAY, OLD));
+        assertTrue(f.hooks.getAll().isEmpty()); assertFalse(f.open.contains(OLD));
+    }
+
+    @Test void successfulSendWithoutByeResponseIsNotStoppedAndAckAllowsRetryToFinish() throws Exception {
+        Fixture f = new Fixture(); f.start(OLD); f.dialog(OLD);
+        assertFalse(f.play.stopManaged(f.node, f.device, f.channel, OLD));
+        SipSubscribe.EventResult<?> response = new SipSubscribe.EventResult<>(); response.statusCode = 200;
+        f.byeOk.get(OLD).response(response);
+        assertTrue(f.play.stopManaged(f.node, f.device, f.channel, OLD));
+        assertNull(f.invites.getInviteInfoByStream(InviteSessionType.PLAY, OLD));
+        assertNull(f.sessions.getSsrcTransactionByStream("rtp", OLD));
+    }
+
+    @Test void wrongNodeArrivalDoesNotPublishThenCorrectNodeDoes() throws Exception {
+        Fixture f = new Fixture(); f.start(OLD);
+        MediaServer wrong = new MediaServer(); wrong.setId("node-b");
+        f.hooks.onApplicationEvent(f.arrival(OLD, wrong));
+        assertEquals(0, f.successes.get()); assertEquals(1, f.hooks.getAll().size());
+        f.hooks.onApplicationEvent(f.arrival(OLD, f.node));
+        assertEquals(1, f.successes.get()); assertTrue(f.hooks.getAll().isEmpty());
+    }
+
+    @Test void cancelledArrivalAndLateSipCallbacksCannotChangeNewSlot() throws Exception {
+        Fixture f = new Fixture(); f.start(OLD);
+        SipSubscribe.Event oldOk = f.inviteOk.get(OLD), oldError = f.inviteError.get(OLD);
+        f.play.stopManaged(f.node, f.device, f.channel, OLD);
+        // Simulate externally reconciled old slot. Its pending dialog is still not a new generation's slot.
+        f.invites.removeInviteInfo(InviteSessionType.PLAY, f.channel.getId(), OLD);
+        f.start(NEXT);
+        f.hooks.onApplicationEvent(f.arrival(OLD, f.node));
+        f.dialog(OLD);
+        SipSubscribe.EventResult<?> event = new SipSubscribe.EventResult<>(); event.statusCode = 200;
+        oldOk.response(event);
+        event.statusCode = 500; oldError.response(event);
+        assertNotNull(f.invites.getInviteInfoByStream(InviteSessionType.PLAY, NEXT));
+        assertTrue(f.open.contains(NEXT));
+        assertEquals(1, f.hooks.getAll().size());
+        assertEquals(NEXT, f.hooks.getAll().get(0).getStream());
+        assertEquals(0, f.successes.get());
+    }
+
+    @Test void cancellationInsideRtpCreationPreventsInviteAndCleansAllocatedPort() throws Exception {
+        Fixture f = new Fixture(); f.cancelDuringOpen = true;
+        assertNull(f.start(OLD));
+        assertFalse(f.open.contains(OLD)); assertTrue(f.inviteOk.isEmpty()); assertTrue(f.hooks.getAll().isEmpty());
+    }
+
+    @Test void cancelledBeforeStartAndSinglePortNeverCreateResources() throws Exception {
+        Fixture f = new Fixture(); f.cancelled.add(OLD);
+        assertNull(f.start(OLD));
+        f.node.setRtpEnable(false); assertNull(f.start(NEXT));
+        assertTrue(f.open.isEmpty()); assertTrue(f.inviteOk.isEmpty());
+    }
+
+    @Test void differentExistingStreamIsNotAdoptedOrStopped() throws Exception {
+        Fixture f = new Fixture(); f.start(OLD);
+        assertNull(f.start(NEXT));
+        assertTrue(f.open.contains(OLD)); assertFalse(f.open.contains(NEXT));
+        assertNotNull(f.invites.getInviteInfoByStream(InviteSessionType.PLAY, OLD));
+    }
+
+    @Test void localCloseFailureCannotBecomeStopSuccessEvenWithBye200() throws Exception {
+        Fixture f = new Fixture(); f.start(OLD); f.dialog(OLD); f.closeAcknowledged = false;
+        assertFalse(f.play.stopManaged(f.node, f.device, f.channel, OLD));
+        SipSubscribe.EventResult<?> response = new SipSubscribe.EventResult<>(); response.statusCode = 200;
+        f.byeOk.get(OLD).response(response);
+        assertFalse(f.play.stopManaged(f.node, f.device, f.channel, OLD));
+        assertTrue(f.hooks.getAll().isEmpty());
+    }
+
+    @Test void realCommanderKeepsDialogOnByeTransportFailureAndRemovesOnlyOnAck() throws Exception {
+        Fixture f = new Fixture(); f.start(OLD); SsrcTransaction tx = f.dialog(OLD);
+        com.ruoyi.wvp.gb28181.transmit.cmd.impl.SIPCommander commander = new com.ruoyi.wvp.gb28181.transmit.cmd.impl.SIPCommander();
+        com.ruoyi.wvp.gb28181.transmit.SIPSender sender = mock(com.ruoyi.wvp.gb28181.transmit.SIPSender.class);
+        com.ruoyi.wvp.gb28181.transmit.cmd.SIPRequestHeaderProvider headers = mock(com.ruoyi.wvp.gb28181.transmit.cmd.SIPRequestHeaderProvider.class);
+        com.ruoyi.wvp.gb28181.SipLayer layer = mock(com.ruoyi.wvp.gb28181.SipLayer.class);
+        Fixture.wire(commander, "sessionManager", f.sessions); Fixture.wire(commander, "sipSender", sender);
+        Fixture.wire(commander, "headerProvider", headers); Fixture.wire(commander, "sipLayer", layer);
+        Fixture.wire(f.play, "cmder", commander);
+        when(headers.createByteRequest(f.device, "channel", tx.getSipTransactionInfo())).thenReturn(mock(javax.sip.message.Request.class));
+        when(layer.getLocalIp(any())).thenReturn("127.0.0.1");
+        doThrow(new SipException("offline")).when(sender).transmitRequest(any(), any(), any(), any());
+        assertFalse(f.play.stopManaged(f.node, f.device, f.channel, OLD));
+        assertSame(tx, f.sessions.getSsrcTransactionByStream("rtp", OLD));
+        assertTrue(f.hooks.getAll().isEmpty()); assertFalse(f.open.contains(OLD));
+        reset(sender);
+        java.util.concurrent.atomic.AtomicReference<SipSubscribe.Event> ack = new java.util.concurrent.atomic.AtomicReference<>();
+        doAnswer(i -> { ack.set(i.getArgument(3)); return null; }).when(sender).transmitRequest(any(), any(), any(), any());
+        assertFalse(f.play.stopManaged(f.node, f.device, f.channel, OLD));
+        assertSame(tx, f.sessions.getSsrcTransactionByStream("rtp", OLD));
+        SipSubscribe.EventResult<?> event = new SipSubscribe.EventResult<>(); event.statusCode = 200; event.callId = tx.getCallId();
+        ack.get().response(event);
+        assertNull(f.sessions.getSsrcTransactionByStream("rtp", OLD));
+        assertTrue(f.play.stopManaged(f.node, f.device, f.channel, OLD));
+    }
+
+    @Test void lateByeAckCannotDeleteReplacementDialog() throws Exception {
+        Fixture f = new Fixture(); f.start(OLD); SsrcTransaction old = f.dialog(OLD);
+        assertFalse(f.play.stopManaged(f.node, f.device, f.channel, OLD));
+        SsrcTransaction replacement = f.dialog(OLD); replacement.setCallId("replacement-dialog"); f.sessions.put(replacement);
+        SipSubscribe.EventResult<?> event = new SipSubscribe.EventResult<>(); event.statusCode = 200; event.callId = old.getCallId();
+        f.byeOk.get(OLD).response(event);
+        assertSame(replacement, f.sessions.getSsrcTransactionByStream("rtp", OLD));
+        assertFalse(f.play.stopManaged(f.node, f.device, f.channel, OLD));
+    }
+
+    @Test void rtpBoundaryAlsoRejectsSharedPortWithoutAllocating() throws Exception {
+        Fixture f = new Fixture(); f.node.setRtpEnable(false);
+        RTPServerParam param = new RTPServerParam(); param.setMediaServerItem(f.node); param.setStreamId(OLD);
+        assertNull(f.rtp.openRTPServer(param, (code, msg, result) -> assertNotEquals(0, code)));
+        assertTrue(f.open.isEmpty()); assertTrue(f.hooks.getAll().isEmpty());
+    }
+
+    @Test void cancellationDuringMediaReadNeverPublishesReady() throws Exception {
+        Fixture f = new Fixture(); f.start(OLD);
+        when(f.media.getStreamInfoByAppAndStream(any(), eq("rtp"), eq(OLD), any(), any())).thenAnswer(i -> {
+            f.cancelled.add(OLD);
+            StreamInfo info = new StreamInfo(); info.setStream(OLD); info.setMediaServer(f.node); return info;
+        });
+        f.hooks.onApplicationEvent(f.arrival(OLD, f.node));
+        assertEquals(0, f.successes.get()); assertFalse(f.open.contains(OLD)); assertTrue(f.hooks.getAll().isEmpty());
+    }
+
+    @Test void legacyPlayStillReusesItsReadyStreamWithoutManagedAllocation() throws Exception {
+        Fixture f = new Fixture(); String stream = "device_channel";
+        SSRCInfo ssrc = new SSRCInfo(30000, "0123450001", "rtp", stream, null);
+        StreamInfo live = new StreamInfo(); live.setStream(stream); live.setApp("rtp"); live.setMediaServer(f.node);
+        InviteInfo existing = InviteInfo.getInviteInfo("device", 7, stream, ssrc, "node-a", "127.0.0.1", 30000,
+                "UDP", InviteSessionType.PLAY, InviteSessionStatus.ready, false);
+        existing.setStreamInfo(live); f.invites.updateInviteInfo(existing);
+        when(f.media.isStreamReady(f.node, "rtp", stream)).thenReturn(true);
+        AtomicInteger callbacks = new AtomicInteger();
+        assertSame(ssrc, f.play.play(f.node, "device", "channel", null, (code, msg, info) -> {
+            assertEquals(0, code); assertSame(live, info); callbacks.incrementAndGet();
+        }));
+        assertEquals(1, callbacks.get()); assertTrue(f.open.isEmpty());
+    }
+
+    @Test void sameGenerationCanJoinReadyInviteWithoutOpeningAnotherRtp() throws Exception {
+        Fixture f = new Fixture(); SSRCInfo first = f.start(OLD);
+        f.hooks.onApplicationEvent(f.arrival(OLD, f.node));
+        assertSame(first, f.start(OLD));
+        assertEquals(Collections.singleton(OLD), f.open);
+        assertEquals(2, f.successes.get());
+    }
+
+    @Test void missingInviteAndDialogIsUnknownNotProofOfStop() throws Exception {
+        Fixture f = new Fixture();
+        assertFalse(f.play.stopManaged(f.node, f.device, f.channel, OLD));
+    }
+
+    @Test void wrongNodeStopCannotCancelOrCloseOwnedGeneration() throws Exception {
+        Fixture f = new Fixture(); f.start(OLD);
+        MediaServer wrong = new MediaServer(); wrong.setId("node-b");
+        assertFalse(f.play.stopManaged(wrong, f.device, f.channel, OLD));
+        assertFalse(f.cancelled.contains(OLD)); assertTrue(f.open.contains(OLD));
+        assertEquals(1, f.hooks.getAll().size());
+    }
+
+    @Test void mismatchedArrivalPayloadCannotConsumeOwnedSubscription() throws Exception {
+        Fixture f = new Fixture(); f.start(OLD);
+        MediaArrivalEvent event = f.arrival(OLD, f.node); event.getMediaInfo().setStream(NEXT);
+        f.hooks.onApplicationEvent(event);
+        assertEquals(0, f.successes.get()); assertEquals(1, f.hooks.getAll().size());
+        assertNull(f.invites.getInviteInfoByStream(InviteSessionType.PLAY, NEXT));
+        f.hooks.onApplicationEvent(f.arrival(OLD, f.node));
+        assertEquals(1, f.successes.get());
+    }
+
+    static class Fixture {
+        final PlayServiceImpl play = new PlayServiceImpl();
+        final RtpServerServiceImpl rtp = new RtpServerServiceImpl();
+        final HookSubscribe hooks = new HookSubscribe();
+        final InviteStreamServiceImpl invites = new InviteStreamServiceImpl();
+        final SipInviteSessionManager sessions = new SipInviteSessionManager();
+        final ISIPCommander sip = mock(ISIPCommander.class);
+        final IMediaServerService media = mock(IMediaServerService.class);
+        final VideoLifecycleStore store = mock(VideoLifecycleStore.class);
+        final MediaServer node = new MediaServer();
+        final Device device = new Device();
+        final DeviceChannel channel = new DeviceChannel();
+        final Set<String> open = new HashSet<>(), cancelled = new HashSet<>();
+        final Map<String, SipSubscribe.Event> inviteOk = new HashMap<>(), inviteError = new HashMap<>(), byeOk = new HashMap<>();
+        final AtomicInteger successes = new AtomicInteger();
+        boolean cancelDuringOpen, closeAcknowledged = true;
+
+        @SuppressWarnings({"unchecked", "rawtypes"})
+        Fixture() throws Exception {
+            node.setId("node-a"); node.setRtpEnable(true); node.setSdpIp("127.0.0.1");
+            device.setDeviceId("device"); device.setStreamMode("UDP");
+            channel.setId(7); channel.setDeviceId("channel");
+            UserSetting settings = new UserSetting(); settings.setServerId("test"); settings.setPlayTimeout(30000);
+            RedisTemplate<Object, Object> redis = mock(RedisTemplate.class);
+            HashOperations<Object, Object, Object> hash = mock(HashOperations.class);
+            Map<Object, Map<Object, Object>> data = new HashMap<>();
+            when(redis.opsForHash()).thenReturn(hash);
+            doAnswer(i -> { data.computeIfAbsent(i.getArgument(0), k -> new LinkedHashMap<>()).put(i.getArgument(1), i.getArgument(2)); return null; }).when(hash).put(any(), any(), any());
+            when(hash.get(any(), any())).thenAnswer(i -> data.getOrDefault(i.getArgument(0), Collections.emptyMap()).get(i.getArgument(1)));
+            when(hash.values(any())).thenAnswer(i -> new ArrayList<>(data.getOrDefault(i.getArgument(0), Collections.emptyMap()).values()));
+            when(hash.delete(any(), any())).thenAnswer(i -> data.getOrDefault(i.getArgument(0), Collections.emptyMap()).remove(i.getArgument(1)) == null ? 0L : 1L);
+            when(hash.scan(any(), any(ScanOptions.class))).thenAnswer(i -> {
+                String pattern = ((ScanOptions)i.getArgument(1)).getPattern().replace("*", ".*");
+                Iterator<Map.Entry<Object, Object>> iterator = new ArrayList<>(data.getOrDefault(i.getArgument(0), Collections.emptyMap()).entrySet()).stream()
+                        .filter(e -> e.getKey().toString().matches(pattern)).iterator();
+                Cursor<Map.Entry<Object, Object>> cursor = mock(Cursor.class);
+                when(cursor.hasNext()).thenAnswer(a -> iterator.hasNext()); when(cursor.next()).thenAnswer(a -> iterator.next()); return cursor;
+            });
+            StringRedisTemplate strings = mock(StringRedisTemplate.class);
+            SetOperations<String, String> sets = mock(SetOperations.class);
+            AtomicInteger ssrc = new AtomicInteger(1);
+            when(strings.opsForSet()).thenReturn(sets); when(sets.size(anyString())).thenReturn(100L);
+            when(sets.pop(anyString())).thenAnswer(i -> String.format("12345%04d", ssrc.getAndIncrement()));
+            SSRCFactory factory = new SSRCFactory();
+            wire(factory, "redisTemplate", strings); wire(factory, "userSetting", settings);
+            wire(invites, "redisTemplate", redis); wire(invites, "userSetting", settings);
+            wire(sessions, "redisTemplate", redis); wire(sessions, "userSetting", settings);
+            when(store.isStreamCancelled(anyString())).thenAnswer(i -> cancelled.contains(i.getArgument(0)));
+            doAnswer(i -> { cancelled.add(i.getArgument(0)); return null; }).when(store).markStreamCancelled(anyString());
+            when(media.createRTPServer(any(), anyString(), anyLong(), anyInt(), anyBoolean(), anyBoolean(), anyBoolean(), anyInt())).thenAnswer(i -> {
+                String stream = i.getArgument(1); open.add(stream); if (cancelDuringOpen) cancelled.add(stream); return 30000;
+            });
+            doAnswer(i -> { if (closeAcknowledged) open.remove(i.getArgument(1)); ((CommonCallback<Boolean>)i.getArgument(2)).run(closeAcknowledged); return null; })
+                    .when(media).closeRTPServer(any(), anyString(), any());
+            when(media.getStreamInfoByAppAndStream(any(), eq("rtp"), anyString(), any(), any())).thenAnswer(i -> {
+                StreamInfo info = new StreamInfo(); info.setStream(i.getArgument(2)); info.setApp("rtp"); info.setMediaServer(node); return info;
+            });
+            when(media.getOne("node-a")).thenReturn(node);
+            doAnswer(i -> { String stream = ((SSRCInfo)i.getArgument(1)).getStream(); inviteOk.put(stream, i.getArgument(4)); inviteError.put(stream, i.getArgument(5)); return null; })
+                    .when(sip).playStreamCmd(any(), any(), any(), any(), any(), any(), anyLong());
+            doAnswer(i -> { byeOk.put(i.getArgument(3), i.getArgument(5)); return null; }).when(sip).streamByeCmd(any(), anyString(), eq("rtp"), anyString(), any(), any());
+            IRedisCatchStorage cache = mock(IRedisCatchStorage.class); when(cache.getDevice("device")).thenReturn(device);
+            IDeviceChannelService channels = mock(IDeviceChannelService.class); when(channels.getOneForSource("device", "channel")).thenReturn(channel);
+            wire(rtp, "mediaServerService", media); wire(rtp, "dynamicTask", mock(DynamicTask.class)); wire(rtp, "ssrcFactory", factory);
+            wire(rtp, "userSetting", settings); wire(rtp, "subscribe", hooks); wire(rtp, "videoLifecycleStore", store);
+            wire(rtp, "sessionManager", sessions);
+            wire(play, "cmder", sip); wire(play, "redisCatchStorage", cache); wire(play, "deviceChannelService", channels);
+            wire(play, "inviteStreamService", invites); wire(play, "sessionManager", sessions); wire(play, "subscribe", hooks);
+            wire(play, "receiveRtpServerService", rtp); wire(play, "mediaServerService", media); wire(play, "videoLifecycleStore", store); wire(play, "userSetting", settings);
+        }
+        SSRCInfo start(String stream) { return play.playManaged(node, "device", "channel", stream, (code, msg, result) -> { if (code == 0) successes.incrementAndGet(); }); }
+        SsrcTransaction dialog(String stream) {
+            SsrcTransaction tx = new SsrcTransaction(); tx.setDeviceId("device"); tx.setChannelId(7); tx.setApp("rtp"); tx.setStream(stream);
+            tx.setCallId("call-" + stream); tx.setMediaServerId("node-a"); tx.setSipTransactionInfo(new SipTransactionInfo()); sessions.put(tx); return tx;
+        }
+        MediaArrivalEvent arrival(String stream, MediaServer server) {
+            MediaArrivalEvent event = new MediaArrivalEvent(this); event.setApp("rtp"); event.setStream(stream); event.setMediaServer(server); event.setSchema("rtsp");
+            MediaInfo info = new MediaInfo(); info.setApp("rtp"); info.setStream(stream); event.setMediaInfo(info); return event;
+        }
+        static void wire(Object bean, String field, Object value) { ReflectionTestUtils.setField(bean, field, value); }
+    }
+}

+ 57 - 0
video-service/src/test/java/com/zksy/video/lifecycle/ManagedHookIsolationTest.java

@@ -0,0 +1,57 @@
+package com.zksy.video.lifecycle;
+
+import com.ruoyi.wvp.gb28181.service.impl.PlayServiceImpl;
+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.MediaNotFoundEvent;
+import org.junit.jupiter.api.Test;
+
+import java.util.concurrent.atomic.AtomicInteger;
+import static org.junit.jupiter.api.Assertions.*;
+
+class ManagedHookIsolationTest {
+    @Test void managedNotFoundNeverEntersLegacyTwoOrFourPartAutoplay() {
+        // No registries/SIP wired: touching legacy parsing is itself a failure.
+        PlayServiceImpl play = new PlayServiceImpl();
+        for (String stream : new String[]{"managed_0123456789abcdef0123456789abcdef", "managed_x_20260101000000_20260101010000"}) {
+            MediaNotFoundEvent event = new MediaNotFoundEvent(this);
+            event.setApp("rtp"); event.setStream(stream);
+            assertDoesNotThrow(() -> play.onApplicationEvent(event));
+        }
+    }
+
+    @Test void nodeSpecificSubscriptionsCoexistWithLegacyWildcard() {
+        HookSubscribe hooks = new HookSubscribe();
+        AtomicInteger a = new AtomicInteger(), b = new AtomicInteger(), wildcard = new AtomicInteger();
+        hooks.addSubscribe(Hook.getInstance(HookType.on_media_arrival, "rtp", "stream", "a"), data -> a.incrementAndGet());
+        hooks.addSubscribe(Hook.getInstance(HookType.on_media_arrival, "rtp", "stream", "b"), data -> b.incrementAndGet());
+        hooks.addSubscribe(Hook.getInstance(HookType.on_media_arrival, "rtp", "stream"), data -> wildcard.incrementAndGet());
+        hooks.onApplicationEvent(arrival("a"));
+        assertEquals(1, a.get()); assertEquals(0, b.get()); assertEquals(1, wildcard.get());
+    }
+
+    @Test void oldOwnerCannotRemoveReplacementEvenDuringItsCallback() {
+        HookSubscribe hooks = new HookSubscribe();
+        Hook hook = Hook.getInstance(HookType.on_media_arrival, "rtp", "stream", "a");
+        AtomicInteger replacement = new AtomicInteger();
+        HookSubscribe.Subscription[] old = new HookSubscribe.Subscription[1];
+        old[0] = hooks.addOwnedSubscribe(hook, data -> {
+            hooks.addOwnedSubscribe(hook, next -> replacement.incrementAndGet());
+            assertFalse(hooks.removeOwnedSubscribe(old[0]));
+        });
+        hooks.onApplicationEvent(arrival("a"));
+        hooks.onApplicationEvent(arrival("a"));
+        assertEquals(1, replacement.get());
+        assertEquals(1, hooks.getAll().size());
+    }
+
+    private MediaArrivalEvent arrival(String nodeId) {
+        MediaServer node = new MediaServer(); node.setId(nodeId);
+        MediaArrivalEvent event = new MediaArrivalEvent(this);
+        event.setApp("rtp"); event.setStream("stream"); event.setSchema("rtsp"); event.setMediaServer(node);
+        return event;
+    }
+}

+ 42 - 0
video-service/src/test/java/com/zksy/video/lifecycle/ManagedInviteRetentionTest.java

@@ -0,0 +1,42 @@
+package com.zksy.video.lifecycle;
+
+import com.ruoyi.wvp.common.*;
+import com.ruoyi.wvp.gb28181.service.impl.InviteStreamServiceImpl;
+import com.ruoyi.wvp.media.event.media.MediaDepartureEvent;
+import org.junit.jupiter.api.Test;
+import org.springframework.data.redis.core.*;
+import org.springframework.test.util.ReflectionTestUtils;
+import java.util.*;
+import static org.mockito.Mockito.*;
+
+class ManagedInviteRetentionTest {
+    @Test void managedDepartureDoesNotDiscardTheOnlyRemainingCleanupHandle() {
+        RedisTemplate<Object,Object> redis = mock(RedisTemplate.class);
+        InviteStreamServiceImpl invites = new InviteStreamServiceImpl();
+        ReflectionTestUtils.setField(invites, "redisTemplate", redis);
+        MediaDepartureEvent event = new MediaDepartureEvent(this);
+        event.setApp("rtp"); event.setSchema("rtsp");
+        event.setStream("managed_12345678901234567890123456789012");
+        invites.onApplicationEvent(event);
+        verifyNoInteractions(redis);
+    }
+
+    @Test void genericExpiryDoesNotDeleteUnconfirmedManagedInvite() {
+        RedisTemplate<Object,Object> redis = mock(RedisTemplate.class);
+        HashOperations<Object,Object,Object> hashes = mock(HashOperations.class);
+        when(redis.opsForHash()).thenReturn(hashes);
+        InviteStreamServiceImpl invites = new InviteStreamServiceImpl();
+        ReflectionTestUtils.setField(invites, "redisTemplate", redis);
+        InviteInfo pending = new InviteInfo(); pending.setType(InviteSessionType.PLAY); pending.setChannelId(1);
+        pending.setDeviceId("camera-A"); pending.setStream("managed_12345678901234567890123456789012");
+        pending.setCreateTime(1L); pending.setExpirationTime(1L);
+        when(hashes.size(any())).thenReturn(1L);
+        when(hashes.values(any())).thenReturn(List.of(pending));
+        Cursor<Map.Entry<Object,Object>> cursor = mock(Cursor.class);
+        when(cursor.hasNext()).thenReturn(true, false);
+        when(cursor.next()).thenReturn(Map.entry("PLAY:1:" + pending.getStream(), pending));
+        when(hashes.scan(any(), any())).thenReturn(cursor);
+        invites.execute();
+        verify(hashes, never()).delete(any(), any());
+    }
+}

+ 84 - 0
video-service/src/test/java/com/zksy/video/lifecycle/ManualLegacyHandleTest.java

@@ -0,0 +1,84 @@
+package com.zksy.video.lifecycle;
+
+import com.alibaba.fastjson2.JSONObject;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.ruoyi.wvp.common.StreamInfo;
+import com.ruoyi.wvp.media.bean.MediaServer;
+import com.ruoyi.wvp.media.service.IMediaServerService;
+import com.ruoyi.wvp.media.zlm.ZLMRESTfulUtils;
+import com.zksy.video.ManualVideoController;
+import com.zksy.video.ManualVideoService;
+import org.junit.jupiter.api.Test;
+import java.util.*;
+import java.util.concurrent.atomic.AtomicBoolean;
+import static org.junit.jupiter.api.Assertions.*;
+import static org.mockito.Mockito.*;
+
+/** Legacy manual entrypoints with a real service/controller and substituted media-node I/O. */
+class ManualLegacyHandleTest {
+    @Test void secondLegacyUserSharesOnlyPersonallyConfirmedHandleAndOriginalNode() {
+        Fixture f = new Fixture();
+        Map<String, Object> first = f.service.start("cam", f.url);
+        assertEquals("ACTIVE", first.get("status")); assertEquals("opaque-key", first.get("proxyKey"));
+        MediaServer changedDefault = new MediaServer(); changedDefault.setId("node-b");
+        when(f.nodes.getDefaultMediaServer()).thenReturn(changedDefault);
+        Map<String, Object> next = f.service.start("cam", f.url);
+        assertEquals("ACTIVE", next.get("status")); assertEquals("opaque-key", next.get("proxyKey"));
+        assertEquals("node-a", next.get("mediaServerId")); assertEquals("manual_cam", next.get("stream"));
+        verify(f.zlm, times(1)).addStreamProxy(any(), anyString(), anyString(), anyString(), anyBoolean(), anyBoolean(), anyString(), anyInt());
+        verify(f.nodes, times(1)).getDefaultMediaServer();
+    }
+
+    @Test void unknownExistingProxyOrDifferentSourceCannotInventOrReuseKey() {
+        Fixture f = new Fixture(); f.live.set(true);
+        Map<String, Object> unknown = f.service.start("cam", f.url);
+        assertEquals("CLEANUP_PENDING", unknown.get("status")); assertFalse(unknown.containsKey("proxyKey"));
+        f.live.set(false); f.service.start("cam", f.url);
+        Map<String, Object> mismatch = f.service.start("cam", "rtsp://different.invalid/live");
+        assertEquals("CLEANUP_PENDING", mismatch.get("status")); assertFalse(mismatch.containsKey("proxyKey"));
+        verify(f.zlm, times(1)).addStreamProxy(any(), anyString(), anyString(), anyString(), anyBoolean(), anyBoolean(), anyString(), anyInt());
+    }
+
+    @Test void nodeAndKeyStopWorksWithoutProcessMemoryAndFalseIsExplicitError() {
+        Fixture f = new Fixture(); ManualVideoController controller = new ManualVideoController(f.service);
+        when(f.zlm.delStreamProxy(f.node, "opaque-key")).thenReturn(JSONObject.parseObject("{\"code\":0,\"data\":{\"flag\":false}}"));
+        assertEquals(500, controller.stop(Map.of("key", "opaque-key", "mediaServerId", "node-a")).get("code"));
+        when(f.zlm.delStreamProxy(f.node, "opaque-key")).thenReturn(JSONObject.parseObject("{\"code\":0,\"data\":{\"flag\":true}}"));
+        assertEquals(200, controller.stop(Map.of("key", "opaque-key", "mediaServerId", "node-a")).get("code"));
+        verify(f.nodes, never()).getDefaultMediaServer();
+    }
+
+    @Test void keyOnlyWorksOnlyForConfirmedLegacyNodeAndSuccessfulDeleteInvalidatesReuse() {
+        Fixture f = new Fixture(); ManualVideoController controller = new ManualVideoController(f.service);
+        assertEquals(500, controller.stop(Map.of("key", "opaque-key")).get("code"));
+        verify(f.zlm, never()).delStreamProxy(any(), anyString());
+        f.service.start("cam", f.url);
+        when(f.zlm.delStreamProxy(f.node, "opaque-key")).thenReturn(JSONObject.parseObject("{\"code\":0}"));
+        assertEquals(200, controller.stop(Map.of("key", "opaque-key")).get("code"));
+        assertEquals(500, controller.stop(Map.of("key", "opaque-key")).get("code"));
+        // A same-name live proxy after deletion is not the deleted handle.
+        assertEquals("CLEANUP_PENDING", f.service.start("cam", f.url).get("status"));
+        verify(f.zlm, times(1)).delStreamProxy(f.node, "opaque-key");
+    }
+
+    private static class Fixture {
+        final IMediaServerService nodes = mock(IMediaServerService.class);
+        final ZLMRESTfulUtils zlm = mock(ZLMRESTfulUtils.class);
+        final MediaServer node = new MediaServer();
+        final ManualVideoService service = new ManualVideoService(nodes, zlm, new ObjectMapper());
+        final AtomicBoolean live = new AtomicBoolean();
+        final String url = "rtsp://camera.invalid/live";
+        Fixture() {
+            node.setId("node-a"); node.setStatus(true); node.setType("zlm");
+            when(nodes.getDefaultMediaServer()).thenReturn(node); when(nodes.getOne("node-a")).thenReturn(node);
+            when(zlm.getMediaList(node, "city_video", "manual_cam")).thenAnswer(i -> JSONObject.parseObject(live.get()
+                    ? "{\"code\":0,\"data\":[{\"app\":\"city_video\",\"stream\":\"manual_cam\",\"vhost\":\"__defaultVhost__\",\"originType\":4,\"originUrl\":\"rtsp://camera.invalid/live\"}]}"
+                    : "{\"code\":0,\"data\":[]}"));
+            when(zlm.addStreamProxy(node, "city_video", "manual_cam", url, true, false, "0", 15)).thenAnswer(i -> {
+                live.set(true); return JSONObject.parseObject("{\"code\":0,\"data\":{\"key\":\"opaque-key\"}}");
+            });
+            StreamInfo info = new StreamInfo(); info.setApp("city_video"); info.setStream("manual_cam"); info.setMediaServer(node);
+            when(nodes.getStreamInfoByAppAndStream(eq(node), eq("city_video"), eq("manual_cam"), any(), isNull())).thenReturn(info);
+        }
+    }
+}

+ 243 - 0
video-service/src/test/java/com/zksy/video/lifecycle/ManualLifecycleMediaTest.java

@@ -0,0 +1,243 @@
+package com.zksy.video.lifecycle;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.ruoyi.wvp.media.service.IMediaServerService;
+import com.ruoyi.wvp.media.zlm.ZLMRESTfulUtils;
+import com.ruoyi.wvp.media.bean.MediaServer;
+import com.alibaba.fastjson2.JSONObject;
+import java.util.Map;
+import com.zksy.video.ManualVideoService;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.NullSource;
+import org.junit.jupiter.params.provider.ValueSource;
+import com.ruoyi.wvp.common.StreamInfo;
+
+import static org.junit.jupiter.api.Assertions.*;
+import static org.mockito.Mockito.*;
+
+/** Actual adapters are exercised; only media-node/ZLM boundaries are substituted. */
+class ManualLifecycleMediaTest {
+    private final IMediaServerService servers = mock(IMediaServerService.class);
+    private final ZLMRESTfulUtils zlm = mock(ZLMRESTfulUtils.class);
+    private final ManualLifecycleMedia adapter = new ManualLifecycleMedia(
+            new ManualVideoService(servers, zlm, new ObjectMapper()));
+
+    @Test void unavailableRecordedNodeKeepsCleanupPending() {
+        VideoLifecycleRecord record = proxyRecord();
+        assertEquals("CLEANUP_PENDING", adapter.cancel(record).get("status"));
+        verify(servers, never()).getDefaultMediaServer();
+        verifyNoInteractions(zlm);
+    }
+
+    private VideoLifecycleRecord proxyRecord() {
+        VideoLifecycleRecord record = new VideoLifecycleRecord();
+        record.setGeneration("b43b54f9-9d20-4440-b26c-97cbe7264901");
+        record.setSourceType("MANUAL");
+        record.setVideoId("cam-1");
+        record.setUrl("rtsp://camera.invalid/live");
+        record.setStream("manual_b43b54f99d204440b26c97cbe7264901");
+        record.setProxyKey("actual-zlm-key");
+        record.setMediaServerId("node-a");
+        record.setStatus("ACTIVE");
+        return record;
+    }
+
+    private MediaServer onlineNode() {
+        MediaServer node = new MediaServer();
+        node.setId("node-a"); node.setType("zlm"); node.setStatus(true);
+        when(servers.getOne("node-a")).thenReturn(node);
+        return node;
+    }
+
+    @Test void statusDoesNotTreatConstructibleUrlAsLiveMedia() {
+        VideoLifecycleRecord record = proxyRecord();
+        MediaServer node = onlineNode();
+        when(zlm.getMediaList(node, "city_video", record.getStream()))
+                .thenReturn(JSONObject.parseObject("{\"code\":0,\"data\":[]}"));
+        Map<String, Object> result = adapter.status(record);
+        assertEquals("STARTING", result.get("status"));
+        assertFalse(result.containsKey("media"));
+        verify(servers, never()).getDefaultMediaServer();
+        verify(servers, never()).getStreamInfoByAppAndStream(any(), anyString(), anyString(), any(), any());
+    }
+
+    @Test void prepareUsesEntireGenerationAndPersistsNodeBeforeAnyStart() {
+        VideoLifecycleRecord first = proxyRecord();
+        first.setStream(null); first.setProxyKey(null); first.setMediaServerId(null);
+        VideoLifecycleRecord second = proxyRecord();
+        second.setGeneration("b43b54f9-9d20-4440-b26c-97cbe7264902");
+        second.setStream(null); second.setProxyKey(null); second.setMediaServerId(null);
+        MediaServer node = onlineNode();
+        when(servers.getDefaultMediaServer()).thenReturn(node);
+        adapter.prepare(first); adapter.prepare(second);
+        assertEquals("manual_b43b54f99d204440b26c97cbe7264901", first.getStream());
+        assertNotEquals(first.getStream(), second.getStream());
+        assertEquals("node-a", first.getMediaServerId());
+        verifyNoInteractions(zlm);
+    }
+
+    @Test void successfulAddWithoutActualKeyRemainsPending() {
+        VideoLifecycleRecord record = proxyRecord(); record.setProxyKey(null);
+        MediaServer node = onlineNode();
+        when(zlm.getMediaList(node, "city_video", record.getStream()))
+                .thenReturn(JSONObject.parseObject("{\"code\":0,\"data\":[]}"));
+        when(zlm.addStreamProxy(node, "city_video", record.getStream(), record.getUrl(), true, false, "0", 15))
+                .thenReturn(JSONObject.parseObject("{\"code\":0,\"data\":{}}"));
+        Map<String, Object> result = adapter.start(record);
+        assertEquals("CLEANUP_PENDING", result.get("status"));
+        assertFalse(result.containsKey("proxyKey"));
+        assertFalse(result.containsKey("media"));
+        verify(servers, never()).getDefaultMediaServer();
+    }
+
+    @ParameterizedTest @NullSource
+    @ValueSource(strings = {"{}", "{\"code\":-1}", "{\"code\":0,\"data\":{\"flag\":false}}"})
+    void deletionFailureCannotClaimStopped(String response) {
+        VideoLifecycleRecord record = proxyRecord();
+        MediaServer node = onlineNode();
+        when(zlm.delStreamProxy(node, "actual-zlm-key")).thenReturn(JSONObject.parseObject(response));
+        assertEquals("CLEANUP_PENDING", adapter.cancel(record).get("status"));
+        verify(servers, never()).getDefaultMediaServer();
+    }
+
+    @Test void exactKeyDeletionSucceedsButInFlightStartStillPreventsStopped() {
+        VideoLifecycleRecord record = proxyRecord();
+        MediaServer node = onlineNode();
+        when(zlm.delStreamProxy(node, "actual-zlm-key")).thenReturn(JSONObject.parseObject("{\"code\":0,\"data\":{\"flag\":true}}"));
+        record.setStartInFlight(true);
+        assertEquals("CLEANUP_PENDING", adapter.cancel(record).get("status"));
+        record.setStartInFlight(false);
+        assertEquals("STOPPED", adapter.cancel(record).get("status"));
+        verify(zlm, times(2)).delStreamProxy(node, "actual-zlm-key");
+        verify(servers, never()).getDefaultMediaServer();
+    }
+
+    @Test void adoptionReusesOnlyLiveMatchingOldStreamAndRetainsItsActualHandle() {
+        VideoLifecycleRecord record = proxyRecord(); record.setStream("manual_old");
+        MediaServer node = onlineNode();
+        live(node, record, 4, record.getUrl());
+        adapter.prepare(record);
+        Map<String, Object> result = adapter.start(record);
+        assertEquals("ACTIVE", result.get("status"));
+        Map<?, ?> media = (Map<?, ?>) result.get("media");
+        assertEquals("manual_old", media.get("stream"));
+        assertEquals("node-a", media.get("mediaServerId"));
+        assertEquals("actual-zlm-key", media.get("proxyKey"));
+        verify(zlm, never()).addStreamProxy(any(), anyString(), anyString(), anyString(), anyBoolean(), anyBoolean(), anyString(), anyInt());
+        verify(servers, never()).getDefaultMediaServer();
+    }
+
+    @Test void absentOldStreamDoesNotStartAReplacement() {
+        VideoLifecycleRecord record = proxyRecord(); record.setStream("manual_old");
+        MediaServer node = onlineNode();
+        when(zlm.getMediaList(node, "city_video", "manual_old")).thenReturn(JSONObject.parseObject("{\"code\":0,\"data\":[]}"));
+        assertEquals("CLEANUP_PENDING", adapter.start(record).get("status"));
+        assertEquals("manual_old", record.getStream());
+        verify(zlm, never()).addStreamProxy(any(), anyString(), anyString(), anyString(), anyBoolean(), anyBoolean(), anyString(), anyInt());
+    }
+
+    private void live(MediaServer node, VideoLifecycleRecord record, int originType, String originUrl) {
+        JSONObject row = new JSONObject();
+        row.put("app", "city_video"); row.put("stream", record.getStream()); row.put("vhost", "__defaultVhost__");
+        row.put("originType", originType); row.put("originUrl", originUrl);
+        JSONObject response = new JSONObject(); response.put("code", 0);
+        response.put("data", new com.alibaba.fastjson2.JSONArray(java.util.List.of(row)));
+        when(zlm.getMediaList(node, "city_video", record.getStream())).thenReturn(response);
+        StreamInfo info = new StreamInfo(); info.setApp("city_video"); info.setStream(record.getStream()); info.setMediaServer(node);
+        when(servers.getStreamInfoByAppAndStream(eq(node), eq("city_video"), eq(record.getStream()), any(), isNull())).thenReturn(info);
+    }
+
+    @ParameterizedTest @NullSource
+    @ValueSource(strings = {"{}", "{\"code\":-1}", "{\"code\":0,\"data\":{}}", "{\"code\":0,\"data\":[{}]}"})
+    void rawMediaErrorsRemainUnknownRatherThanAbsent(String response) {
+        VideoLifecycleRecord record = proxyRecord(); MediaServer node = onlineNode();
+        when(zlm.getMediaList(node, "city_video", record.getStream())).thenReturn(JSONObject.parseObject(response));
+        assertEquals("CLEANUP_PENDING", adapter.status(record).get("status"));
+    }
+
+    @ParameterizedTest @ValueSource(ints = {1, 3, 5})
+    void adoptionRejectsWrongActualSourceType(int originType) {
+        VideoLifecycleRecord record = proxyRecord(); record.setStream("manual_old");
+        live(onlineNode(), record, originType, record.getUrl());
+        assertEquals("CLEANUP_PENDING", adapter.start(record).get("status"));
+        verify(zlm, never()).addStreamProxy(any(), anyString(), anyString(), anyString(), anyBoolean(), anyBoolean(), anyString(), anyInt());
+    }
+
+    @Test void adoptionRejectsWrongUrlAndNeverChoosesANodeForMissingIdentity() {
+        VideoLifecycleRecord record = proxyRecord(); record.setStream("manual_old");
+        live(onlineNode(), record, 4, "rtsp://different.invalid/live");
+        assertEquals("CLEANUP_PENDING", adapter.start(record).get("status"));
+        record.setMediaServerId(null);
+        assertThrows(IllegalStateException.class, () -> adapter.prepare(record));
+        assertEquals("CLEANUP_PENDING", adapter.start(record).get("status"));
+        verify(servers, never()).getDefaultMediaServer();
+    }
+
+    @Test void actualAddKeySurvivesUnknownReadinessAndOnlyItsNodeCanBeCleaned() {
+        VideoLifecycleRecord record = proxyRecord(); record.setProxyKey(null);
+        MediaServer node = onlineNode();
+        when(zlm.getMediaList(node, "city_video", record.getStream()))
+                .thenReturn(JSONObject.parseObject("{\"code\":0,\"data\":[]}"), JSONObject.parseObject("{\"code\":-1}"));
+        when(zlm.addStreamProxy(node, "city_video", record.getStream(), record.getUrl(), true, false, "0", 15))
+                .thenReturn(JSONObject.parseObject("{\"code\":0,\"data\":{\"key\":\"opaque-key-from-zlm\"}}"));
+        Map<String, Object> result = adapter.start(record);
+        assertEquals("CLEANUP_PENDING", result.get("status"));
+        assertEquals("opaque-key-from-zlm", result.get("proxyKey"));
+        assertEquals("node-a", result.get("mediaServerId"));
+        assertEquals("opaque-key-from-zlm", record.getProxyKey());
+        when(zlm.delStreamProxy(node, "opaque-key-from-zlm")).thenReturn(JSONObject.parseObject("{\"code\":0}"));
+        assertEquals("STOPPED", adapter.cancel(record).get("status"));
+        verify(servers, never()).getDefaultMediaServer();
+    }
+
+    @ParameterizedTest @NullSource
+    @ValueSource(strings = {"{}", "{\"code\":-1,\"data\":{\"key\":\"not-successful\"}}"})
+    void onlyExplicitCodeZeroCanSupplyActualKey(String response) {
+        VideoLifecycleRecord record = proxyRecord(); record.setProxyKey(null); MediaServer node = onlineNode();
+        when(zlm.getMediaList(node, "city_video", record.getStream())).thenReturn(JSONObject.parseObject("{\"code\":0,\"data\":[]}"));
+        when(zlm.addStreamProxy(node, "city_video", record.getStream(), record.getUrl(), true, false, "0", 15))
+                .thenReturn(JSONObject.parseObject(response));
+        assertEquals("CLEANUP_PENDING", adapter.start(record).get("status"));
+        assertNull(record.getProxyKey());
+    }
+
+    @Test void cancelledStartNeverAddsAProxyAndUnknownOriginNeverClaimsStopped() {
+        VideoLifecycleRecord record = proxyRecord(); record.setProxyKey(null); record.setCancelled(true);
+        assertEquals("CLEANUP_PENDING", adapter.start(record).get("status"));
+        record.setUrl(null); record.setStream(null);
+        assertEquals("CLEANUP_PENDING", adapter.cancel(record).get("status"));
+        verifyNoInteractions(zlm, servers);
+    }
+
+    @Test void nativeMediaHasNoProxyButStillHonorsInFlightFence() {
+        VideoLifecycleRecord record = proxyRecord(); record.setUrl("https://camera.invalid/live.m3u8");
+        record.setStream(null); record.setProxyKey(null); record.setMediaServerId(null);
+        adapter.prepare(record);
+        assertEquals("ACTIVE", adapter.start(record).get("status"));
+        assertEquals("STOPPED", adapter.cancel(record).get("status"));
+        record.setStartInFlight(true);
+        assertEquals("CLEANUP_PENDING", adapter.cancel(record).get("status"));
+        verifyNoInteractions(zlm, servers);
+    }
+
+    @Test void oldKeyOnlyApiRejectsUnobservedKeyRatherThanGuessingNode() {
+        ManualVideoService legacy = new ManualVideoService(servers, zlm, new ObjectMapper());
+        assertThrows(IllegalStateException.class, () -> legacy.stop("__defaultVhost__/city_video/manual_cam-1"));
+        verifyNoInteractions(zlm, servers);
+    }
+
+    @Test void missingActualProxyKeyNeverClaimsCleanupCompleted() {
+        VideoLifecycleRecord record = new VideoLifecycleRecord();
+        record.setGeneration("b43b54f9-9d20-4440-b26c-97cbe7264901");
+        record.setSourceType("MANUAL");
+        record.setVideoId("cam-1");
+        record.setUrl("rtsp://camera.invalid/live");
+        record.setStream("manual_cam_1_b43b54f99d204440b26c97cbe7264901");
+        record.setCancelled(true);
+        record.setStatus("CLEANUP_PENDING");
+
+        assertEquals("CLEANUP_PENDING", adapter.cancel(record).get("status"));
+        verifyNoInteractions(zlm);
+    }
+}

+ 136 - 0
video-service/src/test/java/com/zksy/video/lifecycle/VideoLifecycleRaceTest.java

@@ -0,0 +1,136 @@
+package com.zksy.video.lifecycle;
+
+import com.alibaba.fastjson2.JSON;
+import org.junit.jupiter.api.Test;
+import java.time.Instant;
+import java.util.*;
+import static org.junit.jupiter.api.Assertions.*;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.*;
+
+class VideoLifecycleRaceTest {
+    // Redis returns separate snapshots; sharing the same mutable object conceals lost updates.
+    static class Snapshots implements VideoLifecycleStore {
+        final Map<String, String> rows = new HashMap<>();
+        final Set<String> cancelled = new HashSet<>();
+        public synchronized VideoLifecycleRecord find(String id) { return JSON.parseObject(rows.get(id), VideoLifecycleRecord.class); }
+        public synchronized boolean compareAndSet(VideoLifecycleRecord expected, VideoLifecycleRecord row) {
+            VideoLifecycleRecord actual = find(row.getGeneration());
+            if (expected == null ? actual != null : actual == null || actual.getRevision() != expected.getRevision()) return false;
+            row.setRevision(expected == null ? 0 : expected.getRevision() + 1);
+            rows.put(row.getGeneration(), JSON.toJSONString(row)); return true;
+        }
+        public void markStreamCancelled(String stream) { cancelled.add(stream); }
+        public boolean isStreamCancelled(String stream) { return cancelled.contains(stream); }
+    }
+    static Map<String, Object> request() {
+        return Map.of("generation", "f647180f-41de-4cec-8db3-26f3adad8c08", "startDeadline", Instant.now().plusSeconds(30).toEpochMilli(),
+                "source", Map.of("type", "GB28181", "videoId", "camera-A", "deviceId", "34020000002000000001", "channelId", "34020000001320000001"));
+    }
+    @Test void repeatedStartOnlyReadsTheRecordedGenerationAndDoesNotAllocateAgain() {
+        VideoLifecycleMedia media = mock(VideoLifecycleMedia.class);
+        when(media.supports("GB28181")).thenReturn(true);
+        when(media.start(any())).thenReturn(Map.of("status", "ACTIVE", "media", Map.of("webrtc", "https://media.invalid/A")));
+        doCallRealMethod().when(media).status(any());
+        VideoLifecycleService service = new VideoLifecycleService(new Snapshots(), List.of(media));
+        Map<String,Object> request = request();
+        assertEquals("ACTIVE", service.start(request).get("status"));
+        assertEquals("ACTIVE", service.start(request).get("status"));
+        verify(media, times(1)).start(any());
+    }
+
+    @Test void anExpiredNewGenerationNeverAllocatesAndCannotBeExtended() {
+        VideoLifecycleMedia media = mock(VideoLifecycleMedia.class);
+        VideoLifecycleService service = new VideoLifecycleService(new Snapshots(), List.of(media));
+        Map<String,Object> request = new HashMap<>(request());
+        request.put("startDeadline", 1L);
+        assertEquals("FAILED", service.start(request).get("status"));
+        request.put("startDeadline", Instant.now().plusSeconds(30).toEpochMilli());
+        assertThrows(IllegalArgumentException.class, () -> service.start(request));
+        verifyNoInteractions(media);
+    }
+
+    @Test void aDifferentSourceCannotUseAnExistingGeneration() {
+        VideoLifecycleMedia media = mock(VideoLifecycleMedia.class);
+        when(media.supports("GB28181")).thenReturn(true);
+        when(media.start(any())).thenReturn(Map.of("status", "STARTING"));
+        VideoLifecycleService service = new VideoLifecycleService(new Snapshots(), List.of(media));
+        Map<String,Object> request = new HashMap<>(request());
+        service.start(request);
+        request.put("source", Map.of("type", "MANUAL", "videoId", "another", "url", "https://media.invalid/B"));
+        assertThrows(IllegalArgumentException.class, () -> service.cancel(request));
+        verify(media, never()).cancel(any());
+    }
+
+    @Test void deletionAcknowledgedDuringAllocationIsNotPrematureStopEvidence() {
+        VideoLifecycleMedia media = mock(VideoLifecycleMedia.class);
+        when(media.supports("GB28181")).thenReturn(true);
+        when(media.cancel(any())).thenReturn(Map.of("status", "STOPPED"));
+        VideoLifecycleService service = new VideoLifecycleService(new Snapshots(), List.of(media));
+        Map<String,Object> request = request();
+        when(media.start(any())).thenAnswer(call -> {
+            assertEquals("CLEANUP_PENDING", service.cancel(request).get("status"));
+            return Map.of("status", "ACTIVE", "stream", "managed-A", "media", Map.of("webrtc", "https://media.invalid/A"));
+        });
+        Map<String,Object> result = service.start(request);
+        assertEquals("STOPPED", result.get("status"), "a second cleanup after allocation completes may attest stop");
+        assertFalse(result.containsKey("media"));
+        verify(media, times(2)).cancel(any());
+    }
+
+    @Test void simultaneousServicesIssueOnlyOneAllocationForTheSameGeneration() {
+        VideoLifecycleMedia media = mock(VideoLifecycleMedia.class);
+        when(media.supports("GB28181")).thenReturn(true);
+        Snapshots shared = new Snapshots();
+        VideoLifecycleService first = new VideoLifecycleService(shared, List.of(media));
+        VideoLifecycleService second = new VideoLifecycleService(shared, List.of(media));
+        Map<String,Object> request = request();
+        when(media.start(any())).thenAnswer(call -> {
+            assertEquals("STARTING", second.start(request).get("status"));
+            return Map.of("status", "ACTIVE", "media", Map.of("webrtc", "https://media.invalid/A"));
+        });
+        assertEquals("ACTIVE", first.start(request).get("status"));
+        verify(media, times(1)).start(any());
+    }
+
+    @Test void readinessArrivingAfterTheImmutableStartDeadlineIsCleanedInsteadOfPublished() {
+        java.util.concurrent.atomic.AtomicLong now = new java.util.concurrent.atomic.AtomicLong(1000);
+        java.time.Clock clock = new java.time.Clock() {
+            public java.time.ZoneId getZone() { return java.time.ZoneOffset.UTC; }
+            public java.time.Clock withZone(java.time.ZoneId zone) { return this; }
+            public Instant instant() { return Instant.ofEpochMilli(now.get()); }
+        };
+        VideoLifecycleMedia media = mock(VideoLifecycleMedia.class);
+        when(media.supports("GB28181")).thenReturn(true);
+        when(media.cancel(any())).thenReturn(Map.of("status", "STOPPED"));
+        VideoLifecycleService service = new VideoLifecycleService(new Snapshots(), List.of(media), clock);
+        Map<String,Object> request = new HashMap<>(request()); request.put("startDeadline", 31000L);
+        when(media.start(any())).thenAnswer(call -> {
+            now.set(32000L);
+            return Map.of("status", "ACTIVE", "media", Map.of("webrtc", "https://media.invalid/late"));
+        });
+        Map<String,Object> result = service.start(request);
+        assertEquals("STOPPED", result.get("status"));
+        assertFalse(result.containsKey("media"));
+        verify(media).cancel(any());
+    }
+
+    @Test void cancellingDuringStartCannotBeOverwrittenByALateActiveSnapshot() {
+        VideoLifecycleMedia media = mock(VideoLifecycleMedia.class);
+        when(media.supports("GB28181")).thenReturn(true);
+        when(media.intendedStream(any())).thenReturn("managed-A");
+        doCallRealMethod().when(media).prepare(any());
+        when(media.cancel(any())).thenReturn(Map.of("status", "CLEANUP_PENDING"));
+        VideoLifecycleService service = new VideoLifecycleService(new Snapshots(), List.of(media));
+        Map<String,Object> request = request();
+        when(media.start(any())).thenAnswer(call -> {
+            assertEquals("CLEANUP_PENDING", service.cancel(request).get("status"));
+            return Map.of("status", "ACTIVE", "stream", "managed-A", "media", Map.of("webrtc", "https://media.invalid/A"));
+        });
+        Map<String,Object> result = service.start(request);
+        assertEquals("CLEANUP_PENDING", result.get("status"));
+        assertFalse(result.containsKey("media"));
+        assertEquals("CLEANUP_PENDING", service.start(request).get("status"), "cancel accepted is not stop confirmation");
+        verify(media, times(1)).start(any());
+    }
+}

+ 9 - 14
video-service/src/test/java/com/zksy/video/lifecycle/VideoLifecycleServiceTest.java

@@ -17,21 +17,16 @@ import static org.mockito.Mockito.*;
  * 结果未知只能说 pending,不能谎报已停或已成功。
  * 结果未知只能说 pending,不能谎报已停或已成功。
  */
  */
 class VideoLifecycleServiceTest {
 class VideoLifecycleServiceTest {
-    private final Map<String, VideoLifecycleRecord> rows = new HashMap<>();
-    private final java.util.Set<String> cancelledStreams = new java.util.HashSet<>();
-    private final VideoLifecycleStore store = new VideoLifecycleStore() {
-        @Override public VideoLifecycleRecord find(String generation) { return rows.get(generation); }
-        @Override public void save(VideoLifecycleRecord record) { rows.put(record.getGeneration(), record); }
-        @Override public void markStreamCancelled(String stream) { cancelledStreams.add(stream); }
-        @Override public boolean isStreamCancelled(String stream) { return cancelledStreams.contains(stream); }
-    };
+    private final VideoLifecycleRaceTest.Snapshots store = new VideoLifecycleRaceTest.Snapshots();
     private VideoLifecycleMedia media;
     private VideoLifecycleMedia media;
     private VideoLifecycleService service;
     private VideoLifecycleService service;
 
 
     @BeforeEach void setUp() {
     @BeforeEach void setUp() {
         media = mock(VideoLifecycleMedia.class);
         media = mock(VideoLifecycleMedia.class);
         when(media.supports("GB28181")).thenReturn(true);
         when(media.supports("GB28181")).thenReturn(true);
-        service = new VideoLifecycleService(store, List.of(media));
+        doCallRealMethod().when(media).prepare(any());
+        service = new VideoLifecycleService(store, List.of(media), java.time.Clock.fixed(
+                java.time.Instant.parse("2026-11-12T01:00:00Z"), java.time.ZoneOffset.UTC));
     }
     }
 
 
     private static Map<String, Object> body(String generation) {
     private static Map<String, Object> body(String generation) {
@@ -43,14 +38,14 @@ class VideoLifecycleServiceTest {
         Map<String, Object> body = new LinkedHashMap<>();
         Map<String, Object> body = new LinkedHashMap<>();
         body.put("generation", generation);
         body.put("generation", generation);
         body.put("source", source);
         body.put("source", source);
-        body.put("startDeadline", 1_700_000_000_000L);
+        body.put("startDeadline", java.time.Instant.parse("2026-11-12T01:00:30Z").toEpochMilli());
         return body;
         return body;
     }
     }
 
 
     @Test void cancelBeforeStartLeavesATombstoneAndNoMediaIsEverCreated() {
     @Test void cancelBeforeStartLeavesATombstoneAndNoMediaIsEverCreated() {
         assertEquals("CLEANUP_PENDING", service.cancel(body("gen-cancel-first")).get("status"));
         assertEquals("CLEANUP_PENDING", service.cancel(body("gen-cancel-first")).get("status"));
         Map<String, Object> started = service.start(body("gen-cancel-first"));
         Map<String, Object> started = service.start(body("gen-cancel-first"));
-        assertEquals("STOPPED", started.get("status"));
+        assertEquals("CLEANUP_PENDING", started.get("status"));
         assertNull(started.get("media"));
         assertNull(started.get("media"));
         verify(media, never()).start(any());
         verify(media, never()).start(any());
     }
     }
@@ -60,7 +55,7 @@ class VideoLifecycleServiceTest {
         when(media.start(any())).thenThrow(new IllegalStateException("媒体结果未确认"));
         when(media.start(any())).thenThrow(new IllegalStateException("媒体结果未确认"));
         Map<String, Object> started = service.start(body("gen-unknown"));
         Map<String, Object> started = service.start(body("gen-unknown"));
         assertEquals("CLEANUP_PENDING", started.get("status"));
         assertEquals("CLEANUP_PENDING", started.get("status"));
-        assertEquals("34020000002000000001_34020000001320000001", rows.get("gen-unknown").getStream());
+        assertEquals("34020000002000000001_34020000001320000001", store.find("gen-unknown").getStream());
     }
     }
 
 
     @Test void cancelUsesTheRecordedHandleAndOnlyReportsStoppedWhenConfirmed() {
     @Test void cancelUsesTheRecordedHandleAndOnlyReportsStoppedWhenConfirmed() {
@@ -97,7 +92,7 @@ class VideoLifecycleServiceTest {
     @Test void unsupportedSourceFailsCleanlyWithoutTouchingMedia() {
     @Test void unsupportedSourceFailsCleanlyWithoutTouchingMedia() {
         Map<String, Object> body = body("gen-unsupported");
         Map<String, Object> body = body("gen-unsupported");
         ((Map<String, Object>) body.get("source")).put("type", "OTHER");
         ((Map<String, Object>) body.get("source")).put("type", "OTHER");
-        assertEquals("FAILED", service.start(body).get("status"));
+        assertThrows(IllegalArgumentException.class, () -> service.start(body));
         verify(media, never()).start(any());
         verify(media, never()).start(any());
     }
     }
 
 
@@ -107,7 +102,7 @@ class VideoLifecycleServiceTest {
                 "media", Map.of("webrtc", "https://media.invalid/late")));
                 "media", Map.of("webrtc", "https://media.invalid/late")));
         assertEquals("CLEANUP_PENDING", service.cancel(body("gen-late")).get("status"));
         assertEquals("CLEANUP_PENDING", service.cancel(body("gen-late")).get("status"));
         Map<String, Object> started = service.start(body("gen-late"));
         Map<String, Object> started = service.start(body("gen-late"));
-        assertEquals("STOPPED", started.get("status"));
+        assertEquals("CLEANUP_PENDING", started.get("status"));
         assertNull(started.get("media"));
         assertNull(started.get("media"));
         verify(media, never()).start(any());
         verify(media, never()).start(any());
     }
     }