RtpController.java 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269
  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.ZLMRTPServerFactory;
  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.service.IMediaServerService;
  15. import com.genersoft.iot.vmp.vmanager.bean.ErrorCode;
  16. import com.genersoft.iot.vmp.vmanager.bean.OtherRtpSendInfo;
  17. import io.swagger.v3.oas.annotations.Operation;
  18. import io.swagger.v3.oas.annotations.Parameter;
  19. import io.swagger.v3.oas.annotations.tags.Tag;
  20. import okhttp3.OkHttpClient;
  21. import okhttp3.Request;
  22. import org.slf4j.Logger;
  23. import org.slf4j.LoggerFactory;
  24. import org.springframework.beans.factory.annotation.Autowired;
  25. import org.springframework.data.redis.core.RedisTemplate;
  26. import org.springframework.util.ObjectUtils;
  27. import org.springframework.web.bind.annotation.*;
  28. import java.io.IOException;
  29. import java.util.HashMap;
  30. import java.util.Map;
  31. import java.util.UUID;
  32. import java.util.concurrent.TimeUnit;
  33. @SuppressWarnings("rawtypes")
  34. @Tag(name = "第三方服务对接")
  35. @RestController
  36. @RequestMapping("/api/rtp")
  37. public class RtpController {
  38. private final static Logger logger = LoggerFactory.getLogger(RtpController.class);
  39. @Autowired
  40. private ZLMRTPServerFactory zlmServerFactory;
  41. @Autowired
  42. private ZlmHttpHookSubscribe hookSubscribe;
  43. @Autowired
  44. private IMediaServerService mediaServerService;
  45. @Autowired
  46. private SendRtpPortManager sendRtpPortManager;
  47. @Autowired
  48. private UserSetting userSetting;
  49. @Autowired
  50. private DynamicTask dynamicTask;
  51. @Autowired
  52. private RedisTemplate<Object, Object> redisTemplate;
  53. @GetMapping(value = "/receive/open")
  54. @ResponseBody
  55. @Operation(summary = "开启收流和获取发流信息")
  56. @Parameter(name = "isSend", description = "是否发送,false时只开启收流, true同时返回推流信息", required = true)
  57. @Parameter(name = "callId", description = "整个过程的唯一标识,为了与后续接口关联", required = true)
  58. @Parameter(name = "ssrc", description = "来源流的SSRC,不传则不校验来源ssrc", required = false)
  59. @Parameter(name = "stream", description = "形成的流的ID", required = true)
  60. @Parameter(name = "tcpMode", description = "收流模式, 0为UDP, 1为TCP被动", required = true)
  61. @Parameter(name = "callBack", description = "回调地址,如果收流超时会通道回调通知,回调为get请求,参数为callId", required = true)
  62. public OtherRtpSendInfo openRtpServer(Boolean isSend, @RequestParam(required = false)String ssrc, String callId, String stream, Integer tcpMode, String callBack) {
  63. logger.info("[第三方服务对接->开启收流和获取发流信息] isSend->{}, ssrc->{}, callId->{}, stream->{}, tcpMode->{}, callBack->{}",
  64. isSend, ssrc, callId, stream, tcpMode==0?"UDP":"TCP被动", callBack);
  65. MediaServerItem mediaServerItem = mediaServerService.getDefaultMediaServer();
  66. if (mediaServerItem == null) {
  67. throw new ControllerException(ErrorCode.ERROR100.getCode(),"没有可用的MediaServer");
  68. }
  69. if (stream == null) {
  70. throw new ControllerException(ErrorCode.ERROR100.getCode(),"stream参数不可为空");
  71. }
  72. if (isSend != null && isSend && callId == null) {
  73. throw new ControllerException(ErrorCode.ERROR100.getCode(),"isSend为true时,CallID不能为空");
  74. }
  75. int ssrcInt = 0;
  76. if (ssrc != null) {
  77. try {
  78. ssrcInt = Integer.parseInt(ssrc);
  79. }catch (NumberFormatException e) {
  80. throw new ControllerException(ErrorCode.ERROR100.getCode(),"ssrc格式错误");
  81. }
  82. }
  83. int localPort = zlmServerFactory.createRTPServer(mediaServerItem, stream, ssrcInt, null, false, tcpMode);
  84. // 注册回调如果rtp收流超时则通过回调发送通知
  85. if (callBack != null) {
  86. HookSubscribeForRtpServerTimeout hookSubscribeForRtpServerTimeout = HookSubscribeFactory.on_rtp_server_timeout(stream, String.valueOf(ssrcInt), mediaServerItem.getId());
  87. // 订阅 zlm启动事件, 新的zlm也会从这里进入系统
  88. hookSubscribe.addSubscribe(hookSubscribeForRtpServerTimeout,
  89. (mediaServerItemInUse, response)->{
  90. if (stream.equals(response.getString("stream_id"))) {
  91. logger.info("[第三方服务对接->开启收流和获取发流信息] 等待收流超时 callId->{}, 发送回调", callId);
  92. OkHttpClient.Builder httpClientBuilder = new OkHttpClient.Builder();
  93. OkHttpClient client = httpClientBuilder.build();
  94. String url = callBack + "?callId=" + callId;
  95. Request request = new Request.Builder().get().url(url).build();
  96. try {
  97. client.newCall(request).execute();
  98. } catch (IOException e) {
  99. logger.error("[第三方服务对接->开启收流和获取发流信息] 等待收流超时 callId->{}, 发送回调失败", callId, e);
  100. }
  101. }
  102. });
  103. }
  104. OtherRtpSendInfo otherRtpSendInfo = new OtherRtpSendInfo();
  105. otherRtpSendInfo.setReceiveIp(mediaServerItem.getSdpIp());
  106. otherRtpSendInfo.setReceivePort(localPort);
  107. otherRtpSendInfo.setCallId(callId);
  108. otherRtpSendInfo.setStream(stream);
  109. String receiveKey = VideoManagerConstants.WVP_OTHER_RECEIVE_RTP_INFO + userSetting.getServerId() + "_" + stream;
  110. // 将信息写入redis中,以备后用
  111. redisTemplate.opsForValue().set(receiveKey, otherRtpSendInfo);
  112. if (isSend != null && isSend) {
  113. String key = VideoManagerConstants.WVP_OTHER_SEND_RTP_INFO + userSetting.getServerId() + "_" + callId;
  114. // 预创建发流信息
  115. int port = sendRtpPortManager.getNextPort(mediaServerItem.getId());
  116. // 将信息写入redis中,以备后用
  117. redisTemplate.opsForValue().set(key, otherRtpSendInfo, 300, TimeUnit.SECONDS);
  118. otherRtpSendInfo.setIp(mediaServerItem.getSdpIp());
  119. otherRtpSendInfo.setPort(port);
  120. logger.info("[第三方服务对接->开启收流和获取发流信息] 结果,callId->{}, {}", callId, otherRtpSendInfo);
  121. }
  122. return otherRtpSendInfo;
  123. }
  124. @GetMapping(value = "/receive/close")
  125. @ResponseBody
  126. @Operation(summary = "关闭收流")
  127. @Parameter(name = "stream", description = "流的ID", required = true)
  128. public void closeRtpServer(String stream) {
  129. logger.info("[第三方服务对接->关闭收流] stream->{}", stream);
  130. MediaServerItem mediaServerItem = mediaServerService.getDefaultMediaServer();
  131. zlmServerFactory.closeRtpServer(mediaServerItem,stream);
  132. String receiveKey = VideoManagerConstants.WVP_OTHER_RECEIVE_RTP_INFO + userSetting.getServerId() + "_" + stream;
  133. // 将信息写入redis中,以备后用
  134. redisTemplate.delete(receiveKey);
  135. }
  136. @GetMapping(value = "/send/start")
  137. @ResponseBody
  138. @Operation(summary = "发送流")
  139. @Parameter(name = "ssrc", description = "发送流的SSRC", required = true)
  140. @Parameter(name = "ip", description = "目标IP", required = true)
  141. @Parameter(name = "port", description = "目标端口", required = true)
  142. @Parameter(name = "app", description = "待发送应用名", required = true)
  143. @Parameter(name = "stream", description = "待发送流Id", required = true)
  144. @Parameter(name = "callId", description = "整个过程的唯一标识,不传则使用随机端口发流", required = true)
  145. @Parameter(name = "onlyAudio", description = "是否只有音频", required = true)
  146. @Parameter(name = "isUdp", description = "是否为UDP", required = true)
  147. @Parameter(name = "streamType", description = "流类型,1为es流,2为ps流, 默认es流", required = false)
  148. @Parameter(name = "pt", description = "rtp的pt", required = true)
  149. public void sendRTP(String ssrc, String ip, Integer port, String app, String stream, String callId, Boolean onlyAudio, Boolean isUdp, @RequestParam(required = false)Integer streamType, Integer pt) {
  150. logger.info("[第三方服务对接->发送流] ssrc->{}, ip->{}, port->{}, app->{}, stream->{}, callId->{}, onlyAudio->{}, streamType->{}, pt->{}",
  151. ssrc, ip, port, app, stream, callId, onlyAudio, streamType == 1? "ES":"PS", pt);
  152. if (ObjectUtils.isEmpty(streamType)) {
  153. streamType = 1;
  154. }
  155. MediaServerItem mediaServerItem = mediaServerService.getDefaultMediaServer();
  156. String key = VideoManagerConstants.WVP_OTHER_SEND_RTP_INFO + userSetting.getServerId() + "_" + callId;
  157. OtherRtpSendInfo sendInfo = (OtherRtpSendInfo)redisTemplate.opsForValue().get(key);
  158. if (sendInfo == null) {
  159. sendInfo = new OtherRtpSendInfo();
  160. }
  161. sendInfo.setPushApp(app);
  162. sendInfo.setPushStream(stream);
  163. sendInfo.setPushSSRC(ssrc);
  164. Map<String, Object> param = new HashMap<>(12);
  165. param.put("vhost","__defaultVhost__");
  166. param.put("app",app);
  167. param.put("stream",stream);
  168. param.put("ssrc", ssrc);
  169. param.put("dst_url",ip);
  170. param.put("dst_port", port);
  171. String is_Udp = isUdp ? "1" : "0";
  172. param.put("is_udp", is_Udp);
  173. param.put("src_port", sendInfo.getPort());
  174. param.put("use_ps", streamType==2 ? "1" : "0");
  175. param.put("only_audio", onlyAudio ? "1" : "0");
  176. param.put("pt", pt);
  177. Boolean streamReady = zlmServerFactory.isStreamReady(mediaServerItem, app, stream);
  178. if (streamReady) {
  179. logger.info("[第三方服务对接->发送流] 流存在,开始发流,callId->{}", callId);
  180. JSONObject jsonObject = zlmServerFactory.startSendRtpStream(mediaServerItem, param);
  181. if (jsonObject.getInteger("code") == 0) {
  182. logger.info("[第三方服务对接->发送流] 发流成功,callId->{}", callId);
  183. redisTemplate.opsForValue().set(key, sendInfo);
  184. }else {
  185. redisTemplate.delete(key);
  186. logger.info("[第三方服务对接->发送流] 发流失败,callId->{}, {}", callId, jsonObject.getString("msg"));
  187. throw new ControllerException(ErrorCode.ERROR100.getCode(), "[发流失败] " + jsonObject.getString("msg"));
  188. }
  189. }else {
  190. logger.info("[第三方服务对接->发送流] 流不存在,等待流上线,callId->{}", callId);
  191. String uuid = UUID.randomUUID().toString();
  192. HookSubscribeForStreamChange hookSubscribeForStreamChange = HookSubscribeFactory.on_stream_changed(app, stream, true, "rtsp", mediaServerItem.getId());
  193. dynamicTask.startDelay(uuid, ()->{
  194. logger.info("[第三方服务对接->发送流] 等待流上线超时 callId->{}", callId);
  195. redisTemplate.delete(key);
  196. hookSubscribe.removeSubscribe(hookSubscribeForStreamChange);
  197. }, 10000);
  198. // 订阅 zlm启动事件, 新的zlm也会从这里进入系统
  199. OtherRtpSendInfo finalSendInfo = sendInfo;
  200. hookSubscribe.addSubscribe(hookSubscribeForStreamChange,
  201. (mediaServerItemInUse, response)->{
  202. dynamicTask.stop(uuid);
  203. logger.info("[第三方服务对接->发送流] 流上线,开始发流 callId->{}", callId);
  204. JSONObject jsonObject = zlmServerFactory.startSendRtpStream(mediaServerItem, param);
  205. System.out.println("========发流结果==========");
  206. System.out.println(jsonObject);
  207. if (jsonObject.getInteger("code") == 0) {
  208. logger.info("[第三方服务对接->发送流] 发流成功,callId->{}", callId);
  209. redisTemplate.opsForValue().set(key, finalSendInfo);
  210. }else {
  211. redisTemplate.delete(key);
  212. logger.info("[第三方服务对接->发送流] 发流失败,callId->{}, {}", callId, jsonObject.getString("msg"));
  213. throw new ControllerException(ErrorCode.ERROR100.getCode(), "[发流失败] " + jsonObject.getString("msg"));
  214. }
  215. });
  216. }
  217. }
  218. @GetMapping(value = "/send/stop")
  219. @ResponseBody
  220. @Operation(summary = "关闭发送流")
  221. @Parameter(name = "callId", description = "整个过程的唯一标识,不传则使用随机端口发流", required = true)
  222. public void closeSendRTP(String callId) {
  223. logger.info("[第三方服务对接->关闭发送流] callId->{}", callId);
  224. String key = VideoManagerConstants.WVP_OTHER_SEND_RTP_INFO + userSetting.getServerId() + "_" + callId;
  225. OtherRtpSendInfo sendInfo = (OtherRtpSendInfo)redisTemplate.opsForValue().get(key);
  226. if (sendInfo == null){
  227. throw new ControllerException(ErrorCode.ERROR100.getCode(), "未开启发流");
  228. }
  229. Map<String, Object> param = new HashMap<>();
  230. param.put("vhost","__defaultVhost__");
  231. param.put("app",sendInfo.getPushApp());
  232. param.put("stream",sendInfo.getPushStream());
  233. param.put("ssrc",sendInfo.getPushSSRC());
  234. MediaServerItem mediaServerItem = mediaServerService.getDefaultMediaServer();
  235. Boolean result = zlmServerFactory.stopSendRtpStream(mediaServerItem, param);
  236. if (!result) {
  237. logger.info("[第三方服务对接->关闭发送流] 失败 callId->{}", callId);
  238. throw new ControllerException(ErrorCode.ERROR100.getCode(), "停止发流失败");
  239. }else {
  240. logger.info("[第三方服务对接->关闭发送流] 成功 callId->{}", callId);
  241. }
  242. }
  243. }