PlayServiceImpl.java 88 KB

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