PlayServiceImpl.java 96 KB

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