648540858
2024-01-10 c25a99d60bef3d3bbd59fee895bd658928fd00db
src/main/java/com/genersoft/iot/vmp/service/impl/MediaServerServiceImpl.java
old mode 100644 new mode 100755
@@ -24,23 +24,30 @@
import com.genersoft.iot.vmp.utils.JsonUtil;
import com.genersoft.iot.vmp.utils.redis.RedisUtil;
import com.genersoft.iot.vmp.vmanager.bean.ErrorCode;
import com.genersoft.iot.vmp.vmanager.bean.RecordFile;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.util.Assert;
import org.springframework.util.ObjectUtils;
import java.io.File;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
/**
 * 媒体服务器节点管理
@@ -87,7 +94,7 @@
    @Autowired
    private ZLMRTPServerFactory zlmrtpServerFactory;
    private ZLMServerFactory zlmServerFactory;
    @Autowired
    private EventPublisher publisher;
@@ -104,6 +111,11 @@
    @Autowired
    private RedisTemplate<Object, Object> redisTemplate;
    @Qualifier("taskExecutor")
    @Autowired
    private ThreadPoolTaskExecutor taskExecutor;
    /**
     * 初始化
@@ -116,36 +128,8 @@
                continue;
            }
            // 更新
            if (ssrcFactory.hasMediaServerSSRC(mediaServerItem.getId())) {
            if (!ssrcFactory.hasMediaServerSSRC(mediaServerItem.getId())) {
                ssrcFactory.initMediaServerSSRC(mediaServerItem.getId(), null);
            }
            if (userSetting.getGbSendStreamStrict()) {
                int startPort = 50000;
                int endPort = 60000;
                String sendRtpPortRange = mediaServerItem.getSendRtpPortRange();
                if (sendRtpPortRange == null) {
                    logger.warn("[zlm] ] 未配置发流端口范围,默认使用50000到60000");
                }else {
                    String[] sendRtpPortRangeArray = sendRtpPortRange.trim().split(",");
                    if (sendRtpPortRangeArray.length != 2) {
                        logger.warn("[zlm] ] 发流端口范围错误,默认使用50000到60000");
                    }else {
                        try {
                            startPort = Integer.parseInt(sendRtpPortRangeArray[0]);
                            endPort = Integer.parseInt(sendRtpPortRangeArray[1]);
                            if (endPort <= startPort) {
                                logger.warn("[zlm] ] 发流端口范围错误,结束端口应大于开始端口,使用默认端口");
                                startPort = 50000;
                                endPort = 60000;
                            }
                        }catch (NumberFormatException e) {
                            logger.warn("[zlm] ] 发流端口范围错误,默认使用50000到60000");
                        }
                    }
                }
                logger.info("[[zlm] ] 配置发流端口范围,{}-{}", startPort, endPort);
                sendRtpPortManager.initServerPort(mediaServerItem.getId(), startPort, endPort);
            }
            // 查询redis是否存在此mediaServer
            String key = VideoManagerConstants.MEDIA_SERVER_PREFIX + userSetting.getServerId() + "_" + mediaServerItem.getId();
@@ -177,11 +161,16 @@
        }
        if (streamId == null) {
            streamId = String.format("%08x", Integer.parseInt(ssrc)).toUpperCase();
            streamId = String.format("%08x", Long.parseLong(ssrc)).toUpperCase();
        }
        int ssrcCheckParam = 0;
        if (ssrcCheck && tcpMode > 1) {
            // 目前zlm不支持 tcp模式更新ssrc,暂时关闭ssrc校验
            logger.warn("[openRTPServer] TCP被动/TCP主动收流时,默认关闭ssrc检验");
        }
        int rtpServerPort;
        if (mediaServerItem.isRtpEnable()) {
            rtpServerPort = zlmrtpServerFactory.createRTPServer(mediaServerItem, streamId, ssrcCheck?Integer.parseInt(ssrc):0, port, reUsePort, tcpMode);
            rtpServerPort = zlmServerFactory.createRTPServer(mediaServerItem, streamId, (ssrcCheck && tcpMode == 0) ? Long.parseLong(ssrc) : 0, port, reUsePort, tcpMode);
        } else {
            rtpServerPort = mediaServerItem.getRtpProxyPort();
        }
@@ -193,7 +182,7 @@
        if (mediaServerItem == null) {
            return;
        }
        zlmrtpServerFactory.closeRtpServer(mediaServerItem, streamId);
        zlmServerFactory.closeRtpServer(mediaServerItem, streamId);
    }
    @Override
@@ -202,7 +191,7 @@
            callback.run(false);
            return;
        }
        zlmrtpServerFactory.closeRtpServer(mediaServerItem, streamId, callback);
        zlmServerFactory.closeRtpServer(mediaServerItem, streamId, callback);
    }
    @Override
@@ -213,7 +202,7 @@
    @Override
    public Boolean updateRtpServerSSRC(MediaServerItem mediaServerItem, String streamId, String ssrc) {
        return zlmrtpServerFactory.updateRtpServerSSRC(mediaServerItem, streamId, ssrc);
        return zlmServerFactory.updateRtpServerSSRC(mediaServerItem, streamId, ssrc);
    }
    @Override
@@ -240,7 +229,7 @@
        mediaServerMapper.update(mediaSerItem);
        MediaServerItem mediaServerItemInRedis = getOne(mediaSerItem.getId());
        MediaServerItem mediaServerItemInDataBase = mediaServerMapper.queryOne(mediaSerItem.getId());
        if (mediaServerItemInRedis == null || ssrcFactory.hasMediaServerSSRC(mediaSerItem.getId())) {
        if (mediaServerItemInRedis == null || !ssrcFactory.hasMediaServerSSRC(mediaSerItem.getId())) {
            ssrcFactory.initMediaServerSSRC(mediaServerItemInDataBase.getId(),null);
        }
        String key = VideoManagerConstants.MEDIA_SERVER_PREFIX + userSetting.getServerId() + "_" + mediaServerItemInDataBase.getId();
@@ -422,7 +411,7 @@
        }
        mediaServerMapper.update(serverItem);
        String key = VideoManagerConstants.MEDIA_SERVER_PREFIX + userSetting.getServerId() + "_" + zlmServerConfig.getGeneralMediaServerId();
        if (ssrcFactory.hasMediaServerSSRC(serverItem.getId())) {
        if (!ssrcFactory.hasMediaServerSSRC(serverItem.getId())) {
            ssrcFactory.initMediaServerSSRC(zlmServerConfig.getGeneralMediaServerId(), null);
        }
        redisTemplate.opsForValue().set(key, serverItem);
@@ -430,17 +419,6 @@
        if (serverItem.isAutoConfig()) {
            // 查看assist服务的录像路径配置
            if (serverItem.getRecordAssistPort() > 0 && userSetting.getRecordPath() == null) {
                JSONObject info = assistRESTfulUtils.getInfo(serverItem, null);
                if (info != null && info.getInteger("code") != null && info.getInteger("code") == 0 ) {
                    JSONObject dataJson = info.getJSONObject("data");
                    if (dataJson != null) {
                        String recordPath = dataJson.getString("record");
                        userSetting.setRecordPath(recordPath);
                    }
                }
            }
            setZLMConfig(serverItem, "0".equals(zlmServerConfig.getHookEnable()));
        }
        final String zlmKeepaliveKey = zlmKeepaliveKeyPrefix + serverItem.getId();
@@ -575,7 +553,7 @@
        logger.info("[ZLM] 正在设置 :{} -> {}:{}",
                mediaServerItem.getId(), mediaServerItem.getIp(), mediaServerItem.getHttpPort());
        String protocol = sslEnabled ? "https" : "http";
        String hookPrex = String.format("%s://%s:%s/index/hook", protocol, mediaServerItem.getHookIp(), serverPort);
        String hookPrefix = String.format("%s://%s:%s/index/hook", protocol, mediaServerItem.getHookIp(), serverPort);
        Map<String, Object> param = new HashMap<>();
        param.put("api.secret",mediaServerItem.getSecret()); // -profile:v Baseline
@@ -584,25 +562,21 @@
        }
        param.put("hook.enable","1");
        param.put("hook.on_flow_report","");
        param.put("hook.on_play",String.format("%s/on_play", hookPrex));
        param.put("hook.on_play",String.format("%s/on_play", hookPrefix));
        param.put("hook.on_http_access","");
        param.put("hook.on_publish", String.format("%s/on_publish", hookPrex));
        param.put("hook.on_publish", String.format("%s/on_publish", hookPrefix));
        param.put("hook.on_record_ts","");
        param.put("hook.on_rtsp_auth","");
        param.put("hook.on_rtsp_realm","");
        param.put("hook.on_server_started",String.format("%s/on_server_started", hookPrex));
        param.put("hook.on_server_started",String.format("%s/on_server_started", hookPrefix));
        param.put("hook.on_shell_login","");
        param.put("hook.on_stream_changed",String.format("%s/on_stream_changed", hookPrex));
        param.put("hook.on_stream_none_reader",String.format("%s/on_stream_none_reader", hookPrex));
        param.put("hook.on_stream_not_found",String.format("%s/on_stream_not_found", hookPrex));
        param.put("hook.on_server_keepalive",String.format("%s/on_server_keepalive", hookPrex));
        param.put("hook.on_send_rtp_stopped",String.format("%s/on_send_rtp_stopped", hookPrex));
        param.put("hook.on_rtp_server_timeout",String.format("%s/on_rtp_server_timeout", hookPrex));
        if (mediaServerItem.getRecordAssistPort() > 0) {
            param.put("hook.on_record_mp4",String.format("http://127.0.0.1:%s/api/record/on_record_mp4", mediaServerItem.getRecordAssistPort()));
        }else {
            param.put("hook.on_record_mp4","");
        }
        param.put("hook.on_stream_changed",String.format("%s/on_stream_changed", hookPrefix));
        param.put("hook.on_stream_none_reader",String.format("%s/on_stream_none_reader", hookPrefix));
        param.put("hook.on_stream_not_found",String.format("%s/on_stream_not_found", hookPrefix));
        param.put("hook.on_server_keepalive",String.format("%s/on_server_keepalive", hookPrefix));
        param.put("hook.on_send_rtp_stopped",String.format("%s/on_send_rtp_stopped", hookPrefix));
        param.put("hook.on_rtp_server_timeout",String.format("%s/on_rtp_server_timeout", hookPrefix));
        param.put("hook.on_record_mp4",String.format("%s/on_record_mp4", hookPrefix));
        param.put("hook.timeoutSec","20");
        // 推流断开后可以在超时时间内重新连接上继续推流,这样播放器会接着播放。
        // 置0关闭此特性(推流断开会导致立即断开播放器)
@@ -611,15 +585,13 @@
        param.put("protocol.continue_push_ms", "3000" );
        // 最多等待未初始化的Track时间,单位毫秒,超时之后会忽略未初始化的Track, 设置此选项优化那些音频错误的不规范流,
        // 等zlm支持给每个rtpServer设置关闭音频的时候可以不设置此选项
//        param.put("general.wait_track_ready_ms", "3000" );
        if (mediaServerItem.isRtpEnable() && !ObjectUtils.isEmpty(mediaServerItem.getRtpPortRange())) {
            param.put("rtp_proxy.port_range", mediaServerItem.getRtpPortRange().replace(",", "-"));
        }
        if (userSetting.getRecordPath() != null) {
            File recordPathFile = new File(userSetting.getRecordPath());
            File mp4SavePathFile = recordPathFile.getParentFile().getAbsoluteFile();
            param.put("protocol.mp4_save_path", mp4SavePathFile.getAbsoluteFile());
        if (mediaServerItem.getRecordPath() != null) {
            File recordPathFile = new File(mediaServerItem.getRecordPath());
            param.put("protocol.mp4_save_path", recordPathFile.getParentFile().getPath());
            param.put("record.appName", recordPathFile.getName());
        }
@@ -752,15 +724,6 @@
    }
    @Override
    public boolean checkRtpServer(MediaServerItem mediaServerItem, String app, String stream) {
        JSONObject rtpInfo = zlmresTfulUtils.getRtpInfo(mediaServerItem, stream);
        if(rtpInfo.getInteger("code") == 0){
            return rtpInfo.getBoolean("exist");
        }
        return false;
    }
    @Override
    public MediaServerLoad getLoad(MediaServerItem mediaServerItem) {
        MediaServerLoad result = new MediaServerLoad();
        result.setId(mediaServerItem.getId());
@@ -772,4 +735,8 @@
        return result;
    }
    @Override
    public List<MediaServerItem> getAllWithAssistPort() {
        return mediaServerMapper.queryAllWithAssistPort();
    }
}