PlayServiceImpl.java 88 KB

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