PlayServiceImpl.java 96 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664
  1. package com.genersoft.iot.vmp.service.impl;
  2. import com.alibaba.fastjson2.JSONObject;
  3. import com.genersoft.iot.vmp.common.InviteInfo;
  4. import com.genersoft.iot.vmp.common.InviteSessionStatus;
  5. import com.genersoft.iot.vmp.common.InviteSessionType;
  6. import com.genersoft.iot.vmp.common.StreamInfo;
  7. import com.genersoft.iot.vmp.conf.DynamicTask;
  8. import com.genersoft.iot.vmp.conf.SipConfig;
  9. import com.genersoft.iot.vmp.conf.UserSetting;
  10. import com.genersoft.iot.vmp.conf.exception.ControllerException;
  11. import com.genersoft.iot.vmp.conf.exception.ServiceException;
  12. import com.genersoft.iot.vmp.conf.exception.SsrcTransactionNotFoundException;
  13. import com.genersoft.iot.vmp.gb28181.bean.*;
  14. import com.genersoft.iot.vmp.gb28181.event.SipSubscribe;
  15. import com.genersoft.iot.vmp.gb28181.session.AudioBroadcastManager;
  16. import com.genersoft.iot.vmp.gb28181.session.SSRCFactory;
  17. import com.genersoft.iot.vmp.gb28181.session.VideoStreamSessionManager;
  18. import com.genersoft.iot.vmp.gb28181.transmit.cmd.ISIPCommanderForPlatform;
  19. import com.genersoft.iot.vmp.gb28181.transmit.cmd.impl.SIPCommander;
  20. import com.genersoft.iot.vmp.gb28181.utils.SipUtils;
  21. import com.genersoft.iot.vmp.media.zlm.*;
  22. import com.genersoft.iot.vmp.media.zlm.dto.HookSubscribeFactory;
  23. import com.genersoft.iot.vmp.media.zlm.dto.HookSubscribeForStreamChange;
  24. import com.genersoft.iot.vmp.media.zlm.dto.MediaServerItem;
  25. import com.genersoft.iot.vmp.media.zlm.dto.hook.HookParam;
  26. import com.genersoft.iot.vmp.media.zlm.dto.hook.OnStreamChangedHookParam;
  27. import com.genersoft.iot.vmp.service.*;
  28. import com.genersoft.iot.vmp.service.bean.ErrorCallback;
  29. import com.genersoft.iot.vmp.service.bean.InviteErrorCode;
  30. import com.genersoft.iot.vmp.service.bean.RequestPushStreamMsg;
  31. import com.genersoft.iot.vmp.service.bean.SSRCInfo;
  32. import com.genersoft.iot.vmp.service.redisMsg.RedisGbPlayMsgListener;
  33. import com.genersoft.iot.vmp.storager.IRedisCatchStorage;
  34. import com.genersoft.iot.vmp.storager.IVideoManagerStorage;
  35. import com.genersoft.iot.vmp.utils.DateUtil;
  36. import com.genersoft.iot.vmp.vmanager.bean.AudioBroadcastResult;
  37. import com.genersoft.iot.vmp.vmanager.bean.ErrorCode;
  38. import com.genersoft.iot.vmp.vmanager.bean.StreamContent;
  39. import com.genersoft.iot.vmp.vmanager.gb28181.play.bean.AudioBroadcastEvent;
  40. import gov.nist.javax.sip.message.SIPResponse;
  41. import org.slf4j.Logger;
  42. import org.slf4j.LoggerFactory;
  43. import org.springframework.beans.factory.annotation.Autowired;
  44. import org.springframework.beans.factory.annotation.Qualifier;
  45. import org.springframework.data.redis.core.RedisTemplate;
  46. import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
  47. import org.springframework.stereotype.Service;
  48. import org.springframework.util.ObjectUtils;
  49. import javax.sdp.*;
  50. import javax.sip.InvalidArgumentException;
  51. import javax.sip.ResponseEvent;
  52. import javax.sip.SipException;
  53. import javax.sip.header.CallIdHeader;
  54. import java.io.File;
  55. import java.math.BigDecimal;
  56. import java.math.RoundingMode;
  57. import java.text.ParseException;
  58. import java.util.*;
  59. @SuppressWarnings(value = {"rawtypes", "unchecked"})
  60. @Service
  61. public class PlayServiceImpl implements IPlayService {
  62. private final static Logger logger = LoggerFactory.getLogger(PlayServiceImpl.class);
  63. @Autowired
  64. private IVideoManagerStorage storager;
  65. @Autowired
  66. private SIPCommander cmder;
  67. @Autowired
  68. private AudioBroadcastManager audioBroadcastManager;
  69. @Autowired
  70. private IDeviceService deviceService;
  71. @Autowired
  72. private ISIPCommanderForPlatform sipCommanderFroPlatform;
  73. @Autowired
  74. private IRedisCatchStorage redisCatchStorage;
  75. @Autowired
  76. private ZLMRTPServerFactory zlmrtpServerFactory;
  77. @Autowired
  78. private IInviteStreamService inviteStreamService;
  79. @Autowired
  80. private SendRtpPortManager sendRtpPortManager;
  81. @Autowired
  82. private ZLMRESTfulUtils zlmresTfulUtils;
  83. @Autowired
  84. private AssistRESTfulUtils assistRESTfulUtils;
  85. @Autowired
  86. private IMediaService mediaService;
  87. @Autowired
  88. private IMediaServerService mediaServerService;
  89. @Autowired
  90. private VideoStreamSessionManager streamSession;
  91. @Autowired
  92. private UserSetting userSetting;
  93. @Autowired
  94. private SipConfig sipConfig;
  95. @Autowired
  96. private DynamicTask dynamicTask;
  97. @Autowired
  98. private ZlmHttpHookSubscribe subscribe;
  99. @Autowired
  100. private ISIPCommanderForPlatform commanderForPlatform;
  101. @Qualifier("taskExecutor")
  102. @Autowired
  103. private ThreadPoolTaskExecutor taskExecutor;
  104. @Autowired
  105. private RedisGbPlayMsgListener redisGbPlayMsgListener;
  106. @Autowired
  107. private ZlmHttpHookSubscribe hookSubscribe;
  108. @Autowired
  109. private SSRCFactory ssrcFactory;
  110. @Autowired
  111. private RedisTemplate<Object, Object> redisTemplate;
  112. @Override
  113. public SSRCInfo play(MediaServerItem mediaServerItem, String deviceId, String channelId, ErrorCallback<Object> callback) {
  114. if (mediaServerItem == null) {
  115. throw new ControllerException(ErrorCode.ERROR100.getCode(), "未找到可用的zlm");
  116. }
  117. Device device = redisCatchStorage.getDevice(deviceId);
  118. InviteInfo inviteInfo = inviteStreamService.getInviteInfoByDeviceAndChannel(InviteSessionType.PLAY, deviceId, channelId);
  119. if (inviteInfo != null ) {
  120. if (inviteInfo.getStreamInfo() == null) {
  121. // 点播发起了但是尚未成功, 仅注册回调等待结果即可
  122. inviteStreamService.once(InviteSessionType.PLAY, deviceId, channelId, null, callback);
  123. return inviteInfo.getSsrcInfo();
  124. }else {
  125. StreamInfo streamInfo = inviteInfo.getStreamInfo();
  126. String streamId = streamInfo.getStream();
  127. if (streamId == null) {
  128. callback.run(InviteErrorCode.ERROR_FOR_CATCH_DATA.getCode(), "点播失败, redis缓存streamId等于null", null);
  129. inviteStreamService.call(InviteSessionType.PLAY, device.getDeviceId(), channelId, null,
  130. InviteErrorCode.ERROR_FOR_CATCH_DATA.getCode(),
  131. "点播失败, redis缓存streamId等于null",
  132. null);
  133. return inviteInfo.getSsrcInfo();
  134. }
  135. String mediaServerId = streamInfo.getMediaServerId();
  136. MediaServerItem mediaInfo = mediaServerService.getOne(mediaServerId);
  137. Boolean ready = zlmrtpServerFactory.isStreamReady(mediaInfo, "rtp", streamId);
  138. if (ready != null && ready) {
  139. callback.run(InviteErrorCode.SUCCESS.getCode(), InviteErrorCode.SUCCESS.getMsg(), streamInfo);
  140. inviteStreamService.call(InviteSessionType.PLAY, device.getDeviceId(), channelId, null,
  141. InviteErrorCode.SUCCESS.getCode(),
  142. InviteErrorCode.SUCCESS.getMsg(),
  143. streamInfo);
  144. return inviteInfo.getSsrcInfo();
  145. }else {
  146. // 点播发起了但是尚未成功, 仅注册回调等待结果即可
  147. inviteStreamService.once(InviteSessionType.PLAY, deviceId, channelId, null, callback);
  148. storager.stopPlay(streamInfo.getDeviceID(), streamInfo.getChannelId());
  149. inviteStreamService.removeInviteInfoByDeviceAndChannel(InviteSessionType.PLAY, deviceId, channelId);
  150. }
  151. }
  152. }
  153. String streamId = null;
  154. if (mediaServerItem.isRtpEnable()) {
  155. streamId = String.format("%s_%s", device.getDeviceId(), channelId);
  156. }
  157. SSRCInfo ssrcInfo = mediaServerService.openRTPServer(mediaServerItem, streamId, null, device.isSsrcCheck(), false, 0, false, false, device.getStreamModeForParam());
  158. if (ssrcInfo == null) {
  159. callback.run(InviteErrorCode.ERROR_FOR_RESOURCE_EXHAUSTION.getCode(), InviteErrorCode.ERROR_FOR_RESOURCE_EXHAUSTION.getMsg(), null);
  160. inviteStreamService.call(InviteSessionType.PLAY, device.getDeviceId(), channelId, null,
  161. InviteErrorCode.ERROR_FOR_RESOURCE_EXHAUSTION.getCode(),
  162. InviteErrorCode.ERROR_FOR_RESOURCE_EXHAUSTION.getMsg(),
  163. null);
  164. return null;
  165. }
  166. // TODO 记录点播的状态
  167. play(mediaServerItem, ssrcInfo, device, channelId, callback);
  168. return ssrcInfo;
  169. }
  170. private void talk(MediaServerItem mediaServerItem, Device device, String channelId, String stream,
  171. ZlmHttpHookSubscribe.Event hookEvent, SipSubscribe.Event errorEvent,
  172. Runnable timeoutCallback, AudioBroadcastEvent audioEvent) {
  173. String playSsrc = ssrcFactory.getPlaySsrc(mediaServerItem.getId());
  174. if (playSsrc == null) {
  175. audioEvent.call("ssrc已经用尽");
  176. return;
  177. }
  178. SendRtpItem sendRtpItem = new SendRtpItem();
  179. sendRtpItem.setApp("talk");
  180. sendRtpItem.setStream(stream);
  181. sendRtpItem.setSsrc(playSsrc);
  182. sendRtpItem.setDeviceId(device.getDeviceId());
  183. sendRtpItem.setPlatformId(device.getDeviceId());
  184. sendRtpItem.setChannelId(channelId);
  185. sendRtpItem.setRtcp(false);
  186. sendRtpItem.setMediaServerId(mediaServerItem.getId());
  187. sendRtpItem.setOnlyAudio(true);
  188. sendRtpItem.setPlayType(InviteStreamType.TALK);
  189. sendRtpItem.setPt(8);
  190. sendRtpItem.setStatus(1);
  191. sendRtpItem.setTcpActive(false);
  192. sendRtpItem.setTcp(true);
  193. sendRtpItem.setUsePs(false);
  194. sendRtpItem.setReceiveStream(stream + "_talk");
  195. String callId = SipUtils.getNewCallId();
  196. int port = sendRtpPortManager.getNextPort(mediaServerItem.getId());
  197. //端口获取失败的ssrcInfo 没有必要发送点播指令
  198. if (port <= 0) {
  199. logger.info("[语音对讲] 端口分配异常,deviceId={},channelId={}", device.getDeviceId(), channelId);
  200. audioEvent.call("端口分配异常");
  201. return;
  202. }
  203. sendRtpItem.setLocalPort(port);
  204. sendRtpItem.setPort(port);
  205. logger.info("[语音对讲]开始 deviceId: {}, channelId: {},收流端口: {}, 收流模式:{}, SSRC: {}, SSRC校验:{}", device.getDeviceId(), channelId, sendRtpItem.getLocalPort(), device.getStreamMode(), sendRtpItem.getSsrc(), false);
  206. // 超时处理
  207. String timeOutTaskKey = UUID.randomUUID().toString();
  208. dynamicTask.startDelay(timeOutTaskKey, () -> {
  209. logger.info("[语音对讲] 收流超时 deviceId: {}, channelId: {},端口:{}, SSRC: {}", device.getDeviceId(), channelId, sendRtpItem.getPort(), sendRtpItem.getSsrc());
  210. timeoutCallback.run();
  211. // 点播超时回复BYE 同时释放ssrc以及此次点播的资源
  212. try {
  213. cmder.streamByeCmd(device, channelId, sendRtpItem.getStream(), null);
  214. } catch (InvalidArgumentException | ParseException | SipException | SsrcTransactionNotFoundException e) {
  215. logger.error("[语音对讲]超时, 发送BYE失败 {}", e.getMessage());
  216. } finally {
  217. timeoutCallback.run();
  218. mediaServerService.releaseSsrc(mediaServerItem.getId(), sendRtpItem.getSsrc());
  219. streamSession.remove(device.getDeviceId(), channelId, sendRtpItem.getStream());
  220. }
  221. }, userSetting.getPlayTimeout());
  222. Map<String, Object> param = new HashMap<>(12);
  223. param.put("vhost","__defaultVhost__");
  224. param.put("app", sendRtpItem.getApp());
  225. param.put("stream", sendRtpItem.getStream());
  226. param.put("ssrc", sendRtpItem.getSsrc());
  227. param.put("src_port", sendRtpItem.getLocalPort());
  228. param.put("pt", sendRtpItem.getPt());
  229. param.put("use_ps", sendRtpItem.isUsePs() ? "1" : "0");
  230. param.put("only_audio", sendRtpItem.isOnlyAudio() ? "1" : "0");
  231. param.put("is_udp", sendRtpItem.isTcp() ? "0" : "1");
  232. param.put("recv_stream_id", sendRtpItem.getReceiveStream());
  233. param.put("close_delay_ms", userSetting.getPlayTimeout() * 1000);
  234. zlmrtpServerFactory.startSendRtpPassive(mediaServerItem, param, jsonObject -> {
  235. if (jsonObject == null || jsonObject.getInteger("code") != 0 ) {
  236. mediaServerService.releaseSsrc(mediaServerItem.getId(), sendRtpItem.getSsrc());
  237. logger.info("[语音对讲]失败 deviceId: {}, channelId: {}", device.getDeviceId(), channelId);
  238. audioEvent.call("失败, " + jsonObject.getString("msg"));
  239. // 查看是否已经建立了通道,存在则发送bye
  240. stopTalk(device, channelId);
  241. }
  242. });
  243. // 查看设备是否已经在推流
  244. try {
  245. cmder.talkStreamCmd(mediaServerItem, sendRtpItem, device, channelId, callId, (mediaServerItemInuse, hookParam) -> {
  246. logger.info("[语音对讲] 流已生成, 开始推流: " + hookParam);
  247. dynamicTask.stop(timeOutTaskKey);
  248. // TODO 暂不做处理
  249. }, (mediaServerItemInuse, hookParam) -> {
  250. logger.info("[语音对讲] 设备开始推流: " + hookParam);
  251. dynamicTask.stop(timeOutTaskKey);
  252. }, (event) -> {
  253. dynamicTask.stop(timeOutTaskKey);
  254. if (event.event instanceof ResponseEvent) {
  255. ResponseEvent responseEvent = (ResponseEvent) event.event;
  256. if (responseEvent.getResponse() instanceof SIPResponse) {
  257. SIPResponse response = (SIPResponse) responseEvent.getResponse();
  258. sendRtpItem.setFromTag(response.getFromTag());
  259. sendRtpItem.setToTag(response.getToTag());
  260. sendRtpItem.setCallId(response.getCallIdHeader().getCallId());
  261. redisCatchStorage.updateSendRTPSever(sendRtpItem);
  262. streamSession.put(device.getDeviceId(), channelId, "talk",
  263. sendRtpItem.getStream(), sendRtpItem.getSsrc(), sendRtpItem.getMediaServerId(),
  264. response, InviteSessionType.TALK);
  265. } else {
  266. logger.error("[语音对讲]收到的消息错误,response不是SIPResponse");
  267. }
  268. } else {
  269. logger.error("[语音对讲]收到的消息错误,event不是ResponseEvent");
  270. }
  271. }, (event) -> {
  272. dynamicTask.stop(timeOutTaskKey);
  273. mediaServerService.closeRTPServer(mediaServerItem, sendRtpItem.getStream());
  274. // 释放ssrc
  275. mediaServerService.releaseSsrc(mediaServerItem.getId(), sendRtpItem.getSsrc());
  276. streamSession.remove(device.getDeviceId(), channelId, sendRtpItem.getStream());
  277. errorEvent.response(event);
  278. });
  279. } catch (InvalidArgumentException | SipException | ParseException e) {
  280. logger.error("[命令发送失败] 对讲消息: {}", e.getMessage());
  281. dynamicTask.stop(timeOutTaskKey);
  282. mediaServerService.closeRTPServer(mediaServerItem, sendRtpItem.getStream());
  283. // 释放ssrc
  284. mediaServerService.releaseSsrc(mediaServerItem.getId(), sendRtpItem.getSsrc());
  285. streamSession.remove(device.getDeviceId(), channelId, sendRtpItem.getStream());
  286. SipSubscribe.EventResult eventResult = new SipSubscribe.EventResult();
  287. eventResult.type = SipSubscribe.EventResultType.cmdSendFailEvent;
  288. eventResult.statusCode = -1;
  289. eventResult.msg = "命令发送失败";
  290. errorEvent.response(eventResult);
  291. }
  292. // }
  293. }
  294. @Override
  295. public void play(MediaServerItem mediaServerItem, SSRCInfo ssrcInfo, Device device, String channelId,
  296. ErrorCallback<Object> callback) {
  297. if (mediaServerItem == null || ssrcInfo == null) {
  298. callback.run(InviteErrorCode.ERROR_FOR_PARAMETER_ERROR.getCode(),
  299. InviteErrorCode.ERROR_FOR_PARAMETER_ERROR.getMsg(),
  300. null);
  301. return;
  302. }
  303. logger.info("[点播开始] deviceId: {}, channelId: {},码流类型:{}, 收流端口: {}, 收流模式:{}, SSRC: {}, SSRC校验:{}",
  304. device.getDeviceId(), channelId, device.isSwitchPrimarySubStream() ? "辅码流" : "主码流", ssrcInfo.getPort(),
  305. device.getStreamMode(), ssrcInfo.getSsrc(), device.isSsrcCheck());
  306. //端口获取失败的ssrcInfo 没有必要发送点播指令
  307. if (ssrcInfo.getPort() <= 0) {
  308. logger.info("[点播端口分配异常],deviceId={},channelId={},ssrcInfo={}", device.getDeviceId(), channelId, ssrcInfo);
  309. // 释放ssrc
  310. mediaServerService.releaseSsrc(mediaServerItem.getId(), ssrcInfo.getSsrc());
  311. streamSession.remove(device.getDeviceId(), channelId, ssrcInfo.getStream());
  312. callback.run(InviteErrorCode.ERROR_FOR_RESOURCE_EXHAUSTION.getCode(), "点播端口分配异常", null);
  313. inviteStreamService.call(InviteSessionType.PLAY, device.getDeviceId(), channelId, null,
  314. InviteErrorCode.ERROR_FOR_RESOURCE_EXHAUSTION.getCode(), "点播端口分配异常", null);
  315. return;
  316. }
  317. // 初始化redis中的invite消息状态
  318. InviteInfo inviteInfo = InviteInfo.getInviteInfo(device.getDeviceId(), channelId, ssrcInfo.getStream(), ssrcInfo,
  319. mediaServerItem.getSdpIp(), ssrcInfo.getPort(), device.getStreamMode(), InviteSessionType.PLAY,
  320. InviteSessionStatus.ready);
  321. inviteInfo.setSubStream(device.isSwitchPrimarySubStream());
  322. inviteStreamService.updateInviteInfo(inviteInfo);
  323. // 超时处理
  324. String timeOutTaskKey = UUID.randomUUID().toString();
  325. dynamicTask.startDelay(timeOutTaskKey, () -> {
  326. // 执行超时任务时查询是否已经成功,成功了则不执行超时任务,防止超时任务取消失败的情况
  327. InviteInfo inviteInfoForTimeOut = inviteStreamService.getInviteInfoByDeviceAndChannel(InviteSessionType.PLAY, device.getDeviceId(), channelId);
  328. if (inviteInfoForTimeOut == null || inviteInfoForTimeOut.getStreamInfo() == null) {
  329. logger.info("[点播超时] 收流超时 deviceId: {}, channelId: {},码流类型:{},端口:{}, SSRC: {}",
  330. device.getDeviceId(), channelId, device.isSwitchPrimarySubStream() ? "辅码流" : "主码流",
  331. ssrcInfo.getPort(), ssrcInfo.getSsrc());
  332. // 点播超时回复BYE 同时释放ssrc以及此次点播的资源
  333. // InviteInfo inviteInfoForTimeout = inviteStreamService.getInviteInfoByDeviceAndChannel(InviteSessionType.play, device.getDeviceId(), channelId);
  334. // if (inviteInfoForTimeout == null) {
  335. // return;
  336. // }
  337. // if (InviteSessionStatus.ok == inviteInfoForTimeout.getStatus() ) {
  338. // // TODO 发送bye
  339. // }else {
  340. // // TODO 发送cancel
  341. // }
  342. callback.run(InviteErrorCode.ERROR_FOR_STREAM_TIMEOUT.getCode(), InviteErrorCode.ERROR_FOR_STREAM_TIMEOUT.getMsg(), null);
  343. inviteStreamService.call(InviteSessionType.PLAY, device.getDeviceId(), channelId, null,
  344. InviteErrorCode.ERROR_FOR_STREAM_TIMEOUT.getCode(), InviteErrorCode.ERROR_FOR_STREAM_TIMEOUT.getMsg(), null);
  345. inviteStreamService.removeInviteInfoByDeviceAndChannel(InviteSessionType.PLAY, device.getDeviceId(), channelId);
  346. try {
  347. cmder.streamByeCmd(device, channelId, ssrcInfo.getStream(), null);
  348. } catch (InvalidArgumentException | ParseException | SipException |
  349. SsrcTransactionNotFoundException e) {
  350. logger.error("[点播超时], 发送BYE失败 {}", e.getMessage());
  351. } finally {
  352. mediaServerService.releaseSsrc(mediaServerItem.getId(), ssrcInfo.getSsrc());
  353. mediaServerService.closeRTPServer(mediaServerItem, ssrcInfo.getStream());
  354. streamSession.remove(device.getDeviceId(), channelId, ssrcInfo.getStream());
  355. mediaServerService.closeRTPServer(mediaServerItem, ssrcInfo.getStream());
  356. // 取消订阅消息监听
  357. HookSubscribeForStreamChange hookSubscribe = HookSubscribeFactory.on_stream_changed("rtp", ssrcInfo.getStream(), true, "rtsp", mediaServerItem.getId());
  358. subscribe.removeSubscribe(hookSubscribe);
  359. }
  360. }
  361. }, userSetting.getPlayTimeout());
  362. try {
  363. cmder.playStreamCmd(mediaServerItem, ssrcInfo, device, channelId, (mediaServerItemInuse, hookParam ) -> {
  364. logger.info("收到订阅消息: " + hookParam);
  365. dynamicTask.stop(timeOutTaskKey);
  366. // hook响应
  367. StreamInfo streamInfo = onPublishHandlerForPlay(mediaServerItemInuse, hookParam, device.getDeviceId(), channelId);
  368. if (streamInfo == null){
  369. callback.run(InviteErrorCode.ERROR_FOR_STREAM_PARSING_EXCEPTIONS.getCode(),
  370. InviteErrorCode.ERROR_FOR_STREAM_PARSING_EXCEPTIONS.getMsg(), null);
  371. inviteStreamService.call(InviteSessionType.PLAY, device.getDeviceId(), channelId, null,
  372. InviteErrorCode.ERROR_FOR_STREAM_PARSING_EXCEPTIONS.getCode(),
  373. InviteErrorCode.ERROR_FOR_STREAM_PARSING_EXCEPTIONS.getMsg(), null);
  374. return;
  375. }
  376. callback.run(InviteErrorCode.SUCCESS.getCode(), InviteErrorCode.SUCCESS.getMsg(), streamInfo);
  377. inviteStreamService.call(InviteSessionType.PLAY, device.getDeviceId(), channelId, null,
  378. InviteErrorCode.SUCCESS.getCode(),
  379. InviteErrorCode.SUCCESS.getMsg(),
  380. streamInfo);
  381. logger.info("[点播成功] deviceId: {}, channelId:{}, 码流类型:{}", device.getDeviceId(),
  382. device.isSwitchPrimarySubStream() ? "辅码流" : "主码流");
  383. String streamUrl;
  384. if (mediaServerItemInuse.getRtspPort() != 0) {
  385. streamUrl = String.format("rtsp://127.0.0.1:%s/%s/%s", mediaServerItemInuse.getRtspPort(), "rtp", ssrcInfo.getStream());
  386. }else {
  387. streamUrl = String.format("http://127.0.0.1:%s/%s/%s.live.mp4", mediaServerItemInuse.getHttpPort(), "rtp", ssrcInfo.getStream());
  388. }
  389. String path = "snap";
  390. String fileName = device.getDeviceId() + "_" + channelId + ".jpg";
  391. // 请求截图
  392. logger.info("[请求截图]: " + fileName);
  393. zlmresTfulUtils.getSnap(mediaServerItemInuse, streamUrl, 15, 1, path, fileName);
  394. }, (event) -> {
  395. inviteInfo.setStatus(InviteSessionStatus.ok);
  396. ResponseEvent responseEvent = (ResponseEvent) event.event;
  397. String contentString = new String(responseEvent.getResponse().getRawContent());
  398. // 获取ssrc
  399. int ssrcIndex = contentString.indexOf("y=");
  400. // 检查是否有y字段
  401. if (ssrcIndex >= 0) {
  402. //ssrc规定长度为10字节,不取余下长度以避免后续还有“f=”字段 TODO 后续对不规范的非10位ssrc兼容
  403. String ssrcInResponse = contentString.substring(ssrcIndex + 2, ssrcIndex + 12).trim();
  404. // 查询到ssrc不一致且开启了ssrc校验则需要针对处理
  405. if (ssrcInfo.getSsrc().equals(ssrcInResponse)) {
  406. if (device.getStreamMode().equalsIgnoreCase("TCP-ACTIVE")) {
  407. String substring = contentString.substring(0, contentString.indexOf("y="));
  408. try {
  409. SessionDescription sdp = SdpFactory.getInstance().createSessionDescription(substring);
  410. int port = -1;
  411. Vector mediaDescriptions = sdp.getMediaDescriptions(true);
  412. for (Object description : mediaDescriptions) {
  413. MediaDescription mediaDescription = (MediaDescription) description;
  414. Media media = mediaDescription.getMedia();
  415. Vector mediaFormats = media.getMediaFormats(false);
  416. if (mediaFormats.contains("96")) {
  417. port = media.getMediaPort();
  418. break;
  419. }
  420. }
  421. logger.info("[点播-TCP主动连接对方] deviceId: {}, channelId: {}, 连接对方的地址:{}:{}, 收流模式:{}, SSRC: {}, SSRC校验:{}", device.getDeviceId(), channelId, sdp.getConnection().getAddress(), port, device.getStreamMode(), ssrcInfo.getSsrc(), device.isSsrcCheck());
  422. JSONObject jsonObject = zlmresTfulUtils.connectRtpServer(mediaServerItem, sdp.getConnection().getAddress(), port, ssrcInfo.getStream());
  423. logger.info("[点播-TCP主动连接对方] 结果: {}", jsonObject);
  424. } catch (SdpException e) {
  425. logger.error("[点播-TCP主动连接对方] deviceId: {}, channelId: {}, 解析200OK的SDP信息失败", device.getDeviceId(), channelId, e);
  426. dynamicTask.stop(timeOutTaskKey);
  427. mediaServerService.closeRTPServer(mediaServerItem, ssrcInfo.getStream());
  428. // 释放ssrc
  429. mediaServerService.releaseSsrc(mediaServerItem.getId(), ssrcInfo.getSsrc());
  430. streamSession.remove(device.getDeviceId(), channelId, ssrcInfo.getStream());
  431. callback.run(InviteErrorCode.ERROR_FOR_SDP_PARSING_EXCEPTIONS.getCode(),
  432. InviteErrorCode.ERROR_FOR_SDP_PARSING_EXCEPTIONS.getMsg(), null);
  433. inviteStreamService.call(InviteSessionType.PLAY, device.getDeviceId(), channelId, null,
  434. InviteErrorCode.ERROR_FOR_SDP_PARSING_EXCEPTIONS.getCode(),
  435. InviteErrorCode.ERROR_FOR_SDP_PARSING_EXCEPTIONS.getMsg(), null);
  436. }
  437. }
  438. return;
  439. }
  440. logger.info("[点播消息] 收到invite 200, 发现下级自定义了ssrc: {}", ssrcInResponse);
  441. if (!mediaServerItem.isRtpEnable() || device.isSsrcCheck()) {
  442. logger.info("[点播消息] SSRC修正 {}->{}", ssrcInfo.getSsrc(), ssrcInResponse);
  443. // 释放ssrc
  444. mediaServerService.releaseSsrc(mediaServerItem.getId(), ssrcInfo.getSsrc());
  445. // 单端口模式streamId也有变化,重新设置监听即可
  446. if (!mediaServerItem.isRtpEnable()) {
  447. // 添加订阅
  448. HookSubscribeForStreamChange hookSubscribe = HookSubscribeFactory.on_stream_changed("rtp", ssrcInfo.getStream(), true, "rtsp", mediaServerItem.getId());
  449. subscribe.removeSubscribe(hookSubscribe);
  450. String stream = String.format("%08x", Integer.parseInt(ssrcInResponse)).toUpperCase();
  451. hookSubscribe.getContent().put("stream", stream);
  452. inviteStreamService.updateInviteInfoForStream(inviteInfo, stream);
  453. subscribe.addSubscribe(hookSubscribe, (mediaServerItemInUse, hookParam) -> {
  454. logger.info("[ZLM HOOK] ssrc修正后收到订阅消息: " + hookParam);
  455. dynamicTask.stop(timeOutTaskKey);
  456. // hook响应
  457. StreamInfo streamInfo = onPublishHandlerForPlay(mediaServerItemInUse, hookParam, device.getDeviceId(), channelId);
  458. if (streamInfo == null){
  459. callback.run(InviteErrorCode.ERROR_FOR_STREAM_PARSING_EXCEPTIONS.getCode(),
  460. InviteErrorCode.ERROR_FOR_STREAM_PARSING_EXCEPTIONS.getMsg(), null);
  461. inviteStreamService.call(InviteSessionType.PLAY, device.getDeviceId(), channelId, null,
  462. InviteErrorCode.ERROR_FOR_STREAM_PARSING_EXCEPTIONS.getCode(),
  463. InviteErrorCode.ERROR_FOR_STREAM_PARSING_EXCEPTIONS.getMsg(), null);
  464. return;
  465. }
  466. callback.run(InviteErrorCode.SUCCESS.getCode(),
  467. InviteErrorCode.SUCCESS.getMsg(), streamInfo);
  468. inviteStreamService.call(InviteSessionType.PLAY, device.getDeviceId(), channelId, null,
  469. InviteErrorCode.SUCCESS.getCode(),
  470. InviteErrorCode.SUCCESS.getMsg(),
  471. streamInfo);
  472. });
  473. return;
  474. }
  475. // 更新ssrc
  476. Boolean result = mediaServerService.updateRtpServerSSRC(mediaServerItem, ssrcInfo.getStream(), ssrcInResponse);
  477. if (!result) {
  478. try {
  479. logger.warn("[点播] 更新ssrc失败,停止点播 {}/{}", device.getDeviceId(), channelId);
  480. cmder.streamByeCmd(device, channelId, ssrcInfo.getStream(), null, null);
  481. } catch (InvalidArgumentException | SipException | ParseException | SsrcTransactionNotFoundException e) {
  482. logger.error("[命令发送失败] 停止点播, 发送BYE: {}", e.getMessage());
  483. }
  484. dynamicTask.stop(timeOutTaskKey);
  485. // 释放ssrc
  486. mediaServerService.releaseSsrc(mediaServerItem.getId(), ssrcInfo.getSsrc());
  487. streamSession.remove(device.getDeviceId(), channelId, ssrcInfo.getStream());
  488. callback.run(InviteErrorCode.ERROR_FOR_RESET_SSRC.getCode(),
  489. "下级自定义了ssrc,重新设置收流信息失败", null);
  490. inviteStreamService.call(InviteSessionType.PLAY, device.getDeviceId(), channelId, null,
  491. InviteErrorCode.ERROR_FOR_RESET_SSRC.getCode(),
  492. "下级自定义了ssrc,重新设置收流信息失败", null);
  493. }else {
  494. if (ssrcInfo.getStream()!= null && !ssrcInfo.getStream().equals(inviteInfo.getStream())) {
  495. inviteStreamService.removeInviteInfo(inviteInfo);
  496. }
  497. ssrcInfo.setSsrc(ssrcInResponse);
  498. inviteInfo.setSsrcInfo(ssrcInfo);
  499. inviteInfo.setStream(ssrcInfo.getStream());
  500. }
  501. }else {
  502. logger.info("[点播消息] 收到invite 200, 下级自定义了ssrc, 但是当前模式无需修正");
  503. }
  504. }
  505. inviteStreamService.updateInviteInfo(inviteInfo);
  506. }, (event) -> {
  507. dynamicTask.stop(timeOutTaskKey);
  508. mediaServerService.closeRTPServer(mediaServerItem, ssrcInfo.getStream());
  509. // 释放ssrc
  510. mediaServerService.releaseSsrc(mediaServerItem.getId(), ssrcInfo.getSsrc());
  511. streamSession.remove(device.getDeviceId(), channelId, ssrcInfo.getStream());
  512. callback.run(InviteErrorCode.ERROR_FOR_SIGNALLING_ERROR.getCode(),
  513. String.format("点播失败, 错误码: %s, %s", event.statusCode, event.msg), null);
  514. inviteStreamService.call(InviteSessionType.PLAY, device.getDeviceId(), channelId, null,
  515. InviteErrorCode.ERROR_FOR_RESET_SSRC.getCode(),
  516. String.format("点播失败, 错误码: %s, %s", event.statusCode, event.msg), null);
  517. inviteStreamService.removeInviteInfoByDeviceAndChannel(InviteSessionType.PLAY, device.getDeviceId(), channelId);
  518. });
  519. } catch (InvalidArgumentException | SipException | ParseException e) {
  520. logger.error("[命令发送失败] 点播消息: {}", e.getMessage());
  521. dynamicTask.stop(timeOutTaskKey);
  522. mediaServerService.closeRTPServer(mediaServerItem, ssrcInfo.getStream());
  523. // 释放ssrc
  524. mediaServerService.releaseSsrc(mediaServerItem.getId(), ssrcInfo.getSsrc());
  525. streamSession.remove(device.getDeviceId(), channelId, ssrcInfo.getStream());
  526. callback.run(InviteErrorCode.ERROR_FOR_SIP_SENDING_FAILED.getCode(),
  527. InviteErrorCode.ERROR_FOR_SIP_SENDING_FAILED.getMsg(), null);
  528. inviteStreamService.call(InviteSessionType.PLAY, device.getDeviceId(), channelId, null,
  529. InviteErrorCode.ERROR_FOR_SIP_SENDING_FAILED.getCode(),
  530. InviteErrorCode.ERROR_FOR_SIP_SENDING_FAILED.getMsg(), null);
  531. inviteStreamService.removeInviteInfoByDeviceAndChannel(InviteSessionType.PLAY, device.getDeviceId(), channelId);
  532. }
  533. }
  534. @Override
  535. public StreamInfo onPublishHandlerForPlay(MediaServerItem mediaServerItem, HookParam hookParam, String deviceId, String channelId) {
  536. OnStreamChangedHookParam streamChangedHookParam = (OnStreamChangedHookParam) hookParam;
  537. StreamInfo streamInfo = onPublishHandler(mediaServerItem, streamChangedHookParam, deviceId, channelId);
  538. Device device = redisCatchStorage.getDevice(deviceId);
  539. if (streamInfo != null) {
  540. DeviceChannel deviceChannel = storager.queryChannel(deviceId, channelId);
  541. if (deviceChannel != null) {
  542. deviceChannel.setStreamId(streamInfo.getStream());
  543. storager.startPlay(deviceId, channelId, streamInfo.getStream());
  544. }
  545. InviteInfo inviteInfo = inviteStreamService.getInviteInfoByDeviceAndChannel(InviteSessionType.PLAY, deviceId, channelId);
  546. if (inviteInfo != null) {
  547. inviteInfo.setStatus(InviteSessionStatus.ok);
  548. inviteInfo.setStreamInfo(streamInfo);
  549. inviteStreamService.updateInviteInfo(inviteInfo);
  550. }
  551. }
  552. return streamInfo;
  553. }
  554. private StreamInfo onPublishHandlerForPlayback(MediaServerItem mediaServerItem, HookParam param, String deviceId, String channelId, String startTime, String endTime) {
  555. OnStreamChangedHookParam streamChangedHookParam = (OnStreamChangedHookParam) param;
  556. StreamInfo streamInfo = onPublishHandler(mediaServerItem, streamChangedHookParam, deviceId, channelId);
  557. if (streamInfo != null) {
  558. streamInfo.setStartTime(startTime);
  559. streamInfo.setEndTime(endTime);
  560. DeviceChannel deviceChannel = storager.queryChannel(deviceId, channelId);
  561. if (deviceChannel != null) {
  562. deviceChannel.setStreamId(streamInfo.getStream());
  563. storager.startPlay(deviceId, channelId, streamInfo.getStream());
  564. }
  565. InviteInfo inviteInfo = inviteStreamService.getInviteInfoByDeviceAndChannel(InviteSessionType.PLAYBACK, deviceId, channelId);
  566. if (inviteInfo != null) {
  567. inviteInfo.setStatus(InviteSessionStatus.ok);
  568. inviteInfo.setStreamInfo(streamInfo);
  569. inviteStreamService.updateInviteInfo(inviteInfo);
  570. }
  571. }
  572. return streamInfo;
  573. }
  574. @Override
  575. public MediaServerItem getNewMediaServerItem(Device device) {
  576. if (device == null) {
  577. return null;
  578. }
  579. MediaServerItem mediaServerItem;
  580. if (ObjectUtils.isEmpty(device.getMediaServerId()) || "auto".equals(device.getMediaServerId())) {
  581. mediaServerItem = mediaServerService.getMediaServerForMinimumLoad(null);
  582. } else {
  583. mediaServerItem = mediaServerService.getOne(device.getMediaServerId());
  584. }
  585. if (mediaServerItem == null) {
  586. logger.warn("点播时未找到可使用的ZLM...");
  587. }
  588. return mediaServerItem;
  589. }
  590. @Override
  591. public MediaServerItem getNewMediaServerItemHasAssist(Device device) {
  592. if (device == null) {
  593. return null;
  594. }
  595. MediaServerItem mediaServerItem;
  596. if (ObjectUtils.isEmpty(device.getMediaServerId()) || "auto".equals(device.getMediaServerId())) {
  597. mediaServerItem = mediaServerService.getMediaServerForMinimumLoad(true);
  598. } else {
  599. mediaServerItem = mediaServerService.getOne(device.getMediaServerId());
  600. }
  601. if (mediaServerItem == null) {
  602. logger.warn("[获取可用的ZLM节点]未找到可使用的ZLM...");
  603. }
  604. return mediaServerItem;
  605. }
  606. @Override
  607. public void playBack(String deviceId, String channelId, String startTime,
  608. String endTime, ErrorCallback<Object> callback) {
  609. Device device = storager.queryVideoDevice(deviceId);
  610. if (device == null) {
  611. return;
  612. }
  613. MediaServerItem newMediaServerItem = getNewMediaServerItem(device);
  614. SSRCInfo ssrcInfo = mediaServerService.openRTPServer(newMediaServerItem, null, null, device.isSsrcCheck(), true, 0, false,false, device.getStreamModeForParam());
  615. playBack(newMediaServerItem, ssrcInfo, deviceId, channelId, startTime, endTime, callback);
  616. }
  617. @Override
  618. public void playBack(MediaServerItem mediaServerItem, SSRCInfo ssrcInfo,
  619. String deviceId, String channelId, String startTime,
  620. String endTime, ErrorCallback<Object> callback) {
  621. if (mediaServerItem == null || ssrcInfo == null) {
  622. callback.run(InviteErrorCode.ERROR_FOR_PARAMETER_ERROR.getCode(),
  623. InviteErrorCode.ERROR_FOR_PARAMETER_ERROR.getMsg(),
  624. null);
  625. return;
  626. }
  627. Device device = storager.queryVideoDevice(deviceId);
  628. if (device == null) {
  629. throw new ControllerException(ErrorCode.ERROR100.getCode(), "设备: " + deviceId + "不存在");
  630. }
  631. logger.info("[录像回放] deviceId: {}, channelId: {}, 开始时间: {}, 结束时间: {}, 收流端口:{}, 收流模式:{}, SSRC: {}, SSRC校验:{}",
  632. device.getDeviceId(), channelId, startTime, endTime, ssrcInfo.getPort(), device.getStreamMode(),
  633. ssrcInfo.getSsrc(), device.isSsrcCheck());
  634. // 初始化redis中的invite消息状态
  635. InviteInfo inviteInfo = InviteInfo.getInviteInfo(device.getDeviceId(), channelId, ssrcInfo.getStream(), ssrcInfo,
  636. mediaServerItem.getSdpIp(), ssrcInfo.getPort(), device.getStreamMode(), InviteSessionType.PLAYBACK,
  637. InviteSessionStatus.ready);
  638. inviteStreamService.updateInviteInfo(inviteInfo);
  639. String playBackTimeOutTaskKey = UUID.randomUUID().toString();
  640. dynamicTask.startDelay(playBackTimeOutTaskKey, () -> {
  641. logger.warn("[录像回放] 超时,deviceId:{} ,channelId:{}", deviceId, channelId);
  642. inviteStreamService.removeInviteInfo(inviteInfo);
  643. callback.run(InviteErrorCode.ERROR_FOR_SIGNALLING_TIMEOUT.getCode(), InviteErrorCode.ERROR_FOR_SIGNALLING_TIMEOUT.getMsg(), null);
  644. try {
  645. cmder.streamByeCmd(device, channelId, ssrcInfo.getStream(), null);
  646. } catch (InvalidArgumentException | ParseException | SipException e) {
  647. logger.error("[录像回放] 超时 发送BYE失败 {}", e.getMessage());
  648. } catch (SsrcTransactionNotFoundException e) {
  649. // 点播超时回复BYE 同时释放ssrc以及此次点播的资源
  650. mediaServerService.releaseSsrc(mediaServerItem.getId(), ssrcInfo.getSsrc());
  651. mediaServerService.closeRTPServer(mediaServerItem, ssrcInfo.getStream());
  652. streamSession.remove(deviceId, channelId, ssrcInfo.getStream());
  653. }
  654. }, userSetting.getPlayTimeout());
  655. SipSubscribe.Event errorEvent = event -> {
  656. logger.info("[录像回放] 失败,{} {}", event.statusCode, event.msg);
  657. dynamicTask.stop(playBackTimeOutTaskKey);
  658. callback.run(InviteErrorCode.ERROR_FOR_SIGNALLING_ERROR.getCode(),
  659. String.format("回放失败, 错误码: %s, %s", event.statusCode, event.msg), null);
  660. mediaServerService.releaseSsrc(mediaServerItem.getId(), ssrcInfo.getSsrc());
  661. mediaServerService.closeRTPServer(mediaServerItem, ssrcInfo.getStream());
  662. streamSession.remove(device.getDeviceId(), channelId, ssrcInfo.getStream());
  663. inviteStreamService.removeInviteInfo(inviteInfo);
  664. };
  665. ZlmHttpHookSubscribe.Event hookEvent = (mediaServerItemInuse, hookParam) -> {
  666. logger.info("收到回放订阅消息: " + hookParam);
  667. dynamicTask.stop(playBackTimeOutTaskKey);
  668. StreamInfo streamInfo = onPublishHandlerForPlayback(mediaServerItemInuse, hookParam, deviceId, channelId, startTime, endTime);
  669. if (streamInfo == null) {
  670. logger.warn("设备回放API调用失败!");
  671. callback.run(InviteErrorCode.ERROR_FOR_STREAM_PARSING_EXCEPTIONS.getCode(),
  672. InviteErrorCode.ERROR_FOR_STREAM_PARSING_EXCEPTIONS.getMsg(), null);
  673. return;
  674. }
  675. callback.run(InviteErrorCode.SUCCESS.getCode(), InviteErrorCode.SUCCESS.getMsg(), streamInfo);
  676. logger.info("[录像回放] 成功 deviceId: {}, channelId: {}, 开始时间: {}, 结束时间: {}", device.getDeviceId(), channelId, startTime, endTime);
  677. };
  678. try {
  679. cmder.playbackStreamCmd(mediaServerItem, ssrcInfo, device, channelId, startTime, endTime,
  680. hookEvent, eventResult -> {
  681. inviteInfo.setStatus(InviteSessionStatus.ok);
  682. ResponseEvent responseEvent = (ResponseEvent) eventResult.event;
  683. String contentString = new String(responseEvent.getResponse().getRawContent());
  684. // 获取ssrc
  685. int ssrcIndex = contentString.indexOf("y=");
  686. // 检查是否有y字段
  687. if (ssrcIndex >= 0) {
  688. //ssrc规定长度为10字节,不取余下长度以避免后续还有“f=”字段 TODO 后续对不规范的非10位ssrc兼容
  689. String ssrcInResponse = contentString.substring(ssrcIndex + 2, ssrcIndex + 12);
  690. // 查询到ssrc不一致且开启了ssrc校验则需要针对处理
  691. if (ssrcInfo.getSsrc().equals(ssrcInResponse)) {
  692. if (device.getStreamMode().equalsIgnoreCase("TCP-ACTIVE")) {
  693. String substring = contentString.substring(0, contentString.indexOf("y="));
  694. try {
  695. SessionDescription sdp = SdpFactory.getInstance().createSessionDescription(substring);
  696. int port = -1;
  697. Vector mediaDescriptions = sdp.getMediaDescriptions(true);
  698. for (Object description : mediaDescriptions) {
  699. MediaDescription mediaDescription = (MediaDescription) description;
  700. Media media = mediaDescription.getMedia();
  701. Vector mediaFormats = media.getMediaFormats(false);
  702. if (mediaFormats.contains("96")) {
  703. port = media.getMediaPort();
  704. break;
  705. }
  706. }
  707. logger.info("[录像回放-TCP主动连接对方] deviceId: {}, channelId: {}, 连接对方的地址:{}:{}, 收流模式:{}, SSRC: {}, SSRC校验:{}", device.getDeviceId(), channelId, sdp.getConnection().getAddress(), port, device.getStreamMode(), ssrcInfo.getSsrc(), device.isSsrcCheck());
  708. JSONObject jsonObject = zlmresTfulUtils.connectRtpServer(mediaServerItem, sdp.getConnection().getAddress(), port, ssrcInfo.getStream());
  709. logger.info("[录像回放-TCP主动连接对方] 结果: {}", jsonObject);
  710. } catch (SdpException e) {
  711. logger.error("[录像回放-TCP主动连接对方] deviceId: {}, channelId: {}, 解析200OK的SDP信息失败", device.getDeviceId(), channelId, e);
  712. dynamicTask.stop(playBackTimeOutTaskKey);
  713. mediaServerService.closeRTPServer(mediaServerItem, ssrcInfo.getStream());
  714. // 释放ssrc
  715. mediaServerService.releaseSsrc(mediaServerItem.getId(), ssrcInfo.getSsrc());
  716. streamSession.remove(device.getDeviceId(), channelId, ssrcInfo.getStream());
  717. callback.run(InviteErrorCode.ERROR_FOR_SDP_PARSING_EXCEPTIONS.getCode(),
  718. InviteErrorCode.ERROR_FOR_SDP_PARSING_EXCEPTIONS.getMsg(), null);
  719. inviteStreamService.call(InviteSessionType.PLAY, device.getDeviceId(), channelId, null,
  720. InviteErrorCode.ERROR_FOR_SDP_PARSING_EXCEPTIONS.getCode(),
  721. InviteErrorCode.ERROR_FOR_SDP_PARSING_EXCEPTIONS.getMsg(), null);
  722. }
  723. }
  724. return;
  725. }
  726. logger.info("[录像回放] 收到invite 200, 发现下级自定义了ssrc: {}", ssrcInResponse);
  727. if (!mediaServerItem.isRtpEnable() || device.isSsrcCheck()) {
  728. logger.info("[录像回放] SSRC修正 {}->{}", ssrcInfo.getSsrc(), ssrcInResponse);
  729. // 释放ssrc
  730. mediaServerService.releaseSsrc(mediaServerItem.getId(), ssrcInfo.getSsrc());
  731. // 单端口模式streamId也有变化,需要重新设置监听
  732. if (!mediaServerItem.isRtpEnable()) {
  733. // 添加订阅
  734. HookSubscribeForStreamChange hookSubscribe = HookSubscribeFactory.on_stream_changed("rtp", ssrcInfo.getStream(), true, "rtsp", mediaServerItem.getId());
  735. subscribe.removeSubscribe(hookSubscribe);
  736. String stream = String.format("%08x", Integer.parseInt(ssrcInResponse)).toUpperCase();
  737. hookSubscribe.getContent().put("stream", stream);
  738. inviteStreamService.updateInviteInfoForStream(inviteInfo, stream);
  739. subscribe.addSubscribe(hookSubscribe, (mediaServerItemInUse, hookParam) -> {
  740. logger.info("[ZLM HOOK] ssrc修正后收到订阅消息: " + hookParam);
  741. dynamicTask.stop(playBackTimeOutTaskKey);
  742. // hook响应
  743. hookEvent.response(mediaServerItemInUse, hookParam);
  744. });
  745. }
  746. // 更新ssrc
  747. Boolean result = mediaServerService.updateRtpServerSSRC(mediaServerItem, ssrcInfo.getStream(), ssrcInResponse);
  748. if (!result) {
  749. try {
  750. logger.warn("[录像回放] 更新ssrc失败,停止录像回放 {}/{}", device.getDeviceId(), channelId);
  751. cmder.streamByeCmd(device, channelId, ssrcInfo.getStream(), null, null);
  752. } catch (InvalidArgumentException | SipException | ParseException | SsrcTransactionNotFoundException e) {
  753. logger.error("[命令发送失败] 停止点播, 发送BYE: {}", e.getMessage());
  754. }
  755. dynamicTask.stop(playBackTimeOutTaskKey);
  756. // 释放ssrc
  757. mediaServerService.releaseSsrc(mediaServerItem.getId(), ssrcInfo.getSsrc());
  758. streamSession.remove(device.getDeviceId(), channelId, ssrcInfo.getStream());
  759. callback.run(InviteErrorCode.ERROR_FOR_RESET_SSRC.getCode(),
  760. "下级自定义了ssrc,重新设置收流信息失败", null);
  761. }else {
  762. if (ssrcInfo.getStream()!= null && !ssrcInfo.getStream().equals(inviteInfo.getStream())) {
  763. inviteStreamService.removeInviteInfo(inviteInfo);
  764. }
  765. ssrcInfo.setSsrc(ssrcInResponse);
  766. inviteInfo.setSsrcInfo(ssrcInfo);
  767. inviteInfo.setStream(ssrcInfo.getStream());
  768. }
  769. }else {
  770. logger.info("[点播消息] 收到invite 200, 下级自定义了ssrc, 但是当前模式无需修正");
  771. }
  772. }
  773. inviteStreamService.updateInviteInfo(inviteInfo);
  774. }, errorEvent);
  775. } catch (InvalidArgumentException | SipException | ParseException e) {
  776. logger.error("[命令发送失败] 回放: {}", e.getMessage());
  777. SipSubscribe.EventResult eventResult = new SipSubscribe.EventResult();
  778. eventResult.type = SipSubscribe.EventResultType.cmdSendFailEvent;
  779. eventResult.statusCode = -1;
  780. eventResult.msg = "命令发送失败";
  781. errorEvent.response(eventResult);
  782. }
  783. }
  784. @Override
  785. public void download(String deviceId, String channelId, String startTime, String endTime, int downloadSpeed, ErrorCallback<Object> callback) {
  786. Device device = storager.queryVideoDevice(deviceId);
  787. if (device == null) {
  788. return;
  789. }
  790. MediaServerItem newMediaServerItem = getNewMediaServerItemHasAssist(device);
  791. if (newMediaServerItem == null) {
  792. callback.run(InviteErrorCode.ERROR_FOR_ASSIST_NOT_READY.getCode(),
  793. InviteErrorCode.ERROR_FOR_ASSIST_NOT_READY.getMsg(),
  794. null);
  795. return;
  796. }
  797. SSRCInfo ssrcInfo = mediaServerService.openRTPServer(newMediaServerItem, null, null, device.isSsrcCheck(), true, 0, false,false, device.getStreamModeForParam());
  798. download(newMediaServerItem, ssrcInfo, deviceId, channelId, startTime, endTime, downloadSpeed, callback);
  799. }
  800. @Override
  801. public void download(MediaServerItem mediaServerItem, SSRCInfo ssrcInfo, String deviceId, String channelId, String startTime, String endTime, int downloadSpeed, ErrorCallback<Object> callback) {
  802. if (mediaServerItem == null || ssrcInfo == null) {
  803. callback.run(InviteErrorCode.ERROR_FOR_PARAMETER_ERROR.getCode(),
  804. InviteErrorCode.ERROR_FOR_PARAMETER_ERROR.getMsg(),
  805. null);
  806. return;
  807. }
  808. Device device = storager.queryVideoDevice(deviceId);
  809. if (device == null) {
  810. callback.run(InviteErrorCode.ERROR_FOR_PARAMETER_ERROR.getCode(),
  811. "设备:" + deviceId + "不存在",
  812. null);
  813. return;
  814. }
  815. logger.info("[录像下载] deviceId: {}, channelId: {}, 下载速度:{}, 收流端口:{}, 收流模式:{}, SSRC: {}, SSRC校验:{}", device.getDeviceId(), channelId, downloadSpeed, ssrcInfo.getPort(), device.getStreamMode(), ssrcInfo.getSsrc(), device.isSsrcCheck());
  816. // 初始化redis中的invite消息状态
  817. InviteInfo inviteInfo = InviteInfo.getInviteInfo(device.getDeviceId(), channelId, ssrcInfo.getStream(), ssrcInfo,
  818. mediaServerItem.getSdpIp(), ssrcInfo.getPort(), device.getStreamMode(), InviteSessionType.DOWNLOAD,
  819. InviteSessionStatus.ready);
  820. inviteStreamService.updateInviteInfo(inviteInfo);
  821. String downLoadTimeOutTaskKey = UUID.randomUUID().toString();
  822. dynamicTask.startDelay(downLoadTimeOutTaskKey, () -> {
  823. logger.warn(String.format("录像下载请求超时,deviceId:%s ,channelId:%s", deviceId, channelId));
  824. inviteStreamService.removeInviteInfo(inviteInfo);
  825. callback.run(InviteErrorCode.ERROR_FOR_SIGNALLING_TIMEOUT.getCode(),
  826. InviteErrorCode.ERROR_FOR_SIGNALLING_TIMEOUT.getMsg(), null);
  827. // 点播超时回复BYE 同时释放ssrc以及此次点播的资源
  828. try {
  829. cmder.streamByeCmd(device, channelId, ssrcInfo.getStream(), null);
  830. } catch (InvalidArgumentException | ParseException | SipException e) {
  831. logger.error("[录像流]录像下载请求超时, 发送BYE失败 {}", e.getMessage());
  832. } catch (SsrcTransactionNotFoundException e) {
  833. mediaServerService.releaseSsrc(mediaServerItem.getId(), ssrcInfo.getSsrc());
  834. mediaServerService.closeRTPServer(mediaServerItem, ssrcInfo.getStream());
  835. streamSession.remove(deviceId, channelId, ssrcInfo.getStream());
  836. }
  837. }, userSetting.getPlayTimeout());
  838. SipSubscribe.Event errorEvent = event -> {
  839. dynamicTask.stop(downLoadTimeOutTaskKey);
  840. callback.run(InviteErrorCode.ERROR_FOR_SIGNALLING_TIMEOUT.getCode(),
  841. String.format("录像下载失败, 错误码: %s, %s", event.statusCode, event.msg), null);
  842. streamSession.remove(device.getDeviceId(), channelId, ssrcInfo.getStream());
  843. inviteStreamService.removeInviteInfo(inviteInfo);
  844. };
  845. ZlmHttpHookSubscribe.Event hookEvent = (mediaServerItemInuse, hookParam) -> {
  846. logger.info("[录像下载]收到订阅消息: " + hookParam);
  847. dynamicTask.stop(downLoadTimeOutTaskKey);
  848. StreamInfo streamInfo = onPublishHandlerForDownload(mediaServerItemInuse, hookParam, deviceId, channelId, startTime, endTime);
  849. if (streamInfo == null) {
  850. logger.warn("[录像下载] 获取流地址信息失败");
  851. callback.run(InviteErrorCode.ERROR_FOR_STREAM_PARSING_EXCEPTIONS.getCode(),
  852. InviteErrorCode.ERROR_FOR_STREAM_PARSING_EXCEPTIONS.getMsg(), null);
  853. return;
  854. }
  855. callback.run(InviteErrorCode.SUCCESS.getCode(), InviteErrorCode.SUCCESS.getMsg(), streamInfo);
  856. logger.info("[录像下载] 调用成功 deviceId: {}, channelId: {}, 开始时间: {}, 结束时间: {}", device.getDeviceId(), channelId, startTime, endTime);
  857. };
  858. try {
  859. cmder.downloadStreamCmd(mediaServerItem, ssrcInfo, device, channelId, startTime, endTime, downloadSpeed,
  860. hookEvent, errorEvent, eventResult ->{
  861. inviteInfo.setStatus(InviteSessionStatus.ok);
  862. ResponseEvent responseEvent = (ResponseEvent) eventResult.event;
  863. String contentString = new String(responseEvent.getResponse().getRawContent());
  864. // 获取ssrc
  865. int ssrcIndex = contentString.indexOf("y=");
  866. // 检查是否有y字段
  867. if (ssrcIndex >= 0) {
  868. //ssrc规定长度为10字节,不取余下长度以避免后续还有“f=”字段 TODO 后续对不规范的非10位ssrc兼容
  869. String ssrcInResponse = contentString.substring(ssrcIndex + 2, ssrcIndex + 12);
  870. // 查询到ssrc不一致且开启了ssrc校验则需要针对处理
  871. if (ssrcInfo.getSsrc().equals(ssrcInResponse)) {
  872. if (device.getStreamMode().equalsIgnoreCase("TCP-ACTIVE")) {
  873. String substring = contentString.substring(0, contentString.indexOf("y="));
  874. try {
  875. SessionDescription sdp = SdpFactory.getInstance().createSessionDescription(substring);
  876. int port = -1;
  877. Vector mediaDescriptions = sdp.getMediaDescriptions(true);
  878. for (Object description : mediaDescriptions) {
  879. MediaDescription mediaDescription = (MediaDescription) description;
  880. Media media = mediaDescription.getMedia();
  881. Vector mediaFormats = media.getMediaFormats(false);
  882. if (mediaFormats.contains("96")) {
  883. port = media.getMediaPort();
  884. break;
  885. }
  886. }
  887. logger.info("[录像下载-TCP主动连接对方] deviceId: {}, channelId: {}, 连接对方的地址:{}:{}, 收流模式:{}, SSRC: {}, SSRC校验:{}", device.getDeviceId(), channelId, sdp.getConnection().getAddress(), port, device.getStreamMode(), ssrcInfo.getSsrc(), device.isSsrcCheck());
  888. JSONObject jsonObject = zlmresTfulUtils.connectRtpServer(mediaServerItem, sdp.getConnection().getAddress(), port, ssrcInfo.getStream());
  889. logger.info("[录像下载-TCP主动连接对方] 结果: {}", jsonObject);
  890. } catch (SdpException e) {
  891. logger.error("[录像下载-TCP主动连接对方] deviceId: {}, channelId: {}, 解析200OK的SDP信息失败", device.getDeviceId(), channelId, e);
  892. dynamicTask.stop(downLoadTimeOutTaskKey);
  893. mediaServerService.closeRTPServer(mediaServerItem, ssrcInfo.getStream());
  894. // 释放ssrc
  895. mediaServerService.releaseSsrc(mediaServerItem.getId(), ssrcInfo.getSsrc());
  896. streamSession.remove(device.getDeviceId(), channelId, ssrcInfo.getStream());
  897. callback.run(InviteErrorCode.ERROR_FOR_SDP_PARSING_EXCEPTIONS.getCode(),
  898. InviteErrorCode.ERROR_FOR_SDP_PARSING_EXCEPTIONS.getMsg(), null);
  899. inviteStreamService.call(InviteSessionType.PLAY, device.getDeviceId(), channelId, null,
  900. InviteErrorCode.ERROR_FOR_SDP_PARSING_EXCEPTIONS.getCode(),
  901. InviteErrorCode.ERROR_FOR_SDP_PARSING_EXCEPTIONS.getMsg(), null);
  902. }
  903. }
  904. return;
  905. }
  906. logger.info("[录像下载] 收到invite 200, 发现下级自定义了ssrc: {}", ssrcInResponse);
  907. if (!mediaServerItem.isRtpEnable() || device.isSsrcCheck()) {
  908. logger.info("[录像下载] SSRC修正 {}->{}", ssrcInfo.getSsrc(), ssrcInResponse);
  909. // 释放ssrc
  910. mediaServerService.releaseSsrc(mediaServerItem.getId(), ssrcInfo.getSsrc());
  911. // 单端口模式streamId也有变化,需要重新设置监听
  912. if (!mediaServerItem.isRtpEnable()) {
  913. // 添加订阅
  914. HookSubscribeForStreamChange hookSubscribe = HookSubscribeFactory.on_stream_changed("rtp", ssrcInfo.getStream(), true, "rtsp", mediaServerItem.getId());
  915. subscribe.removeSubscribe(hookSubscribe);
  916. String stream = String.format("%08x", Integer.parseInt(ssrcInResponse)).toUpperCase();
  917. hookSubscribe.getContent().put("stream", stream);
  918. inviteStreamService.updateInviteInfoForStream(inviteInfo, stream);
  919. subscribe.addSubscribe(hookSubscribe, (mediaServerItemInUse, hookParam) -> {
  920. logger.info("[ZLM HOOK] ssrc修正后收到订阅消息: " + hookParam);
  921. dynamicTask.stop(downLoadTimeOutTaskKey);
  922. hookEvent.response(mediaServerItemInUse, hookParam);
  923. });
  924. }
  925. // 更新ssrc
  926. Boolean result = mediaServerService.updateRtpServerSSRC(mediaServerItem, ssrcInfo.getStream(), ssrcInResponse);
  927. if (!result) {
  928. try {
  929. logger.warn("[录像下载] 更新ssrc失败,停止录像回放 {}/{}", device.getDeviceId(), channelId);
  930. cmder.streamByeCmd(device, channelId, ssrcInfo.getStream(), null, null);
  931. } catch (InvalidArgumentException | SipException | ParseException | SsrcTransactionNotFoundException e) {
  932. logger.error("[命令发送失败] 停止点播, 发送BYE: {}", e.getMessage());
  933. }
  934. dynamicTask.stop(downLoadTimeOutTaskKey);
  935. // 释放ssrc
  936. mediaServerService.releaseSsrc(mediaServerItem.getId(), ssrcInfo.getSsrc());
  937. streamSession.remove(device.getDeviceId(), channelId, ssrcInfo.getStream());
  938. callback.run(InviteErrorCode.ERROR_FOR_RESET_SSRC.getCode(),
  939. "下级自定义了ssrc,重新设置收流信息失败", null);
  940. }else {
  941. if (ssrcInfo.getStream()!= null && !ssrcInfo.getStream().equals(inviteInfo.getStream())) {
  942. inviteStreamService.removeInviteInfo(inviteInfo);
  943. }
  944. ssrcInfo.setSsrc(ssrcInResponse);
  945. inviteInfo.setSsrcInfo(ssrcInfo);
  946. inviteInfo.setStream(ssrcInfo.getStream());
  947. }
  948. }else {
  949. logger.info("[录像下载] 收到invite 200, 下级自定义了ssrc, 但是当前模式无需修正");
  950. }
  951. }
  952. inviteStreamService.updateInviteInfo(inviteInfo);
  953. });
  954. } catch (InvalidArgumentException | SipException | ParseException e) {
  955. logger.error("[命令发送失败] 录像下载: {}", e.getMessage());
  956. SipSubscribe.EventResult eventResult = new SipSubscribe.EventResult();
  957. eventResult.type = SipSubscribe.EventResultType.cmdSendFailEvent;
  958. eventResult.statusCode = -1;
  959. eventResult.msg = "命令发送失败";
  960. errorEvent.response(eventResult);
  961. }
  962. }
  963. @Override
  964. public StreamInfo getDownLoadInfo(String deviceId, String channelId, String stream) {
  965. InviteInfo inviteInfo = inviteStreamService.getInviteInfo(InviteSessionType.DOWNLOAD, deviceId, channelId, stream);
  966. if (inviteInfo != null && inviteInfo.getStreamInfo() != null) {
  967. if (inviteInfo.getStreamInfo().getProgress() == 1) {
  968. return inviteInfo.getStreamInfo();
  969. }
  970. // 获取当前已下载时长
  971. String mediaServerId = inviteInfo.getStreamInfo().getMediaServerId();
  972. MediaServerItem mediaServerItem = mediaServerService.getOne(mediaServerId);
  973. if (mediaServerItem == null) {
  974. logger.warn("查询录像信息时发现节点已离线");
  975. return null;
  976. }
  977. if (mediaServerItem.getRecordAssistPort() > 0) {
  978. JSONObject jsonObject = assistRESTfulUtils.fileDuration(mediaServerItem, inviteInfo.getStreamInfo().getApp(), inviteInfo.getStreamInfo().getStream(), null);
  979. if (jsonObject == null) {
  980. throw new ControllerException(ErrorCode.ERROR100.getCode(), "连接Assist服务失败");
  981. }
  982. if (jsonObject.getInteger("code") == 0) {
  983. long duration = jsonObject.getLong("data");
  984. if (duration == 0) {
  985. inviteInfo.getStreamInfo().setProgress(0);
  986. } else {
  987. String startTime = inviteInfo.getStreamInfo().getStartTime();
  988. String endTime = inviteInfo.getStreamInfo().getEndTime();
  989. long start = DateUtil.yyyy_MM_dd_HH_mm_ssToTimestamp(startTime);
  990. long end = DateUtil.yyyy_MM_dd_HH_mm_ssToTimestamp(endTime);
  991. BigDecimal currentCount = new BigDecimal(duration / 1000);
  992. BigDecimal totalCount = new BigDecimal(end - start);
  993. BigDecimal divide = currentCount.divide(totalCount, 2, RoundingMode.HALF_UP);
  994. double process = divide.doubleValue();
  995. inviteInfo.getStreamInfo().setProgress(process);
  996. }
  997. inviteStreamService.updateInviteInfo(inviteInfo);
  998. }
  999. }
  1000. return inviteInfo.getStreamInfo();
  1001. }
  1002. return null;
  1003. }
  1004. private StreamInfo onPublishHandlerForDownload(MediaServerItem mediaServerItemInuse, HookParam hookParam, String deviceId, String channelId, String startTime, String endTime) {
  1005. OnStreamChangedHookParam streamChangedHookParam = (OnStreamChangedHookParam) hookParam;
  1006. StreamInfo streamInfo = onPublishHandler(mediaServerItemInuse, streamChangedHookParam, deviceId, channelId);
  1007. if (streamInfo != null) {
  1008. streamInfo.setProgress(0);
  1009. streamInfo.setStartTime(startTime);
  1010. streamInfo.setEndTime(endTime);
  1011. InviteInfo inviteInfo = inviteStreamService.getInviteInfo(InviteSessionType.DOWNLOAD, deviceId, channelId, streamInfo.getStream());
  1012. if (inviteInfo != null) {
  1013. logger.info("[录像下载] 更新invite消息中的stream信息");
  1014. inviteInfo.setStatus(InviteSessionStatus.ok);
  1015. inviteInfo.setStreamInfo(streamInfo);
  1016. inviteStreamService.updateInviteInfo(inviteInfo);
  1017. }
  1018. }
  1019. return streamInfo;
  1020. }
  1021. public StreamInfo onPublishHandler(MediaServerItem mediaServerItem, OnStreamChangedHookParam hookParam, String deviceId, String channelId) {
  1022. StreamInfo streamInfo = mediaService.getStreamInfoByAppAndStream(mediaServerItem, "rtp", hookParam.getStream(), hookParam.getTracks(), null);
  1023. streamInfo.setDeviceID(deviceId);
  1024. streamInfo.setChannelId(channelId);
  1025. return streamInfo;
  1026. }
  1027. @Override
  1028. public void zlmServerOffline(String mediaServerId) {
  1029. // 处理正在向上推流的上级平台
  1030. List<SendRtpItem> sendRtpItems = redisCatchStorage.querySendRTPServer(null);
  1031. if (sendRtpItems.size() > 0) {
  1032. for (SendRtpItem sendRtpItem : sendRtpItems) {
  1033. if (sendRtpItem.getMediaServerId().equals(mediaServerId)) {
  1034. ParentPlatform platform = storager.queryParentPlatByServerGBId(sendRtpItem.getPlatformId());
  1035. try {
  1036. sipCommanderFroPlatform.streamByeCmd(platform, sendRtpItem.getCallId());
  1037. } catch (SipException | InvalidArgumentException | ParseException e) {
  1038. logger.error("[命令发送失败] 国标级联 发送BYE: {}", e.getMessage());
  1039. }
  1040. }
  1041. }
  1042. }
  1043. // 处理正在观看的国标设备
  1044. List<SsrcTransaction> allSsrc = streamSession.getAllSsrc();
  1045. if (allSsrc.size() > 0) {
  1046. for (SsrcTransaction ssrcTransaction : allSsrc) {
  1047. if (ssrcTransaction.getMediaServerId().equals(mediaServerId)) {
  1048. Device device = deviceService.getDevice(ssrcTransaction.getDeviceId());
  1049. if (device == null) {
  1050. continue;
  1051. }
  1052. try {
  1053. cmder.streamByeCmd(device, ssrcTransaction.getChannelId(),
  1054. ssrcTransaction.getStream(), null);
  1055. } catch (InvalidArgumentException | ParseException | SipException |
  1056. SsrcTransactionNotFoundException e) {
  1057. logger.error("[zlm离线]为正在使用此zlm的设备, 发送BYE失败 {}", e.getMessage());
  1058. }
  1059. }
  1060. }
  1061. }
  1062. }
  1063. @Override
  1064. public AudioBroadcastResult audioBroadcast(Device device, String channelId, Boolean broadcastMode) {
  1065. // TODO 必须多端口模式才支持语音喊话鹤语音对讲
  1066. if (device == null || channelId == null) {
  1067. return null;
  1068. }
  1069. logger.info("[语音喊话] device: {}, channel: {}", device.getDeviceId(), channelId);
  1070. DeviceChannel deviceChannel = storager.queryChannel(device.getDeviceId(), channelId);
  1071. if (deviceChannel == null) {
  1072. logger.warn("开启语音广播的时候未找到通道: {}", channelId);
  1073. return null;
  1074. }
  1075. MediaServerItem mediaServerItem = mediaServerService.getMediaServerForMinimumLoad(null);
  1076. if (broadcastMode == null) {
  1077. broadcastMode = true;
  1078. }
  1079. String app = broadcastMode?"broadcast":"talk";
  1080. String stream = device.getDeviceId() + "_" + channelId;
  1081. AudioBroadcastResult audioBroadcastResult = new AudioBroadcastResult();
  1082. audioBroadcastResult.setApp(app);
  1083. audioBroadcastResult.setStream(stream);
  1084. audioBroadcastResult.setStreamInfo(new StreamContent(mediaService.getStreamInfoByAppAndStream(mediaServerItem, app, stream, null, null, null, false)));
  1085. audioBroadcastResult.setCodec("G.711");
  1086. return audioBroadcastResult;
  1087. }
  1088. @Override
  1089. public boolean audioBroadcastCmd(Device device, String channelId, MediaServerItem mediaServerItem, String app, String stream, int timeout, boolean isFromPlatform, AudioBroadcastEvent event) throws InvalidArgumentException, ParseException, SipException {
  1090. if (device == null || channelId == null) {
  1091. return false;
  1092. }
  1093. logger.info("[语音喊话] device: {}, channel: {}", device.getDeviceId(), channelId);
  1094. DeviceChannel deviceChannel = storager.queryChannel(device.getDeviceId(), channelId);
  1095. if (deviceChannel == null) {
  1096. logger.warn("开启语音广播的时候未找到通道: {}", channelId);
  1097. event.call("开启语音广播的时候未找到通道");
  1098. return false;
  1099. }
  1100. // 查询通道使用状态
  1101. if (audioBroadcastManager.exit(device.getDeviceId(), channelId)) {
  1102. SendRtpItem sendRtpItem = redisCatchStorage.querySendRTPServer(device.getDeviceId(), channelId, null, null);
  1103. if (sendRtpItem != null && sendRtpItem.isOnlyAudio()) {
  1104. // 查询流是否存在,不存在则认为是异常状态
  1105. Boolean streamReady = zlmrtpServerFactory.isStreamReady(mediaServerItem, sendRtpItem.getApp(), sendRtpItem.getStream());
  1106. if (streamReady) {
  1107. logger.warn("语音广播已经开启: {}", channelId);
  1108. event.call("语音广播已经开启");
  1109. return false;
  1110. } else {
  1111. stopAudioBroadcast(device.getDeviceId(), channelId);
  1112. }
  1113. }
  1114. }
  1115. SendRtpItem sendRtpItem = redisCatchStorage.querySendRTPServer(device.getDeviceId(), channelId, null, null);
  1116. if (sendRtpItem != null) {
  1117. MediaServerItem mediaServer = mediaServerService.getOne(sendRtpItem.getMediaServerId());
  1118. Boolean streamReady = zlmrtpServerFactory.isStreamReady(mediaServer, "rtp", sendRtpItem.getReceiveStream());
  1119. if (streamReady) {
  1120. logger.warn("[语音对讲] 进行中: {}", channelId);
  1121. event.call("语音对讲进行中");
  1122. return false;
  1123. } else {
  1124. stopTalk(device, channelId);
  1125. }
  1126. }
  1127. // 发送通知
  1128. cmder.audioBroadcastCmd(device, channelId, eventResultForOk -> {
  1129. // 发送成功
  1130. AudioBroadcastCatch audioBroadcastCatch = new AudioBroadcastCatch(device.getDeviceId(), channelId, mediaServerItem, app, stream, event, AudioBroadcastCatchStatus.Ready, isFromPlatform);
  1131. audioBroadcastManager.update(audioBroadcastCatch);
  1132. }, eventResultForError -> {
  1133. // 发送失败
  1134. logger.error("语音广播发送失败: {}:{}", channelId, eventResultForError.msg);
  1135. event.call("语音广播发送失败");
  1136. stopAudioBroadcast(device.getDeviceId(), channelId);
  1137. });
  1138. return true;
  1139. }
  1140. @Override
  1141. public boolean audioBroadcastInUse(Device device, String channelId) {
  1142. if (audioBroadcastManager.exit(device.getDeviceId(), channelId)) {
  1143. SendRtpItem sendRtpItem = redisCatchStorage.querySendRTPServer(device.getDeviceId(), channelId, null, null);
  1144. if (sendRtpItem != null && sendRtpItem.isOnlyAudio()) {
  1145. // 查询流是否存在,不存在则认为是异常状态
  1146. MediaServerItem mediaServerServiceOne = mediaServerService.getOne(sendRtpItem.getMediaServerId());
  1147. Boolean streamReady = zlmrtpServerFactory.isStreamReady(mediaServerServiceOne, sendRtpItem.getApp(), sendRtpItem.getStream());
  1148. if (streamReady) {
  1149. logger.warn("语音广播通道使用中: {}", channelId);
  1150. return true;
  1151. }
  1152. }
  1153. }
  1154. return false;
  1155. }
  1156. @Override
  1157. public void stopAudioBroadcast(String deviceId, String channelId) {
  1158. logger.info("[停止对讲] 设备:{}, 通道:{}", deviceId, channelId);
  1159. List<AudioBroadcastCatch> audioBroadcastCatchList = new ArrayList<>();
  1160. if (channelId == null) {
  1161. audioBroadcastCatchList.addAll(audioBroadcastManager.get(deviceId));
  1162. } else {
  1163. audioBroadcastCatchList.add(audioBroadcastManager.get(deviceId, channelId));
  1164. }
  1165. if (audioBroadcastCatchList.size() > 0) {
  1166. for (AudioBroadcastCatch audioBroadcastCatch : audioBroadcastCatchList) {
  1167. Device device = deviceService.getDevice(deviceId);
  1168. if (device == null || audioBroadcastCatch == null) {
  1169. return;
  1170. }
  1171. SendRtpItem sendRtpItem = redisCatchStorage.querySendRTPServer(deviceId, audioBroadcastCatch.getChannelId(), null, null);
  1172. if (sendRtpItem != null) {
  1173. redisCatchStorage.deleteSendRTPServer(deviceId, sendRtpItem.getChannelId(), null, null);
  1174. MediaServerItem mediaInfo = mediaServerService.getOne(sendRtpItem.getMediaServerId());
  1175. Map<String, Object> param = new HashMap<>();
  1176. param.put("vhost", "__defaultVhost__");
  1177. param.put("app", sendRtpItem.getApp());
  1178. param.put("stream", sendRtpItem.getStream());
  1179. zlmresTfulUtils.stopSendRtp(mediaInfo, param);
  1180. try {
  1181. cmder.streamByeCmd(device, sendRtpItem.getChannelId(), audioBroadcastCatch.getSipTransactionInfo(), null);
  1182. } catch (InvalidArgumentException | ParseException | SipException |
  1183. SsrcTransactionNotFoundException e) {
  1184. logger.error("[消息发送失败] 发送语音喊话BYE失败");
  1185. }
  1186. }
  1187. audioBroadcastManager.del(deviceId, channelId);
  1188. }
  1189. }
  1190. }
  1191. @Override
  1192. public void zlmServerOnline(String mediaServerId) {
  1193. // TODO 查找之前的点播,流如果不存在则给下级发送bye
  1194. // MediaServerItem mediaServerItem = mediaServerService.getOne(mediaServerId);
  1195. // zlmresTfulUtils.getMediaList(mediaServerItem, (mediaList ->{
  1196. // Integer code = mediaList.getInteger("code");
  1197. // if (code == 0) {
  1198. // JSONArray data = mediaList.getJSONArray("data");
  1199. // if (data == null || data.size() == 0) {
  1200. // zlmServerOffline(mediaServerId);
  1201. // }else {
  1202. // Map<String, JSONObject> mediaListMap = new HashMap<>();
  1203. // for (int i = 0; i < data.size(); i++) {
  1204. // JSONObject json = data.getJSONObject(i);
  1205. // String app = json.getString("app");
  1206. // if ("rtp".equals(app)) {
  1207. // String stream = json.getString("stream");
  1208. // if (mediaListMap.get(stream) != null) {
  1209. // continue;
  1210. // }
  1211. // mediaListMap.put(stream, json);
  1212. // // 处理正在观看的国标设备
  1213. // List<SsrcTransaction> ssrcTransactions = streamSession.getSsrcTransactionForAll(null, null, null, stream);
  1214. // if (ssrcTransactions.size() > 0) {
  1215. // for (SsrcTransaction ssrcTransaction : ssrcTransactions) {
  1216. // if(ssrcTransaction.getMediaServerId().equals(mediaServerId)) {
  1217. // cmder.streamByeCmd(ssrcTransaction.getDeviceId(), ssrcTransaction.getChannelId(),
  1218. // ssrcTransaction.getStream(), null);
  1219. // }
  1220. // }
  1221. // }
  1222. // }
  1223. // }
  1224. // if (mediaListMap.size() > 0 ) {
  1225. // // 处理正在向上推流的上级平台
  1226. // List<SendRtpItem> sendRtpItems = redisCatchStorage.querySendRTPServer(null);
  1227. // if (sendRtpItems.size() > 0) {
  1228. // for (SendRtpItem sendRtpItem : sendRtpItems) {
  1229. // if (sendRtpItem.getMediaServerId().equals(mediaServerId)) {
  1230. // if (mediaListMap.get(sendRtpItem.getStreamId()) == null) {
  1231. // ParentPlatform platform = storager.queryPlatformByServerGBId(sendRtpItem.getPlatformId());
  1232. // sipCommanderFroPlatform.streamByeCmd(platform, sendRtpItem.getCallId());
  1233. // }
  1234. // }
  1235. // }
  1236. // }
  1237. // }
  1238. // }
  1239. // }
  1240. // }));
  1241. }
  1242. @Override
  1243. public void pauseRtp(String streamId) throws ServiceException, InvalidArgumentException, ParseException, SipException {
  1244. InviteInfo inviteInfo = inviteStreamService.getInviteInfoByStream(InviteSessionType.PLAYBACK, streamId);
  1245. if (null == inviteInfo || inviteInfo.getStreamInfo() == null) {
  1246. logger.warn("streamId不存在!");
  1247. throw new ServiceException("streamId不存在");
  1248. }
  1249. inviteInfo.getStreamInfo().setPause(true);
  1250. inviteStreamService.updateInviteInfo(inviteInfo);
  1251. MediaServerItem mediaServerItem = mediaServerService.getOne(inviteInfo.getStreamInfo().getMediaServerId());
  1252. if (null == mediaServerItem) {
  1253. logger.warn("mediaServer 不存在!");
  1254. throw new ServiceException("mediaServer不存在");
  1255. }
  1256. // zlm 暂停RTP超时检查
  1257. JSONObject jsonObject = zlmresTfulUtils.pauseRtpCheck(mediaServerItem, streamId);
  1258. if (jsonObject == null || jsonObject.getInteger("code") != 0) {
  1259. throw new ServiceException("暂停RTP接收失败");
  1260. }
  1261. Device device = storager.queryVideoDevice(inviteInfo.getDeviceId());
  1262. cmder.playPauseCmd(device, inviteInfo.getStreamInfo());
  1263. }
  1264. @Override
  1265. public void resumeRtp(String streamId) throws ServiceException, InvalidArgumentException, ParseException, SipException {
  1266. InviteInfo inviteInfo = inviteStreamService.getInviteInfoByStream(InviteSessionType.PLAYBACK, streamId);
  1267. if (null == inviteInfo || inviteInfo.getStreamInfo() == null) {
  1268. logger.warn("streamId不存在!");
  1269. throw new ServiceException("streamId不存在");
  1270. }
  1271. inviteInfo.getStreamInfo().setPause(false);
  1272. inviteStreamService.updateInviteInfo(inviteInfo);
  1273. MediaServerItem mediaServerItem = mediaServerService.getOne(inviteInfo.getStreamInfo().getMediaServerId());
  1274. if (null == mediaServerItem) {
  1275. logger.warn("mediaServer 不存在!");
  1276. throw new ServiceException("mediaServer不存在");
  1277. }
  1278. // zlm 暂停RTP超时检查
  1279. JSONObject jsonObject = zlmresTfulUtils.resumeRtpCheck(mediaServerItem, streamId);
  1280. if (jsonObject == null || jsonObject.getInteger("code") != 0) {
  1281. throw new ServiceException("继续RTP接收失败");
  1282. }
  1283. Device device = storager.queryVideoDevice(inviteInfo.getDeviceId());
  1284. cmder.playResumeCmd(device, inviteInfo.getStreamInfo());
  1285. }
  1286. @Override
  1287. public void startPushStream(SendRtpItem sendRtpItem, SIPResponse sipResponse, ParentPlatform platform, CallIdHeader callIdHeader) {
  1288. // 开始发流
  1289. String is_Udp = sendRtpItem.isTcp() ? "0" : "1";
  1290. MediaServerItem mediaInfo = mediaServerService.getOne(sendRtpItem.getMediaServerId());
  1291. logger.info("[开始推流] rtp/{}, 目标={}:{},SSRC={}, RTCP={}", sendRtpItem.getStream(),
  1292. sendRtpItem.getIp(), sendRtpItem.getPort(), sendRtpItem.getSsrc(), sendRtpItem.isRtcp());
  1293. Map<String, Object> param = new HashMap<>(12);
  1294. param.put("vhost", "__defaultVhost__");
  1295. param.put("app", sendRtpItem.getApp());
  1296. param.put("stream", sendRtpItem.getStream());
  1297. param.put("ssrc", sendRtpItem.getSsrc());
  1298. param.put("src_port", sendRtpItem.getLocalPort());
  1299. param.put("pt", sendRtpItem.getPt());
  1300. param.put("use_ps", sendRtpItem.isUsePs() ? "1" : "0");
  1301. param.put("only_audio", sendRtpItem.isOnlyAudio() ? "1" : "0");
  1302. param.put("is_udp", is_Udp);
  1303. if (!sendRtpItem.isTcp()) {
  1304. // udp模式下开启rtcp保活
  1305. param.put("udp_rtcp_timeout", sendRtpItem.isRtcp() ? "1" : "0");
  1306. }
  1307. if (mediaInfo == null) {
  1308. RequestPushStreamMsg requestPushStreamMsg = RequestPushStreamMsg.getInstance(
  1309. sendRtpItem.getMediaServerId(), sendRtpItem.getApp(), sendRtpItem.getStream(),
  1310. sendRtpItem.getIp(), sendRtpItem.getPort(), sendRtpItem.getSsrc(), sendRtpItem.isTcp(),
  1311. sendRtpItem.getLocalPort(), sendRtpItem.getPt(), sendRtpItem.isUsePs(), sendRtpItem.isOnlyAudio());
  1312. redisGbPlayMsgListener.sendMsgForStartSendRtpStream(sendRtpItem.getServerId(), requestPushStreamMsg, json -> {
  1313. startSendRtpStreamHand(sendRtpItem, platform, json, param, callIdHeader);
  1314. });
  1315. } else {
  1316. // 如果是严格模式,需要关闭端口占用
  1317. JSONObject startSendRtpStreamResult = null;
  1318. if (sendRtpItem.getLocalPort() != 0) {
  1319. if (sendRtpItem.isTcpActive()) {
  1320. startSendRtpStreamResult = zlmrtpServerFactory.startSendRtpPassive(mediaInfo, param);
  1321. } else {
  1322. param.put("dst_url", sendRtpItem.getIp());
  1323. param.put("dst_port", sendRtpItem.getPort());
  1324. startSendRtpStreamResult = zlmrtpServerFactory.startSendRtpStream(mediaInfo, param);
  1325. }
  1326. } else {
  1327. if (sendRtpItem.isTcpActive()) {
  1328. startSendRtpStreamResult = zlmrtpServerFactory.startSendRtpPassive(mediaInfo, param);
  1329. } else {
  1330. param.put("dst_url", sendRtpItem.getIp());
  1331. param.put("dst_port", sendRtpItem.getPort());
  1332. startSendRtpStreamResult = zlmrtpServerFactory.startSendRtpStream(mediaInfo, param);
  1333. }
  1334. }
  1335. if (startSendRtpStreamResult != null) {
  1336. startSendRtpStreamHand(sendRtpItem, platform, startSendRtpStreamResult, param, callIdHeader);
  1337. }
  1338. }
  1339. }
  1340. @Override
  1341. public void startSendRtpStreamHand(SendRtpItem sendRtpItem, ParentPlatform parentPlatform,
  1342. JSONObject jsonObject, Map<String, Object> param, CallIdHeader callIdHeader) {
  1343. if (jsonObject == null) {
  1344. logger.error("RTP推流失败: 请检查ZLM服务");
  1345. } else if (jsonObject.getInteger("code") == 0) {
  1346. logger.info("调用ZLM推流接口, 结果: {}", jsonObject);
  1347. logger.info("RTP推流成功[ {}/{} ],{}->{}, ", param.get("app"), param.get("stream"), jsonObject.getString("local_port"),
  1348. sendRtpItem.isTcpActive()?"被动发流": param.get("dst_url") + ":" + param.get("dst_port"));
  1349. } else {
  1350. logger.error("RTP推流失败: {}, 参数:{}", jsonObject.getString("msg"), JSONObject.toJSONString(param));
  1351. if (sendRtpItem.isOnlyAudio()) {
  1352. Device device = deviceService.getDevice(sendRtpItem.getDeviceId());
  1353. AudioBroadcastCatch audioBroadcastCatch = audioBroadcastManager.get(sendRtpItem.getDeviceId(), sendRtpItem.getChannelId());
  1354. if (audioBroadcastCatch != null) {
  1355. try {
  1356. cmder.streamByeCmd(device, sendRtpItem.getChannelId(), audioBroadcastCatch.getSipTransactionInfo(), null);
  1357. } catch (SipException | ParseException | InvalidArgumentException |
  1358. SsrcTransactionNotFoundException e) {
  1359. logger.error("[命令发送失败] 停止语音对讲: {}", e.getMessage());
  1360. }
  1361. }
  1362. } else {
  1363. // 向上级平台
  1364. try {
  1365. commanderForPlatform.streamByeCmd(parentPlatform, callIdHeader.getCallId());
  1366. } catch (SipException | InvalidArgumentException | ParseException e) {
  1367. logger.error("[命令发送失败] 国标级联 发送BYE: {}", e.getMessage());
  1368. }
  1369. }
  1370. }
  1371. }
  1372. @Override
  1373. public void talkCmd(Device device, String channelId, MediaServerItem mediaServerItem, String stream, AudioBroadcastEvent event) {
  1374. if (device == null || channelId == null) {
  1375. return;
  1376. }
  1377. // TODO 必须多端口模式才支持语音喊话鹤语音对讲
  1378. logger.info("[语音对讲] device: {}, channel: {}", device.getDeviceId(), channelId);
  1379. DeviceChannel deviceChannel = storager.queryChannel(device.getDeviceId(), channelId);
  1380. if (deviceChannel == null) {
  1381. logger.warn("开启语音对讲的时候未找到通道: {}", channelId);
  1382. event.call("开启语音对讲的时候未找到通道");
  1383. return;
  1384. }
  1385. // 查询通道使用状态
  1386. if (audioBroadcastManager.exit(device.getDeviceId(), channelId)) {
  1387. SendRtpItem sendRtpItem = redisCatchStorage.querySendRTPServer(device.getDeviceId(), channelId, null, null);
  1388. if (sendRtpItem != null && sendRtpItem.isOnlyAudio()) {
  1389. // 查询流是否存在,不存在则认为是异常状态
  1390. MediaServerItem mediaServer = mediaServerService.getOne(sendRtpItem.getMediaServerId());
  1391. Boolean streamReady = zlmrtpServerFactory.isStreamReady(mediaServer, sendRtpItem.getApp(), sendRtpItem.getStream());
  1392. if (streamReady) {
  1393. logger.warn("[语音对讲] 正在语音广播,无法开启语音通话: {}", channelId);
  1394. event.call("正在语音广播");
  1395. return;
  1396. } else {
  1397. stopAudioBroadcast(device.getDeviceId(), channelId);
  1398. }
  1399. }
  1400. }
  1401. SendRtpItem sendRtpItem = redisCatchStorage.querySendRTPServer(device.getDeviceId(), channelId, stream, null);
  1402. if (sendRtpItem != null) {
  1403. MediaServerItem mediaServer = mediaServerService.getOne(sendRtpItem.getMediaServerId());
  1404. Boolean streamReady = zlmrtpServerFactory.isStreamReady(mediaServer, "rtp", sendRtpItem.getReceiveStream());
  1405. if (streamReady) {
  1406. logger.warn("[语音对讲] 进行中: {}", channelId);
  1407. event.call("语音对讲进行中");
  1408. return;
  1409. } else {
  1410. stopTalk(device, channelId);
  1411. }
  1412. }
  1413. talk(mediaServerItem, device, channelId, stream, (mediaServerItem1, hookParam) -> {
  1414. logger.info("[语音对讲] 收到设备发来的流");
  1415. }, eventResult -> {
  1416. logger.warn("[语音对讲] 失败,{}/{}, 错误码 {} {}", device.getDeviceId(), channelId, eventResult.statusCode, eventResult.msg);
  1417. event.call("失败,错误码 " + eventResult.statusCode + ", " + eventResult.msg);
  1418. }, () -> {
  1419. logger.warn("[语音对讲] 失败,{}/{} 超时", device.getDeviceId(), channelId);
  1420. event.call("失败,超时 ");
  1421. stopTalk(device, channelId);
  1422. }, errorMsg -> {
  1423. logger.warn("[语音对讲] 失败,{}/{} {}", device.getDeviceId(), channelId, errorMsg);
  1424. event.call(errorMsg);
  1425. stopTalk(device, channelId);
  1426. });
  1427. }
  1428. private void stopTalk(Device device, String channelId) {
  1429. stopTalk(device, channelId, null);
  1430. }
  1431. @Override
  1432. public void stopTalk(Device device, String channelId, Boolean streamIsReady) {
  1433. logger.info("[语音对讲] 停止, {}/{}", device.getDeviceId(), channelId);
  1434. SendRtpItem sendRtpItem = redisCatchStorage.querySendRTPServer(device.getDeviceId(), channelId, null, null);
  1435. if (sendRtpItem == null) {
  1436. logger.info("[语音对讲] 停止失败, 未找到发送信息,可能已经停止");
  1437. return;
  1438. }
  1439. // 停止向设备推流
  1440. String mediaServerId = sendRtpItem.getMediaServerId();
  1441. if (mediaServerId == null) {
  1442. return;
  1443. }
  1444. MediaServerItem mediaServer = mediaServerService.getOne(mediaServerId);
  1445. if (streamIsReady == null || streamIsReady) {
  1446. Map<String, Object> param = new HashMap<>();
  1447. param.put("vhost", "__defaultVhost__");
  1448. param.put("app", sendRtpItem.getApp());
  1449. param.put("stream", sendRtpItem.getStream());
  1450. param.put("ssrc", sendRtpItem.getSsrc());
  1451. zlmrtpServerFactory.stopSendRtpStream(mediaServer, param);
  1452. }
  1453. ssrcFactory.releaseSsrc(mediaServerId, sendRtpItem.getSsrc());
  1454. SsrcTransaction ssrcTransaction = streamSession.getSsrcTransaction(device.getDeviceId(), channelId, null, sendRtpItem.getStream());
  1455. if (ssrcTransaction != null) {
  1456. try {
  1457. cmder.streamByeCmd(device, channelId, sendRtpItem.getStream(), null);
  1458. } catch (InvalidArgumentException | ParseException | SipException | SsrcTransactionNotFoundException e) {
  1459. logger.info("[语音对讲] 停止消息发送失败,可能已经停止");
  1460. }
  1461. }
  1462. redisCatchStorage.deleteSendRTPServer(device.getDeviceId(), channelId,null, null);
  1463. }
  1464. @Override
  1465. public void getSnap(String deviceId, String channelId, String fileName, ErrorCallback errorCallback) {
  1466. Device device = deviceService.getDevice(deviceId);
  1467. if (device == null) {
  1468. errorCallback.run(InviteErrorCode.ERROR_FOR_PARAMETER_ERROR.getCode(), InviteErrorCode.ERROR_FOR_PARAMETER_ERROR.getMsg(), null);
  1469. return;
  1470. }
  1471. InviteInfo inviteInfo = inviteStreamService.getInviteInfoByDeviceAndChannel(InviteSessionType.PLAY, deviceId, channelId);
  1472. if (inviteInfo != null) {
  1473. if (inviteInfo.getStreamInfo() != null) {
  1474. // 已存在线直接截图
  1475. MediaServerItem mediaServerItemInuse = mediaServerService.getOne(inviteInfo.getStreamInfo().getMediaServerId());
  1476. String streamUrl;
  1477. if (mediaServerItemInuse.getRtspPort() != 0) {
  1478. streamUrl = String.format("rtsp://127.0.0.1:%s/%s/%s", mediaServerItemInuse.getRtspPort(), "rtp", inviteInfo.getStreamInfo().getStream());
  1479. }else {
  1480. streamUrl = String.format("http://127.0.0.1:%s/%s/%s.live.mp4", mediaServerItemInuse.getHttpPort(), "rtp", inviteInfo.getStreamInfo().getStream());
  1481. }
  1482. String path = "snap";
  1483. // 请求截图
  1484. logger.info("[请求截图]: " + fileName);
  1485. zlmresTfulUtils.getSnap(mediaServerItemInuse, streamUrl, 15, 1, path, fileName);
  1486. File snapFile = new File(path + File.separator + fileName);
  1487. if (snapFile.exists()) {
  1488. errorCallback.run(InviteErrorCode.SUCCESS.getCode(), InviteErrorCode.SUCCESS.getMsg(), snapFile.getAbsoluteFile());
  1489. }else {
  1490. errorCallback.run(InviteErrorCode.FAIL.getCode(), InviteErrorCode.FAIL.getMsg(), null);
  1491. }
  1492. return;
  1493. }
  1494. }
  1495. MediaServerItem newMediaServerItem = getNewMediaServerItem(device);
  1496. play(newMediaServerItem, deviceId, channelId, (code, msg, data)->{
  1497. if (code == InviteErrorCode.SUCCESS.getCode()) {
  1498. InviteInfo inviteInfoForPlay = inviteStreamService.getInviteInfoByDeviceAndChannel(InviteSessionType.PLAY, deviceId, channelId);
  1499. if (inviteInfoForPlay != null && inviteInfoForPlay.getStreamInfo() != null) {
  1500. getSnap(deviceId, channelId, fileName, errorCallback);
  1501. }else {
  1502. errorCallback.run(InviteErrorCode.FAIL.getCode(), InviteErrorCode.FAIL.getMsg(), null);
  1503. }
  1504. }else {
  1505. errorCallback.run(InviteErrorCode.FAIL.getCode(), InviteErrorCode.FAIL.getMsg(), null);
  1506. }
  1507. });
  1508. }
  1509. }