PlayServiceImpl.java 93 KB

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