Sfoglia il codice sorgente

fix(video): 按观看代次精确启动与回收媒体资源

Kazerin 3 settimane fa
parent
commit
a4c3dc7b10

+ 25 - 0
docs/video-session-prepared-20261111.sql

@@ -0,0 +1,25 @@
+-- cockpit-video-monitoring/03 — 观看代次与启动截止,基于 01 之后的实际表结构。
+-- 仅生成,未对真实数据库执行。必须在 01(anonymous_token_hash)之后、部署 03 代码之前执行。
+-- 一次性迁移:重复执行会失败并回滚,不用 IF NOT EXISTS 掩盖异构字段。
+BEGIN;
+ALTER TABLE app_user.video_play_session
+    ADD COLUMN media_generation varchar(64) NULL;
+ALTER TABLE app_user.video_play_session
+    ADD COLUMN start_deadline timestamp NULL;
+COMMENT ON COLUMN app_user.video_play_session.media_generation
+    IS '观看代次(UUID):媒体资源的身份,主服务与 video-service 用它精确启动/取消,不用设备号猜';
+COMMENT ON COLUMN app_user.video_play_session.start_deadline
+    IS '本代次媒体启动截止时间;同一代次不可延长,过期后不得迟到复活';
+-- 同一代次的共享观看者需要按代次分组查询(启动计数/最后一位回收)。
+CREATE INDEX ix_video_session_generation
+    ON app_user.video_play_session(video_id, media_generation)
+    WHERE media_generation IS NOT NULL;
+COMMIT;
+
+-- 回退须先停止视频入口,并确认没有任何 STARTING/ACTIVE/CLEANUP_PENDING 会话行。
+-- 不自动删除、回填或伪造代次;历史行的 media_generation 保持 NULL 由主服务按“句柄一致才采纳”处理。
+-- BEGIN;
+-- DROP INDEX app_user.ix_video_session_generation;
+-- ALTER TABLE app_user.video_play_session DROP COLUMN start_deadline;
+-- ALTER TABLE app_user.video_play_session DROP COLUMN media_generation;
+-- COMMIT;

+ 27 - 14
video-service/src/main/java/com/ruoyi/wvp/gb28181/service/impl/PlayServiceImpl.java

@@ -80,6 +80,10 @@ public class PlayServiceImpl implements IPlayService {
     @Autowired
     private IMediaServerService mediaServerService;
 
+    /** 观看代次墓碑:已取消的 stream 不得因“流未找到”被自动点播复活。 */
+    @Autowired
+    private com.zksy.video.lifecycle.VideoLifecycleStore videoLifecycleStore;
+
     @Autowired
     private SipInviteSessionManager sessionManager;
 
@@ -119,6 +123,10 @@ public class PlayServiceImpl implements IPlayService {
         if (!"rtp".equals(event.getApp())) {
             return;
         }
+        if (videoLifecycleStore != null && videoLifecycleStore.isStreamCancelled(event.getStream())) {
+            log.info("[ZLM HOOK] 该流已被取消,不自动点播:{}", event.getStream());
+            return;
+        }
         String[] s = event.getStream().split("_");
         if ((s.length != 2 && s.length != 4)) {
             return;
@@ -975,21 +983,26 @@ public class PlayServiceImpl implements IPlayService {
             return;
         }
         inviteStreamService.removeInviteInfo(inviteInfo);
-        if (InviteSessionStatus.ok == inviteInfo.getStatus()) {
-            try {
-                log.info("[停止点播/回放/下载] {}/{}", device.getDeviceId(), channel.getDeviceId());
-                cmder.streamByeCmd(device, channel.getDeviceId(), "rtp", inviteInfo.getStream(), null, null);
-            } catch (InvalidArgumentException | SipException | ParseException | SsrcTransactionNotFoundException e) {
-                log.error("[命令发送失败] 停止点播/回放/下载, 发送BYE: {}", e.getMessage());
-                throw new ControllerException(ErrorCode.ERROR100.getCode(), "命令发送失败: " + e.getMessage());
+        try {
+            if (InviteSessionStatus.ok == inviteInfo.getStatus()) {
+                try {
+                    log.info("[停止点播/回放/下载] {}/{}", device.getDeviceId(), channel.getDeviceId());
+                    cmder.streamByeCmd(device, channel.getDeviceId(), "rtp", inviteInfo.getStream(), null, null);
+                } catch (InvalidArgumentException | SipException | ParseException | SsrcTransactionNotFoundException e) {
+                    log.error("[命令发送失败] 停止点播/回放/下载, 发送BYE: {}", e.getMessage());
+                    throw new ControllerException(ErrorCode.ERROR100.getCode(), "命令发送失败: " + e.getMessage());
+                }
+            }
+        } finally {
+            // BYE 失败也必须在本地结束本代接收资源,否则 RTP/SSRC/订阅会泄漏到下一代。
+            if (inviteInfo.getType() == InviteSessionType.PLAY) {
+                deviceChannelService.stopPlay(channel.getId());
+            }
+            MediaServer rtpServer = inviteInfo.getStreamInfo() != null ? inviteInfo.getStreamInfo().getMediaServer()
+                    : inviteInfo.getMediaServerId() == null ? null : mediaServerService.getOne(inviteInfo.getMediaServerId());
+            if (rtpServer != null && inviteInfo.getSsrcInfo() != null) {
+                receiveRtpServerService.closeRTPServer(rtpServer, inviteInfo.getSsrcInfo());
             }
-        }
-
-        if (inviteInfo.getType() == InviteSessionType.PLAY) {
-            deviceChannelService.stopPlay(channel.getId());
-        }
-        if (inviteInfo.getStreamInfo() != null) {
-            receiveRtpServerService.closeRTPServer(inviteInfo.getStreamInfo().getMediaServer(), inviteInfo.getSsrcInfo());
         }
     }
 

+ 5 - 2
video-service/src/main/java/com/zksy/video/ManualVideoService.java

@@ -16,14 +16,17 @@ public class ManualVideoService {
     private final ZLMRESTfulUtils zlm;
     private final ObjectMapper 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 由调用方按观看代次生成,同一设备不同代次不复用物理流。 */
     @SuppressWarnings("unchecked")
-    public synchronized Map<String,Object> start(String id,String url) {
+    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 stream="manual_"+id,key="__defaultVhost__/city_video/"+stream;
+        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("手动设备拉流失败,请检查视频地址与设备网络");

+ 99 - 0
video-service/src/main/java/com/zksy/video/lifecycle/Gb28181LifecycleMedia.java

@@ -0,0 +1,99 @@
+package com.zksy.video.lifecycle;
+
+import java.util.LinkedHashMap;
+import java.util.Map;
+import org.springframework.stereotype.Component;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.ruoyi.wvp.common.InviteSessionType;
+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.IDeviceChannelService;
+import com.ruoyi.wvp.gb28181.service.IDeviceService;
+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.vmanager.bean.StreamContent;
+
+/**
+ * GB28181 源:复用既有 INVITE 点播与停止链路。
+ *
+ * 已知边界:物理流名由 {@link IPlayService} 固定为 {@code 设备ID_通道ID},同一摄像机天然共享一条流;
+ * 本适配器不修改该命名(改动会牵动 SIP 事务、ZLM hook 与既有管理端播放链)。
+ * 因此“不同代次唯一物理流”在 GB28181 侧尚未成立,代次隔离只保证本服务不再为已取消代次发起点播。
+ */
+@Component
+public class Gb28181LifecycleMedia implements VideoLifecycleMedia {
+    private static final String APP = "rtp";
+
+    private final IDeviceService devices;
+    private final IDeviceChannelService channels;
+    private final IPlayService play;
+    private final IMediaServerService servers;
+    private final ObjectMapper json;
+
+    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;
+    }
+
+    @Override public boolean supports(String sourceType) { return "GB28181".equals(sourceType); }
+
+    @Override public String intendedStream(VideoLifecycleRecord record) {
+        return record.getDeviceId() == null || record.getChannelId() == null ? null
+                : streamName(record.getDeviceId(), record.getChannelId());
+    }
+
+    @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) -> { });
+        }
+        return outcome("STARTING", null, stream);
+    }
+
+    @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());
+    }
+
+    @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());
+    }
+
+    static String streamName(String deviceId, String channelId) { return deviceId + "_" + channelId; }
+
+    @SuppressWarnings("unchecked")
+    private Map<String, Object> media(StreamInfo info) { return json.convertValue(new StreamContent(info), Map.class); }
+
+    private static Map<String, Object> outcome(String status, Map<String, Object> media, String stream) {
+        Map<String, Object> result = new LinkedHashMap<>();
+        result.put("status", status);
+        if (media != null) result.put("media", media);
+        if (stream != null) result.put("stream", stream);
+        return result;
+    }
+}

+ 74 - 0
video-service/src/main/java/com/zksy/video/lifecycle/ManualLifecycleMedia.java

@@ -0,0 +1,74 @@
+package com.zksy.video.lifecycle;
+
+import java.net.URI;
+import java.util.LinkedHashMap;
+import java.util.Locale;
+import java.util.Map;
+import java.util.Set;
+import org.springframework.stereotype.Component;
+import com.zksy.video.ManualVideoService;
+
+/**
+ * MANUAL 源:RTSP/RTMP 走真实拉流代理并按代次取唯一 stream;
+ * http(s) 原生地址不经过媒体节点,直接作为 ACTIVE 媒体返回。
+ */
+@Component
+public class ManualLifecycleMedia implements VideoLifecycleMedia {
+    private static final Set<String> PROXY_SCHEMES = Set.of("rtsp", "rtsps", "rtmp", "rtmps");
+
+    private final ManualVideoService manual;
+
+    public ManualLifecycleMedia(ManualVideoService manual) { this.manual = manual; }
+
+    @Override public boolean supports(String sourceType) { return "MANUAL".equals(sourceType); }
+
+    @Override public String intendedStream(VideoLifecycleRecord record) {
+        String url = record.getUrl();
+        if (url == null || url.isBlank()) return null;
+        URI uri = URI.create(url);
+        return uri.getHost() != null && PROXY_SCHEMES.contains(String.valueOf(uri.getScheme()).toLowerCase(Locale.ROOT))
+                ? managedStream(record) : null;
+    }
+
+    @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);
+        }
+        return outcome("ACTIVE", Map.of("native", true, "url", uri.toString()), null, null);
+    }
+
+    @Override public Map<String, Object> cancel(VideoLifecycleRecord record) {
+        String key = record.getProxyKey();
+        if (key != null && !key.isBlank()) {
+            manual.stop(key);
+            return outcome("STOPPED", null, record.getStream(), key);
+        }
+        // 没有真实代理句柄:只可能是原生地址或尚未创建代理,均无媒体需要回收。
+        return outcome("STOPPED", null, record.getStream(), null);
+    }
+
+    /** 唯一物理流名:低于 64 字符且保持既有 manual_ 前缀,避免与旧停止校验冲突。 */
+    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;
+    }
+
+    private static Map<String, Object> outcome(String status, Map<String, Object> media, String stream, String proxyKey) {
+        Map<String, Object> result = new LinkedHashMap<>();
+        result.put("status", status);
+        if (media != null) result.put("media", media);
+        if (stream != null) result.put("stream", stream);
+        if (proxyKey != null) result.put("proxyKey", proxyKey);
+        return result;
+    }
+}

+ 45 - 0
video-service/src/main/java/com/zksy/video/lifecycle/RedisVideoLifecycleStore.java

@@ -0,0 +1,45 @@
+package com.zksy.video.lifecycle;
+
+import java.time.Duration;
+import java.util.regex.Pattern;
+import org.springframework.data.redis.core.RedisTemplate;
+import org.springframework.stereotype.Component;
+
+/**
+ * 用既有 RedisTemplate 保存代次意图。TTL 略长于主服务的观看回收窗口,
+ * 让取消墓碑在迟到 start 到达时仍然可见。
+ */
+@Component
+public class RedisVideoLifecycleStore implements VideoLifecycleStore {
+    private static final String PREFIX = "CITY_VIDEO_LIFECYCLE:";
+    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; }
+
+    @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;
+    }
+
+    @Override public void save(VideoLifecycleRecord record) {
+        if (record == null || !valid(record.getGeneration())) throw new IllegalArgumentException("观看代次标识无效");
+        redis.opsForValue().set(PREFIX + record.getGeneration(), record, TTL);
+    }
+
+    private static boolean valid(String generation) { return generation != null && GENERATION.matcher(generation).matches(); }
+
+    @Override public void markStreamCancelled(String stream) {
+        if (stream != null && STREAM.matcher(stream).matches())
+            redis.opsForValue().set(CANCELLED_PREFIX + stream, Boolean.TRUE, TTL);
+    }
+
+    @Override public boolean isStreamCancelled(String stream) {
+        return stream != null && Boolean.TRUE.equals(redis.opsForValue().get(CANCELLED_PREFIX + stream));
+    }
+}

+ 21 - 0
video-service/src/main/java/com/zksy/video/lifecycle/VideoLifecycleController.java

@@ -0,0 +1,21 @@
+package com.zksy.video.lifecycle;
+
+import java.util.Map;
+import org.springframework.web.bind.annotation.PostMapping;
+import org.springframework.web.bind.annotation.RequestBody;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RestController;
+import com.zksy.common.core.domain.AjaxResult;
+
+/** 主服务专用:只按代次协调真实媒体,复用既有 X-Video-Token 内部鉴权。 */
+@RestController
+@RequestMapping("/internal/video/lifecycle")
+public class VideoLifecycleController {
+    private final VideoLifecycleService service;
+
+    public VideoLifecycleController(VideoLifecycleService service) { this.service = service; }
+
+    @PostMapping("/start") public AjaxResult start(@RequestBody Map<String, Object> body) { return AjaxResult.success(service.start(body)); }
+    @PostMapping("/status") public AjaxResult status(@RequestBody Map<String, Object> body) { return AjaxResult.success(service.status(body)); }
+    @PostMapping("/cancel") public AjaxResult cancel(@RequestBody Map<String, Object> body) { return AjaxResult.success(service.cancel(body)); }
+}

+ 36 - 0
video-service/src/main/java/com/zksy/video/lifecycle/VideoLifecycleMedia.java

@@ -0,0 +1,36 @@
+package com.zksy.video.lifecycle;
+
+import java.util.Map;
+
+/**
+ * 媒体侧适配接缝。实现只负责“这一个代次的真实媒体句柄”,
+ * 不做共享计数或观看归属——那些属于主服务的 VideoSession。
+ */
+public interface VideoLifecycleMedia {
+
+    boolean supports(String sourceType);
+
+    /**
+     * 为该代次启动媒体。返回 {@code status} 与(仅 ACTIVE 时的){@code media}、{@code stream}/{@code proxyKey}。
+     * 不得在已取消的代次上创建任何媒体资源。
+     */
+    Map<String, Object> start(VideoLifecycleRecord record);
+
+    /**
+     * 本代次将会使用的媒体句柄(不调用媒体即可算出)。
+     * 先落库它,取消才能在“启动结果未知”时仍有精确回收目标。
+     */
+    default String intendedStream(VideoLifecycleRecord record) { return null; }
+
+    /**
+     * 查询该代次当前媒体是否已就绪。默认回显已记录状态(同步启动的适配器无需轮询)。
+     */
+    default Map<String, Object> status(VideoLifecycleRecord record) {
+        java.util.Map<String, Object> result = new java.util.LinkedHashMap<>();
+        result.put("status", record.getStatus());
+        return result;
+    }
+
+    /** 用已记录的真实句柄精确回收该代次;无法证明回收完成时返回 CLEANUP_PENDING。 */
+    Map<String, Object> cancel(VideoLifecycleRecord record);
+}

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

@@ -0,0 +1,29 @@
+package com.zksy.video.lifecycle;
+
+import lombok.Data;
+
+/**
+ * 单个观看代次的持久意图。cancel 先到会留下 {@link #cancelled} 墓碑,
+ * 之后同一 generation 的 start 一律不得复活媒体。
+ */
+@Data
+public class VideoLifecycleRecord {
+    /** 主服务生成的观看代次(UUID),媒体资源身份以它为准,不用设备号猜。 */
+    private String generation;
+    /** STARTING / ACTIVE / CLEANUP_PENDING / STOPPED / FAILED */
+    private String status;
+    /** GB28181 或 MANUAL。 */
+    private String sourceType;
+    private String videoId;
+    private String deviceId;
+    private String channelId;
+    /** MANUAL 源的拉流地址;GB28181 为空。 */
+    private String url;
+    /** 本次代次实际使用的媒体 stream;MANUAL 代理另记 proxyKey。 */
+    private String stream;
+    private String proxyKey;
+    /** 取消意图先落库;置位后任何后续 start 都不得创建媒体。 */
+    private boolean cancelled;
+    /** 启动截止时间(epoch millis)。 */
+    private Long deadline;
+}

+ 138 - 0
video-service/src/main/java/com/zksy/video/lifecycle/VideoLifecycleService.java

@@ -0,0 +1,138 @@
+package com.zksy.video.lifecycle;
+
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import org.springframework.stereotype.Service;
+
+/**
+ * 观看代次协调:意图先落库,媒体调用在后;cancel 是墓碑,永远优先于迟到的 start。
+ * 本类不复制主服务的观看归属/共享计数,只对“这一个代次的真实媒体句柄”负责。
+ */
+@Service
+public class VideoLifecycleService {
+    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 final VideoLifecycleStore store;
+    private final List<VideoLifecycleMedia> adapters;
+
+    public VideoLifecycleService(VideoLifecycleStore store, List<VideoLifecycleMedia> adapters) {
+        this.store = store; this.adapters = adapters;
+    }
+
+    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");
+        }
+        if (stored == null) {
+            String intended = media.intendedStream(record);
+            if (intended != null && record.getStream() == null) record.setStream(intended);
+            record.setStatus("STARTING");
+            store.save(record);                       // 意图先于任何媒体调用落库
+        } else {
+            if (TERMINAL.contains(stored.getStatus())) return result(stored, stored.getStatus(), null);
+            record = stored;
+        }
+        try {
+            return merge(record, media.start(record));
+        } catch (IllegalArgumentException invalid) {
+            return settle(record, "FAILED");          // 校验失败:确认未创建任何媒体
+        } catch (RuntimeException unknown) {
+            return settle(record, "CLEANUP_PENDING"); // 结果未知:既不谎报成功也不谎报已停
+        }
+    }
+
+    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> 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);
+        }
+    }
+
+    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> settle(VideoLifecycleRecord record, String state) {
+        record.setStatus(state); store.save(record); return result(record, state, null);
+    }
+
+    private VideoLifecycleMedia adapter(VideoLifecycleRecord record) {
+        return adapters.stream().filter(item -> item.supports(record.getSourceType())).findFirst()
+                .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) {
+        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("观看代次标识无效");
+        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());
+        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")));
+        }
+        return record;
+    }
+
+    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);
+        return result;
+    }
+}

+ 14 - 0
video-service/src/main/java/com/zksy/video/lifecycle/VideoLifecycleStore.java

@@ -0,0 +1,14 @@
+package com.zksy.video.lifecycle;
+
+/** 代次意图的持久存储:取消墓碑必须先于任何媒体调用落库。 */
+public interface VideoLifecycleStore {
+
+    VideoLifecycleRecord find(String generation);
+
+    void save(VideoLifecycleRecord record);
+
+    /** 记下被取消的 stream,供 ZLM 钩子拦住“流未找到就自动点播”的复活路径。 */
+    void markStreamCancelled(String stream);
+
+    boolean isStreamCancelled(String stream);
+}

+ 114 - 0
video-service/src/test/java/com/zksy/video/lifecycle/VideoLifecycleServiceTest.java

@@ -0,0 +1,114 @@
+package com.zksy.video.lifecycle;
+
+import java.util.HashMap;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.mockito.ArgumentCaptor;
+
+import static org.junit.jupiter.api.Assertions.*;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.*;
+
+/**
+ * 协调语义:cancel 是墓碑,迟到的 start 不得复活;回收只用真实句柄;
+ * 结果未知只能说 pending,不能谎报已停或已成功。
+ */
+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 VideoLifecycleMedia media;
+    private VideoLifecycleService service;
+
+    @BeforeEach void setUp() {
+        media = mock(VideoLifecycleMedia.class);
+        when(media.supports("GB28181")).thenReturn(true);
+        service = new VideoLifecycleService(store, List.of(media));
+    }
+
+    private static Map<String, Object> body(String generation) {
+        Map<String, Object> source = new LinkedHashMap<>();
+        source.put("type", "GB28181");
+        source.put("videoId", "cam-1");
+        source.put("deviceId", "34020000002000000001");
+        source.put("channelId", "34020000001320000001");
+        Map<String, Object> body = new LinkedHashMap<>();
+        body.put("generation", generation);
+        body.put("source", source);
+        body.put("startDeadline", 1_700_000_000_000L);
+        return body;
+    }
+
+    @Test void cancelBeforeStartLeavesATombstoneAndNoMediaIsEverCreated() {
+        assertEquals("CLEANUP_PENDING", service.cancel(body("gen-cancel-first")).get("status"));
+        Map<String, Object> started = service.start(body("gen-cancel-first"));
+        assertEquals("STOPPED", started.get("status"));
+        assertNull(started.get("media"));
+        verify(media, never()).start(any());
+    }
+
+    @Test void unknownStartResultKeepsTheIntendedHandleAndReportsPending() {
+        when(media.intendedStream(any())).thenReturn("34020000002000000001_34020000001320000001");
+        when(media.start(any())).thenThrow(new IllegalStateException("媒体结果未确认"));
+        Map<String, Object> started = service.start(body("gen-unknown"));
+        assertEquals("CLEANUP_PENDING", started.get("status"));
+        assertEquals("34020000002000000001_34020000001320000001", rows.get("gen-unknown").getStream());
+    }
+
+    @Test void cancelUsesTheRecordedHandleAndOnlyReportsStoppedWhenConfirmed() {
+        when(media.intendedStream(any())).thenReturn("stream-x");
+        when(media.start(any())).thenReturn(Map.of("status", "ACTIVE",
+                "media", Map.of("webrtc", "https://media.invalid/a"), "stream", "stream-x"));
+        assertEquals("ACTIVE", service.start(body("gen-active")).get("status"));
+        when(media.cancel(any())).thenReturn(Map.of("status", "STOPPED"));
+        assertEquals("STOPPED", service.cancel(body("gen-active")).get("status"));
+        ArgumentCaptor<VideoLifecycleRecord> captured = ArgumentCaptor.forClass(VideoLifecycleRecord.class);
+        verify(media).cancel(captured.capture());
+        assertEquals("stream-x", captured.getValue().getStream());
+        assertTrue(captured.getValue().isCancelled());
+    }
+
+    @Test void unconfirmedCleanupStaysPendingAndNeverClaimsStopped() {
+        when(media.intendedStream(any())).thenReturn("stream-y");
+        when(media.start(any())).thenReturn(Map.of("status", "STARTING"));
+        assertEquals("STARTING", service.start(body("gen-pending")).get("status"));
+        when(media.cancel(any())).thenReturn(Map.of("status", "CLEANUP_PENDING"));
+        assertEquals("CLEANUP_PENDING", service.cancel(body("gen-pending")).get("status"));
+        assertEquals("CLEANUP_PENDING", service.status(body("gen-pending")).get("status"));
+    }
+
+        @Test void cancelledStreamIsRecordedSoTheMediaHookCannotAutoRestartIt() {
+        when(media.intendedStream(any())).thenReturn("34020000002000000001_34020000001320000001");
+        when(media.start(any())).thenReturn(Map.of("status", "STARTING"));
+        service.start(body("gen-hook"));
+        service.cancel(body("gen-hook"));
+        assertTrue(store.isStreamCancelled("34020000002000000001_34020000001320000001"));
+    }
+
+    @SuppressWarnings("unchecked")
+    @Test void unsupportedSourceFailsCleanlyWithoutTouchingMedia() {
+        Map<String, Object> body = body("gen-unsupported");
+        ((Map<String, Object>) body.get("source")).put("type", "OTHER");
+        assertEquals("FAILED", service.start(body).get("status"));
+        verify(media, never()).start(any());
+    }
+
+    @Test void cancelledGenerationNeverPublishesMediaEvenWhenALateStartArrives() {
+        when(media.intendedStream(any())).thenReturn("stream-z");
+        when(media.start(any())).thenReturn(Map.of("status", "ACTIVE",
+                "media", Map.of("webrtc", "https://media.invalid/late")));
+        assertEquals("CLEANUP_PENDING", service.cancel(body("gen-late")).get("status"));
+        Map<String, Object> started = service.start(body("gen-late"));
+        assertEquals("STOPPED", started.get("status"));
+        assertNull(started.get("media"));
+        verify(media, never()).start(any());
+    }
+}