package com.sptg.video.cloud.biz.controller;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.sptg.video.cloud.api.entity.RtspUrl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author zwx
 * @create 2020/10/27 23:54
 */
@RestController
public class RtspVideoController {

    @Autowired
    private RedisTemplate redisTemplate;

    public static final String VIDEO_CLOUD_RTSP_URL = "video:cloud:rtsp:url";

    @PostMapping(value = "/get/httpFlv")
    public String playRtspVideo(@RequestBody RtspUrl rtspUrl){
        if(rtspUrl.getDeviceNum() != null){
            HashOperations<String, String, String> hashOperations = this.redisTemplate.opsForHash();
            String json = hashOperations.get(VIDEO_CLOUD_RTSP_URL, rtspUrl.getDeviceNum());
            JSONObject obj = JSONUtil.parseObj(json);
            if(json == null){
                //执行ffmpeg指令，进行推流
                String httpFlv = execFFmpeg(rtspUrl.getDeviceNum(), rtspUrl.getRtspUrl());
//                String httpFlv = "http-flv-" + rtspUrl.getDeviceNum();
                rtspUrl.setHttpFlv(httpFlv);
                hashOperations.put(VIDEO_CLOUD_RTSP_URL, rtspUrl.getDeviceNum(), JSONUtil.toJsonStr(rtspUrl));
                return httpFlv;
            }else{
                String httpFlv = (String)obj.get("httpFlv");
                return httpFlv;
            }
        }
        return null;
    }

    private String execFFmpeg(String deviceNum, String rtspUrl){
        // Nginx rtmp地址
        // 1935 对应Nginx配置文件中rtmp所监听的端口
        // myapp 对应Nginx配置文件中rtmp下application的值
        // rtmpStream 对应播放页面中16行参数stream的值
        String nginxRtmpUrl = "rtmp://192.168.0.228:1935/myapp/mystream-" + deviceNum;
        pushVideoAsRTSP(rtspUrl, nginxRtmpUrl);
        return "http://139.9.103.171/live?port=1935&app=myapp&stream=mystream-"+deviceNum;
    }

    public Integer pushVideoAsRTSP(String rtspUrl, String nginxRtmpUrl){
        int flag = -1;
        try {
            // ffmpeg 已经在系统环境
            String command = "ffmpeg -rtsp_transport tcp";
            command += " -i " + rtspUrl;
            command += " -vcodec libx264 -preset:v ultrafast -tune:v zerolatency -acodec aac -f flv " + nginxRtmpUrl;

            Process process = Runtime.getRuntime().exec(command);
            flag = process.waitFor();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return flag;
    }
}
