PlayServiceImpl.java 91 KB

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