StreamProxyServiceImpl.java 18 KB

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