StreamProxyServiceImpl.java 19 KB

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