PlayServiceImpl.java 87 KB

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