package com.objecteye.service.impl; import com.objecteye.entity.SyEquipment; import com.objecteye.service.EquipmentService; import com.objecteye.service.PreviewService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.io.IOException; import java.net.InetAddress; import java.util.concurrent.ConcurrentHashMap; @Service public class PreviewServiceImpl implements PreviewService { @Autowired static String ffmpegTnstructions; private EquipmentService equipmentService; private static ConcurrentHashMap rtmpAndprocessMaps = new ConcurrentHashMap<>(); private static ConcurrentHashMap userAndrtmpMaps = new ConcurrentHashMap<>(); @Override public String getRtmp(String userName, Integer deviceId) throws IOException { SyEquipment equipment = equipmentService.findOne(deviceId); String equipmentName = equipment.getEquipmentName(); String rtspUrl = equipment.getRtspUrl(); boolean rtmpStrIsVaild = false; String address = InetAddress.getLocalHost().toString().split("/")[1]; String rtmpStr = "rtmp://" + address + ":1935/hls/" + equipmentName + deviceId; if (rtmpAndprocessMaps.containsKey(rtmpStr)) { if (userAndrtmpMaps.containsKey(userName)) { userAndrtmpMaps.remove(userName); } userAndrtmpMaps.put(userName, rtmpStr); } else { Process process = null; if (rtspUrl.contains("rtsp")) { ffmpegTnstructions = "ffmpeg -re -stream_loop -1 -rtsp_transport tcp -i" + rtspUrl + "-vcodec copy -acodec copy -f flv -r 15 -s 1280x720 -an -y " + rtmpStr; } else { ffmpegTnstructions = "ffmpeg -re -stream_loop -1 -rtsp_transport tcp -i rtsp://" + equipmentName + ":" + equipment.getPassword() + "@" + equipment.getEquipmentIp() + ":" + equipment.getEquipmentPort() + "/h264/ch1/main/av_stream -vcodec copy -acodec copy -f flv -r 15 -s 1280x720 -an -y rtmp://" + address + ":1935/hls/" + equipmentName + deviceId; } process = Runtime.getRuntime().exec(ffmpegTnstructions); rtmpAndprocessMaps.put(rtmpStr, process); userAndrtmpMaps.put(userName, rtmpStr); rtmpStrIsVaild = process.isAlive(); /*if (rtmpStrIsVaild) { System.out.println("转流进程正在运行"); }*/ } for (String rtmpString : rtmpAndprocessMaps.keySet()) { if (!userAndrtmpMaps.containsValue(rtmpString)) { //System.out.println("当前转流进程未使用,停止rtsp转rtmp"); Process detroyPro = rtmpAndprocessMaps.get(rtmpString); if (detroyPro.isAlive()) { detroyPro.destroy(); } rtmpAndprocessMaps.remove(rtmpString); } } if (rtmpStrIsVaild) { return rtmpStr; } return null; } }