StreamProxyServiceImpl.java 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457
  1. package com.genersoft.iot.vmp.service.impl;
  2. import com.alibaba.fastjson.JSONArray;
  3. import com.alibaba.fastjson.JSONObject;
  4. import com.genersoft.iot.vmp.common.StreamInfo;
  5. import com.genersoft.iot.vmp.conf.UserSetting;
  6. import com.genersoft.iot.vmp.conf.exception.ControllerException;
  7. import com.genersoft.iot.vmp.gb28181.bean.GbStream;
  8. import com.genersoft.iot.vmp.gb28181.bean.ParentPlatform;
  9. import com.genersoft.iot.vmp.gb28181.bean.TreeType;
  10. import com.genersoft.iot.vmp.gb28181.event.EventPublisher;
  11. import com.genersoft.iot.vmp.gb28181.event.subscribe.catalog.CatalogEvent;
  12. import com.genersoft.iot.vmp.media.zlm.ZLMRESTfulUtils;
  13. import com.genersoft.iot.vmp.media.zlm.dto.MediaItem;
  14. import com.genersoft.iot.vmp.media.zlm.dto.MediaServerItem;
  15. import com.genersoft.iot.vmp.media.zlm.dto.StreamProxyItem;
  16. import com.genersoft.iot.vmp.service.IGbStreamService;
  17. import com.genersoft.iot.vmp.service.IMediaServerService;
  18. import com.genersoft.iot.vmp.service.IMediaService;
  19. import com.genersoft.iot.vmp.storager.IRedisCatchStorage;
  20. import com.genersoft.iot.vmp.storager.IVideoManagerStorage;
  21. import com.genersoft.iot.vmp.storager.dao.GbStreamMapper;
  22. import com.genersoft.iot.vmp.storager.dao.ParentPlatformMapper;
  23. import com.genersoft.iot.vmp.storager.dao.PlatformGbStreamMapper;
  24. import com.genersoft.iot.vmp.storager.dao.StreamProxyMapper;
  25. import com.genersoft.iot.vmp.service.IStreamProxyService;
  26. import com.genersoft.iot.vmp.utils.DateUtil;
  27. import com.genersoft.iot.vmp.vmanager.bean.ErrorCode;
  28. import com.genersoft.iot.vmp.vmanager.bean.WVPResult;
  29. import com.github.pagehelper.PageInfo;
  30. import org.slf4j.Logger;
  31. import org.slf4j.LoggerFactory;
  32. import org.springframework.beans.factory.annotation.Autowired;
  33. import org.springframework.jdbc.datasource.DataSourceTransactionManager;
  34. import org.springframework.stereotype.Service;
  35. import org.springframework.transaction.TransactionDefinition;
  36. import org.springframework.transaction.TransactionStatus;
  37. import org.springframework.util.ObjectUtils;
  38. import org.springframework.util.StringUtils;
  39. import java.net.InetAddress;
  40. import java.util.*;
  41. /**
  42. * 视频代理业务
  43. */
  44. @Service
  45. public class StreamProxyServiceImpl implements IStreamProxyService {
  46. private final static Logger logger = LoggerFactory.getLogger(StreamProxyServiceImpl.class);
  47. @Autowired
  48. private IVideoManagerStorage videoManagerStorager;
  49. @Autowired
  50. private IMediaService mediaService;
  51. @Autowired
  52. private ZLMRESTfulUtils zlmresTfulUtils;
  53. @Autowired
  54. private StreamProxyMapper streamProxyMapper;
  55. @Autowired
  56. private IRedisCatchStorage redisCatchStorage;
  57. @Autowired
  58. private IVideoManagerStorage storager;
  59. @Autowired
  60. private UserSetting userSetting;
  61. @Autowired
  62. private GbStreamMapper gbStreamMapper;
  63. @Autowired
  64. private PlatformGbStreamMapper platformGbStreamMapper;
  65. @Autowired
  66. private EventPublisher eventPublisher;
  67. @Autowired
  68. private ParentPlatformMapper parentPlatformMapper;
  69. @Autowired
  70. private IGbStreamService gbStreamService;
  71. @Autowired
  72. private IMediaServerService mediaServerService;
  73. @Autowired
  74. DataSourceTransactionManager dataSourceTransactionManager;
  75. @Autowired
  76. TransactionDefinition transactionDefinition;
  77. @Override
  78. public StreamInfo save(StreamProxyItem param) {
  79. MediaServerItem mediaInfo;
  80. if (param.getMediaServerId() == null || "auto".equals(param.getMediaServerId())){
  81. mediaInfo = mediaServerService.getMediaServerForMinimumLoad();
  82. }else {
  83. mediaInfo = mediaServerService.getOne(param.getMediaServerId());
  84. }
  85. if (mediaInfo == null) {
  86. logger.warn("保存代理未找到在线的ZLM...");
  87. throw new ControllerException(ErrorCode.ERROR100.getCode(), "保存代理未找到在线的ZLM");
  88. }
  89. String dstUrl = String.format("rtmp://%s:%s/%s/%s", "127.0.0.1", mediaInfo.getRtmpPort(), param.getApp(),
  90. param.getStream() );
  91. param.setDst_url(dstUrl);
  92. StringBuffer resultMsg = new StringBuffer();
  93. boolean streamLive = false;
  94. param.setMediaServerId(mediaInfo.getId());
  95. boolean saveResult;
  96. // 更新
  97. if (videoManagerStorager.queryStreamProxy(param.getApp(), param.getStream()) != null) {
  98. saveResult = updateStreamProxy(param);
  99. }else { // 新增
  100. saveResult = addStreamProxy(param);
  101. }
  102. if (!saveResult) {
  103. throw new ControllerException(ErrorCode.ERROR100.getCode(),"保存失败");
  104. }
  105. StreamInfo resultForStreamInfo = null;
  106. resultMsg.append("保存成功");
  107. if (param.isEnable()) {
  108. JSONObject jsonObject = addStreamProxyToZlm(param);
  109. if (jsonObject == null || jsonObject.getInteger("code") != 0) {
  110. streamLive = false;
  111. resultMsg.append(", 但是启用失败,请检查流地址是否可用");
  112. param.setEnable(false);
  113. // 直接移除
  114. if (param.isEnable_remove_none_reader()) {
  115. del(param.getApp(), param.getStream());
  116. }else {
  117. updateStreamProxy(param);
  118. }
  119. }else {
  120. streamLive = true;
  121. resultForStreamInfo = mediaService.getStreamInfoByAppAndStream(
  122. mediaInfo, param.getApp(), param.getStream(), null, null);
  123. }
  124. }
  125. if ( !ObjectUtils.isEmpty(param.getPlatformGbId()) && streamLive) {
  126. List<GbStream> gbStreams = new ArrayList<>();
  127. gbStreams.add(param);
  128. if (gbStreamService.addPlatformInfo(gbStreams, param.getPlatformGbId(), param.getCatalogId())){
  129. return resultForStreamInfo;
  130. }else {
  131. resultMsg.append(", 关联国标平台[ " + param.getPlatformGbId() + " ]失败");
  132. throw new ControllerException(ErrorCode.ERROR100.getCode(), resultMsg.toString());
  133. }
  134. }else {
  135. if (!streamLive) {
  136. throw new ControllerException(ErrorCode.ERROR100.getCode(), resultMsg.toString());
  137. }
  138. }
  139. return resultForStreamInfo;
  140. }
  141. /**
  142. * 新增代理流
  143. * @param streamProxyItem
  144. * @return
  145. */
  146. private boolean addStreamProxy(StreamProxyItem streamProxyItem) {
  147. TransactionStatus transactionStatus = dataSourceTransactionManager.getTransaction(transactionDefinition);
  148. boolean result = false;
  149. streamProxyItem.setStreamType("proxy");
  150. streamProxyItem.setStatus(true);
  151. String now = DateUtil.getNow();
  152. streamProxyItem.setCreateTime(now);
  153. try {
  154. if (streamProxyMapper.add(streamProxyItem) > 0) {
  155. if (!ObjectUtils.isEmpty(streamProxyItem.getGbId())) {
  156. if (gbStreamMapper.add(streamProxyItem) < 0) {
  157. //事务回滚
  158. dataSourceTransactionManager.rollback(transactionStatus);
  159. return false;
  160. }
  161. }
  162. }else {
  163. //事务回滚
  164. dataSourceTransactionManager.rollback(transactionStatus);
  165. return false;
  166. }
  167. result = true;
  168. dataSourceTransactionManager.commit(transactionStatus); //手动提交
  169. }catch (Exception e) {
  170. logger.error("向数据库添加流代理失败:", e);
  171. dataSourceTransactionManager.rollback(transactionStatus);
  172. }
  173. return result;
  174. }
  175. /**
  176. * 更新代理流
  177. * @param streamProxyItem
  178. * @return
  179. */
  180. @Override
  181. public boolean updateStreamProxy(StreamProxyItem streamProxyItem) {
  182. TransactionStatus transactionStatus = dataSourceTransactionManager.getTransaction(transactionDefinition);
  183. boolean result = false;
  184. streamProxyItem.setStreamType("proxy");
  185. try {
  186. if (streamProxyMapper.update(streamProxyItem) > 0) {
  187. if (!ObjectUtils.isEmpty(streamProxyItem.getGbId())) {
  188. if (gbStreamMapper.updateByAppAndStream(streamProxyItem) == 0) {
  189. //事务回滚
  190. dataSourceTransactionManager.rollback(transactionStatus);
  191. return false;
  192. }
  193. }
  194. } else {
  195. //事务回滚
  196. dataSourceTransactionManager.rollback(transactionStatus);
  197. return false;
  198. }
  199. dataSourceTransactionManager.commit(transactionStatus); //手动提交
  200. result = true;
  201. }catch (Exception e) {
  202. e.printStackTrace();
  203. dataSourceTransactionManager.rollback(transactionStatus);
  204. }
  205. return result;
  206. }
  207. @Override
  208. public JSONObject addStreamProxyToZlm(StreamProxyItem param) {
  209. JSONObject result = null;
  210. MediaServerItem mediaServerItem = null;
  211. if (param.getMediaServerId() == null) {
  212. logger.warn("添加代理时MediaServerId 为null");
  213. return null;
  214. }else {
  215. mediaServerItem = mediaServerService.getOne(param.getMediaServerId());
  216. }
  217. if (mediaServerItem == null) {
  218. return null;
  219. }
  220. if ("default".equals(param.getType())){
  221. result = zlmresTfulUtils.addStreamProxy(mediaServerItem, param.getApp(), param.getStream(), param.getUrl(),
  222. param.isEnable_hls(), param.isEnable_mp4(), param.getRtp_type());
  223. }else if ("ffmpeg".equals(param.getType())) {
  224. result = zlmresTfulUtils.addFFmpegSource(mediaServerItem, param.getSrc_url(), param.getDst_url(),
  225. param.getTimeout_ms() + "", param.isEnable_hls(), param.isEnable_mp4(),
  226. param.getFfmpeg_cmd_key());
  227. }
  228. return result;
  229. }
  230. @Override
  231. public JSONObject removeStreamProxyFromZlm(StreamProxyItem param) {
  232. if (param ==null) {
  233. return null;
  234. }
  235. MediaServerItem mediaServerItem = mediaServerService.getOne(param.getMediaServerId());
  236. JSONObject result = zlmresTfulUtils.closeStreams(mediaServerItem, param.getApp(), param.getStream());
  237. return result;
  238. }
  239. @Override
  240. public PageInfo<StreamProxyItem> getAll(Integer page, Integer count) {
  241. return videoManagerStorager.queryStreamProxyList(page, count);
  242. }
  243. @Override
  244. public void del(String app, String stream) {
  245. StreamProxyItem streamProxyItem = videoManagerStorager.queryStreamProxy(app, stream);
  246. if (streamProxyItem != null) {
  247. gbStreamService.sendCatalogMsg(streamProxyItem, CatalogEvent.DEL);
  248. videoManagerStorager.deleteStreamProxy(app, stream);
  249. JSONObject jsonObject = removeStreamProxyFromZlm(streamProxyItem);
  250. if (jsonObject != null && jsonObject.getInteger("code") == 0) {
  251. // 如果关联了国标那么移除关联
  252. gbStreamMapper.del(app, stream);
  253. platformGbStreamMapper.delByAppAndStream(app, stream);
  254. // TODO 如果关联的推流, 那么状态设置为离线
  255. }
  256. redisCatchStorage.removeStream(streamProxyItem.getMediaServerId(), "PULL", app, stream);
  257. }
  258. }
  259. @Override
  260. public boolean start(String app, String stream) {
  261. boolean result = false;
  262. StreamProxyItem streamProxy = videoManagerStorager.queryStreamProxy(app, stream);
  263. if (!streamProxy.isEnable() ) {
  264. JSONObject jsonObject = addStreamProxyToZlm(streamProxy);
  265. if (jsonObject == null) {
  266. return false;
  267. }
  268. if (jsonObject.getInteger("code") == 0) {
  269. result = true;
  270. streamProxy.setEnable(true);
  271. updateStreamProxy(streamProxy);
  272. }
  273. }
  274. return result;
  275. }
  276. @Override
  277. public boolean stop(String app, String stream) {
  278. boolean result = false;
  279. StreamProxyItem streamProxyDto = videoManagerStorager.queryStreamProxy(app, stream);
  280. if (streamProxyDto != null && streamProxyDto.isEnable()) {
  281. JSONObject jsonObject = removeStreamProxyFromZlm(streamProxyDto);
  282. if (jsonObject != null && jsonObject.getInteger("code") == 0) {
  283. streamProxyDto.setEnable(false);
  284. result = updateStreamProxy(streamProxyDto);
  285. }
  286. }
  287. return result;
  288. }
  289. @Override
  290. public JSONObject getFFmpegCMDs(MediaServerItem mediaServerItem) {
  291. JSONObject result = new JSONObject();
  292. JSONObject mediaServerConfigResuly = zlmresTfulUtils.getMediaServerConfig(mediaServerItem);
  293. if (mediaServerConfigResuly != null && mediaServerConfigResuly.getInteger("code") == 0
  294. && mediaServerConfigResuly.getJSONArray("data").size() > 0){
  295. JSONObject mediaServerConfig = mediaServerConfigResuly.getJSONArray("data").getJSONObject(0);
  296. for (String key : mediaServerConfig.keySet()) {
  297. if (key.startsWith("ffmpeg.cmd")){
  298. result.put(key, mediaServerConfig.getString(key));
  299. }
  300. }
  301. }
  302. return result;
  303. }
  304. @Override
  305. public StreamProxyItem getStreamProxyByAppAndStream(String app, String streamId) {
  306. return videoManagerStorager.getStreamProxyByAppAndStream(app, streamId);
  307. }
  308. @Override
  309. public void zlmServerOnline(String mediaServerId) {
  310. // 移除开启了无人观看自动移除的流
  311. List<StreamProxyItem> streamProxyItemList = streamProxyMapper.selecAutoRemoveItemByMediaServerId(mediaServerId);
  312. if (streamProxyItemList.size() > 0) {
  313. gbStreamMapper.batchDel(streamProxyItemList);
  314. }
  315. streamProxyMapper.deleteAutoRemoveItemByMediaServerId(mediaServerId);
  316. // 移除拉流代理生成的流信息
  317. // syncPullStream(mediaServerId);
  318. // 恢复流代理, 只查找这个这个流媒体
  319. List<StreamProxyItem> streamProxyListForEnable = storager.getStreamProxyListForEnableInMediaServer(
  320. mediaServerId, true);
  321. for (StreamProxyItem streamProxyDto : streamProxyListForEnable) {
  322. logger.info("恢复流代理," + streamProxyDto.getApp() + "/" + streamProxyDto.getStream());
  323. JSONObject jsonObject = addStreamProxyToZlm(streamProxyDto);
  324. if (jsonObject == null) {
  325. // 设置为离线
  326. logger.info("恢复流代理失败" + streamProxyDto.getApp() + "/" + streamProxyDto.getStream());
  327. updateStatus(false, streamProxyDto.getApp(), streamProxyDto.getStream());
  328. }else {
  329. updateStatus(true, streamProxyDto.getApp(), streamProxyDto.getStream());
  330. }
  331. }
  332. }
  333. @Override
  334. public void zlmServerOffline(String mediaServerId) {
  335. // 移除开启了无人观看自动移除的流
  336. List<StreamProxyItem> streamProxyItemList = streamProxyMapper.selecAutoRemoveItemByMediaServerId(mediaServerId);
  337. if (streamProxyItemList.size() > 0) {
  338. gbStreamMapper.batchDel(streamProxyItemList);
  339. }
  340. streamProxyMapper.deleteAutoRemoveItemByMediaServerId(mediaServerId);
  341. // 其他的流设置离线
  342. streamProxyMapper.updateStatusByMediaServerId(mediaServerId, false);
  343. String type = "PULL";
  344. // 发送redis消息
  345. List<MediaItem> mediaItems = redisCatchStorage.getStreams(mediaServerId, type);
  346. if (mediaItems.size() > 0) {
  347. for (MediaItem mediaItem : mediaItems) {
  348. JSONObject jsonObject = new JSONObject();
  349. jsonObject.put("serverId", userSetting.getServerId());
  350. jsonObject.put("app", mediaItem.getApp());
  351. jsonObject.put("stream", mediaItem.getStream());
  352. jsonObject.put("register", false);
  353. jsonObject.put("mediaServerId", mediaServerId);
  354. redisCatchStorage.sendStreamChangeMsg(type, jsonObject);
  355. // 移除redis内流的信息
  356. redisCatchStorage.removeStream(mediaServerId, type, mediaItem.getApp(), mediaItem.getStream());
  357. }
  358. }
  359. }
  360. @Override
  361. public void clean() {
  362. }
  363. @Override
  364. public int updateStatus(boolean status, String app, String stream) {
  365. return streamProxyMapper.updateStatus(app, stream, status);
  366. }
  367. private void syncPullStream(String mediaServerId){
  368. MediaServerItem mediaServer = mediaServerService.getOne(mediaServerId);
  369. if (mediaServer != null) {
  370. List<MediaItem> allPullStream = redisCatchStorage.getStreams(mediaServerId, "PULL");
  371. if (allPullStream.size() > 0) {
  372. zlmresTfulUtils.getMediaList(mediaServer, jsonObject->{
  373. Map<String, StreamInfo> stringStreamInfoMap = new HashMap<>();
  374. if (jsonObject.getInteger("code") == 0) {
  375. JSONArray data = jsonObject.getJSONArray("data");
  376. if(data != null && data.size() > 0) {
  377. for (int i = 0; i < data.size(); i++) {
  378. JSONObject streamJSONObj = data.getJSONObject(i);
  379. if ("rtsp".equals(streamJSONObj.getString("schema"))) {
  380. StreamInfo streamInfo = new StreamInfo();
  381. String app = streamJSONObj.getString("app");
  382. String stream = streamJSONObj.getString("stream");
  383. streamInfo.setApp(app);
  384. streamInfo.setStream(stream);
  385. stringStreamInfoMap.put(app+stream, streamInfo);
  386. }
  387. }
  388. }
  389. }
  390. if (stringStreamInfoMap.size() == 0) {
  391. redisCatchStorage.removeStream(mediaServerId, "PULL");
  392. }else {
  393. for (String key : stringStreamInfoMap.keySet()) {
  394. StreamInfo streamInfo = stringStreamInfoMap.get(key);
  395. if (stringStreamInfoMap.get(streamInfo.getApp() + streamInfo.getStream()) == null) {
  396. redisCatchStorage.removeStream(mediaServerId, "PULL", streamInfo.getApp(),
  397. streamInfo.getStream());
  398. }
  399. }
  400. }
  401. });
  402. }
  403. }
  404. }
  405. }