nishiwei
5 days ago 3f43e40ed1a1e9f66b3ad2862da9dbc4b710c712
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
package com.ard.sample.component.websocket.handler;
 
import com.ard.common.core.redis.RedisConst;
import com.ard.common.core.redis.RedisOpsUtils;
import com.ard.sample.common.model.ResponseResult;
import com.ard.sample.component.websocket.enums.MessageType;
import com.ard.sample.manage.model.dto.*;
import com.ard.sample.manage.service.IDeviceService;
import com.ard.sample.manage.service.ILiveStreamService;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
 
import java.util.HashMap;
import java.util.List;
import java.util.Map;
 
@Slf4j
@Component
public class LiveStreamHandler {
    @Autowired
    protected ObjectMapper _objectMapper;
    @Autowired
    private IDeviceService _deviceService;
    @Autowired
    private ILiveStreamService _liveStreamService;
    @Autowired
    private DockWebSocketHandler _dockWebSocketHandler;
 
    /**
     * 开启直播
     */
    public void StartLiveStreaming(String sn ,String userId) {
        //调用开始直播
        ResponseResult rlive = null;
        String resultLive = "";
        try {
            // 获取直播参数
            LiveTypeDTO param = getLiveParam(sn);
            // 判断param是否为空,不为空则返回正确的直播参数,为null则未获取直播参数,不为空则继续操作
            if (param == null) {
                log.info("SN: {}-未获取到直播参数param为null,无法开启直播!", sn);
                return;
            }
            // 如果存在直播则读取直播地址返回
            if (RedisOpsUtils.checkExist(RedisConst.WEBSOCKET_VIDEO_ADDRESS_PREFIX + sn)) {
                resultLive = String.valueOf(RedisOpsUtils.get(RedisConst.WEBSOCKET_VIDEO_ADDRESS_PREFIX + sn));
                log.info("SN: {}-redis中存在相机的播放地址信息,直接返回地址!", sn);
            } else {
                log.info("SN: {}-redis中未找到相机的播放地址信息!停止直播后再开启直播", sn);
                StopLiveStreaming(sn);
                // 如果不存在直播,则开始直播,并返回直播地址
                rlive = _liveStreamService.liveStart(param);
                if (rlive.getCode() == 0) {
                    // 直播成功后,在redis中存一个标记,将videoid保留,留给停止直播使用
                    log.info("SN: {}-开启直播成功!", sn);
                    rlive.setGateway(sn);
                    rlive.setType(MessageType.LIVESTREAM.getType());
                    resultLive = _objectMapper.writeValueAsString(rlive);
                    RedisOpsUtils.set(RedisConst.WEBSOCKET_VIDEO_ADDRESS_PREFIX + sn, resultLive);
                    LiveDTO live = (LiveDTO) rlive.getData();
                    Boolean isWeb = _deviceService.updateWebrtcUrl(sn,live.getWebrtcUrl());
                    if (isWeb) {
                        log.info("SN: {}-更新webrtc地址成功!", sn);
                    }
                }
                else {
                    log.info("SN: {}-开启直播失败!返回值:{}", sn, rlive);
                }
            }
            _dockWebSocketHandler.sendMessageToSubscribers(sn, MessageType.LIVESTREAM.getType(), resultLive, userId);
            log.info("SN: {}-直播地址:{}", sn, resultLive);
        } catch (Exception e) {
            log.info("SN: {}-开启直播失败!原因:{}", sn, e.getMessage());
            e.printStackTrace();
        }
    }
 
    public void StopLiveStreaming(String sn) {
        ResponseResult rlive = null;
        try {
            // 获取直播参数
            LiveTypeDTO param = getLiveParam(sn);
            // 停止直播逻辑
            rlive = _liveStreamService.liveStop(param.getVideoId());
            log.info("SN: {}-停止直播!返回值:{}", sn, rlive);
        } catch (Exception e) {
            log.info("SN: {}-停止直播时发生异常,原因:{}", sn, e.getMessage(), e);
        } finally {
            // 无论停流是否成功都清理缓存地址:
            // 设备离线等原因导致停流异常时,若不清 Redis,后续订阅会直接拿到失效地址,
            // 页面持续黑屏,只有等设备离线清理缓存后才能恢复
            RedisOpsUtils.del(RedisConst.WEBSOCKET_VIDEO_ADDRESS_PREFIX + sn);
            log.info("SN: {}-已删除redis直播信息!", sn);
        }
    }
 
    public String getResult(String sn, String msg) {
        Map<String, String> result = new HashMap<>();
        result.put("gateway", sn);
        result.put("code", "1");
        result.put("message", msg);
        result.put("data", null);
        result.put("type", MessageType.LIVESTREAM.getType());
        // 将Map转换为JSON字符串
        String jsonString = "";
        try {
            jsonString = _objectMapper.writeValueAsString(result);
        } catch (Exception e) {
            e.printStackTrace();
        }
 
        return jsonString;
    }
 
    /**
     * 获取直播参数
     */
    public LiveTypeDTO getLiveParam(String sn) throws Exception {
        LiveTypeDTO param = new LiveTypeDTO();
        // 检查设备是否在线
        if (!_deviceService.checkDeviceOnline(sn)) {
            log.info("SN: {}-设备不在线,请检查网络连接!", sn);
            // 抛弃出异常,给调用者处理
            throw new Exception("设备不在线,请检查网络连接!");
        }
        // 读取直播能力拼接参数
        List<CapacityDeviceDTO> devicesList = _liveStreamService.getLiveCapacity();
        if (devicesList == null || devicesList.isEmpty()) {
            log.info("SN: {}-未获得设备直播能力!", sn);
            return null;
            // 抛弃出异常,给调用者处理
            // throw new Exception("未获得设备直播能力!");
        }
        for (CapacityDeviceDTO device : devicesList) {
            if (!device.getSn().equals(sn)) {
                continue;
            }
            List<CapacityCameraDTO> camerasList = device.getCamerasList();
            if (camerasList == null || camerasList.isEmpty()) {
                continue;
            }
            for (CapacityCameraDTO camera : camerasList) {
                List<CapacityVideoDTO> videosList = camera.getVideosList();
                if (videosList == null || videosList.isEmpty()) {
                    continue;
                }
                // 机场1:M30 / M30T 相机索引为 52-x-x / 53-x-x,live_capacity 可能同时上报
                // normal-0、zoom-0、ir-0 多条码流。默认优先选 normal 码流(可见光),
                // 避免原来“循环取最后一条”时默认落到红外。其他机型保持原行为(取最后一条)。
                boolean m30SeriesCamera = camera.getIndex() != null
                        && (camera.getIndex().startsWith("52-") || camera.getIndex().startsWith("53-"));
                CapacityVideoDTO selectedVideo = null;
                for (CapacityVideoDTO video : videosList) {
                    selectedVideo = video;
                    if (m30SeriesCamera && video.getIndex() != null
                            && video.getIndex().startsWith("normal")) {
                        break;
                    }
                }
                if (selectedVideo == null) {
                    continue;
                }
                List<String> switchVideoTypes = selectedVideo.getSwitchVideoTypes();
                if (switchVideoTypes == null || switchVideoTypes.isEmpty()) {
                    // 没有镜头类型信息时跳过该相机,避免 get(0) 越界
                    continue;
                }
                // 机场1:video_id 格式固定为 {sn}/{camera_index}/{video_index}。
                // 按选中的码流独立构造,单码流设备结果与原来完全一致。
                String videoid = device.getSn() + "/" + camera.getIndex() + "/" + selectedVideo.getIndex();
                param.setUrlType(1);
                param.setUrl("");
                param.setVideoId(videoid);
                param.setVideoQuality(1);
                param.setVideoType(switchVideoTypes.get(0));
            }
        }
        return param;
    }
}