PlayServiceImpl.java 57 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100
  1. package com.genersoft.iot.vmp.service.impl;
  2. import com.alibaba.fastjson2.JSON;
  3. import com.alibaba.fastjson2.JSONArray;
  4. import com.alibaba.fastjson2.JSONObject;
  5. import com.genersoft.iot.vmp.common.StreamInfo;
  6. import com.genersoft.iot.vmp.conf.DynamicTask;
  7. import com.genersoft.iot.vmp.conf.UserSetting;
  8. import com.genersoft.iot.vmp.conf.exception.ControllerException;
  9. import com.genersoft.iot.vmp.conf.exception.ServiceException;
  10. import com.genersoft.iot.vmp.conf.exception.SsrcTransactionNotFoundException;
  11. import com.genersoft.iot.vmp.gb28181.GBEventSubscribe;
  12. import com.genersoft.iot.vmp.gb28181.GBHookSubscribeFactory;
  13. import com.genersoft.iot.vmp.gb28181.HookSubscribeForKey;
  14. import com.genersoft.iot.vmp.gb28181.bean.*;
  15. import com.genersoft.iot.vmp.gb28181.event.SipSubscribe;
  16. import com.genersoft.iot.vmp.gb28181.session.VideoStreamSessionManager;
  17. import com.genersoft.iot.vmp.gb28181.transmit.callback.DeferredResultHolder;
  18. import com.genersoft.iot.vmp.gb28181.transmit.callback.RequestMessage;
  19. import com.genersoft.iot.vmp.gb28181.transmit.cmd.impl.SIPCommander;
  20. import com.genersoft.iot.vmp.gb28181.transmit.cmd.impl.SIPCommanderFroPlatform;
  21. import com.genersoft.iot.vmp.media.zlm.AssistRESTfulUtils;
  22. import com.genersoft.iot.vmp.media.zlm.ZLMRESTfulUtils;
  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.HookSubscribeForStreamChange;
  26. import com.genersoft.iot.vmp.media.zlm.dto.MediaServerItem;
  27. import com.genersoft.iot.vmp.service.IDeviceService;
  28. import com.genersoft.iot.vmp.service.IMediaServerService;
  29. import com.genersoft.iot.vmp.service.IMediaService;
  30. import com.genersoft.iot.vmp.service.IPlayService;
  31. import com.genersoft.iot.vmp.service.bean.*;
  32. import com.genersoft.iot.vmp.storager.IRedisCatchStorage;
  33. import com.genersoft.iot.vmp.storager.IVideoManagerStorage;
  34. import com.genersoft.iot.vmp.utils.DateUtil;
  35. import com.genersoft.iot.vmp.utils.redis.RedisUtil;
  36. import com.genersoft.iot.vmp.vmanager.bean.ErrorCode;
  37. import com.genersoft.iot.vmp.vmanager.bean.WVPResult;
  38. import gov.nist.javax.sip.message.SIPRequest;
  39. import org.slf4j.Logger;
  40. import org.slf4j.LoggerFactory;
  41. import org.springframework.beans.factory.annotation.Autowired;
  42. import org.springframework.beans.factory.annotation.Qualifier;
  43. import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
  44. import org.springframework.stereotype.Service;
  45. import org.springframework.util.ObjectUtils;
  46. import org.springframework.web.context.request.async.DeferredResult;
  47. import javax.sip.InvalidArgumentException;
  48. import javax.sip.ResponseEvent;
  49. import javax.sip.SipException;
  50. import java.math.BigDecimal;
  51. import java.math.RoundingMode;
  52. import java.text.ParseException;
  53. import java.util.List;
  54. import java.util.UUID;
  55. @SuppressWarnings(value = {"rawtypes", "unchecked"})
  56. @Service
  57. public class PlayServiceImpl implements IPlayService {
  58. private final static Logger logger = LoggerFactory.getLogger(PlayServiceImpl.class);
  59. @Autowired
  60. private IVideoManagerStorage storager;
  61. @Autowired
  62. private SIPCommander cmder;
  63. @Autowired
  64. private SIPCommanderFroPlatform sipCommanderFroPlatform;
  65. @Autowired
  66. private IRedisCatchStorage redisCatchStorage;
  67. @Autowired
  68. private DeferredResultHolder resultHolder;
  69. @Autowired
  70. private ZLMRESTfulUtils zlmresTfulUtils;
  71. @Autowired
  72. private AssistRESTfulUtils assistRESTfulUtils;
  73. @Autowired
  74. private IMediaService mediaService;
  75. @Autowired
  76. private IMediaServerService mediaServerService;
  77. @Autowired
  78. private VideoStreamSessionManager streamSession;
  79. @Autowired
  80. private IDeviceService deviceService;
  81. @Autowired
  82. private UserSetting userSetting;
  83. @Autowired
  84. private DynamicTask dynamicTask;
  85. @Autowired
  86. private ZlmHttpHookSubscribe subscribe;
  87. @Autowired
  88. private GBEventSubscribe GBHookSubscribe;
  89. @Qualifier("taskExecutor")
  90. @Autowired
  91. private ThreadPoolTaskExecutor taskExecutor;
  92. @Override
  93. public void play(MediaServerItem mediaServerItem, String deviceId,
  94. String channelId,int isUsePs,
  95. ZlmHttpHookSubscribe.Event hookEvent, SipSubscribe.Event errorEvent,
  96. Runnable timeoutCallback) {
  97. if (mediaServerItem == null) {
  98. throw new ControllerException(ErrorCode.ERROR100.getCode(), "未找到可用的zlm");
  99. }
  100. String key = DeferredResultHolder.CALLBACK_CMD_PLAY + deviceId + channelId;
  101. RequestMessage msg = new RequestMessage();
  102. msg.setKey(key);
  103. Device device = redisCatchStorage.getDevice(deviceId);
  104. StreamInfo streamInfo = redisCatchStorage.queryPlayByDevice(deviceId, channelId);
  105. if (streamInfo != null) {
  106. String streamId = streamInfo.getStream();
  107. if (streamId == null) {
  108. WVPResult wvpResult = new WVPResult();
  109. wvpResult.setCode(ErrorCode.ERROR100.getCode());
  110. wvpResult.setMsg("点播失败, redis缓存streamId等于null");
  111. msg.setData(wvpResult);
  112. resultHolder.invokeAllResult(msg);
  113. return;
  114. }
  115. String mediaServerId = streamInfo.getMediaServerId();
  116. MediaServerItem mediaInfo = mediaServerService.getOne(mediaServerId);
  117. JSONObject rtpInfo = zlmresTfulUtils.getRtpInfo(mediaInfo, streamId);
  118. if (rtpInfo.getInteger("code") == 0) {
  119. if (rtpInfo.getBoolean("exist")) {
  120. int localPort = rtpInfo.getInteger("local_port");
  121. if (localPort == 0) {
  122. logger.warn("[点播],点播时发现rtpServerC存在,但是尚未开始推流");
  123. // 此时说明rtpServer已经创建但是流还没有推上来
  124. WVPResult wvpResult = new WVPResult();
  125. wvpResult.setCode(ErrorCode.ERROR100.getCode());
  126. wvpResult.setMsg("点播已经在进行中,请稍候重试");
  127. msg.setData(wvpResult);
  128. resultHolder.invokeAllResult(msg);
  129. return;
  130. } else {
  131. WVPResult wvpResult = new WVPResult();
  132. wvpResult.setCode(ErrorCode.SUCCESS.getCode());
  133. wvpResult.setMsg(ErrorCode.SUCCESS.getMsg());
  134. wvpResult.setData(streamInfo);
  135. msg.setData(wvpResult);
  136. resultHolder.invokeAllResult(msg);
  137. if (hookEvent != null) {
  138. hookEvent.response(mediaServerItem, JSON.parseObject(JSON.toJSONString(streamInfo)));
  139. }
  140. }
  141. } else {
  142. redisCatchStorage.stopPlay(streamInfo);
  143. storager.stopPlay(streamInfo.getDeviceID(), streamInfo.getChannelId());
  144. streamInfo = null;
  145. }
  146. } else {
  147. //zlm连接失败
  148. redisCatchStorage.stopPlay(streamInfo);
  149. storager.stopPlay(streamInfo.getDeviceID(), streamInfo.getChannelId());
  150. streamInfo = null;
  151. }
  152. }
  153. if (streamInfo == null) {
  154. String streamId = null;
  155. if (mediaServerItem.isRtpEnable()) {
  156. logger.info("test ----- {}",device.getDeviceId());
  157. logger.info("test ----- {}",channelId);
  158. streamId = String.format("%s_%s", device.getDeviceId(), channelId);
  159. }
  160. SSRCInfo ssrcInfo = mediaServerService.openRTPServer(mediaServerItem, streamId, device.isSsrcCheck(), false);
  161. logger.info(JSONObject.toJSONString(ssrcInfo));
  162. if (ssrcInfo == null) {
  163. WVPResult wvpResult = new WVPResult();
  164. wvpResult.setCode(ErrorCode.ERROR100.getCode());
  165. wvpResult.setMsg("开启收流失败");
  166. msg.setData(wvpResult);
  167. resultHolder.invokeAllResult(msg);
  168. return;
  169. }
  170. play(mediaServerItem, ssrcInfo, device, channelId,
  171. isUsePs,
  172. (mediaServerItemInUse, response) -> {
  173. if (hookEvent != null) {
  174. hookEvent.response(mediaServerItem, response);
  175. }
  176. }, event -> {
  177. // sip error错误
  178. WVPResult wvpResult = new WVPResult();
  179. wvpResult.setCode(ErrorCode.ERROR100.getCode());
  180. wvpResult.setMsg(String.format("点播失败, 错误码: %s, %s", event.statusCode, event.msg));
  181. msg.setData(wvpResult);
  182. resultHolder.invokeAllResult(msg);
  183. if (errorEvent != null) {
  184. errorEvent.response(event);
  185. }
  186. }, (code, msgStr) -> {
  187. // invite点播超时
  188. WVPResult wvpResult = new WVPResult();
  189. wvpResult.setCode(ErrorCode.ERROR100.getCode());
  190. if (code == 0) {
  191. wvpResult.setMsg("点播超时,请稍候重试");
  192. } else if (code == 1) {
  193. wvpResult.setMsg("收流超时,请稍候重试");
  194. }
  195. msg.setData(wvpResult);
  196. // 回复之前所有的点播请求
  197. resultHolder.invokeAllResult(msg);
  198. });
  199. }
  200. }
  201. @Override
  202. public void play(MediaServerItem mediaServerItem, SSRCInfo ssrcInfo,
  203. Device device, String channelId,
  204. int isUsePs,
  205. ZlmHttpHookSubscribe.Event hookEvent, SipSubscribe.Event errorEvent,
  206. InviteTimeOutCallback timeoutCallback) {
  207. logger.info("[点播开始] deviceId: {}, channelId: {},收流端口: {}, 收流模式:{}, SSRC: {}, SSRC校验:{}", device.getDeviceId(), channelId, ssrcInfo.getPort(), device.getStreamMode(), ssrcInfo.getSsrc(), device.isSsrcCheck());
  208. // 超时处理
  209. String timeOutTaskKey = UUID.randomUUID().toString();
  210. dynamicTask.startDelay(timeOutTaskKey, () -> {
  211. // 执行超时任务时查询是否已经成功,成功了则不执行超时任务,防止超时任务取消失败的情况
  212. if (redisCatchStorage.queryPlayByDevice(device.getDeviceId(), channelId) == null) {
  213. logger.info("[点播超时] 收流超时 deviceId: {}, channelId: {},端口:{}, SSRC: {}", device.getDeviceId(), channelId, ssrcInfo.getPort(), ssrcInfo.getSsrc());
  214. // 点播超时回复BYE 同时释放ssrc以及此次点播的资源
  215. try {
  216. cmder.streamByeCmd(device, channelId, ssrcInfo.getStream(), null);
  217. } catch (InvalidArgumentException | ParseException | SipException | SsrcTransactionNotFoundException e) {
  218. logger.error("[点播超时], 发送BYE失败 {}", e.getMessage());
  219. } finally {
  220. timeoutCallback.run(1, "收流超时");
  221. mediaServerService.releaseSsrc(mediaServerItem.getId(), ssrcInfo.getSsrc());
  222. mediaServerService.closeRTPServer(mediaServerItem, ssrcInfo.getStream());
  223. streamSession.remove(device.getDeviceId(), channelId, ssrcInfo.getStream());
  224. mediaServerService.closeRTPServer(mediaServerItem, ssrcInfo.getStream());
  225. // 取消订阅消息监听
  226. HookSubscribeForStreamChange hookSubscribe = HookSubscribeFactory.on_stream_changed("rtp", ssrcInfo.getStream(), true, "rtsp", mediaServerItem.getId());
  227. subscribe.removeSubscribe(hookSubscribe);
  228. }
  229. }
  230. }, userSetting.getPlayTimeout());
  231. //端口获取失败的ssrcInfo 没有必要发送点播指令
  232. if (ssrcInfo.getPort() <= 0) {
  233. logger.info("[点播端口分配异常],deviceId={},channelId={},ssrcInfo={}", device.getDeviceId(), channelId, ssrcInfo);
  234. dynamicTask.stop(timeOutTaskKey);
  235. // 释放ssrc
  236. mediaServerService.releaseSsrc(mediaServerItem.getId(), ssrcInfo.getSsrc());
  237. streamSession.remove(device.getDeviceId(), channelId, ssrcInfo.getStream());
  238. RequestMessage msg = new RequestMessage();
  239. msg.setKey(DeferredResultHolder.CALLBACK_CMD_PLAY + device.getDeviceId() + channelId);
  240. msg.setData(WVPResult.fail(ErrorCode.ERROR100.getCode(), "点播端口分配异常"));
  241. resultHolder.invokeAllResult(msg);
  242. return;
  243. }
  244. try {
  245. cmder.playStreamCmd(mediaServerItem, ssrcInfo, device, channelId,isUsePs, (MediaServerItem mediaServerItemInuse, JSONObject response) -> {
  246. logger.info("收到订阅消息: " + response.toJSONString());
  247. logger.info("停止超时任务: " + timeOutTaskKey);
  248. dynamicTask.stop(timeOutTaskKey);
  249. // hook响应
  250. onPublishHandlerForPlay(mediaServerItemInuse, response, device.getDeviceId(), channelId);
  251. hookEvent.response(mediaServerItemInuse, response);
  252. logger.info("[点播成功] deviceId: {}, channelId: {}", device.getDeviceId(), channelId);
  253. String streamUrl = String.format("http://127.0.0.1:%s/%s/%s.live.flv", mediaServerItemInuse.getHttpPort(), "rtp", ssrcInfo.getStream());
  254. String path = "snap";
  255. String fileName = device.getDeviceId() + "_" + channelId + ".jpg";
  256. // 请求截图
  257. logger.info("[请求截图]: " + fileName);
  258. zlmresTfulUtils.getSnap(mediaServerItemInuse, streamUrl, 15, 1, path, fileName);
  259. }, (event) -> {
  260. ResponseEvent responseEvent = (ResponseEvent) event.event;
  261. String contentString = new String(responseEvent.getResponse().getRawContent());
  262. // 获取ssrc
  263. int ssrcIndex = contentString.indexOf("y=");
  264. // 检查是否有y字段
  265. if (ssrcIndex >= 0) {
  266. //ssrc规定长度为10字节,不取余下长度以避免后续还有“f=”字段 TODO 后续对不规范的非10位ssrc兼容
  267. String ssrcInResponse = contentString.substring(ssrcIndex + 2, ssrcIndex + 12);
  268. // 查询到ssrc不一致且开启了ssrc校验则需要针对处理
  269. if (ssrcInfo.getSsrc().equals(ssrcInResponse)) {
  270. return;
  271. }
  272. logger.info("[点播消息] 收到invite 200, 发现下级自定义了ssrc: {}", ssrcInResponse);
  273. if (!mediaServerItem.isRtpEnable() || device.isSsrcCheck()) {
  274. logger.info("[点播消息] SSRC修正 {}->{}", ssrcInfo.getSsrc(), ssrcInResponse);
  275. if (!mediaServerItem.getSsrcConfig().checkSsrc(ssrcInResponse)) {
  276. // ssrc 不可用
  277. // 释放ssrc
  278. mediaServerService.releaseSsrc(mediaServerItem.getId(), ssrcInfo.getSsrc());
  279. streamSession.remove(device.getDeviceId(), channelId, ssrcInfo.getStream());
  280. event.msg = "下级自定义了ssrc,但是此ssrc不可用";
  281. event.statusCode = 400;
  282. errorEvent.response(event);
  283. return;
  284. }
  285. // 单端口模式streamId也有变化,需要重新设置监听
  286. if (!mediaServerItem.isRtpEnable()) {
  287. // 添加订阅
  288. HookSubscribeForStreamChange hookSubscribe = HookSubscribeFactory.on_stream_changed("rtp", ssrcInfo.getStream(), true, "rtsp", mediaServerItem.getId());
  289. subscribe.removeSubscribe(hookSubscribe);
  290. hookSubscribe.getContent().put("stream", String.format("%08x", Integer.parseInt(ssrcInResponse)).toUpperCase());
  291. subscribe.addSubscribe(hookSubscribe, (MediaServerItem mediaServerItemInUse, JSONObject response) -> {
  292. logger.info("[ZLM HOOK] ssrc修正后收到订阅消息: " + response.toJSONString());
  293. dynamicTask.stop(timeOutTaskKey);
  294. // hook响应
  295. onPublishHandlerForPlay(mediaServerItemInUse, response, device.getDeviceId(), channelId);
  296. hookEvent.response(mediaServerItemInUse, response);
  297. });
  298. }
  299. // 关闭rtp server
  300. mediaServerService.closeRTPServer(mediaServerItem, ssrcInfo.getStream());
  301. // 重新开启ssrc server
  302. mediaServerService.openRTPServer(mediaServerItem, ssrcInfo.getStream(), ssrcInResponse, device.isSsrcCheck(), false, ssrcInfo.getPort());
  303. }
  304. }
  305. }, (event) -> {
  306. dynamicTask.stop(timeOutTaskKey);
  307. mediaServerService.closeRTPServer(mediaServerItem, ssrcInfo.getStream());
  308. // 释放ssrc
  309. mediaServerService.releaseSsrc(mediaServerItem.getId(), ssrcInfo.getSsrc());
  310. streamSession.remove(device.getDeviceId(), channelId, ssrcInfo.getStream());
  311. errorEvent.response(event);
  312. });
  313. } catch (InvalidArgumentException | SipException | ParseException e) {
  314. logger.error("[命令发送失败] 点播消息: {}", e.getMessage());
  315. dynamicTask.stop(timeOutTaskKey);
  316. mediaServerService.closeRTPServer(mediaServerItem, ssrcInfo.getStream());
  317. // 释放ssrc
  318. mediaServerService.releaseSsrc(mediaServerItem.getId(), ssrcInfo.getSsrc());
  319. streamSession.remove(device.getDeviceId(), channelId, ssrcInfo.getStream());
  320. SipSubscribe.EventResult eventResult = new SipSubscribe.EventResult(new CmdSendFailEvent(null));
  321. eventResult.msg = "命令发送失败";
  322. errorEvent.response(eventResult);
  323. }
  324. }
  325. public void openBroadcast(MediaServerItem mediaServerItem,
  326. String deviceId,
  327. String app,
  328. String audioStreamId,
  329. HookSubscribeForKey broadcastForInviteHook,
  330. NodeCallBack nodeCallBack,
  331. Runnable timeoutCallback){
  332. logger.warn("[语音广播] 开语音广播");
  333. // PlayResult playResult = new PlayResult();
  334. Device device = redisCatchStorage.getDevice(deviceId);
  335. // rtp语音通道创建完成,开始发送broadcast,
  336. try {
  337. cmder.audioBroadcastCmd(device);
  338. }catch (InvalidArgumentException | SipException | ParseException e) {
  339. logger.error("[命令发送失败] 发送broadcast中 errorMsg: {}", e.getMessage());
  340. nodeCallBack.run(1,"[命令发送失败] 无法发送broadcast消息");
  341. }
  342. // 获取对应的音频流信息
  343. // logger.info("webrtc stream {}",streamAuthorityInfo);
  344. // 注册subScript事件
  345. GBHookSubscribe.addInviteSubscribe(broadcastForInviteHook,(int code, JSONObject json, SIPRequest request)->{
  346. logger.info("[语音广播] 接收到设备invite信息___订阅事件触发 JSONDATA: {}",json.toJSONString());
  347. String streamId = null;
  348. String ssrcStr = json.getString("ssrc");
  349. ssrcStr = ssrcStr.replaceAll("\\s*|\r|\n|\t","");
  350. SSRCInfo ssrcInfo = new SSRCInfo(31234,ssrcStr,audioStreamId);
  351. if (mediaServerItem.isRtpEnable()) {
  352. streamId = String.format("broadcast_%s", device.getDeviceId());
  353. }
  354. logger.info("[语音广播] 尝试创建rtp语音推流通道");
  355. // TODO: 2023/3/7 开始下发invite信息给设备
  356. try {
  357. // 创建音频解码服务
  358. // 向流媒体服务器申请创建 rtpServer 服务端口
  359. ssrcInfo = mediaServerService.startSendRtpServer(mediaServerItem,app, streamId, audioStreamId,
  360. json.getString("addr"),
  361. json.getString("port"),
  362. ssrcStr
  363. );
  364. if(ssrcInfo == null){
  365. logger.error("[zlm控制异常] 创建媒体流失败");
  366. nodeCallBack.run(2,"[zlm控制异常] 创建媒体流失败");
  367. return;
  368. }
  369. // 回复invite 200 信息至设备
  370. cmder.sendBoradcastInviteCmd(request,mediaServerItem, ssrcInfo, device, null, null,
  371. null,
  372. null,
  373. null);
  374. //
  375. nodeCallBack.run(0,"ok");
  376. }catch(InvalidArgumentException | SipException | ParseException e){
  377. logger.error("[下发audio拉流invite失败]",e);
  378. // SipSubscribe.EventResult eventResult = new SipSubscribe.EventResult(new CmdSendFailEvent(null));
  379. // eventResult.msg = "命令发送失败";
  380. // errorEvent.response(eventResult);
  381. }
  382. });
  383. return ;
  384. }
  385. public void openBroadcast(MediaServerItem mediaServerItem,
  386. Device device,
  387. int waitTime,
  388. BroadcastCallback callback){
  389. logger.warn("[语音广播] 开语音广播 新");
  390. JSONObject errJson = new JSONObject();
  391. try {
  392. cmder.audioBroadcastCmd(device);
  393. }catch (InvalidArgumentException | SipException | ParseException e) {
  394. logger.error("[命令发送失败] 发送broadcast中 errorMsg: {}", e.getMessage());
  395. errJson.put("msg","[命令发送失败] 无法发送broadcast消息");
  396. callback.run(2,errJson,null);
  397. }
  398. logger.warn("等待设备返回invite");
  399. HookSubscribeForKey broadcastForInviteHook = GBHookSubscribeFactory.on_broadcast_invite(device.getDeviceId());
  400. // 创建计时器,计时结束未收到invite则自动进行失败处理
  401. String timeOutTaskKey = UUID.randomUUID().toString();
  402. dynamicTask.startDelay(timeOutTaskKey,()->{
  403. // todo 发送 bye 通知给设备?
  404. logger.warn("invite超时");
  405. errJson.put("msg","等待设备语音invite信息超时");
  406. callback.run(1,errJson,null);
  407. },waitTime);
  408. GBHookSubscribe.addInviteSubscribe(broadcastForInviteHook,
  409. (int code, JSONObject json, SIPRequest request)->{
  410. // invite信息返回
  411. logger.info("[语音广播] 接收到设备invite信息___订阅事件触发 JSONDATA: {}",json.toJSONString());
  412. // 取消计时器
  413. dynamicTask.stop(timeOutTaskKey);
  414. callback.run(0,json,request);
  415. });
  416. };
  417. @Override
  418. public void onPublishHandlerForPlay(MediaServerItem mediaServerItem, JSONObject response, String deviceId, String channelId) {
  419. StreamInfo streamInfo = onPublishHandler(mediaServerItem, response, deviceId, channelId);
  420. RequestMessage msg = new RequestMessage();
  421. msg.setKey(DeferredResultHolder.CALLBACK_CMD_PLAY + deviceId + channelId);
  422. if (streamInfo != null) {
  423. DeviceChannel deviceChannel = storager.queryChannel(deviceId, channelId);
  424. if (deviceChannel != null) {
  425. deviceChannel.setStreamId(streamInfo.getStream());
  426. storager.startPlay(deviceId, channelId, streamInfo.getStream());
  427. }
  428. redisCatchStorage.startPlay(streamInfo);
  429. WVPResult wvpResult = new WVPResult();
  430. wvpResult.setCode(ErrorCode.SUCCESS.getCode());
  431. wvpResult.setMsg(ErrorCode.SUCCESS.getMsg());
  432. wvpResult.setData(streamInfo);
  433. msg.setData(wvpResult);
  434. resultHolder.invokeAllResult(msg);
  435. } else {
  436. logger.warn("设备预览API调用失败!");
  437. msg.setData(WVPResult.fail(ErrorCode.ERROR100.getCode(), "设备预览API调用失败!"));
  438. resultHolder.invokeAllResult(msg);
  439. }
  440. }
  441. private void onPublishHandlerForPlayback(MediaServerItem mediaServerItem, JSONObject response, String deviceId, String channelId, PlayBackCallback playBackCallback) {
  442. StreamInfo streamInfo = onPublishHandler(mediaServerItem, response, deviceId, channelId);
  443. PlayBackResult<StreamInfo> playBackResult = new PlayBackResult<>();
  444. if (streamInfo != null) {
  445. DeviceChannel deviceChannel = storager.queryChannel(deviceId, channelId);
  446. if (deviceChannel != null) {
  447. deviceChannel.setStreamId(streamInfo.getStream());
  448. storager.startPlay(deviceId, channelId, streamInfo.getStream());
  449. }
  450. redisCatchStorage.startPlay(streamInfo);
  451. playBackResult.setCode(ErrorCode.SUCCESS.getCode());
  452. playBackResult.setMsg(ErrorCode.SUCCESS.getMsg());
  453. playBackResult.setData(streamInfo);
  454. playBackCallback.call(playBackResult);
  455. } else {
  456. logger.warn("录像回放调用失败!");
  457. playBackResult.setCode(ErrorCode.ERROR100.getCode());
  458. playBackResult.setMsg("录像回放调用失败!");
  459. playBackCallback.call(playBackResult);
  460. }
  461. }
  462. @Override
  463. public MediaServerItem getNewMediaServerItem(Device device) {
  464. if (device == null) {
  465. return null;
  466. }
  467. MediaServerItem mediaServerItem;
  468. if (ObjectUtils.isEmpty(device.getMediaServerId()) || "auto".equals(device.getMediaServerId())) {
  469. mediaServerItem = mediaServerService.getMediaServerForMinimumLoad(null);
  470. } else {
  471. // 尝试获取device配置的zlm服务
  472. mediaServerItem = mediaServerService.getOne(device.getMediaServerId());
  473. // 如果默认zlm无法找到则随机分配一个zlm
  474. if(mediaServerItem == null){
  475. logger.warn("无法找到设备默认流媒体服务,即将使用默认流媒体服务");
  476. mediaServerItem = mediaServerService.getMediaServerForMinimumLoad(null);
  477. }
  478. }
  479. if (mediaServerItem == null) {
  480. logger.warn("点播时未找到可使用的ZLM...");
  481. }
  482. return mediaServerItem;
  483. }
  484. @Override
  485. public MediaServerItem getNewMediaServerItemHasAssist(Device device) {
  486. if (device == null) {
  487. return null;
  488. }
  489. MediaServerItem mediaServerItem;
  490. if (ObjectUtils.isEmpty(device.getMediaServerId()) || "auto".equals(device.getMediaServerId())) {
  491. mediaServerItem = mediaServerService.getMediaServerForMinimumLoad(true);
  492. } else {
  493. mediaServerItem = mediaServerService.getOne(device.getMediaServerId());
  494. }
  495. if (mediaServerItem == null) {
  496. logger.warn("[获取可用的ZLM节点]未找到可使用的ZLM...");
  497. }
  498. return mediaServerItem;
  499. }
  500. @Override
  501. public void playBack(String deviceId, String channelId, String startTime,
  502. String endTime, InviteStreamCallback inviteStreamCallback,
  503. PlayBackCallback callback) {
  504. Device device = storager.queryVideoDevice(deviceId);
  505. if (device == null) {
  506. return;
  507. }
  508. MediaServerItem newMediaServerItem = getNewMediaServerItem(device);
  509. SSRCInfo ssrcInfo = mediaServerService.openRTPServer(newMediaServerItem, null, device.isSsrcCheck(), true);
  510. playBack(newMediaServerItem, ssrcInfo, deviceId, channelId, startTime, endTime, inviteStreamCallback, callback);
  511. }
  512. @Override
  513. public void playBack(MediaServerItem mediaServerItem, SSRCInfo ssrcInfo,
  514. String deviceId, String channelId, String startTime,
  515. String endTime, InviteStreamCallback infoCallBack,
  516. PlayBackCallback playBackCallback) {
  517. if (mediaServerItem == null || ssrcInfo == null) {
  518. return;
  519. }
  520. Device device = storager.queryVideoDevice(deviceId);
  521. if (device == null) {
  522. throw new ControllerException(ErrorCode.ERROR100.getCode(), "设备: " + deviceId + "不存在");
  523. }
  524. PlayBackResult<StreamInfo> playBackResult = new PlayBackResult<>();
  525. String playBackTimeOutTaskKey = UUID.randomUUID().toString();
  526. dynamicTask.startDelay(playBackTimeOutTaskKey, () -> {
  527. logger.warn(String.format("设备回放超时,deviceId:%s ,channelId:%s", deviceId, channelId));
  528. playBackResult.setCode(ErrorCode.ERROR100.getCode());
  529. playBackResult.setMsg("回放超时");
  530. try {
  531. cmder.streamByeCmd(device, channelId, ssrcInfo.getStream(), null);
  532. } catch (InvalidArgumentException | ParseException | SipException e) {
  533. logger.error("[录像流]回放超时 发送BYE失败 {}", e.getMessage());
  534. } catch (SsrcTransactionNotFoundException e) {
  535. // 点播超时回复BYE 同时释放ssrc以及此次点播的资源
  536. mediaServerService.releaseSsrc(mediaServerItem.getId(), ssrcInfo.getSsrc());
  537. mediaServerService.closeRTPServer(mediaServerItem, ssrcInfo.getStream());
  538. streamSession.remove(deviceId, channelId, ssrcInfo.getStream());
  539. }
  540. // 回复之前所有的点播请求
  541. playBackCallback.call(playBackResult);
  542. }, userSetting.getPlayTimeout());
  543. SipSubscribe.Event errorEvent = event -> {
  544. dynamicTask.stop(playBackTimeOutTaskKey);
  545. playBackResult.setCode(ErrorCode.ERROR100.getCode());
  546. playBackResult.setMsg(String.format("回放失败, 错误码: %s, %s", event.statusCode, event.msg));
  547. playBackResult.setEvent(event);
  548. playBackCallback.call(playBackResult);
  549. streamSession.remove(device.getDeviceId(), channelId, ssrcInfo.getStream());
  550. };
  551. InviteStreamCallback hookEvent = (InviteStreamInfo inviteStreamInfo) -> {
  552. logger.info("收到回放订阅消息: " + inviteStreamInfo.getResponse().toJSONString());
  553. dynamicTask.stop(playBackTimeOutTaskKey);
  554. StreamInfo streamInfo = onPublishHandler(inviteStreamInfo.getMediaServerItem(), inviteStreamInfo.getResponse(), deviceId, channelId);
  555. if (streamInfo == null) {
  556. logger.warn("设备回放API调用失败!");
  557. playBackResult.setCode(ErrorCode.ERROR100.getCode());
  558. playBackResult.setMsg("设备回放API调用失败!");
  559. playBackCallback.call(playBackResult);
  560. return;
  561. }
  562. redisCatchStorage.startPlayback(streamInfo, inviteStreamInfo.getCallId());
  563. playBackResult.setCode(ErrorCode.SUCCESS.getCode());
  564. playBackResult.setMsg(ErrorCode.SUCCESS.getMsg());
  565. playBackResult.setData(streamInfo);
  566. playBackResult.setMediaServerItem(inviteStreamInfo.getMediaServerItem());
  567. playBackResult.setResponse(inviteStreamInfo.getResponse());
  568. playBackCallback.call(playBackResult);
  569. };
  570. try {
  571. cmder.playbackStreamCmd(mediaServerItem, ssrcInfo, device, channelId, startTime, endTime, infoCallBack,
  572. hookEvent, eventResult -> {
  573. if (eventResult.type == SipSubscribe.EventResultType.response) {
  574. ResponseEvent responseEvent = (ResponseEvent) eventResult.event;
  575. String contentString = new String(responseEvent.getResponse().getRawContent());
  576. // 获取ssrc
  577. int ssrcIndex = contentString.indexOf("y=");
  578. // 检查是否有y字段
  579. if (ssrcIndex >= 0) {
  580. //ssrc规定长度为10字节,不取余下长度以避免后续还有“f=”字段 TODO 后续对不规范的非10位ssrc兼容
  581. String ssrcInResponse = contentString.substring(ssrcIndex + 2, ssrcIndex + 12);
  582. // 查询到ssrc不一致且开启了ssrc校验则需要针对处理
  583. if (ssrcInfo.getSsrc().equals(ssrcInResponse)) {
  584. return;
  585. }
  586. logger.info("[回放消息] 收到invite 200, 发现下级自定义了ssrc: {}", ssrcInResponse);
  587. if (!mediaServerItem.isRtpEnable() || device.isSsrcCheck()) {
  588. logger.info("[回放消息] SSRC修正 {}->{}", ssrcInfo.getSsrc(), ssrcInResponse);
  589. if (!mediaServerItem.getSsrcConfig().checkSsrc(ssrcInResponse)) {
  590. // ssrc 不可用
  591. // 释放ssrc
  592. mediaServerService.releaseSsrc(mediaServerItem.getId(), ssrcInfo.getSsrc());
  593. streamSession.remove(device.getDeviceId(), channelId, ssrcInfo.getStream());
  594. eventResult.msg = "下级自定义了ssrc,但是此ssrc不可用";
  595. eventResult.statusCode = 400;
  596. errorEvent.response(eventResult);
  597. return;
  598. }
  599. // 单端口模式streamId也有变化,需要重新设置监听
  600. if (!mediaServerItem.isRtpEnable()) {
  601. // 添加订阅
  602. HookSubscribeForStreamChange hookSubscribe = HookSubscribeFactory.on_stream_changed("rtp", ssrcInfo.getStream(), true, "rtsp", mediaServerItem.getId());
  603. subscribe.removeSubscribe(hookSubscribe);
  604. hookSubscribe.getContent().put("stream", String.format("%08x", Integer.parseInt(ssrcInResponse)).toUpperCase());
  605. subscribe.addSubscribe(hookSubscribe, (MediaServerItem mediaServerItemInUse, JSONObject response) -> {
  606. logger.info("[ZLM HOOK] ssrc修正后收到订阅消息: " + response.toJSONString());
  607. dynamicTask.stop(playBackTimeOutTaskKey);
  608. // hook响应
  609. onPublishHandlerForPlayback(mediaServerItemInUse, response, device.getDeviceId(), channelId, playBackCallback);
  610. hookEvent.call(new InviteStreamInfo(mediaServerItem, null, eventResult.callId, "rtp", ssrcInfo.getStream()));
  611. });
  612. }
  613. // 关闭rtp server
  614. mediaServerService.closeRTPServer(mediaServerItem, ssrcInfo.getStream());
  615. // 重新开启ssrc server
  616. mediaServerService.openRTPServer(mediaServerItem, ssrcInfo.getStream(), ssrcInResponse, device.isSsrcCheck(), true, ssrcInfo.getPort());
  617. }
  618. }
  619. }
  620. }, errorEvent);
  621. } catch (InvalidArgumentException | SipException | ParseException e) {
  622. logger.error("[命令发送失败] 回放: {}", e.getMessage());
  623. SipSubscribe.EventResult eventResult = new SipSubscribe.EventResult(new CmdSendFailEvent(null));
  624. eventResult.msg = "命令发送失败";
  625. errorEvent.response(eventResult);
  626. }
  627. }
  628. @Override
  629. public void download(String deviceId, String channelId, String startTime, String endTime, int downloadSpeed, InviteStreamCallback infoCallBack, PlayBackCallback playBackCallback) {
  630. Device device = storager.queryVideoDevice(deviceId);
  631. if (device == null) {
  632. return;
  633. }
  634. MediaServerItem newMediaServerItem = getNewMediaServerItemHasAssist(device);
  635. if (newMediaServerItem == null) {
  636. PlayBackResult<StreamInfo> downloadResult = new PlayBackResult<>();
  637. downloadResult.setCode(ErrorCode.ERROR100.getCode());
  638. downloadResult.setMsg("未找到assist服务");
  639. playBackCallback.call(downloadResult);
  640. return;
  641. }
  642. SSRCInfo ssrcInfo = mediaServerService.openRTPServer(newMediaServerItem, null, device.isSsrcCheck(), true);
  643. download(newMediaServerItem, ssrcInfo, deviceId, channelId, startTime, endTime, downloadSpeed, infoCallBack, playBackCallback);
  644. }
  645. @Override
  646. public void download(MediaServerItem mediaServerItem, SSRCInfo ssrcInfo, String deviceId, String channelId, String startTime, String endTime, int downloadSpeed, InviteStreamCallback infoCallBack, PlayBackCallback hookCallBack) {
  647. if (mediaServerItem == null || ssrcInfo == null) {
  648. return;
  649. }
  650. Device device = storager.queryVideoDevice(deviceId);
  651. if (device == null) {
  652. throw new ControllerException(ErrorCode.ERROR400.getCode(), "设备:" + deviceId + "不存在");
  653. }
  654. PlayBackResult<StreamInfo> downloadResult = new PlayBackResult<>();
  655. String downLoadTimeOutTaskKey = UUID.randomUUID().toString();
  656. dynamicTask.startDelay(downLoadTimeOutTaskKey, () -> {
  657. logger.warn(String.format("录像下载请求超时,deviceId:%s ,channelId:%s", deviceId, channelId));
  658. downloadResult.setCode(ErrorCode.ERROR100.getCode());
  659. downloadResult.setMsg("录像下载请求超时");
  660. hookCallBack.call(downloadResult);
  661. // 点播超时回复BYE 同时释放ssrc以及此次点播的资源
  662. try {
  663. cmder.streamByeCmd(device, channelId, ssrcInfo.getStream(), null);
  664. } catch (InvalidArgumentException | ParseException | SipException e) {
  665. logger.error("[录像流]录像下载请求超时, 发送BYE失败 {}", e.getMessage());
  666. } catch (SsrcTransactionNotFoundException e) {
  667. mediaServerService.releaseSsrc(mediaServerItem.getId(), ssrcInfo.getSsrc());
  668. mediaServerService.closeRTPServer(mediaServerItem, ssrcInfo.getStream());
  669. streamSession.remove(deviceId, channelId, ssrcInfo.getStream());
  670. }
  671. }, userSetting.getPlayTimeout());
  672. SipSubscribe.Event errorEvent = event -> {
  673. dynamicTask.stop(downLoadTimeOutTaskKey);
  674. downloadResult.setCode(ErrorCode.ERROR100.getCode());
  675. downloadResult.setMsg(String.format("录像下载失败, 错误码: %s, %s", event.statusCode, event.msg));
  676. downloadResult.setEvent(event);
  677. hookCallBack.call(downloadResult);
  678. streamSession.remove(device.getDeviceId(), channelId, ssrcInfo.getStream());
  679. };
  680. InviteStreamCallback hookEvent = (InviteStreamInfo inviteStreamInfo) -> {
  681. logger.info("收到订阅消息: " + inviteStreamInfo.getCallId());
  682. dynamicTask.stop(downLoadTimeOutTaskKey);
  683. StreamInfo streamInfo = onPublishHandler(inviteStreamInfo.getMediaServerItem(), inviteStreamInfo.getResponse(), deviceId, channelId);
  684. streamInfo.setStartTime(startTime);
  685. streamInfo.setEndTime(endTime);
  686. redisCatchStorage.startDownload(streamInfo, inviteStreamInfo.getCallId());
  687. downloadResult.setCode(ErrorCode.SUCCESS.getCode());
  688. downloadResult.setMsg(ErrorCode.SUCCESS.getMsg());
  689. downloadResult.setData(streamInfo);
  690. downloadResult.setMediaServerItem(inviteStreamInfo.getMediaServerItem());
  691. downloadResult.setResponse(inviteStreamInfo.getResponse());
  692. hookCallBack.call(downloadResult);
  693. };
  694. try {
  695. cmder.downloadStreamCmd(mediaServerItem, ssrcInfo, device, channelId, startTime, endTime, downloadSpeed, infoCallBack,
  696. hookEvent, errorEvent, eventResult ->
  697. {
  698. if (eventResult.type == SipSubscribe.EventResultType.response) {
  699. ResponseEvent responseEvent = (ResponseEvent) eventResult.event;
  700. String contentString = new String(responseEvent.getResponse().getRawContent());
  701. // 获取ssrc
  702. int ssrcIndex = contentString.indexOf("y=");
  703. // 检查是否有y字段
  704. if (ssrcIndex >= 0) {
  705. //ssrc规定长度为10字节,不取余下长度以避免后续还有“f=”字段 TODO 后续对不规范的非10位ssrc兼容
  706. String ssrcInResponse = contentString.substring(ssrcIndex + 2, ssrcIndex + 12);
  707. // 查询到ssrc不一致且开启了ssrc校验则需要针对处理
  708. if (ssrcInfo.getSsrc().equals(ssrcInResponse)) {
  709. return;
  710. }
  711. logger.info("[回放消息] 收到invite 200, 发现下级自定义了ssrc: {}", ssrcInResponse);
  712. if (!mediaServerItem.isRtpEnable() || device.isSsrcCheck()) {
  713. logger.info("[回放消息] SSRC修正 {}->{}", ssrcInfo.getSsrc(), ssrcInResponse);
  714. if (!mediaServerItem.getSsrcConfig().checkSsrc(ssrcInResponse)) {
  715. // ssrc 不可用
  716. // 释放ssrc
  717. mediaServerService.releaseSsrc(mediaServerItem.getId(), ssrcInfo.getSsrc());
  718. streamSession.remove(device.getDeviceId(), channelId, ssrcInfo.getStream());
  719. eventResult.msg = "下级自定义了ssrc,但是此ssrc不可用";
  720. eventResult.statusCode = 400;
  721. errorEvent.response(eventResult);
  722. return;
  723. }
  724. // 单端口模式streamId也有变化,需要重新设置监听
  725. if (!mediaServerItem.isRtpEnable()) {
  726. // 添加订阅
  727. HookSubscribeForStreamChange hookSubscribe = HookSubscribeFactory.on_stream_changed("rtp", ssrcInfo.getStream(), true, "rtsp", mediaServerItem.getId());
  728. subscribe.removeSubscribe(hookSubscribe);
  729. hookSubscribe.getContent().put("stream", String.format("%08x", Integer.parseInt(ssrcInResponse)).toUpperCase());
  730. subscribe.addSubscribe(hookSubscribe, (MediaServerItem mediaServerItemInUse, JSONObject response) -> {
  731. logger.info("[ZLM HOOK] ssrc修正后收到订阅消息: " + response.toJSONString());
  732. dynamicTask.stop(downLoadTimeOutTaskKey);
  733. // hook响应
  734. onPublishHandlerForPlayback(mediaServerItemInUse, response, device.getDeviceId(), channelId, hookCallBack);
  735. hookEvent.call(new InviteStreamInfo(mediaServerItem, null, eventResult.callId, "rtp", ssrcInfo.getStream()));
  736. });
  737. }
  738. // 关闭rtp server
  739. mediaServerService.closeRTPServer(mediaServerItem, ssrcInfo.getStream());
  740. // 重新开启ssrc server
  741. mediaServerService.openRTPServer(mediaServerItem, ssrcInfo.getStream(), ssrcInResponse, device.isSsrcCheck(), true, ssrcInfo.getPort());
  742. }
  743. }
  744. }
  745. });
  746. } catch (InvalidArgumentException | SipException | ParseException e) {
  747. logger.error("[命令发送失败] 录像下载: {}", e.getMessage());
  748. SipSubscribe.EventResult eventResult = new SipSubscribe.EventResult(new CmdSendFailEvent(null));
  749. eventResult.msg = "命令发送失败";
  750. errorEvent.response(eventResult);
  751. }
  752. }
  753. @Override
  754. public StreamInfo getDownLoadInfo(String deviceId, String channelId, String stream) {
  755. StreamInfo streamInfo = redisCatchStorage.queryDownload(deviceId, channelId, stream, null);
  756. if (streamInfo != null) {
  757. if (streamInfo.getProgress() == 1) {
  758. return streamInfo;
  759. }
  760. // 获取当前已下载时长
  761. String mediaServerId = streamInfo.getMediaServerId();
  762. MediaServerItem mediaServerItem = mediaServerService.getOne(mediaServerId);
  763. if (mediaServerItem == null) {
  764. logger.warn("查询录像信息时发现节点已离线");
  765. return null;
  766. }
  767. if (mediaServerItem.getRecordAssistPort() > 0) {
  768. JSONObject jsonObject = assistRESTfulUtils.fileDuration(mediaServerItem, streamInfo.getApp(), streamInfo.getStream(), null);
  769. if (jsonObject == null) {
  770. throw new ControllerException(ErrorCode.ERROR100.getCode(), "连接Assist服务失败");
  771. }
  772. if (jsonObject.getInteger("code") == 0) {
  773. long duration = jsonObject.getLong("data");
  774. if (duration == 0) {
  775. streamInfo.setProgress(0);
  776. } else {
  777. String startTime = streamInfo.getStartTime();
  778. String endTime = streamInfo.getEndTime();
  779. long start = DateUtil.yyyy_MM_dd_HH_mm_ssToTimestamp(startTime);
  780. long end = DateUtil.yyyy_MM_dd_HH_mm_ssToTimestamp(endTime);
  781. BigDecimal currentCount = new BigDecimal(duration / 1000);
  782. BigDecimal totalCount = new BigDecimal(end - start);
  783. BigDecimal divide = currentCount.divide(totalCount, 2, RoundingMode.HALF_UP);
  784. double process = divide.doubleValue();
  785. streamInfo.setProgress(process);
  786. }
  787. }
  788. }
  789. }
  790. return streamInfo;
  791. }
  792. @Override
  793. public void onPublishHandlerForDownload(InviteStreamInfo inviteStreamInfo, String deviceId, String channelId, String uuid) {
  794. RequestMessage msg = new RequestMessage();
  795. msg.setKey(DeferredResultHolder.CALLBACK_CMD_DOWNLOAD + deviceId + channelId);
  796. msg.setId(uuid);
  797. StreamInfo streamInfo = onPublishHandler(inviteStreamInfo.getMediaServerItem(), inviteStreamInfo.getResponse(), deviceId, channelId);
  798. if (streamInfo != null) {
  799. redisCatchStorage.startDownload(streamInfo, inviteStreamInfo.getCallId());
  800. msg.setData(JSON.toJSONString(streamInfo));
  801. resultHolder.invokeResult(msg);
  802. } else {
  803. logger.warn("设备预览API调用失败!");
  804. msg.setData(WVPResult.fail(ErrorCode.ERROR100.getCode(), "设备预览API调用失败!"));
  805. resultHolder.invokeResult(msg);
  806. }
  807. }
  808. public StreamInfo onPublishHandler(MediaServerItem mediaServerItem, JSONObject resonse, String deviceId, String channelId) {
  809. String streamId = resonse.getString("stream");
  810. JSONArray tracks = resonse.getJSONArray("tracks");
  811. StreamInfo streamInfo = mediaService.getStreamInfoByAppAndStream(mediaServerItem, "rtp", streamId, tracks, null);
  812. streamInfo.setDeviceID(deviceId);
  813. streamInfo.setChannelId(channelId);
  814. return streamInfo;
  815. }
  816. @Override
  817. public void zlmServerOffline(String mediaServerId) {
  818. // 处理正在向上推流的上级平台
  819. List<SendRtpItem> sendRtpItems = redisCatchStorage.querySendRTPServer(null);
  820. if (sendRtpItems.size() > 0) {
  821. for (SendRtpItem sendRtpItem : sendRtpItems) {
  822. if (sendRtpItem.getMediaServerId().equals(mediaServerId)) {
  823. ParentPlatform platform = storager.queryParentPlatByServerGBId(sendRtpItem.getPlatformId());
  824. try {
  825. sipCommanderFroPlatform.streamByeCmd(platform, sendRtpItem.getCallId());
  826. } catch (SipException | InvalidArgumentException | ParseException e) {
  827. logger.error("[命令发送失败] 国标级联 发送BYE: {}", e.getMessage());
  828. }
  829. }
  830. }
  831. }
  832. // 处理正在观看的国标设备
  833. List<SsrcTransaction> allSsrc = streamSession.getAllSsrc();
  834. if (allSsrc.size() > 0) {
  835. for (SsrcTransaction ssrcTransaction : allSsrc) {
  836. if (ssrcTransaction.getMediaServerId().equals(mediaServerId)) {
  837. Device device = deviceService.getDevice(ssrcTransaction.getDeviceId());
  838. if (device == null) {
  839. continue;
  840. }
  841. try {
  842. cmder.streamByeCmd(device, ssrcTransaction.getChannelId(),
  843. ssrcTransaction.getStream(), null);
  844. } catch (InvalidArgumentException | ParseException | SipException |
  845. SsrcTransactionNotFoundException e) {
  846. logger.error("[zlm离线]为正在使用此zlm的设备, 发送BYE失败 {}", e.getMessage());
  847. }
  848. }
  849. }
  850. }
  851. }
  852. @Override
  853. public void zlmServerOnline(String mediaServerId) {
  854. // TODO 查找之前的点播,流如果不存在则给下级发送bye
  855. // MediaServerItem mediaServerItem = mediaServerService.getOne(mediaServerId);
  856. // zlmresTfulUtils.getMediaList(mediaServerItem, (mediaList ->{
  857. // Integer code = mediaList.getInteger("code");
  858. // if (code == 0) {
  859. // JSONArray data = mediaList.getJSONArray("data");
  860. // if (data == null || data.size() == 0) {
  861. // zlmServerOffline(mediaServerId);
  862. // }else {
  863. // Map<String, JSONObject> mediaListMap = new HashMap<>();
  864. // for (int i = 0; i < data.size(); i++) {
  865. // JSONObject json = data.getJSONObject(i);
  866. // String app = json.getString("app");
  867. // if ("rtp".equals(app)) {
  868. // String stream = json.getString("stream");
  869. // if (mediaListMap.get(stream) != null) {
  870. // continue;
  871. // }
  872. // mediaListMap.put(stream, json);
  873. // // 处理正在观看的国标设备
  874. // List<SsrcTransaction> ssrcTransactions = streamSession.getSsrcTransactionForAll(null, null, null, stream);
  875. // if (ssrcTransactions.size() > 0) {
  876. // for (SsrcTransaction ssrcTransaction : ssrcTransactions) {
  877. // if(ssrcTransaction.getMediaServerId().equals(mediaServerId)) {
  878. // cmder.streamByeCmd(ssrcTransaction.getDeviceId(), ssrcTransaction.getChannelId(),
  879. // ssrcTransaction.getStream(), null);
  880. // }
  881. // }
  882. // }
  883. // }
  884. // }
  885. // if (mediaListMap.size() > 0 ) {
  886. // // 处理正在向上推流的上级平台
  887. // List<SendRtpItem> sendRtpItems = redisCatchStorage.querySendRTPServer(null);
  888. // if (sendRtpItems.size() > 0) {
  889. // for (SendRtpItem sendRtpItem : sendRtpItems) {
  890. // if (sendRtpItem.getMediaServerId().equals(mediaServerId)) {
  891. // if (mediaListMap.get(sendRtpItem.getStreamId()) == null) {
  892. // ParentPlatform platform = storager.queryPlatformByServerGBId(sendRtpItem.getPlatformId());
  893. // sipCommanderFroPlatform.streamByeCmd(platform, sendRtpItem.getCallId());
  894. // }
  895. // }
  896. // }
  897. // }
  898. // }
  899. // }
  900. // }
  901. // }));
  902. }
  903. @Override
  904. public void pauseRtp(String streamId) throws ServiceException, InvalidArgumentException, ParseException, SipException {
  905. String key = redisCatchStorage.queryPlaybackForKey(null, null, streamId, null);
  906. StreamInfo streamInfo = redisCatchStorage.queryPlayback(null, null, streamId, null);
  907. if (null == streamInfo) {
  908. logger.warn("streamId不存在!");
  909. throw new ServiceException("streamId不存在");
  910. }
  911. streamInfo.setPause(true);
  912. RedisUtil.set(key, streamInfo);
  913. MediaServerItem mediaServerItem = mediaServerService.getOne(streamInfo.getMediaServerId());
  914. if (null == mediaServerItem) {
  915. logger.warn("mediaServer 不存在!");
  916. throw new ServiceException("mediaServer不存在");
  917. }
  918. // zlm 暂停RTP超时检查
  919. JSONObject jsonObject = zlmresTfulUtils.pauseRtpCheck(mediaServerItem, streamId);
  920. if (jsonObject == null || jsonObject.getInteger("code") != 0) {
  921. throw new ServiceException("暂停RTP接收失败");
  922. }
  923. Device device = storager.queryVideoDevice(streamInfo.getDeviceID());
  924. cmder.playPauseCmd(device, streamInfo);
  925. }
  926. @Override
  927. public void resumeRtp(String streamId) throws ServiceException, InvalidArgumentException, ParseException, SipException {
  928. String key = redisCatchStorage.queryPlaybackForKey(null, null, streamId, null);
  929. StreamInfo streamInfo = redisCatchStorage.queryPlayback(null, null, streamId, null);
  930. if (null == streamInfo) {
  931. logger.warn("streamId不存在!");
  932. throw new ServiceException("streamId不存在");
  933. }
  934. streamInfo.setPause(false);
  935. RedisUtil.set(key, streamInfo);
  936. MediaServerItem mediaServerItem = mediaServerService.getOne(streamInfo.getMediaServerId());
  937. if (null == mediaServerItem) {
  938. logger.warn("mediaServer 不存在!");
  939. throw new ServiceException("mediaServer不存在");
  940. }
  941. // zlm 暂停RTP超时检查
  942. JSONObject jsonObject = zlmresTfulUtils.resumeRtpCheck(mediaServerItem, streamId);
  943. if (jsonObject == null || jsonObject.getInteger("code") != 0) {
  944. throw new ServiceException("继续RTP接收失败");
  945. }
  946. Device device = storager.queryVideoDevice(streamInfo.getDeviceID());
  947. cmder.playResumeCmd(device, streamInfo);
  948. }
  949. public void broadcast(
  950. MediaServerItem mediaServerItem,
  951. Device device,
  952. BroadcastItem broadcastItem,
  953. int waitTime,
  954. BroadcastCallback callback
  955. ){
  956. logger.info("[语言广播] 开始返回invite200,并创建zlm服务");
  957. JSONObject errJson = new JSONObject();
  958. try {
  959. String steamId = broadcastItem.getStream();
  960. String ssrcStr = broadcastItem.getSsrc();
  961. ssrcStr = ssrcStr.replaceAll("\\s*|\r|\n|\t", "");
  962. SSRCInfo ssrcInfo = mediaServerService.startSendRtpServer(mediaServerItem,
  963. broadcastItem.getApp(),
  964. broadcastItem.getStream(),
  965. broadcastItem.getStream(),
  966. broadcastItem.getIpcIp(),
  967. String.valueOf(broadcastItem.getIpcAudioPort()),
  968. ssrcStr
  969. );
  970. if (ssrcInfo == null) {
  971. logger.error("[zlm控制异常] 创建媒体流失败");
  972. errJson.put("msg", "[zlm控制异常] 创建媒体流失败");
  973. callback.run(2, errJson, null);
  974. return;
  975. }
  976. // 回复invite 200 信息至设备
  977. cmder.sendBoradcastInviteCmd(broadcastItem.getRequest(), mediaServerItem, ssrcInfo, device, null, null,
  978. null,
  979. null,
  980. null);
  981. //
  982. callback.run(0, null,null);
  983. }catch(InvalidArgumentException | SipException | ParseException e){
  984. logger.error("[下发audio拉流invite失败]",e);
  985. logger.error("[zlm控制异常] 创建媒体流失败");
  986. errJson.put("msg", "[zlm控制异常] 创建媒体流失败");
  987. callback.run(2, errJson, null);
  988. // SipSubscribe.EventResult eventResult = new SipSubscribe.EventResult(new CmdSendFailEvent(null));
  989. // eventResult.msg = "命令发送失败";
  990. // errorEvent.response(eventResult);
  991. }
  992. };
  993. }