From b4048fbe80dba8e7756ae557a15ab60b4f80a44b Mon Sep 17 00:00:00 2001
From: 648540858 <648540858@qq.com>
Date: 星期二, 04 四月 2023 09:09:07 +0800
Subject: [PATCH] 合并开源主线

---
 src/main/java/com/genersoft/iot/vmp/gb28181/transmit/event/request/impl/InviteRequestProcessor.java |  182 +++++++++++++++++++++++++++++++--------------
 1 files changed, 124 insertions(+), 58 deletions(-)

diff --git a/src/main/java/com/genersoft/iot/vmp/gb28181/transmit/event/request/impl/InviteRequestProcessor.java b/src/main/java/com/genersoft/iot/vmp/gb28181/transmit/event/request/impl/InviteRequestProcessor.java
index 6e188a5..30ac381 100644
--- a/src/main/java/com/genersoft/iot/vmp/gb28181/transmit/event/request/impl/InviteRequestProcessor.java
+++ b/src/main/java/com/genersoft/iot/vmp/gb28181/transmit/event/request/impl/InviteRequestProcessor.java
@@ -1,12 +1,14 @@
 package com.genersoft.iot.vmp.gb28181.transmit.event.request.impl;
 
 import com.alibaba.fastjson2.JSONObject;
+import com.genersoft.iot.vmp.common.VideoManagerConstants;
 import com.genersoft.iot.vmp.conf.DynamicTask;
 import com.genersoft.iot.vmp.conf.SipConfig;
 import com.genersoft.iot.vmp.conf.UserSetting;
 import com.genersoft.iot.vmp.gb28181.bean.*;
 import com.genersoft.iot.vmp.gb28181.event.SipSubscribe;
 import com.genersoft.iot.vmp.gb28181.session.AudioBroadcastManager;
+import com.genersoft.iot.vmp.gb28181.session.SsrcConfig;
 import com.genersoft.iot.vmp.gb28181.session.VideoStreamSessionManager;
 import com.genersoft.iot.vmp.gb28181.transmit.SIPProcessorObserver;
 import com.genersoft.iot.vmp.gb28181.transmit.SIPSender;
@@ -274,7 +276,7 @@
                     }
                     return;
                 } else {
-                    logger.info("閫氶亾涓嶅瓨鍦紝杩斿洖404");
+                    logger.info("閫氶亾涓嶅瓨鍦紝杩斿洖404: {}", channelId);
                     try {
                         // 閫氶亾涓嶅瓨鍦紝鍙�404锛岃祫婧愪笉瀛樺湪
                         responseAck(request, Response.NOT_FOUND);
@@ -359,7 +361,7 @@
                     return;
                 }
                 String username = sdp.getOrigin().getUsername();
-                String addressStr = sdp.getOrigin().getAddress();
+                String addressStr = sdp.getConnection().getAddress();
 
                 logger.info("[涓婄骇鐐规挱]鐢ㄦ埛锛歿}锛� 閫氶亾锛歿}, 鍦板潃锛歿}:{}锛� ssrc锛歿}", username, channelId, addressStr, port, ssrc);
                 Device device = null;
@@ -439,24 +441,25 @@
 
                         try {
                             // 瓒呮椂鏈敹鍒癆ck搴旇鍥炲bye,褰撳墠绛夊緟鏃堕棿涓�10绉�
-                            dynamicTask.startDelay(callIdHeader.getCallId(), () -> {
-                                logger.info("Ack 绛夊緟瓒呮椂");
-                                mediaServerService.releaseSsrc(mediaServerItemInUSe.getId(), sendRtpItem.getSsrc());
-                                // 鍥炲bye
-                                try {
-                                    cmderFroPlatform.streamByeCmd(platform, callIdHeader.getCallId());
-                                } catch (SipException | InvalidArgumentException | ParseException e) {
-                                    logger.error("[鍛戒护鍙戦�佸け璐 鍥芥爣绾ц仈 鍙戦�丅YE: {}", e.getMessage());
-                                }
-                            }, 60 * 1000);
-                            responseSdpAck(request, content.toString(), platform);
+                            if (userSetting.getPushStreamAfterAck()) {
+                                dynamicTask.startDelay(callIdHeader.getCallId(), () -> {
+                                    logger.info("Ack 绛夊緟瓒呮椂");
+                                    mediaServerService.releaseSsrc(mediaServerItemInUSe.getId(), sendRtpItem.getSsrc());
+                                    // 鍥炲bye
+                                    try {
+                                        cmderFroPlatform.streamByeCmd(platform, callIdHeader.getCallId());
+                                    } catch (SipException | InvalidArgumentException | ParseException e) {
+                                        logger.error("[鍛戒护鍙戦�佸け璐 鍥芥爣绾ц仈 鍙戦�丅YE: {}", e.getMessage());
+                                    }
+                                }, 60 * 1000);
+                            }
 
-                        } catch (SipException e) {
-                            e.printStackTrace();
-                        } catch (InvalidArgumentException e) {
-                            e.printStackTrace();
-                        } catch (ParseException e) {
-                            e.printStackTrace();
+                            SIPResponse sipResponse = responseSdpAck(request, content.toString(), platform);
+                            if (!userSetting.getPushStreamAfterAck()) {
+                                playService.startPushStream(sendRtpItem, sipResponse, platform, request.getCallIdHeader());
+                            }
+                        } catch (SipException | InvalidArgumentException | ParseException e) {
+                            logger.error("[鍛戒护鍙戦�佸け璐 鍥芥爣绾ц仈 鍥炲SdpAck", e);
                         }
                     };
                     SipSubscribe.Event errorEvent = ((event) -> {
@@ -465,14 +468,14 @@
                             Response response = getMessageFactory().createResponse(event.statusCode, evt.getRequest());
                             sipSender.transmitRequest(request.getLocalAddress().getHostAddress(), response);
                         } catch (ParseException | SipException  e) {
-                            e.printStackTrace();
+                            logger.error("鏈鐞嗙殑寮傚父 ", e);
                         }
                     });
                     sendRtpItem.setApp("rtp");
                     if ("Playback".equalsIgnoreCase(sessionName)) {
                         sendRtpItem.setPlayType(InviteStreamType.PLAYBACK);
                         SSRCInfo ssrcInfo = mediaServerService.openRTPServer(mediaServerItem, null, device.isSsrcCheck(), true);
-                        sendRtpItem.setStreamId(ssrcInfo.getStream());
+                        sendRtpItem.setStream(ssrcInfo.getStream());
                         // 鍐欏叆redis锛� 瓒呮椂鏃跺洖澶�
                         redisCatchStorage.updateSendRTPSever(sendRtpItem);
                         playService.playBack(mediaServerItem, ssrcInfo, device.getDeviceId(), channelId, DateUtil.formatter.format(start),
@@ -517,7 +520,7 @@
                             }
                             SSRCInfo ssrcInfo = mediaServerService.openRTPServer(mediaServerItem, streamId, null, device.isSsrcCheck(), false);
                             logger.info(JSONObject.toJSONString(ssrcInfo));
-                            sendRtpItem.setStreamId(ssrcInfo.getStream());
+                            sendRtpItem.setStream(ssrcInfo.getStream());
                             sendRtpItem.setSsrc(ssrc.equals(ssrcDefault) ? ssrcInfo.getSsrc() : ssrc);
 
                             // 鍐欏叆redis锛� 瓒呮椂鏃跺洖澶�
@@ -527,16 +530,25 @@
                                 redisCatchStorage.deleteSendRTPServer(platform.getServerGBId(), finalChannelId, callIdHeader.getCallId(), null);
                             });
                         } else {
-                            sendRtpItem.setStreamId(playTransaction.getStream());
+                            sendRtpItem.setStream(playTransaction.getStream());
                             // 鍐欏叆redis锛� 瓒呮椂鏃跺洖澶�
                             redisCatchStorage.updateSendRTPSever(sendRtpItem);
                             JSONObject jsonObject = new JSONObject();
                             jsonObject.put("app", sendRtpItem.getApp());
-                            jsonObject.put("stream", sendRtpItem.getStreamId());
+                            jsonObject.put("stream", sendRtpItem.getStream());
                             hookEvent.response(mediaServerItem, jsonObject);
                         }
                     }
                 } else if (gbStream != null) {
+                    if(ssrc.equals(ssrcDefault))
+                    {
+                        SsrcConfig ssrcConfig = mediaServerItem.getSsrcConfig();
+                        if(ssrcConfig != null)
+                        {
+                            ssrc = ssrcConfig.getPlaySsrc();
+                            ssrcConfig.releaseSsrc(ssrc);
+                        }
+                    }
                     if("push".equals(gbStream.getStreamType())) {
                         if (streamPushItem != null && streamPushItem.isPushIng()) {
                             // 鎺ㄦ祦鐘舵��
@@ -566,7 +578,7 @@
         } catch (SdpParseException e) {
             logger.error("sdp瑙f瀽閿欒", e);
         } catch (SdpException e) {
-            e.printStackTrace();
+            logger.error("鏈鐞嗙殑寮傚父 ", e);
         }
     }
 
@@ -721,11 +733,11 @@
                     mediaListManager.removedChannelOnlineEventLister(gbStream.getApp(), gbStream.getStream());
                     responseAck(request, Response.REQUEST_TIMEOUT); // 瓒呮椂
                 } catch (SipException e) {
-                    e.printStackTrace();
+                    logger.error("鏈鐞嗙殑寮傚父 ", e);
                 } catch (InvalidArgumentException e) {
-                    e.printStackTrace();
+                    logger.error("鏈鐞嗙殑寮傚父 ", e);
                 } catch (ParseException e) {
-                    e.printStackTrace();
+                    logger.error("鏈鐞嗙殑寮傚父 ", e);
                 }
             }, userSetting.getPlatformPlayTimeout());
             // 娣诲姞鐩戝惉
@@ -744,11 +756,11 @@
                         try {
                             responseAck(request, Response.BUSY_HERE);
                         } catch (SipException e) {
-                            e.printStackTrace();
+                            logger.error("鏈鐞嗙殑寮傚父 ", e);
                         } catch (InvalidArgumentException e) {
-                            e.printStackTrace();
+                            logger.error("鏈鐞嗙殑寮傚父 ", e);
                         } catch (ParseException e) {
-                            e.printStackTrace();
+                            logger.error("鏈鐞嗙殑寮傚父 ", e);
                         }
                         return;
                     }
@@ -806,11 +818,11 @@
                         try {
                             responseAck(request, Response.BUSY_HERE);
                         } catch (SipException e) {
-                            e.printStackTrace();
+                            logger.error("鏈鐞嗙殑寮傚父 ", e);
                         } catch (InvalidArgumentException e) {
-                            e.printStackTrace();
+                            logger.error("鏈鐞嗙殑寮傚父 ", e);
                         } catch (ParseException e) {
-                            e.printStackTrace();
+                            logger.error("鏈鐞嗙殑寮傚父 ", e);
                         }
                         return;
                     }
@@ -863,7 +875,13 @@
         content.append("s=Play\r\n");
         content.append("c=IN IP4 " + mediaServerItem.getSdpIp() + "\r\n");
         content.append("t=0 0\r\n");
-        content.append("m=video " + sendRtpItem.getLocalPort() + " RTP/AVP 96\r\n");
+        // 闈炰弗鏍兼ā寮忕鍙d笉缁熶竴, 澧炲姞鍏煎鎬э紝淇敼涓轰竴涓笉涓�0鐨勭鍙�
+        int localPort = sendRtpItem.getLocalPort();
+        if(localPort == 0)
+        {
+            localPort = new Random().nextInt(65535) + 1;
+        }
+        content.append("m=video " + localPort + " RTP/AVP 96\r\n");
         content.append("a=sendonly\r\n");
         content.append("a=rtpmap:96 PS/90000\r\n");
         if (sendRtpItem.isTcp()) {
@@ -878,23 +896,53 @@
         content.append("f=\r\n");
 
         try {
-            return responseSdpAck(request, content.toString(), platform);
+            SIPResponse sipResponse = responseSdpAck(request, content.toString(), platform);
+            if (!userSetting.getPushStreamAfterAck()) {
+                playService.startPushStream(sendRtpItem, sipResponse, platform, request.getCallIdHeader());
+            }
+            return sipResponse;
         } catch (SipException e) {
-            e.printStackTrace();
+            logger.error("鏈鐞嗙殑寮傚父 ", e);
         } catch (InvalidArgumentException e) {
-            e.printStackTrace();
+            logger.error("鏈鐞嗙殑寮傚父 ", e);
         } catch (ParseException e) {
-            e.printStackTrace();
+            logger.error("鏈鐞嗙殑寮傚父 ", e);
         }
         return null;
     }
 
     public void inviteFromDeviceHandle(SIPRequest request, String requesterId, String channelId) {
 
+        String realChannelId = null;
+
         // 闈炰笂绾у钩鍙拌姹傦紝鏌ヨ鏄惁璁惧璇锋眰锛堥�氬父涓烘帴鏀惰闊冲箍鎾殑璁惧锛�
         Device device = redisCatchStorage.getDevice(requesterId);
-        AudioBroadcastCatch audioBroadcastCatch = audioBroadcastManager.get(requesterId, channelId);
-        if (audioBroadcastCatch == null) {
+        // 鍒ゆ柇requesterId鏄澶囪繕鏄�氶亾
+        if (device == null) {
+            device = storager.queryVideoDeviceByChannelId(requesterId);
+            realChannelId = requesterId;
+        }
+        if (device == null) {
+            // 妫�鏌hannelID鏄惁鍙敤
+            device = redisCatchStorage.getDevice(channelId);
+            if (device == null) {
+                device = storager.queryVideoDeviceByChannelId(channelId);
+                realChannelId = channelId;
+            }
+        }
+
+        if (device == null) {
+            logger.warn("鏉ヨ嚜璁惧鐨処nvite璇锋眰锛屾棤娉曚粠璇锋眰淇℃伅涓‘瀹氭墍灞炶澶囷紝宸插拷鐣ワ紝requesterId锛� {}/{}", requesterId, channelId);
+            try {
+                responseAck(request, Response.FORBIDDEN);
+            } catch (SipException | InvalidArgumentException | ParseException e) {
+                logger.error("[鍛戒护鍙戦�佸け璐 鏉ヨ嚜璁惧鐨処nvite璇锋眰锛屾棤娉曚粠璇锋眰淇℃伅涓‘瀹氭墍灞炶澶� FORBIDDEN: {}", e.getMessage());
+            }
+            return;
+        }
+
+        AudioBroadcastCatch broadcastCatch = audioBroadcastManager.get(device.getDeviceId(), realChannelId);
+        if (broadcastCatch == null) {
             logger.warn("鏉ヨ嚜璁惧鐨処nvite璇锋眰闈炶闊冲箍鎾紝宸插拷鐣ワ紝requesterId锛� {}/{}", requesterId, channelId);
             try {
                 responseAck(request, Response.FORBIDDEN);
@@ -905,11 +953,14 @@
         }
         if (device != null) {
             logger.info("鏀跺埌璁惧" + requesterId + "鐨勮闊冲箍鎾璉nvite璇锋眰");
-
+            String key = VideoManagerConstants.BROADCAST_WAITE_INVITE +  device.getDeviceId() + broadcastCatch.getChannelId();
+            dynamicTask.stop(key);
             try {
                 responseAck(request, Response.TRYING);
             } catch (SipException | InvalidArgumentException | ParseException e) {
                 logger.error("[鍛戒护鍙戦�佸け璐 invite BAD_REQUEST: {}", e.getMessage());
+                playService.stopAudioBroadcast(device.getDeviceId(), broadcastCatch.getChannelId());
+                return;
             }
             String contentString = new String(request.getRawContent());
             // jainSip涓嶆敮鎸亂=瀛楁锛� 绉婚櫎绉婚櫎浠ヨВ鏋愩��
@@ -964,24 +1015,31 @@
                         responseAck(request, Response.UNSUPPORTED_MEDIA_TYPE); // 涓嶆敮鎸佺殑鏍煎紡锛屽彂415
                     } catch (SipException | InvalidArgumentException | ParseException e) {
                         logger.error("[鍛戒护鍙戦�佸け璐 invite 涓嶆敮鎸佺殑濯掍綋鏍煎紡: {}", e.getMessage());
+                        playService.stopAudioBroadcast(device.getDeviceId(), broadcastCatch.getChannelId());
+                        return;
                     }
                     return;
                 }
                 String addressStr = sdp.getOrigin().getAddress();
-                logger.info("璁惧{}璇锋眰璇煶娴侊紝鍦板潃锛歿}:{}锛宻src锛歿}", requesterId, addressStr, port, ssrc);
+                logger.info("璁惧{}璇锋眰璇煶娴侊紝鍦板潃锛歿}:{}锛宻src锛歿}, {}", requesterId, addressStr, port, ssrc,
+                        mediaTransmissionTCP ? (tcpActive? "TCP涓诲姩":"TCP琚姩") : "UDP");
 
-                MediaServerItem mediaServerItem = playService.getNewMediaServerItem(device);
+                MediaServerItem mediaServerItem = broadcastCatch.getMediaServerItem();
                 if (mediaServerItem == null) {
-                    logger.warn("鏈壘鍒板彲鐢ㄧ殑zlm");
+                    logger.warn("鏈壘鍒拌闊冲枈璇濅娇鐢ㄧ殑zlm");
                     try {
                         responseAck(request, Response.BUSY_HERE);
                     } catch (SipException | InvalidArgumentException | ParseException e) {
                         logger.error("[鍛戒护鍙戦�佸け璐 invite 鏈壘鍒板彲鐢ㄧ殑zlm: {}", e.getMessage());
+                        playService.stopAudioBroadcast(device.getDeviceId(), broadcastCatch.getChannelId());
                     }
                     return;
                 }
+                logger.info("璁惧{}璇锋眰璇煶娴侊紝 鏀舵祦鍦板潃锛歿}:{}锛宻src锛歿}, {}, 瀵硅鏂瑰紡锛歿}", requesterId, addressStr, port, ssrc,
+                        mediaTransmissionTCP ? (tcpActive? "TCP涓诲姩":"TCP琚姩") : "UDP", sdp.getSessionName().getValue());
+
                 SendRtpItem sendRtpItem = zlmrtpServerFactory.createSendRtpItem(mediaServerItem, addressStr, port, ssrc, requesterId,
-                        device.getDeviceId(), audioBroadcastCatch.getChannelId(),
+                        device.getDeviceId(), broadcastCatch.getChannelId(),
                         mediaTransmissionTCP, false);
 
                 if (sendRtpItem == null) {
@@ -990,44 +1048,47 @@
                         responseAck(request, Response.BUSY_HERE);
                     } catch (SipException | InvalidArgumentException | ParseException e) {
                         logger.error("[鍛戒护鍙戦�佸け璐 invite 鏈嶅姟鍣ㄧ鍙h祫婧愪笉瓒�: {}", e.getMessage());
+                        playService.stopAudioBroadcast(device.getDeviceId(), broadcastCatch.getChannelId());
+                        return;
                     }
                     return;
                 }
-                sendRtpItem.setTcp(mediaTransmissionTCP);
-                if (tcpActive != null) {
-                    sendRtpItem.setTcpActive(tcpActive);
-                }
-                String app = "broadcast";
-                String stream = device.getDeviceId() + "_" + audioBroadcastCatch.getChannelId();
+
 
                 CallIdHeader callIdHeader = (CallIdHeader) request.getHeader(CallIdHeader.NAME);
                 sendRtpItem.setPlayType(InviteStreamType.BROADCAST);
                 sendRtpItem.setCallId(callIdHeader.getCallId());
                 sendRtpItem.setPlatformId(requesterId);
                 sendRtpItem.setStatus(1);
-                sendRtpItem.setApp(app);
-                sendRtpItem.setStreamId(stream);
+                sendRtpItem.setApp(broadcastCatch.getApp());
+                sendRtpItem.setStream(broadcastCatch.getStream());
                 sendRtpItem.setPt(8);
                 sendRtpItem.setUsePs(false);
                 sendRtpItem.setRtcp(false);
                 sendRtpItem.setOnlyAudio(true);
+                sendRtpItem.setTcp(mediaTransmissionTCP);
+                if (tcpActive != null) {
+                    sendRtpItem.setTcpActive(tcpActive);
+                }
+
                 redisCatchStorage.updateSendRTPSever(sendRtpItem);
 
-
-                Boolean streamReady = zlmrtpServerFactory.isStreamReady(mediaServerItem, app, stream);
+                Boolean streamReady = zlmrtpServerFactory.isStreamReady(mediaServerItem, broadcastCatch.getApp(), broadcastCatch.getStream());
                 if (streamReady) {
                     sendOk(device, sendRtpItem, sdp, request, mediaServerItem, mediaTransmissionTCP, ssrc);
                 }else {
-                    logger.warn("[璇煶閫氳瘽]锛� 鏈彂鐜板緟鎺ㄩ�佺殑娴�,app={},stream={}", app, stream);
+                    logger.warn("[璇煶閫氳瘽]锛� 鏈彂鐜板緟鎺ㄩ�佺殑娴�,app={},stream={}", broadcastCatch.getApp(), broadcastCatch.getStream());
                     try {
                         responseAck(request, Response.GONE);
                     } catch (SipException | InvalidArgumentException | ParseException e) {
                         logger.error("[鍛戒护鍙戦�佸け璐 璇煶閫氳瘽 鍥炲410澶辫触锛� {}", e.getMessage());
+                        return;
                     }
-                    playService.stopAudioBroadcast(device.getDeviceId(), audioBroadcastCatch.getChannelId());
+                    playService.stopAudioBroadcast(device.getDeviceId(), broadcastCatch.getChannelId());
                 }
             } catch (SdpException e) {
                 logger.error("[SDP瑙f瀽寮傚父]", e);
+                playService.stopAudioBroadcast(device.getDeviceId(), broadcastCatch.getChannelId());
             }
         } else {
             logger.warn("鏉ヨ嚜鏃犳晥璁惧/骞冲彴鐨勮姹�");
@@ -1084,6 +1145,11 @@
             audioBroadcastCatch.setSipTransactionInfoByRequset(sipResponse);
             audioBroadcastManager.update(audioBroadcastCatch);
 
+            // 寮�鍚彂娴侊紝澶у崕鍦ㄦ敹鍒�200OK鍚庡氨浼氬紑濮嬪缓绔嬭繛鎺�
+            if (!userSetting.getPushStreamAfterAck()) {
+                playService.startPushStream(sendRtpItem, sipResponse, parentPlatform, request.getCallIdHeader());
+            }
+
         } catch (SipException | InvalidArgumentException | ParseException | SdpParseException e) {
             logger.error("[鍛戒护鍙戦�佸け璐 璇煶鍠婅瘽 鍥炲200OK锛圫DP锛�: {}", e.getMessage());
         }

--
Gitblit v1.8.0