Explorar o código

feat(video): 先登记观看身份再启动媒体并共享代次回收

Kazerin hai 3 semanas
pai
achega
3d21a99549

+ 21 - 1
pipe-network-service/zksy-admin/src/main/java/com/zksy/web/controller/cockpit/CockpitVideoController.java

@@ -35,6 +35,25 @@ public class CockpitVideoController {
         return success(videos.live(field(body, "deviceCode")), request);
     }
 
+    @PostMapping("/sessions/prepare")
+    public ResponseEntity<AjaxResult> prepare(@RequestBody Map<String, Object> body, HttpServletRequest request) {
+        Map<String, Object> data = videos.prepare(field(body, "deviceCode"));
+        data.putAll(metadata(request));
+        return ResponseEntity.status(201).cacheControl(org.springframework.http.CacheControl.noStore()).body(AjaxResult.success(data));
+    }
+
+    @PostMapping("/sessions/{id}/live")
+    public ResponseEntity<AjaxResult> preparedLive(@PathVariable("id") String id,
+            @RequestBody Map<String, Object> body, HttpServletRequest request) {
+        return success(videos.startPrepared(sessionId(id), field(body, "sessionToken")), request);
+    }
+
+    @PostMapping("/sessions/{id}/status")
+    public ResponseEntity<AjaxResult> sessionStatus(@PathVariable("id") String id,
+            @RequestBody Map<String, Object> body, HttpServletRequest request) {
+        return success(videos.status(sessionId(id), field(body, "sessionToken")), request);
+    }
+
     @PostMapping("/sessions/{id}/heartbeat")
     public ResponseEntity<AjaxResult> heartbeat(@PathVariable("id") String id,
             @RequestBody Map<String, Object> body, HttpServletRequest request) {
@@ -68,7 +87,8 @@ public class CockpitVideoController {
 
     private ResponseEntity<AjaxResult> success(Map<String, Object> data, HttpServletRequest request) {
         data.putAll(metadata(request));
-        return ResponseEntity.ok().cacheControl(org.springframework.http.CacheControl.noStore()).body(AjaxResult.success(data));
+        int status = "STARTING".equals(data.get("status")) || "CLEANUP_PENDING".equals(data.get("status")) ? 202 : 200;
+        return ResponseEntity.status(status).cacheControl(org.springframework.http.CacheControl.noStore()).body(AjaxResult.success(data));
     }
 
     @ExceptionHandler(CockpitVideoException.class)

+ 367 - 0
pipe-network-service/zksy-admin/src/test/java/com/zksy/web/controller/cockpit/VideoPreparedSessionTest.java

@@ -0,0 +1,367 @@
+package com.zksy.web.controller.cockpit;
+
+import com.alibaba.fastjson2.JSON;
+import com.alibaba.fastjson2.JSONObject;
+import com.baomidou.mybatisplus.core.MybatisConfiguration;
+import com.baomidou.mybatisplus.core.metadata.TableInfoHelper;
+import com.zksy.base.domain.EquipmentBase;
+import com.zksy.base.mapper.EquipmentBaseMapper;
+import com.zksy.base.mapper.EquipmentVideoBindingMapper;
+import com.zksy.base.mapper.VideoSessionMapper;
+import com.zksy.base.video.VideoCollectorClient;
+import com.zksy.base.video.VideoDeviceRecord;
+import com.zksy.base.video.VideoSession;
+import org.apache.ibatis.builder.MapperBuilderAssistant;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.springframework.beans.BeanUtils;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.context.annotation.Import;
+import org.springframework.core.env.MapPropertySource;
+import org.springframework.http.MediaType;
+import org.springframework.mock.web.MockServletContext;
+import org.springframework.security.core.context.SecurityContextHolder;
+import org.springframework.test.web.servlet.MockMvc;
+import org.springframework.test.web.servlet.ResultActions;
+import org.springframework.test.web.servlet.setup.MockMvcBuilders;
+import org.springframework.transaction.support.AbstractPlatformTransactionManager;
+import org.springframework.transaction.support.DefaultTransactionStatus;
+import org.springframework.transaction.TransactionDefinition;
+import org.springframework.transaction.support.TransactionSynchronizationManager;
+import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
+
+import javax.servlet.Filter;
+import java.nio.charset.StandardCharsets;
+import java.util.ArrayList;
+import java.util.HashSet;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.stream.Collectors;
+
+import static org.junit.jupiter.api.Assertions.*;
+import static org.mockito.ArgumentMatchers.*;
+import static org.mockito.Mockito.*;
+import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
+import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
+
+/** Prepared lifecycle at HTTP + real security/service/transaction seams.
+ * DB rows/commit outcome and media transport are adapters; no shared-count algorithm is copied here.
+ */
+class VideoPreparedSessionTest {
+    private static final String ROOT = "/api/cockpit/v1/video";
+    private static final String CODE = "摄像机/ PREPARED+01";
+    private static final String VIDEO = "prepared-ledger-id";
+    private static final java.util.regex.Pattern UUID_PARAM = java.util.regex.Pattern.compile(
+            "[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}");
+    private AnnotationConfigWebApplicationContext context;
+    private MockMvc mvc;
+    private VideoSessionMapper sessions;
+    private VideoCollectorClient media;
+    private RowTransactions transactions;
+
+    @BeforeEach void setUp() {
+        SecurityContextHolder.clearContext();
+        TableInfoHelper.initTableInfo(new MapperBuilderAssistant(new MybatisConfiguration(), ""), VideoSession.class);
+        context = new AnnotationConfigWebApplicationContext();
+        context.setServletContext(new MockServletContext());
+        context.getEnvironment().getPropertySources().addFirst(new MapPropertySource("prepared-test", Map.of(
+                "token.header", "Authorization", "token.secret", "prepared-offline-contract-not-a-production-secret", "token.expireTime", "60")));
+        context.register(ConfigurationUnderTest.class);
+        context.refresh();
+        mvc = MockMvcBuilders.webAppContextSetup(context)
+                .addFilters(context.getBean("springSecurityFilterChain", Filter.class)).build();
+        sessions = context.getBean(VideoSessionMapper.class);
+        media = context.getBean(VideoCollectorClient.class);
+        transactions = context.getBean(RowTransactions.class);
+        EquipmentBase device = new EquipmentBase();
+        device.setEquipmentId(VIDEO); device.setEquipmentCode(CODE); device.setEquipmentName("准备态摄像机"); device.setEquipmentTypeId(20);
+        when(context.getBean(EquipmentBaseMapper.class).selectList(any())).thenReturn(List.of(device));
+        VideoDeviceRecord binding = new VideoDeviceRecord(); BeanUtils.copyProperties(device, binding);
+        binding.setVideoId(VIDEO); binding.setSourceType("GB28181");
+        binding.setGbDeviceId("34020000002000000001"); binding.setGbChannelId("34020000001320000001");
+        when(context.getBean(EquipmentVideoBindingMapper.class).find(VIDEO)).thenReturn(binding);
+        when(sessions.insert(any(VideoSession.class))).thenAnswer(call -> {
+            assertTrue(TransactionSynchronizationManager.isActualTransactionActive(), "identity must be persisted in a transaction");
+            VideoSession row = call.getArgument(0);
+            transactions.rows().put(row.getSessionId(), copy(row)); return 1;
+        });
+        when(sessions.selectById(anyString())).thenAnswer(call -> copy(transactions.rows().get(call.getArgument(0))));
+        when(sessions.updateById(any(VideoSession.class))).thenAnswer(call -> {
+            VideoSession row = call.getArgument(0);
+            return transactions.rows().replace(row.getSessionId(), copy(row)) == null ? 0 : 1;
+        });
+        when(sessions.lockVideo(VIDEO)).thenAnswer(call -> {
+            assertTrue(TransactionSynchronizationManager.isActualTransactionActive(), "device lock requires a short DB transaction");
+            return VIDEO;
+        });
+        // 内存适配器只做“数据库会给出的答案”,共享/代次判定仍在生产代码里。
+        when(sessions.selectList(any())).thenAnswer(call -> new ArrayList<>(
+                matching(paramsOf(call.getArgument(0))).stream().map(VideoPreparedSessionTest::copy).collect(Collectors.toList())));
+        when(sessions.selectCount(any())).thenAnswer(call -> (long) matching(paramsOf(call.getArgument(0))).size());
+    }
+
+    @AfterEach void close() {
+        if (context != null) context.close();
+        SecurityContextHolder.clearContext();
+    }
+
+    @Test void prepareCommitsKnownOwnershipBeforeAnyMediaAndStoppedIdentityCannotStartLater() throws Exception {
+        JSONObject viewer = JSON.parseObject(mvc.perform(post(ROOT + "/sessions/prepare")
+                .contentType(MediaType.APPLICATION_JSON).content(JSON.toJSONString(Map.of("deviceCode", CODE))))
+                .andExpect(status().isCreated()).andExpect(jsonPath("$.code").value(200))
+                .andExpect(jsonPath("$.data.status").value("PREPARED"))
+                .andExpect(jsonPath("$.data.deviceCode").value(CODE))
+                .andExpect(jsonPath("$.data.sessionId").isNotEmpty())
+                .andExpect(jsonPath("$.data.sessionToken").isNotEmpty())
+                .andExpect(jsonPath("$.data.media").doesNotExist())
+                .andExpect(jsonPath("$.data.mediaGeneration").doesNotExist())
+                .andReturn().getResponse().getContentAsString(StandardCharsets.UTF_8)).getJSONObject("data");
+        action(viewer, "status", viewer.getString("sessionToken")).andExpect(status().isOk())
+                .andExpect(jsonPath("$.data.status").value("PREPARED"));
+        action(viewer, "stop", "A".repeat(43)).andExpect(status().isForbidden());
+        action(viewer, "stop", viewer.getString("sessionToken")).andExpect(status().isOk())
+                .andExpect(jsonPath("$.data.status").value("STOPPED"));
+        action(viewer, "live", viewer.getString("sessionToken")).andExpect(status().isOk())
+                .andExpect(jsonPath("$.data.status").value("STOPPED"))
+                .andExpect(jsonPath("$.data.media").doesNotExist());
+        verifyNoInteractions(media);
+    }
+
+    @Test void knownIdentityStartsAndStopsOneExactGenerationOutsideSqlTransactions() throws Exception {
+        java.util.concurrent.atomic.AtomicReference<Map<String,Object>> started = new java.util.concurrent.atomic.AtomicReference<>();
+        when(media.post(eq("/internal/video/lifecycle/start"), any())).thenAnswer(call -> {
+            assertFalse(TransactionSynchronizationManager.isActualTransactionActive(), "never hold a DB transaction while starting media");
+            Map<String,Object> request = call.getArgument(1);
+            assertEquals(Map.of("type", "GB28181", "videoId", VIDEO, "deviceId", "34020000002000000001",
+                    "channelId", "34020000001320000001"), request.get("source"));
+            assertEquals(java.time.Instant.parse("2026-11-10T08:00:30Z").toEpochMilli(), request.get("startDeadline"));
+            assertTrue(request.get("generation") instanceof String);
+            assertNotNull(java.util.UUID.fromString((String) request.get("generation")));
+            started.set(new LinkedHashMap<>(request));
+            return Map.of("generation", request.get("generation"), "status", "ACTIVE", "media",
+                    Map.of("stream", "prepared_stream", "flv", "https://media.invalid/prepared.flv", "secret", "internal-secret"));
+        });
+        when(media.post(eq("/internal/video/lifecycle/status"), any())).thenAnswer(call -> {
+            assertFalse(TransactionSynchronizationManager.isActualTransactionActive(), "status must not hold a SQL lock");
+            Map<String,Object> request = call.getArgument(1);
+            assertEquals(started.get().get("generation"), request.get("generation"));
+            assertEquals(started.get().get("startDeadline"), request.get("startDeadline"));
+            return Map.of("generation", request.get("generation"), "status", "ACTIVE", "media",
+                    Map.of("stream", "prepared_stream", "flv", "https://media.invalid/prepared.flv"));
+        });
+        when(media.post(eq("/internal/video/lifecycle/cancel"), any())).thenAnswer(call -> {
+            assertFalse(TransactionSynchronizationManager.isActualTransactionActive(), "cancel must not hold a SQL lock");
+            Map<String,Object> request = call.getArgument(1);
+            assertEquals(started.get().get("generation"), request.get("generation"));
+            assertEquals(started.get().get("source"), request.get("source"));
+            return Map.of("generation", request.get("generation"), "status", "STOPPED");
+        });
+        JSONObject viewer = JSON.parseObject(mvc.perform(post(ROOT + "/sessions/prepare")
+                .contentType(MediaType.APPLICATION_JSON).content(JSON.toJSONString(Map.of("deviceCode", CODE))))
+                .andExpect(status().isCreated()).andReturn().getResponse().getContentAsString(StandardCharsets.UTF_8)).getJSONObject("data");
+        new org.springframework.transaction.support.TransactionTemplate(transactions).executeWithoutResult(transaction -> {
+            try {
+        action(viewer, "live", viewer.getString("sessionToken")).andExpect(status().isOk())
+                .andExpect(jsonPath("$.data.status").value("ACTIVE"))
+                .andExpect(jsonPath("$.data.media.flv").value("https://media.invalid/prepared.flv"))
+                .andExpect(jsonPath("$.data.media.secret").doesNotExist())
+                .andExpect(jsonPath("$.data.media.stream").doesNotExist())
+                .andExpect(jsonPath("$.data.generation").doesNotExist());
+        action(viewer, "status", viewer.getString("sessionToken")).andExpect(status().isOk())
+                .andExpect(jsonPath("$.data.status").value("ACTIVE"));
+        action(viewer, "stop", viewer.getString("sessionToken")).andExpect(status().isOk())
+                .andExpect(jsonPath("$.data.status").value("STOPPED"));
+        action(viewer, "live", viewer.getString("sessionToken")).andExpect(status().isOk())
+                .andExpect(jsonPath("$.data.status").value("STOPPED"));
+            } catch (Exception failure) { throw new RuntimeException(failure); }
+        });
+        verify(media, times(1)).post(eq("/internal/video/lifecycle/start"), any());
+        verify(media, times(1)).post(eq("/internal/video/lifecycle/cancel"), any());
+    }
+
+    @Test void failedIdentityRegistrationLeavesNoSessionAndStartsNoMedia() throws Exception {
+        when(sessions.insert(any(VideoSession.class))).thenReturn(0);
+        mvc.perform(post(ROOT + "/sessions/prepare")
+                .contentType(MediaType.APPLICATION_JSON).content(JSON.toJSONString(Map.of("deviceCode", CODE))))
+                .andExpect(status().isServiceUnavailable())
+                .andExpect(jsonPath("$.code").value(503))
+                .andExpect(jsonPath("$.data.category").value("VIDEO_PREPARE_FAILED"));
+        assertTrue(transactions.rows().isEmpty(), "登记失败不得留下半条会话");
+        verifyNoInteractions(media);
+    }
+
+    @Test void anAnonymousViewerJoinsTheLegacyGenerationAndLeavingDoesNotCancelTheSharedStream() throws Exception {
+        VideoSession legacy = seed("legacy-business-viewer", "ACTIVE", null, "legacy_stream");
+        legacy.setUserId(7L);        java.util.concurrent.atomic.AtomicReference<Map<String, Object>> started = new java.util.concurrent.atomic.AtomicReference<>();
+        when(media.post(eq("/internal/video/lifecycle/start"), any())).thenAnswer(call -> {
+            Map<String, Object> request = call.getArgument(1);
+            started.set(request);
+            return Map.of("generation", request.get("generation"), "status", "ACTIVE",
+                    "media", Map.of("stream", "legacy_stream", "flv", "https://media.invalid/legacy.flv"));
+        });
+        JSONObject viewer = prepare();
+        String liveBody = action(viewer, "live", viewer.getString("sessionToken"))
+                .andReturn().getResponse().getContentAsString(StandardCharsets.UTF_8);
+        assertTrue(liveBody.contains("\"status\":\"ACTIVE\""), "live 响应: " + liveBody);
+        assertNotNull(started.get(), "start 必须被调用一次");
+        assertEquals("legacy_stream", ((Map<?, ?>) started.get().get("existingMedia")).get("stream"),
+                "加入既有代次必须带上真实旧句柄,而不是重建");
+        VideoSession anonymous = transactions.rows().get(viewer.getString("sessionId"));
+        VideoSession storedLegacy = transactions.rows().get("legacy-business-viewer");
+        assertNotNull(storedLegacy.getMediaGeneration(), "旧观看者必须被并入一个代次");
+        assertEquals(storedLegacy.getMediaGeneration(), anonymous.getMediaGeneration(), "匿名观看必须加入同一代次");
+        assertEquals("legacy_stream", anonymous.getStreamId());
+
+        action(viewer, "stop", viewer.getString("sessionToken")).andExpect(status().isOk())
+                .andExpect(jsonPath("$.data.status").value("STOPPED"));
+        verify(media, never()).post(eq("/internal/video/lifecycle/cancel"), any());
+        assertEquals("ACTIVE", transactions.rows().get("legacy-business-viewer").getStatus(),
+                "还有另一位有效观看者时不得回收共享底流");
+    }
+
+    @Test void disagreeingLegacyHandlesRefuseTheStartInsteadOfGuessingOne() throws Exception {
+        seed("legacy-a", "ACTIVE", null, "legacy_stream_a");
+        seed("legacy-b", "ACTIVE", null, "legacy_stream_b");
+        JSONObject viewer = prepare();
+        action(viewer, "live", viewer.getString("sessionToken")).andExpect(status().isServiceUnavailable())
+                .andExpect(jsonPath("$.data.category").value("SESSION_HEARTBEAT_FAILED"));
+        verify(media, never()).post(eq("/internal/video/lifecycle/start"), any());
+        assertNull(transactions.rows().get(viewer.getString("sessionId")).getMediaGeneration(),
+                "句柄冲突时不得自行挑一个代次");
+    }
+
+    @Test void aLegacyActiveViewerWithoutAConfirmedHandleRefusesTheStart() throws Exception {
+        seed("legacy-no-handle", "ACTIVE", null, null);
+        JSONObject viewer = prepare();
+        action(viewer, "live", viewer.getString("sessionToken")).andExpect(status().isServiceUnavailable());
+        verify(media, never()).post(eq("/internal/video/lifecycle/start"), any());
+    }
+
+    @Test void aSessionFailedByTheProviderCannotBeRevivedByALaterStart() throws Exception {
+        when(media.post(eq("/internal/video/lifecycle/start"), any())).thenAnswer(call -> {
+            Map<String, Object> request = call.getArgument(1);
+            return Map.of("generation", request.get("generation"), "status", "STARTING");
+        });
+        when(media.post(eq("/internal/video/lifecycle/cancel"), any())).thenAnswer(call -> {
+            Map<String, Object> request = call.getArgument(1);
+            return Map.of("generation", request.get("generation"), "status", "FAILED");
+        });
+        JSONObject viewer = prepare();
+        action(viewer, "live", viewer.getString("sessionToken")).andExpect(status().isAccepted());
+        action(viewer, "stop", viewer.getString("sessionToken")).andExpect(status().isOk())
+                .andExpect(jsonPath("$.data.status").value("FAILED"));
+        action(viewer, "live", viewer.getString("sessionToken")).andExpect(status().isOk())
+                .andExpect(jsonPath("$.data.status").value("FAILED"))
+                .andExpect(jsonPath("$.data.media").doesNotExist());
+        verify(media, times(1)).post(eq("/internal/video/lifecycle/start"), any());
+    }
+
+    /** 预置一位已有观看者(可来自旧业务用户),用于混合观看与旧句柄场景。 */
+    private VideoSession seed(String sessionId, String status, String generation, String stream) {
+        VideoSession row = new VideoSession();
+        row.setSessionId(sessionId); row.setVideoId(VIDEO); row.setMode("LIVE"); row.setStatus(status);
+        row.setMediaGeneration(generation); row.setStreamId(stream);
+        row.setGbDeviceId("34020000002000000001"); row.setGbChannelId("34020000001320000001");
+        java.time.LocalDateTime now = java.time.LocalDateTime.ofInstant(
+                java.time.Instant.parse("2026-11-10T08:00:00Z"), java.time.ZoneOffset.UTC);
+        row.setCreateTime(now); row.setLastSeen(now);
+        row.setStartDeadline(java.time.LocalDateTime.ofInstant(
+                java.time.Instant.parse("2026-11-10T08:00:30Z"), java.time.ZoneOffset.UTC));
+        transactions.rows().put(sessionId, row);
+        return row;
+    }
+
+    private JSONObject prepare() throws Exception {
+        return JSON.parseObject(mvc.perform(post(ROOT + "/sessions/prepare")
+                .contentType(MediaType.APPLICATION_JSON).content(JSON.toJSONString(Map.of("deviceCode", CODE))))
+                .andExpect(status().isCreated()).andReturn().getResponse().getContentAsString(StandardCharsets.UTF_8))
+                .getJSONObject("data");
+    }
+
+    /**
+     * 以 wrapper 的参数值还原生产查询的过滤条件(video_id、mode、status IN、media_generation、session_id <>)。
+     * 区分方式:sessionId 是已存在行的主键,代次不是。
+     */
+    @SuppressWarnings({ "unchecked", "rawtypes" })
+    private static Map<String, Object> paramsOf(Object wrapper) {
+        com.baomidou.mybatisplus.core.conditions.AbstractWrapper raw =
+                (com.baomidou.mybatisplus.core.conditions.AbstractWrapper) wrapper;
+        raw.getSqlSegment();   // 先生成片段,MyBatis-Plus 才会填充参数表
+        return raw.getParamNameValuePairs();
+    }
+
+    private List<VideoSession> matching(Map<String, Object> parameters) {
+        Set<Object> params = new HashSet<>(parameters.values());
+        Set<String> statuses = params.stream()
+                .filter(value -> value instanceof String && Set.of("STARTING", "ACTIVE", "CLEANUP_PENDING").contains(value))
+                .map(String.class::cast).collect(Collectors.toSet());
+        Set<String> uuids = params.stream()
+                .filter(value -> value instanceof String && UUID_PARAM.matcher((String) value).matches())
+                .map(String.class::cast).collect(Collectors.toSet());
+        Set<String> excluded = uuids.stream().filter(transactions.rows()::containsKey).collect(Collectors.toSet());
+        Set<String> generations = new HashSet<>(uuids);
+        generations.removeAll(excluded);
+        List<VideoSession> found = new ArrayList<>();
+        for (VideoSession row : transactions.rows().values()) {
+            if (!params.contains(row.getVideoId())) continue;
+            if (params.contains("LIVE") && !"LIVE".equals(row.getMode())) continue;
+            if (!statuses.isEmpty() && !statuses.contains(row.getStatus())) continue;
+            if (excluded.contains(row.getSessionId())) continue;
+            if (!generations.isEmpty() && !generations.contains(row.getMediaGeneration())) continue;
+            found.add(row);
+        }
+        return found;
+    }
+
+    private ResultActions action(JSONObject viewer, String action, String token) throws Exception {
+        return mvc.perform(post(ROOT + "/sessions/{id}/" + action, viewer.getString("sessionId"))
+                .contentType(MediaType.APPLICATION_JSON).content(JSON.toJSONString(Map.of("sessionToken", token))));
+    }
+
+    private static VideoSession copy(VideoSession source) {
+        if (source == null) return null;
+        VideoSession copy = new VideoSession(); BeanUtils.copyProperties(source, copy); return copy;
+    }
+
+    @Configuration
+    @Import(CockpitVideoControllerTest.HttpConfiguration.class)
+    static class ConfigurationUnderTest {
+        @Bean RowTransactions transactionManager() { return new RowTransactions(); }
+    }
+
+    /** Transactional row storage, with no video selection/counting or lifecycle decisions. */
+    static class RowTransactions extends AbstractPlatformTransactionManager {
+        private final Map<String, VideoSession> committed = new LinkedHashMap<>();
+        private final ThreadLocal<Map<String, VideoSession>> originals = new ThreadLocal<>();
+        private final ThreadLocal<Map<String, VideoSession>> pending = new ThreadLocal<>();
+        Map<String, VideoSession> rows() { return pending.get() == null ? committed : pending.get(); }
+        @Override protected Object doGetTransaction() { return new Object(); }
+        @Override protected boolean isExistingTransaction(Object transaction) { return pending.get() != null; }
+        @Override protected void doBegin(Object transaction, TransactionDefinition definition) {
+            Map<String, VideoSession> snapshot = new LinkedHashMap<>();
+            committed.forEach((id, row) -> snapshot.put(id, copy(row)));
+            originals.set(new LinkedHashMap<>(snapshot)); pending.set(snapshot);
+        }
+        @Override protected void doCommit(DefaultTransactionStatus status) {
+            // A read-only outer transaction must not overwrite independently committed inner writes.
+            originals.get().keySet().stream().filter(id -> !pending.get().containsKey(id)).forEach(committed::remove);
+            pending.get().forEach((id, row) -> {
+                if (!java.util.Objects.equals(row, originals.get().get(id))) committed.put(id, copy(row));
+            });
+        }
+        @Override protected void doRollback(DefaultTransactionStatus status) { }
+        @Override protected Object doSuspend(Object transaction) {
+            Object[] state = {pending.get(), originals.get()}; pending.remove(); originals.remove(); return state;
+        }
+        @SuppressWarnings("unchecked")
+        @Override protected void doResume(Object transaction, Object suspended) {
+            Object[] state = (Object[]) suspended;
+            pending.set((Map<String, VideoSession>) state[0]); originals.set((Map<String, VideoSession>) state[1]);
+        }
+        @Override protected void doCleanupAfterCompletion(Object transaction) { pending.remove(); originals.remove(); }
+    }
+}

+ 3 - 0
pipe-network-service/zksy-framework/src/main/java/com/zksy/framework/config/SecurityConfig.java

@@ -125,6 +125,9 @@ public class SecurityConfig
                 // Video is a narrow anonymous exception, before any broad GET/annotation rule.
                 requests.antMatchers(HttpMethod.GET, "/api/cockpit/v1/video/device").permitAll()
                     .antMatchers(HttpMethod.POST, "/api/cockpit/v1/video/live",
+                        "/api/cockpit/v1/video/sessions/prepare",
+                        "/api/cockpit/v1/video/sessions/*/live",
+                        "/api/cockpit/v1/video/sessions/*/status",
                         "/api/cockpit/v1/video/sessions/*/heartbeat",
                         "/api/cockpit/v1/video/sessions/*/stop").permitAll()
                     .antMatchers("/api/cockpit/v1/video/**").authenticated();

+ 53 - 0
pipe-network-service/zksy-system/src/main/java/com/zksy/base/video/VideoDeviceService.java

@@ -49,11 +49,13 @@ public class VideoDeviceService {
     private final EquipmentBaseService equipmentService;
     private final Clock clock;
     private TransactionTemplate rollbackCleanup;
+    private final com.zksy.cockpit.video.VideoLiveLifecycle liveLifecycle;
 
     @org.springframework.beans.factory.annotation.Autowired(required=false)
     void configureRollbackCleanup(PlatformTransactionManager manager) {
         rollbackCleanup=new TransactionTemplate(manager);
         rollbackCleanup.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
+        liveLifecycle.configure(manager);
     }
 
     @org.springframework.beans.factory.annotation.Autowired
@@ -68,6 +70,7 @@ public class VideoDeviceService {
         this.collector=collector;
         this.sessions=sessions;
         this.equipmentService=equipmentService;
+        this.liveLifecycle=new com.zksy.cockpit.video.VideoLiveLifecycle(sessions, bindings, collector, clock);
     }
 
     public Page<VideoDeviceRecord> list(int pageNum,int pageSize,String query,String sourceType,String stationId) {
@@ -172,6 +175,56 @@ public class VideoDeviceService {
         return data;
     }
 
+    @SuppressWarnings("unchecked")
+    /** Persist anonymous ownership before any request is allowed to allocate media. */
+    public Map<String,Object> prepareAnonymous(String id) {
+        byte[] secret = new byte[32];
+        RANDOM.nextBytes(secret);
+        String token = Base64.getUrlEncoder().withoutPadding().encodeToString(secret);
+        if (rollbackCleanup == null) throw new ServiceException("视频事务未配置");
+        VideoSession session = rollbackCleanup.execute(transaction -> {
+            find(id);
+            VideoSession prepared = new VideoSession();
+            prepared.setSessionId(UUID.randomUUID().toString());
+            prepared.setVideoId(id);
+            prepared.setAnonymousTokenHash(tokenHash(token));
+            prepared.setMode("LIVE");
+            prepared.setStatus("PREPARED");
+            prepared.setCreateTime(LocalDateTime.now(clock));
+            prepared.setLastSeen(prepared.getCreateTime());
+            if (sessions.insert(prepared) != 1) throw new ServiceException("播放会话登记失败");
+            return prepared;
+        });
+        Map<String,Object> data = sessionState(session);
+        data.put("sessionToken", token);
+        return data;
+    }
+
+    public Map<String,Object> anonymousState(String id, String token) {
+        return liveLifecycle.status(() -> ownedAnonymous(id, token));
+    }
+
+    public Map<String,Object> startPrepared(String id, String token) {
+        return liveLifecycle.start(() -> ownedAnonymous(id, token));
+    }
+
+    @Transactional
+    public Map<String,Object> stopAnonymousState(String id, String token) {
+        VideoSession current = ownedAnonymous(id, token);
+        if ("PREPARED".equals(current.getStatus()) || current.getMediaGeneration() != null)
+            return liveLifecycle.stop(() -> ownedAnonymous(id, token));
+        if (!"STOPPED".equals(current.getStatus()) && !"FAILED".equals(current.getStatus())) stop(id, token);
+        return sessionState(ownedAnonymous(id, token));
+    }
+
+    private static Map<String,Object> sessionState(VideoSession session) {
+        Map<String,Object> data = new LinkedHashMap<>();
+        data.put("sessionId", session.getSessionId());
+        data.put("status", session.getStatus());
+        data.put("mode", session.getMode());
+        return data;
+    }
+
     @SuppressWarnings("unchecked")
     private Map<String,Object> startSession(String id,VideoRequests.Range range,Long userId,String anonymousTokenHash) {
         VideoDeviceRecord row=find(id);

+ 5 - 0
pipe-network-service/zksy-system/src/main/java/com/zksy/base/video/VideoSession.java

@@ -21,6 +21,11 @@ public class VideoSession {
     private String gbDeviceId;
     private String gbChannelId;
     private String status;
+    @com.fasterxml.jackson.annotation.JsonIgnore
+    @com.alibaba.fastjson2.annotation.JSONField(serialize = false, deserialize = false)
+    @lombok.ToString.Exclude
+    private String mediaGeneration;
+    private LocalDateTime startDeadline;
     private LocalDateTime createTime;
     private LocalDateTime lastSeen;
     private LocalDateTime endTime;

+ 43 - 2
pipe-network-service/zksy-system/src/main/java/com/zksy/cockpit/video/CockpitVideoService.java

@@ -73,6 +73,30 @@ public class CockpitVideoService {
         return data;
     }
 
+    public Map<String, Object> prepare(String code) {
+        EquipmentBase device = findDevice(code);
+        if (!liveSupported(findBinding(device)))
+            throw new CockpitVideoException(409, "VIDEO_UNAVAILABLE", "设备未绑定或实时视频能力未确认");
+        try {
+            Map<String, Object> data = videos.prepareAnonymous(device.getEquipmentId());
+            data.put("deviceCode", device.getEquipmentCode());
+            data.put("deviceName", device.getEquipmentName());
+            return data;
+        } catch (RuntimeException failure) {
+            throw new CockpitVideoException(503, "VIDEO_PREPARE_FAILED", "观看会话准备失败,尚未启动媒体");
+        }
+    }
+
+    public Map<String, Object> startPrepared(String id, String token) {
+        try { return preparedResult(videos.startPrepared(id, token), id, token); }
+        catch (RuntimeException failure) { throw sessionError(failure, false); }
+    }
+
+    public Map<String, Object> status(String id, String token) {
+        try { return preparedResult(videos.anonymousState(id, token), id, token); }
+        catch (RuntimeException failure) { throw sessionError(failure, false); }
+    }
+
     public Map<String, Object> heartbeat(String id, String token) {
         try {
             videos.heartbeat(id, token);
@@ -84,11 +108,27 @@ public class CockpitVideoService {
 
     public Map<String, Object> stop(String id, String token) {
         try {
-            videos.stop(id, token);
+            return preparedResult(videos.stopAnonymousState(id, token), id, token);
         } catch (RuntimeException failure) {
             throw sessionError(failure, true);
         }
-        return sessionState(id, "STOPPED");
+    }
+
+    private Map<String, Object> preparedResult(Map<String, Object> raw, String id, String token) {
+        Map<String, Object> data = new LinkedHashMap<>();
+        for (String field : List.of("sessionId", "status", "mode")) data.put(field, raw.get(field));
+        if (raw.get("media") instanceof Map) {
+            VideoDeviceRecord binding = bindings.find((String) raw.get("videoId"));
+            @SuppressWarnings("unchecked") Map<String, Object> source = (Map<String, Object>) raw.get("media");
+            Map<String, Object> media = binding == null ? Map.of() : CockpitVideoMedia.publish(source, binding);
+            if (media.isEmpty()) {
+                Map<String, Object> stopped = videos.stopAnonymousState(id, token);
+                if ("CLEANUP_PENDING".equals(stopped.get("status"))) return preparedResult(stopped, id, token);
+                throw new CockpitVideoException(502, "VIDEO_START_FAILED", "未取得可公开播放的媒体地址");
+            }
+            data.put("media", media);
+        }
+        return data;
     }
 
     private static Map<String, Object> sessionState(String id, String state) {
@@ -99,6 +139,7 @@ public class CockpitVideoService {
     }
 
     private static CockpitVideoException sessionError(RuntimeException error, boolean stop) {
+        if (error instanceof CockpitVideoException) return (CockpitVideoException) error;
         // 01's public compatibility seam has no typed codes. Match only its two fixed ownership outcomes.
         if (error instanceof ServiceException && "播放会话不存在或无权操作".equals(error.getMessage()))
             return new CockpitVideoException(403, "SESSION_FORBIDDEN", "播放会话不存在或无权操作");

+ 251 - 0
pipe-network-service/zksy-system/src/main/java/com/zksy/cockpit/video/VideoLiveLifecycle.java

@@ -0,0 +1,251 @@
+package com.zksy.cockpit.video;
+
+import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
+import com.zksy.base.mapper.EquipmentVideoBindingMapper;
+import com.zksy.base.mapper.VideoSessionMapper;
+import com.zksy.base.video.VideoCollectorClient;
+import com.zksy.base.video.VideoDeviceRecord;
+import com.zksy.base.video.VideoSession;
+import com.zksy.common.exception.ServiceException;
+import org.springframework.transaction.PlatformTransactionManager;
+import org.springframework.transaction.TransactionDefinition;
+import org.springframework.transaction.support.TransactionTemplate;
+
+import java.net.URI;
+import java.time.Clock;
+import java.time.LocalDateTime;
+import java.time.ZoneOffset;
+import java.util.*;
+import java.util.function.Supplier;
+
+/** LIVE generation coordination. Every collector call occurs after intent commit, outside even a caller's transaction. */
+public final class VideoLiveLifecycle {
+    private static final Set<String> TERMINAL = Set.of("STOPPED", "FAILED");
+    private static final Set<String> PROVIDER_STATES = Set.of("STARTING", "ACTIVE", "CLEANUP_PENDING", "STOPPED", "FAILED");
+    private final VideoSessionMapper sessions;
+    private final EquipmentVideoBindingMapper bindings;
+    private final VideoCollectorClient collector;
+    private final Clock clock;
+    private TransactionTemplate shortTransaction;
+    private TransactionTemplate outsideTransaction;
+
+    public VideoLiveLifecycle(VideoSessionMapper sessions, EquipmentVideoBindingMapper bindings,
+            VideoCollectorClient collector, Clock clock) {
+        this.sessions = sessions; this.bindings = bindings; this.collector = collector; this.clock = clock;
+    }
+
+    public void configure(PlatformTransactionManager manager) {
+        shortTransaction = new TransactionTemplate(manager);
+        shortTransaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
+        outsideTransaction = new TransactionTemplate(manager);
+        outsideTransaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_NOT_SUPPORTED);
+    }
+
+    public VideoSession prepare(String videoId, Long userId, String tokenHash) {
+        return outside(() -> transaction(() -> {
+            binding(videoId);
+            VideoSession row = new VideoSession();
+            row.setSessionId(UUID.randomUUID().toString()); row.setVideoId(videoId);
+            row.setUserId(userId); row.setAnonymousTokenHash(tokenHash);
+            row.setMode("LIVE"); row.setStatus("PREPARED");
+            row.setCreateTime(LocalDateTime.now(clock)); row.setLastSeen(row.getCreateTime());
+            if (sessions.insert(row) != 1) throw new ServiceException("播放会话登记失败");
+            return row;
+        }));
+    }
+
+    public Map<String,Object> start(Supplier<VideoSession> owned) {
+        return outside(() -> {
+            VideoSession intent = transaction(() -> {
+                VideoSession row = locked(owned);
+                if (TERMINAL.contains(row.getStatus())) return row;
+                if ("PREPARED".equals(row.getStatus()) && expired(row)) return finish(row, "FAILED");
+                if ("PREPARED".equals(row.getStatus())) bindGeneration(row, true);
+                return row;
+            });
+            if (TERMINAL.contains(intent.getStatus())) return result(intent, null);
+            if ("CLEANUP_PENDING".equals(intent.getStatus()) || expired(intent)) return stop(owned);
+            return invoke("ACTIVE".equals(intent.getStatus()) ? "status" : "start", owned, intent);
+        });
+    }
+
+    public Map<String,Object> status(Supplier<VideoSession> owned) {
+        return outside(() -> {
+            VideoSession row = owned.get();
+            if (TERMINAL.contains(row.getStatus())) return result(row, null);
+            if (expired(row) || "CLEANUP_PENDING".equals(row.getStatus())) return stop(owned);
+            if ("PREPARED".equals(row.getStatus())) return result(row, null);
+            if (row.getMediaGeneration() == null) row = transaction(() -> {
+                VideoSession locked = locked(owned); bindGeneration(locked, false); return locked;
+            });
+            return invoke("status", owned, row);
+        });
+    }
+
+    public Map<String,Object> stop(Supplier<VideoSession> owned) {
+        return outside(() -> {
+            VideoSession intent = transaction(() -> {
+                VideoSession row = locked(owned);
+                if (TERMINAL.contains(row.getStatus())) return row;
+                if ("PREPARED".equals(row.getStatus())) return finish(row, "STOPPED");
+                if (row.getMediaGeneration() == null) bindGeneration(row, false);
+                row.setStatus("CLEANUP_PENDING"); update(row);
+                long others = sessions.selectCount(new LambdaQueryWrapper<VideoSession>()
+                        .eq(VideoSession::getVideoId, row.getVideoId()).eq(VideoSession::getMode, "LIVE")
+                        .eq(VideoSession::getMediaGeneration, row.getMediaGeneration())
+                        .in(VideoSession::getStatus, "STARTING", "ACTIVE").ne(VideoSession::getSessionId, row.getSessionId()));
+                return others > 0 ? finish(row, "STOPPED") : row;
+            });
+            if (TERMINAL.contains(intent.getStatus())) return result(intent, null);
+            return invoke("cancel", owned, intent);
+        });
+    }
+
+    /** Called under the device row lock. Never pick an arbitrary row when generations or handles disagree. */
+    private void bindGeneration(VideoSession row, boolean activating) {
+        VideoDeviceRecord source = binding(row.getVideoId());
+        List<VideoSession> resources = new ArrayList<>(sessions.selectList(new LambdaQueryWrapper<VideoSession>()
+                .eq(VideoSession::getVideoId, row.getVideoId()).eq(VideoSession::getMode, "LIVE")
+                .in(VideoSession::getStatus, "STARTING", "ACTIVE", "CLEANUP_PENDING")));
+        if (!"PREPARED".equals(row.getStatus()) && resources.stream().noneMatch(value -> row.getSessionId().equals(value.getSessionId())))
+            resources.add(row);
+        if (activating && resources.stream().anyMatch(value -> "CLEANUP_PENDING".equals(value.getStatus())))
+            throw new ServiceException("视频资源回收中,请等待确认");
+        Set<String> generations = new HashSet<>(), streams = new HashSet<>(), keys = new HashSet<>();
+        Set<LocalDateTime> deadlines = new HashSet<>();
+        boolean nativeSource = nativeSource(source);
+        for (VideoSession value : resources) {
+            if (value.getMediaGeneration() != null) generations.add(value.getMediaGeneration());
+            if (value.getStartDeadline() != null) deadlines.add(value.getStartDeadline());
+            if ("GB28181".equals(source.getSourceType()) && (!Objects.equals(source.getGbDeviceId(), value.getGbDeviceId())
+                    || !Objects.equals(source.getGbChannelId(), value.getGbChannelId())))
+                throw new ServiceException("现存视频来源不一致,需人工核查");
+            if (value.getStreamId() != null) streams.add(value.getStreamId());
+            if (!"GB28181".equals(source.getSourceType()) && value.getProxyKey() != null) keys.add(value.getProxyKey());
+            if (value.getMediaGeneration() == null && "ACTIVE".equals(value.getStatus()) && !nativeSource) {
+                if (!safeStream(value.getStreamId()) || (!"GB28181".equals(source.getSourceType())
+                        && (value.getProxyKey() == null || value.getProxyKey().isBlank())))
+                    throw new ServiceException("旧视频资源句柄未确认,需人工核查");
+            }
+        }
+        if (generations.size() > 1 || deadlines.size() > 1 || streams.size() > 1 || keys.size() > 1)
+            throw new ServiceException("现存视频代次或句柄不一致,需人工核查");
+        String generation = generations.isEmpty() ? UUID.randomUUID().toString() : generations.iterator().next();
+        LocalDateTime deadline = deadlines.isEmpty() ? LocalDateTime.ofInstant(clock.instant().plusSeconds(30), ZoneOffset.UTC)
+                : deadlines.iterator().next();
+        for (VideoSession value : resources) if (value.getMediaGeneration() == null) {
+            value.setMediaGeneration(generation); value.setStartDeadline(deadline); update(value);
+        }
+        row.setMediaGeneration(generation); row.setStartDeadline(deadline);
+        row.setGbDeviceId("GB28181".equals(source.getSourceType()) ? source.getGbDeviceId() : null);
+        row.setGbChannelId("GB28181".equals(source.getSourceType()) ? source.getGbChannelId() : null);
+        if (!streams.isEmpty()) row.setStreamId(streams.iterator().next());
+        if (!keys.isEmpty()) row.setProxyKey(keys.iterator().next());
+        if (activating) row.setStatus("STARTING");
+        update(row);
+    }
+
+    private Map<String,Object> invoke(String action, Supplier<VideoSession> owned, VideoSession intent) {
+        Map<String,Object> response = null;
+        try {
+            Object raw = collector.post("/internal/video/lifecycle/" + action, request(intent));
+            if (raw instanceof Map) response = cast(raw);
+        } catch (RuntimeException transportUnknown) {
+            // A transport failure cannot establish whether this generation was created or stopped.
+        }
+        Map<String,Object> observed = response;
+        return transaction(() -> {
+            VideoSession current = locked(owned);
+            if (!Objects.equals(current.getMediaGeneration(), intent.getMediaGeneration()) || TERMINAL.contains(current.getStatus()))
+                return result(current, null);
+            if (observed == null || !Objects.equals(intent.getMediaGeneration(), observed.get("generation"))
+                    || !PROVIDER_STATES.contains(observed.get("status"))) return result(current, null);
+            String state = (String) observed.get("status");
+            if ("CLEANUP_PENDING".equals(current.getStatus()) && !TERMINAL.contains(state)) return result(current, null);
+            if (TERMINAL.contains(state)) return result(finish(current, state), null);
+            if ("CLEANUP_PENDING".equals(state)) {
+                current.setStatus(state); update(current); return result(current, null);
+            }
+            if ("ACTIVE".equals(state) && observed.get("media") instanceof Map) {
+                Map<String,Object> media = cast(observed.get("media"));
+                if (!validMedia(binding(current.getVideoId()), media)) return result(current, null);
+                boolean newlyActive = !"ACTIVE".equals(current.getStatus());
+                current.setStatus("ACTIVE");
+                current.setStreamId(media.get("stream") instanceof String ? (String) media.get("stream") : null);
+                current.setProxyKey(media.get("proxyKey") instanceof String ? (String) media.get("proxyKey") : null);
+                if (newlyActive) current.setLastSeen(LocalDateTime.now(clock));
+                update(current);
+                return result(current, media);
+            }
+            return result(current, null);
+        });
+    }
+
+    private Map<String,Object> request(VideoSession row) {
+        VideoDeviceRecord binding = binding(row.getVideoId());
+        Map<String,Object> source = new LinkedHashMap<>();
+        source.put("type", binding.getSourceType()); source.put("videoId", row.getVideoId());
+        if ("GB28181".equals(binding.getSourceType())) {
+            source.put("deviceId", binding.getGbDeviceId()); source.put("channelId", binding.getGbChannelId());
+        } else source.put("url", binding.getVideoUrl());
+        Map<String,Object> body = new LinkedHashMap<>();
+        body.put("generation", row.getMediaGeneration()); body.put("source", source);
+        body.put("startDeadline", row.getStartDeadline().toInstant(ZoneOffset.UTC).toEpochMilli());
+        if (!nativeSource(binding) && row.getStreamId() != null) {
+            Map<String,Object> existing = new LinkedHashMap<>(); existing.put("stream", row.getStreamId());
+            if (!"GB28181".equals(binding.getSourceType()) && row.getProxyKey() != null) existing.put("proxyKey", row.getProxyKey());
+            body.put("existingMedia", existing);
+        }
+        return body;
+    }
+
+    private boolean expired(VideoSession row) {
+        if ("STARTING".equals(row.getStatus())) return row.getStartDeadline() == null
+                || !clock.instant().isBefore(row.getStartDeadline().toInstant(ZoneOffset.UTC));
+        return ("PREPARED".equals(row.getStatus()) || "ACTIVE".equals(row.getStatus()))
+                && (row.getLastSeen() == null || row.getLastSeen().isBefore(LocalDateTime.now(clock).minusSeconds(120)));
+    }
+
+    private VideoSession locked(Supplier<VideoSession> owned) {
+        VideoSession before = owned.get(); sessions.lockVideo(before.getVideoId()); return owned.get();
+    }
+    private VideoSession finish(VideoSession row, String state) {
+        row.setStatus(state); row.setEndTime(LocalDateTime.now(clock)); update(row); return row;
+    }
+    private void update(VideoSession row) {
+        if (sessions.updateById(row) != 1) throw new ServiceException("播放会话状态登记失败");
+    }
+    private VideoDeviceRecord binding(String id) {
+        VideoDeviceRecord value = bindings.find(id);
+        if (value == null) throw new ServiceException("视频设备不存在");
+        return value;
+    }
+    private static boolean nativeSource(VideoDeviceRecord source) {
+        return "MANUAL".equals(source.getSourceType()) && source.getVideoUrl() != null
+                && !URI.create(source.getVideoUrl()).getScheme().toLowerCase(Locale.ROOT).startsWith("rt");
+    }
+    private static boolean safeStream(String value) { return value != null && value.matches("[A-Za-z0-9_-]{1,200}"); }
+    private static boolean validMedia(VideoDeviceRecord source, Map<String,Object> media) {
+        boolean address = List.of("url", "flv", "https_flv", "ws_flv", "wss_flv", "hls", "https_hls", "webrtc", "rtc", "rtcs")
+                .stream().map(media::get).anyMatch(value -> {
+                    try {
+                        URI uri = URI.create((String) value);
+                        return uri.getHost() != null && Set.of("http", "https", "ws", "wss").contains(uri.getScheme().toLowerCase(Locale.ROOT));
+                    } catch (RuntimeException invalid) { return false; }
+                });
+        return address && (nativeSource(source) || media.get("stream") instanceof String && safeStream((String) media.get("stream")))
+                && (nativeSource(source) || "GB28181".equals(source.getSourceType())
+                    || media.get("proxyKey") instanceof String && !((String) media.get("proxyKey")).isBlank());
+    }
+    private static Map<String,Object> result(VideoSession row, Map<String,Object> media) {
+        Map<String,Object> result = new LinkedHashMap<>();
+        result.put("sessionId", row.getSessionId()); result.put("status", row.getStatus());
+        result.put("mode", row.getMode()); result.put("videoId", row.getVideoId());
+        if (media != null) result.put("media", media);
+        return result;
+    }
+    @SuppressWarnings("unchecked") private static Map<String,Object> cast(Object value) { return (Map<String,Object>) value; }
+    // Plain constructor calls remain useful for legacy offline fixtures; production configures the real manager.
+    private <T> T transaction(Supplier<T> work) { return shortTransaction == null ? work.get() : shortTransaction.execute(status -> work.get()); }
+    private <T> T outside(Supplier<T> work) { return outsideTransaction == null ? work.get() : outsideTransaction.execute(status -> work.get()); }
+}

+ 87 - 0
pipe-network-service/zksy-system/src/test/java/com/zksy/cockpit/video/VideoLiveSharingTest.java

@@ -0,0 +1,87 @@
+package com.zksy.cockpit.video;
+
+import com.zksy.base.mapper.EquipmentVideoBindingMapper;
+import com.zksy.base.mapper.VideoSessionMapper;
+import com.zksy.base.video.VideoCollectorClient;
+import com.zksy.base.video.VideoDeviceRecord;
+import com.zksy.base.video.VideoSession;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+
+import java.time.Clock;
+import java.time.Instant;
+import java.time.LocalDateTime;
+import java.time.ZoneOffset;
+import java.util.Map;
+
+import static org.junit.jupiter.api.Assertions.*;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.*;
+
+/**
+ * Shared live generation: releasing one viewer must not stop another viewer's stream.
+ * The mapper stands in for the database's count answer; the sharing decision stays in production.
+ */
+class VideoLiveSharingTest {
+    private static final String VIDEO = "sharing-camera-ledger";
+    private static final String GENERATION = "5f2a7c1e-1111-4a2b-9c3d-000000000001";
+
+    private final VideoSessionMapper sessions = mock(VideoSessionMapper.class);
+    private final EquipmentVideoBindingMapper bindings = mock(EquipmentVideoBindingMapper.class);
+    private final VideoCollectorClient collector = mock(VideoCollectorClient.class);
+    private final Clock clock = Clock.fixed(Instant.parse("2026-11-12T01:00:00Z"), ZoneOffset.UTC);
+    private VideoLiveLifecycle lifecycle;
+
+    @BeforeEach void setUp() {
+        lifecycle = new VideoLiveLifecycle(sessions, bindings, collector, clock);
+        VideoDeviceRecord binding = new VideoDeviceRecord();
+        binding.setVideoId(VIDEO);
+        binding.setSourceType("GB28181");
+        binding.setGbDeviceId("34020000002000000001");
+        binding.setGbChannelId("34020000001320000001");
+        when(bindings.find(VIDEO)).thenReturn(binding);
+        when(sessions.lockVideo(VIDEO)).thenReturn(VIDEO);
+        when(sessions.updateById(any(VideoSession.class))).thenReturn(1);
+    }
+
+    private VideoSession activeViewer(String sessionId) {
+        VideoSession row = new VideoSession();
+        row.setSessionId(sessionId);
+        row.setVideoId(VIDEO);
+        row.setMode("LIVE");
+        row.setStatus("ACTIVE");
+        row.setMediaGeneration(GENERATION);
+        row.setStartDeadline(LocalDateTime.now(clock).plusSeconds(30));
+        row.setCreateTime(LocalDateTime.now(clock));
+        row.setLastSeen(LocalDateTime.now(clock));
+        return row;
+    }
+
+    @Test void releasingOneOfTwoViewersKeepsTheSharedStreamRunning() {
+        VideoSession mine = activeViewer("viewer-1");
+        when(sessions.selectCount(any())).thenReturn(1L);
+
+        Map<String, Object> result = lifecycle.stop(() -> mine);
+
+        assertEquals("STOPPED", result.get("status"));
+        assertEquals("viewer-1", result.get("sessionId"));
+        assertNull(result.get("media"), "a shared viewer must not receive another session's media");
+        verify(collector, never()).post(anyString(), any());
+    }
+
+    @Test void releasingTheLastViewerReclaimsTheSharedStreamOnce() {
+        VideoSession mine = activeViewer("viewer-2");
+        when(sessions.selectCount(any())).thenReturn(0L);
+        when(collector.post(eq("/internal/video/lifecycle/cancel"), any())).thenAnswer(call -> {
+            Map<String, Object> body = call.getArgument(1);
+            return Map.of("generation", body.get("generation"), "status", "STOPPED");
+        });
+
+        Map<String, Object> result = lifecycle.stop(() -> mine);
+
+        assertEquals("STOPPED", result.get("status"));
+        verify(collector, times(1)).post(eq("/internal/video/lifecycle/cancel"), any());
+    }
+}