PlayServiceImpl.java 87 KB

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