From a53dce38c2f58c0bfd37203e46dc57aa56025f45 Mon Sep 17 00:00:00 2001
From: 648540858 <648540858@qq.com>
Date: 星期四, 17 十一月 2022 18:22:24 +0800
Subject: [PATCH] Merge pull request #673 from 648540858/wvp-28181-2.0-multi-network

---
 src/main/java/com/genersoft/iot/vmp/service/impl/PlayServiceImpl.java |  118 ++++++++++++++++++++++++++++++++++-------------------------
 1 files changed, 68 insertions(+), 50 deletions(-)

diff --git a/src/main/java/com/genersoft/iot/vmp/service/impl/PlayServiceImpl.java b/src/main/java/com/genersoft/iot/vmp/service/impl/PlayServiceImpl.java
index f4e3227..75fff7f 100644
--- a/src/main/java/com/genersoft/iot/vmp/service/impl/PlayServiceImpl.java
+++ b/src/main/java/com/genersoft/iot/vmp/service/impl/PlayServiceImpl.java
@@ -36,7 +36,6 @@
 import com.genersoft.iot.vmp.utils.redis.RedisUtil;
 import com.genersoft.iot.vmp.vmanager.bean.ErrorCode;
 import com.genersoft.iot.vmp.vmanager.bean.WVPResult;
-import com.genersoft.iot.vmp.vmanager.gb28181.play.bean.PlayResult;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 import org.springframework.beans.factory.annotation.Autowired;
@@ -53,7 +52,6 @@
 import java.math.RoundingMode;
 import java.text.ParseException;
 import java.util.List;
-import java.util.Objects;
 import java.util.UUID;
 
 @SuppressWarnings(value = {"rawtypes", "unchecked"})
@@ -111,46 +109,19 @@
     private ThreadPoolTaskExecutor taskExecutor;
 
     @Override
-    public PlayResult play(MediaServerItem mediaServerItem, String deviceId, String channelId,
-                           ZlmHttpHookSubscribe.Event hookEvent, SipSubscribe.Event errorEvent,
-                           Runnable timeoutCallback) {
+    public void play(MediaServerItem mediaServerItem, String deviceId, String channelId,
+                                 ZlmHttpHookSubscribe.Event hookEvent, SipSubscribe.Event errorEvent,
+                                 Runnable timeoutCallback) {
         if (mediaServerItem == null) {
             throw new ControllerException(ErrorCode.ERROR100.getCode(), "鏈壘鍒板彲鐢ㄧ殑zlm");
         }
-        PlayResult playResult = new PlayResult();
-        RequestMessage msg = new RequestMessage();
         String key = DeferredResultHolder.CALLBACK_CMD_PLAY + deviceId + channelId;
+
+        RequestMessage msg = new RequestMessage();
         msg.setKey(key);
-        String uuid = UUID.randomUUID().toString();
-        msg.setId(uuid);
-        playResult.setUuid(uuid);
-        DeferredResult<WVPResult<StreamInfo>> result = new DeferredResult<>(userSetting.getPlayTimeout().longValue());
-        playResult.setResult(result);
-        // 褰曞儚鏌ヨ浠hannelId浣滀负deviceId鏌ヨ
-        resultHolder.put(key, uuid, result);
 
         Device device = redisCatchStorage.getDevice(deviceId);
         StreamInfo streamInfo = redisCatchStorage.queryPlayByDevice(deviceId, channelId);
-        playResult.setDevice(device);
-
-        result.onCompletion(() -> {
-            // 鐐规挱缁撴潫鏃惰皟鐢ㄦ埅鍥炬帴鍙�
-            taskExecutor.execute(() -> {
-                // TODO 搴旇鍦ㄤ笂娴佹椂璋冪敤鏇村ソ锛岀粨鏉熶篃鍙兘鏄敊璇粨鏉�
-                String path = "snap";
-                String fileName = deviceId + "_" + channelId + ".jpg";
-                WVPResult wvpResult = (WVPResult) result.getResult();
-                if (Objects.requireNonNull(wvpResult).getCode() == 0) {
-                    StreamInfo streamInfoForSuccess = (StreamInfo) wvpResult.getData();
-                    MediaServerItem mediaInfo = mediaServerService.getOne(streamInfoForSuccess.getMediaServerId());
-                    String streamUrl = streamInfoForSuccess.getFmp4();
-
-                    // 璇锋眰鎴浘
-                    logger.info("[璇锋眰鎴浘]: " + fileName);
-                    zlmresTfulUtils.getSnap(mediaInfo, streamUrl, 15, 1, path, fileName);
-                }
-            });
-        });
 
         if (streamInfo != null) {
             String streamId = streamInfo.getStream();
@@ -160,7 +131,7 @@
                 wvpResult.setMsg("鐐规挱澶辫触锛� redis缂撳瓨streamId绛変簬null");
                 msg.setData(wvpResult);
                 resultHolder.invokeAllResult(msg);
-                return playResult;
+                return;
             }
             String mediaServerId = streamInfo.getMediaServerId();
             MediaServerItem mediaInfo = mediaServerService.getOne(mediaServerId);
@@ -178,14 +149,13 @@
                         msg.setData(wvpResult);
 
                         resultHolder.invokeAllResult(msg);
-                        return playResult;
+                        return;
                     } else {
                         WVPResult wvpResult = new WVPResult();
                         wvpResult.setCode(ErrorCode.SUCCESS.getCode());
                         wvpResult.setMsg(ErrorCode.SUCCESS.getMsg());
                         wvpResult.setData(streamInfo);
                         msg.setData(wvpResult);
-
                         resultHolder.invokeAllResult(msg);
                         if (hookEvent != null) {
                             hookEvent.response(mediaServerItem, JSON.parseObject(JSON.toJSONString(streamInfo)));
@@ -211,7 +181,6 @@
                 streamId = String.format("%s_%s", device.getDeviceId(), channelId);
             }
             SSRCInfo ssrcInfo = mediaServerService.openRTPServer(mediaServerItem, streamId, device.isSsrcCheck(), false);
-            logger.info(JSONObject.toJSONString(ssrcInfo));
             if (ssrcInfo == null) {
                 WVPResult wvpResult = new WVPResult();
                 wvpResult.setCode(ErrorCode.ERROR100.getCode());
@@ -219,7 +188,7 @@
                 msg.setData(wvpResult);
 
                 resultHolder.invokeAllResult(msg);
-                return playResult;
+                return;
             }
             play(mediaServerItem, ssrcInfo, device, channelId, (mediaServerItemInUse, response) -> {
                 if (hookEvent != null) {
@@ -247,16 +216,15 @@
                 msg.setData(wvpResult);
                 // 鍥炲涔嬪墠鎵�鏈夌殑鐐规挱璇锋眰
                 resultHolder.invokeAllResult(msg);
-            }, uuid);
+            });
         }
-        return playResult;
     }
 
 
     @Override
     public void play(MediaServerItem mediaServerItem, SSRCInfo ssrcInfo, Device device, String channelId,
                      ZlmHttpHookSubscribe.Event hookEvent, SipSubscribe.Event errorEvent,
-                     InviteTimeOutCallback timeoutCallback, String uuid) {
+                     InviteTimeOutCallback timeoutCallback) {
 
         logger.info("[鐐规挱寮�濮媇 deviceId: {}, channelId: {},鏀舵祦绔彛锛� {}, 鏀舵祦妯″紡锛歿}, SSRC: {}, SSRC鏍¢獙锛歿}", device.getDeviceId(), channelId, ssrcInfo.getPort(), device.getStreamMode(), ssrcInfo.getSsrc(), device.isSsrcCheck());
         // 瓒呮椂澶勭悊
@@ -279,16 +247,36 @@
                 }
             }
         }, userSetting.getPlayTimeout());
+        //绔彛鑾峰彇澶辫触鐨剆srcInfo 娌℃湁蹇呰鍙戦�佺偣鎾寚浠�
+        if (ssrcInfo.getPort() <= 0) {
+            logger.info("[鐐规挱绔彛鍒嗛厤寮傚父]锛宒eviceId={},channelId={},ssrcInfo={}", device.getDeviceId(), channelId, ssrcInfo);
+            dynamicTask.stop(timeOutTaskKey);
+            // 閲婃斁ssrc
+            mediaServerService.releaseSsrc(mediaServerItem.getId(), ssrcInfo.getSsrc());
 
+            streamSession.remove(device.getDeviceId(), channelId, ssrcInfo.getStream());
+
+            RequestMessage msg = new RequestMessage();
+            msg.setKey(DeferredResultHolder.CALLBACK_CMD_PLAY + device.getDeviceId() + channelId);
+            msg.setData(WVPResult.fail(ErrorCode.ERROR100.getCode(), "鐐规挱绔彛鍒嗛厤寮傚父"));
+            resultHolder.invokeAllResult(msg);
+            return;
+        }
         try {
             cmder.playStreamCmd(mediaServerItem, ssrcInfo, device, channelId, (MediaServerItem mediaServerItemInuse, JSONObject response) -> {
                 logger.info("鏀跺埌璁㈤槄娑堟伅锛� " + response.toJSONString());
                 dynamicTask.stop(timeOutTaskKey);
 
                 // hook鍝嶅簲
-                onPublishHandlerForPlay(mediaServerItemInuse, response, device.getDeviceId(), channelId, uuid);
+                onPublishHandlerForPlay(mediaServerItemInuse, response, device.getDeviceId(), channelId);
                 hookEvent.response(mediaServerItemInuse, response);
                 logger.info("[鐐规挱鎴愬姛] deviceId: {}, channelId: {}", device.getDeviceId(), channelId);
+                String streamUrl = String.format("rtsp://127.0.0.1:%s/%s/%s", mediaServerItemInuse.getRtspPort(), "rtp",  ssrcInfo.getStream());
+                String path = "snap";
+                String fileName = device.getDeviceId() + "_" + channelId + ".jpg";
+                // 璇锋眰鎴浘
+                logger.info("[璇锋眰鎴浘]: " + fileName);
+                zlmresTfulUtils.getSnap(mediaServerItemInuse, streamUrl, 15, 1, path, fileName);
 
             }, (event) -> {
                 ResponseEvent responseEvent = (ResponseEvent) event.event;
@@ -328,7 +316,7 @@
                                 logger.info("[ZLM HOOK] ssrc淇鍚庢敹鍒拌闃呮秷鎭細 " + response.toJSONString());
                                 dynamicTask.stop(timeOutTaskKey);
                                 // hook鍝嶅簲
-                                onPublishHandlerForPlay(mediaServerItemInUse, response, device.getDeviceId(), channelId, uuid);
+                                onPublishHandlerForPlay(mediaServerItemInUse, response, device.getDeviceId(), channelId);
                                 hookEvent.response(mediaServerItemInUse, response);
                             });
                         }
@@ -364,13 +352,41 @@
     }
 
     @Override
-    public void onPublishHandlerForPlay(MediaServerItem mediaServerItem, JSONObject response, String deviceId, String channelId, String uuid) {
+    public void onPublishHandlerForPlay(MediaServerItem mediaServerItem, JSONObject response, String deviceId, String channelId) {
+        StreamInfo streamInfo = onPublishHandler(mediaServerItem, response, deviceId, channelId);
         RequestMessage msg = new RequestMessage();
-        if (uuid != null) {
+        msg.setKey(DeferredResultHolder.CALLBACK_CMD_PLAY + deviceId + channelId);
+        if (streamInfo != null) {
+            DeviceChannel deviceChannel = storager.queryChannel(deviceId, channelId);
+            if (deviceChannel != null) {
+                deviceChannel.setStreamId(streamInfo.getStream());
+                storager.startPlay(deviceId, channelId, streamInfo.getStream());
+            }
+            redisCatchStorage.startPlay(streamInfo);
+
+            WVPResult wvpResult = new WVPResult();
+            wvpResult.setCode(ErrorCode.SUCCESS.getCode());
+            wvpResult.setMsg(ErrorCode.SUCCESS.getMsg());
+            wvpResult.setData(streamInfo);
+
+            msg.setData(wvpResult);
+            resultHolder.invokeAllResult(msg);
+
+        } else {
+            logger.warn("璁惧棰勮API璋冪敤澶辫触锛�");
+            msg.setData(WVPResult.fail(ErrorCode.ERROR100.getCode(), "璁惧棰勮API璋冪敤澶辫触锛�"));
+            resultHolder.invokeAllResult(msg);
+        }
+    }
+
+    private void onPublishHandlerForPlayback(MediaServerItem mediaServerItem, JSONObject response, String deviceId, String channelId, String uuid) {
+        RequestMessage msg = new RequestMessage();
+        msg.setKey(DeferredResultHolder.CALLBACK_CMD_PLAY + deviceId + channelId);
+        if (!ObjectUtils.isEmpty(uuid)) {
             msg.setId(uuid);
         }
-        msg.setKey(DeferredResultHolder.CALLBACK_CMD_PLAY + deviceId + channelId);
         StreamInfo streamInfo = onPublishHandler(mediaServerItem, response, deviceId, channelId);
+
         if (streamInfo != null) {
             DeviceChannel deviceChannel = storager.queryChannel(deviceId, channelId);
             if (deviceChannel != null) {
@@ -387,8 +403,8 @@
 
             resultHolder.invokeAllResult(msg);
         } else {
-            logger.warn("璁惧棰勮API璋冪敤澶辫触锛�");
-            msg.setData(WVPResult.fail(ErrorCode.ERROR100.getCode(), "璁惧棰勮API璋冪敤澶辫触锛�"));
+            logger.warn("褰曞儚鍥炴斁璋冪敤澶辫触锛�");
+            msg.setData(WVPResult.fail(ErrorCode.ERROR100.getCode(), "褰曞儚鍥炴斁璋冪敤澶辫触锛�"));
             resultHolder.invokeAllResult(msg);
         }
     }
@@ -542,7 +558,7 @@
                                             logger.info("[ZLM HOOK] ssrc淇鍚庢敹鍒拌闃呮秷鎭細 " + response.toJSONString());
                                             dynamicTask.stop(playBackTimeOutTaskKey);
                                             // hook鍝嶅簲
-                                            onPublishHandlerForPlay(mediaServerItemInUse, response, device.getDeviceId(), channelId, uuid);
+                                            onPublishHandlerForPlayback(mediaServerItemInUse, response, device.getDeviceId(), channelId, uuid);
                                             hookEvent.call(new InviteStreamInfo(mediaServerItem, null, eventResult.callId, "rtp", ssrcInfo.getStream()));
                                         });
                                     }
@@ -565,6 +581,8 @@
         return result;
     }
 
+
+
     @Override
     public DeferredResult<WVPResult<StreamInfo>> download(String deviceId, String channelId, String startTime, String endTime, int downloadSpeed, InviteStreamCallback infoCallBack, PlayBackCallback hookCallBack) {
         Device device = storager.queryVideoDevice(deviceId);

--
Gitblit v1.8.0