RtpController.java 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381
  1. package com.genersoft.iot.vmp.vmanager.rtp;
  2. import com.alibaba.fastjson2.JSONObject;
  3. import com.genersoft.iot.vmp.common.VideoManagerConstants;
  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.media.zlm.SendRtpPortManager;
  8. import com.genersoft.iot.vmp.media.zlm.ZLMServerFactory;
  9. import com.genersoft.iot.vmp.media.zlm.ZlmHttpHookSubscribe;
  10. import com.genersoft.iot.vmp.media.zlm.dto.HookSubscribeFactory;
  11. import com.genersoft.iot.vmp.media.zlm.dto.HookSubscribeForRtpServerTimeout;
  12. import com.genersoft.iot.vmp.media.zlm.dto.HookSubscribeForStreamChange;
  13. import com.genersoft.iot.vmp.media.zlm.dto.MediaServerItem;
  14. import com.genersoft.iot.vmp.media.zlm.dto.hook.OnRtpServerTimeoutHookParam;
  15. import com.genersoft.iot.vmp.service.IMediaServerService;
  16. import com.genersoft.iot.vmp.utils.redis.RedisUtil;
  17. import com.genersoft.iot.vmp.vmanager.bean.ErrorCode;
  18. import com.genersoft.iot.vmp.vmanager.bean.OtherRtpSendInfo;
  19. import io.swagger.v3.oas.annotations.Operation;
  20. import io.swagger.v3.oas.annotations.Parameter;
  21. import io.swagger.v3.oas.annotations.tags.Tag;
  22. import okhttp3.OkHttpClient;
  23. import okhttp3.Request;
  24. import org.slf4j.Logger;
  25. import org.slf4j.LoggerFactory;
  26. import org.springframework.beans.factory.annotation.Autowired;
  27. import org.springframework.data.redis.core.RedisTemplate;
  28. import org.springframework.util.ObjectUtils;
  29. import org.springframework.web.bind.annotation.*;
  30. import java.io.IOException;
  31. import java.util.HashMap;
  32. import java.util.List;
  33. import java.util.Map;
  34. import java.util.UUID;
  35. import java.util.concurrent.TimeUnit;
  36. @SuppressWarnings("rawtypes")
  37. @Tag(name = "第三方服务对接")
  38. @RestController
  39. @RequestMapping("/api/rtp")
  40. public class RtpController {
  41. @Autowired
  42. private ZLMServerFactory zlmServerFactory;
  43. @Autowired
  44. private SendRtpPortManager sendRtpPortManager;
  45. private final static Logger logger = LoggerFactory.getLogger(RtpController.class);
  46. @Autowired
  47. private ZlmHttpHookSubscribe hookSubscribe;
  48. @Autowired
  49. private IMediaServerService mediaServerService;
  50. @Autowired
  51. private UserSetting userSetting;
  52. @Autowired
  53. private DynamicTask dynamicTask;
  54. @Autowired
  55. private RedisTemplate<Object, Object> redisTemplate;
  56. @GetMapping(value = "/receive/open")
  57. @ResponseBody
  58. @Operation(summary = "开启收流和获取发流信息")
  59. @Parameter(name = "isSend", description = "是否发送,false时只开启收流, true同时返回推流信息", required = true)
  60. @Parameter(name = "callId", description = "整个过程的唯一标识,为了与后续接口关联", required = true)
  61. @Parameter(name = "ssrc", description = "来源流的SSRC,不传则不校验来源ssrc", required = false)
  62. @Parameter(name = "stream", description = "形成的流的ID", required = true)
  63. @Parameter(name = "tcpMode", description = "收流模式, 0为UDP, 1为TCP被动", required = true)
  64. @Parameter(name = "callBack", description = "回调地址,如果收流超时会通道回调通知,回调为get请求,参数为callId", required = true)
  65. public OtherRtpSendInfo openRtpServer(Boolean isSend, @RequestParam(required = false)String ssrc, String callId, String stream, Integer tcpMode, String callBack) {
  66. logger.info("[第三方服务对接->开启收流和获取发流信息] isSend->{}, ssrc->{}, callId->{}, stream->{}, tcpMode->{}, callBack->{}",
  67. isSend, ssrc, callId, stream, tcpMode==0?"UDP":"TCP被动", callBack);
  68. MediaServerItem mediaServerItem = mediaServerService.getDefaultMediaServer();
  69. if (mediaServerItem == null) {
  70. throw new ControllerException(ErrorCode.ERROR100.getCode(),"没有可用的MediaServer");
  71. }
  72. if (stream == null) {
  73. throw new ControllerException(ErrorCode.ERROR100.getCode(),"stream参数不可为空");
  74. }
  75. if (isSend != null && isSend && callId == null) {
  76. throw new ControllerException(ErrorCode.ERROR100.getCode(),"isSend为true时,CallID不能为空");
  77. }
  78. int ssrcInt = 0;
  79. if (ssrc != null) {
  80. try {
  81. ssrcInt = Integer.parseInt(ssrc);
  82. }catch (NumberFormatException e) {
  83. throw new ControllerException(ErrorCode.ERROR100.getCode(),"ssrc格式错误");
  84. }
  85. }
  86. String receiveKey = VideoManagerConstants.WVP_OTHER_RECEIVE_RTP_INFO + userSetting.getServerId() + "_" + callId + "_" + stream;
  87. int localPortForVideo = zlmServerFactory.createRTPServer(mediaServerItem, stream, ssrcInt, null, false, tcpMode);
  88. int localPortForAudio = zlmServerFactory.createRTPServer(mediaServerItem, stream + "_a" , ssrcInt, null, false, tcpMode);
  89. if (localPortForVideo == 0 || localPortForAudio == 0) {
  90. throw new ControllerException(ErrorCode.ERROR100.getCode(), "获取端口失败");
  91. }
  92. // 注册回调如果rtp收流超时则通过回调发送通知
  93. if (callBack != null) {
  94. HookSubscribeForRtpServerTimeout hookSubscribeForRtpServerTimeout = HookSubscribeFactory.on_rtp_server_timeout(stream, String.valueOf(ssrcInt), mediaServerItem.getId());
  95. // 订阅 zlm启动事件, 新的zlm也会从这里进入系统
  96. hookSubscribe.addSubscribe(hookSubscribeForRtpServerTimeout,
  97. (mediaServerItemInUse, hookParam)->{
  98. OnRtpServerTimeoutHookParam serverTimeoutHookParam = (OnRtpServerTimeoutHookParam) hookParam;
  99. if (stream.equals(serverTimeoutHookParam.getStream_id())) {
  100. logger.info("[开启收流和获取发流信息] 等待收流超时 callId->{}, 发送回调", callId);
  101. OkHttpClient.Builder httpClientBuilder = new OkHttpClient.Builder();
  102. OkHttpClient client = httpClientBuilder.build();
  103. String url = callBack + "?callId=" + callId;
  104. Request request = new Request.Builder().get().url(url).build();
  105. try {
  106. client.newCall(request).execute();
  107. } catch (IOException e) {
  108. logger.error("[第三方服务对接->开启收流和获取发流信息] 等待收流超时 callId->{}, 发送回调失败", callId, e);
  109. }
  110. hookSubscribe.removeSubscribe(hookSubscribeForRtpServerTimeout);
  111. }
  112. });
  113. }
  114. String key = VideoManagerConstants.WVP_OTHER_SEND_RTP_INFO + userSetting.getServerId() + "_" + callId;
  115. OtherRtpSendInfo otherRtpSendInfo = new OtherRtpSendInfo();
  116. otherRtpSendInfo.setReceiveIp(mediaServerItem.getSdpIp());
  117. otherRtpSendInfo.setReceivePortForVideo(localPortForVideo);
  118. otherRtpSendInfo.setReceivePortForAudio(localPortForAudio);
  119. otherRtpSendInfo.setCallId(callId);
  120. otherRtpSendInfo.setStream(stream);
  121. // 将信息写入redis中,以备后用
  122. redisTemplate.opsForValue().set(receiveKey, otherRtpSendInfo);
  123. if (isSend != null && isSend) {
  124. // 预创建发流信息
  125. int portForVideo = sendRtpPortManager.getNextPort(mediaServerItem);
  126. int portForAudio = sendRtpPortManager.getNextPort(mediaServerItem);
  127. otherRtpSendInfo.setSendLocalIp(mediaServerItem.getSdpIp());
  128. otherRtpSendInfo.setSendLocalPortForVideo(portForVideo);
  129. otherRtpSendInfo.setSendLocalPortForAudio(portForAudio);
  130. // 将信息写入redis中,以备后用
  131. redisTemplate.opsForValue().set(key, otherRtpSendInfo, 300, TimeUnit.SECONDS);
  132. logger.info("[第三方服务对接->开启收流和获取发流信息] 结果,callId->{}, {}", callId, otherRtpSendInfo);
  133. }
  134. // 将信息写入redis中,以备后用
  135. redisTemplate.opsForValue().set(key, otherRtpSendInfo, 300, TimeUnit.SECONDS);
  136. return otherRtpSendInfo;
  137. }
  138. @GetMapping(value = "/receive/close")
  139. @ResponseBody
  140. @Operation(summary = "关闭收流")
  141. @Parameter(name = "stream", description = "流的ID", required = true)
  142. public void closeRtpServer(String stream) {
  143. logger.info("[第三方服务对接->关闭收流] stream->{}", stream);
  144. MediaServerItem mediaServerItem = mediaServerService.getDefaultMediaServer();
  145. zlmServerFactory.closeRtpServer(mediaServerItem,stream);
  146. zlmServerFactory.closeRtpServer(mediaServerItem,stream + "_a");
  147. String receiveKey = VideoManagerConstants.WVP_OTHER_RECEIVE_RTP_INFO + userSetting.getServerId() + "_*_" + stream;
  148. List<Object> scan = RedisUtil.scan(redisTemplate, receiveKey);
  149. if (scan.size() > 0) {
  150. for (Object key : scan) {
  151. // 将信息写入redis中,以备后用
  152. redisTemplate.delete(key);
  153. }
  154. }
  155. }
  156. @GetMapping(value = "/send/start")
  157. @ResponseBody
  158. @Operation(summary = "发送流")
  159. @Parameter(name = "ssrc", description = "发送流的SSRC", required = true)
  160. @Parameter(name = "dstIpForAudio", description = "目标音频收流IP", required = false)
  161. @Parameter(name = "dstIpForVideo", description = "目标视频收流IP", required = false)
  162. @Parameter(name = "dstPortForAudio", description = "目标音频收流端口", required = false)
  163. @Parameter(name = "dstPortForVideo", description = "目标视频收流端口", required = false)
  164. @Parameter(name = "app", description = "待发送应用名", required = true)
  165. @Parameter(name = "stream", description = "待发送流Id", required = true)
  166. @Parameter(name = "callId", description = "整个过程的唯一标识,不传则使用随机端口发流", required = true)
  167. @Parameter(name = "isUdp", description = "是否为UDP", required = true)
  168. @Parameter(name = "ptForAudio", description = "rtp的音频pt", required = false)
  169. @Parameter(name = "ptForVideo", description = "rtp的视频pt", required = false)
  170. public void sendRTP(String ssrc,
  171. @RequestParam(required = false)String dstIpForAudio,
  172. @RequestParam(required = false)String dstIpForVideo,
  173. @RequestParam(required = false)Integer dstPortForAudio,
  174. @RequestParam(required = false)Integer dstPortForVideo,
  175. String app,
  176. String stream,
  177. String callId,
  178. Boolean isUdp,
  179. @RequestParam(required = false)Integer ptForAudio,
  180. @RequestParam(required = false)Integer ptForVideo
  181. ) {
  182. logger.info("[第三方服务对接->发送流] " +
  183. "ssrc->{}, \r\n" +
  184. "dstIpForAudio->{}, \n" +
  185. "dstIpForAudio->{}, \n" +
  186. "dstPortForAudio->{}, \n" +
  187. "dstPortForVideo->{}, \n" +
  188. "app->{}, \n" +
  189. "stream->{}, \n" +
  190. "callId->{}, \n" +
  191. "ptForAudio->{}, \n" +
  192. "ptForVideo->{}",
  193. ssrc,
  194. dstIpForAudio,
  195. dstIpForVideo,
  196. dstPortForAudio,
  197. dstPortForVideo,
  198. app,
  199. stream,
  200. callId,
  201. ptForAudio,
  202. ptForVideo);
  203. if (!((dstPortForAudio > 0 && !ObjectUtils.isEmpty(dstPortForAudio) || (dstPortForVideo > 0 && !ObjectUtils.isEmpty(dstIpForVideo))))) {
  204. throw new ControllerException(ErrorCode.ERROR400.getCode(), "至少应该存在一组音频或视频发送参数");
  205. }
  206. MediaServerItem mediaServerItem = mediaServerService.getDefaultMediaServer();
  207. String key = VideoManagerConstants.WVP_OTHER_SEND_RTP_INFO + userSetting.getServerId() + "_" + callId;
  208. OtherRtpSendInfo sendInfo = (OtherRtpSendInfo)redisTemplate.opsForValue().get(key);
  209. if (sendInfo == null) {
  210. sendInfo = new OtherRtpSendInfo();
  211. }
  212. sendInfo.setPushApp(app);
  213. sendInfo.setPushStream(stream);
  214. sendInfo.setPushSSRC(ssrc);
  215. Map<String, Object> paramForAudio;
  216. Map<String, Object> paramForVideo;
  217. if (!ObjectUtils.isEmpty(dstIpForAudio) && dstPortForAudio > 0) {
  218. paramForAudio = new HashMap<>();
  219. paramForAudio.put("vhost","__defaultVhost__");
  220. paramForAudio.put("app",app);
  221. paramForAudio.put("stream",stream);
  222. paramForAudio.put("ssrc", ssrc);
  223. paramForAudio.put("dst_url", dstIpForAudio);
  224. paramForAudio.put("dst_port", dstPortForAudio);
  225. String is_Udp = isUdp ? "1" : "0";
  226. paramForAudio.put("is_udp", is_Udp);
  227. paramForAudio.put("src_port", sendInfo.getSendLocalPortForAudio());
  228. paramForAudio.put("use_ps", "0");
  229. paramForAudio.put("only_audio", "1");
  230. if (ptForAudio != null) {
  231. paramForAudio.put("pt", ptForAudio);
  232. }
  233. } else {
  234. paramForAudio = null;
  235. }
  236. if (!ObjectUtils.isEmpty(dstIpForVideo) && dstPortForVideo > 0) {
  237. paramForVideo = new HashMap<>();
  238. paramForVideo.put("vhost","__defaultVhost__");
  239. paramForVideo.put("app",app);
  240. paramForVideo.put("stream",stream);
  241. paramForVideo.put("ssrc", ssrc);
  242. paramForVideo.put("dst_url", dstIpForVideo);
  243. paramForVideo.put("dst_port", dstPortForVideo);
  244. String is_Udp = isUdp ? "1" : "0";
  245. paramForVideo.put("is_udp", is_Udp);
  246. paramForVideo.put("src_port", sendInfo.getSendLocalPortForVideo());
  247. paramForVideo.put("use_ps", "0");
  248. paramForVideo.put("only_audio", "0");
  249. if (ptForVideo != null) {
  250. paramForVideo.put("pt", ptForVideo);
  251. }
  252. } else {
  253. paramForVideo = null;
  254. }
  255. Boolean streamReady = zlmServerFactory.isStreamReady(mediaServerItem, app, stream);
  256. if (streamReady) {
  257. if (paramForVideo != null) {
  258. JSONObject jsonObject = zlmServerFactory.startSendRtpStream(mediaServerItem, paramForVideo);
  259. if (jsonObject.getInteger("code") == 0) {
  260. logger.info("[第三方服务对接->发送流] 视频流发流成功,callId->{},param->{}", callId, paramForVideo);
  261. redisTemplate.opsForValue().set(key, sendInfo);
  262. }else {
  263. redisTemplate.delete(key);
  264. logger.info("[第三方服务对接->发送流] 视频流发流失败,callId->{}, {}", callId, jsonObject.getString("msg"));
  265. throw new ControllerException(ErrorCode.ERROR100.getCode(), "[视频流发流失败] " + jsonObject.getString("msg"));
  266. }
  267. }
  268. if(paramForAudio != null) {
  269. JSONObject jsonObject = zlmServerFactory.startSendRtpStream(mediaServerItem, paramForAudio);
  270. if (jsonObject.getInteger("code") == 0) {
  271. logger.info("[第三方服务对接->发送流] 音频流发流成功,callId->{},param->{}", callId, paramForAudio);
  272. redisTemplate.opsForValue().set(key, sendInfo);
  273. }else {
  274. redisTemplate.delete(key);
  275. logger.info("[第三方服务对接->发送流] 音频流发流失败,callId->{}, {}", callId, jsonObject.getString("msg"));
  276. throw new ControllerException(ErrorCode.ERROR100.getCode(), "[音频流发流失败] " + jsonObject.getString("msg"));
  277. }
  278. }
  279. }else {
  280. logger.info("[第三方服务对接->发送流] 流不存在,等待流上线,callId->{}", callId);
  281. String uuid = UUID.randomUUID().toString();
  282. HookSubscribeForStreamChange hookSubscribeForStreamChange = HookSubscribeFactory.on_stream_changed(app, stream, true, "rtsp", mediaServerItem.getId());
  283. dynamicTask.startDelay(uuid, ()->{
  284. logger.info("[第三方服务对接->发送流] 等待流上线超时 callId->{}", callId);
  285. redisTemplate.delete(key);
  286. hookSubscribe.removeSubscribe(hookSubscribeForStreamChange);
  287. }, 10000);
  288. // 订阅 zlm启动事件, 新的zlm也会从这里进入系统
  289. OtherRtpSendInfo finalSendInfo = sendInfo;
  290. hookSubscribe.removeSubscribe(hookSubscribeForStreamChange);
  291. hookSubscribe.addSubscribe(hookSubscribeForStreamChange,
  292. (mediaServerItemInUse, response)->{
  293. dynamicTask.stop(uuid);
  294. logger.info("[第三方服务对接->发送流] 流上线,开始发流 callId->{}", callId);
  295. try {
  296. Thread.sleep(400);
  297. } catch (InterruptedException e) {
  298. throw new RuntimeException(e);
  299. }
  300. if (paramForVideo != null) {
  301. JSONObject jsonObject = zlmServerFactory.startSendRtpStream(mediaServerItem, paramForVideo);
  302. if (jsonObject.getInteger("code") == 0) {
  303. logger.info("[第三方服务对接->发送流] 视频流发流成功,callId->{},param->{}", callId, paramForVideo);
  304. redisTemplate.opsForValue().set(key, finalSendInfo);
  305. }else {
  306. redisTemplate.delete(key);
  307. logger.info("[第三方服务对接->发送流] 视频流发流失败,callId->{}, {}", callId, jsonObject.getString("msg"));
  308. throw new ControllerException(ErrorCode.ERROR100.getCode(), "[视频流发流失败] " + jsonObject.getString("msg"));
  309. }
  310. }
  311. if(paramForAudio != null) {
  312. JSONObject jsonObject = zlmServerFactory.startSendRtpStream(mediaServerItem, paramForAudio);
  313. if (jsonObject.getInteger("code") == 0) {
  314. logger.info("[第三方服务对接->发送流] 音频流发流成功,callId->{},param->{}", callId, paramForAudio);
  315. redisTemplate.opsForValue().set(key, finalSendInfo);
  316. }else {
  317. redisTemplate.delete(key);
  318. logger.info("[第三方服务对接->发送流] 音频流发流失败,callId->{}, {}", callId, jsonObject.getString("msg"));
  319. throw new ControllerException(ErrorCode.ERROR100.getCode(), "[音频流发流失败] " + jsonObject.getString("msg"));
  320. }
  321. }
  322. hookSubscribe.removeSubscribe(hookSubscribeForStreamChange);
  323. });
  324. }
  325. }
  326. @GetMapping(value = "/send/stop")
  327. @ResponseBody
  328. @Operation(summary = "关闭发送流")
  329. @Parameter(name = "callId", description = "整个过程的唯一标识,不传则使用随机端口发流", required = true)
  330. public void closeSendRTP(String callId) {
  331. logger.info("[第三方服务对接->关闭发送流] callId->{}", callId);
  332. String key = VideoManagerConstants.WVP_OTHER_SEND_RTP_INFO + userSetting.getServerId() + "_" + callId;
  333. OtherRtpSendInfo sendInfo = (OtherRtpSendInfo)redisTemplate.opsForValue().get(key);
  334. if (sendInfo == null){
  335. throw new ControllerException(ErrorCode.ERROR100.getCode(), "未开启发流");
  336. }
  337. Map<String, Object> param = new HashMap<>();
  338. param.put("vhost","__defaultVhost__");
  339. param.put("app",sendInfo.getPushApp());
  340. param.put("stream",sendInfo.getPushStream());
  341. param.put("ssrc",sendInfo.getPushSSRC());
  342. MediaServerItem mediaServerItem = mediaServerService.getDefaultMediaServer();
  343. Boolean result = zlmServerFactory.stopSendRtpStream(mediaServerItem, param);
  344. if (!result) {
  345. logger.info("[第三方服务对接->关闭发送流] 失败 callId->{}", callId);
  346. throw new ControllerException(ErrorCode.ERROR100.getCode(), "停止发流失败");
  347. }else {
  348. logger.info("[第三方服务对接->关闭发送流] 成功 callId->{}", callId);
  349. }
  350. redisTemplate.delete(key);
  351. }
  352. }