var videoMonitorProcess = null;
let vlcCloseTime = null;
let { execFile, exec } = require('child_process');
let workState = {
  state: '', //  true:开启成功 false:开启失败
  message: '', //  状态信息
  streamUrl: null, // 视频流地址
};

let optionsDefault = {
  videoDevicePath: '', // 视频流串口地址
  streamType: 1, //  1:rtsp视频流 2:http视频流
  autoCloseTime: 60 * 3, //  自动关闭时间，单位：秒 0:不关闭 默认3分钟
  localIp: '', //  本机IP
  port: 8554, // 视频流端口
};

/**
 * 打开视频流
 * @param options {
 *   videoDevicePath: '', // 视频流串口地址
 *   streamType: 1, //  1:rtsp视频流 2:http视频流
 *   autoCloseTime: 60 * 3, //  自动关闭时间，单位：秒 0:不关闭 默认3分钟
 *   localIp: '', //  本机IP
 *   port: 8554, // 视频流端口
 * }
 * @param callback 回调
 * @param exitCallback 视频流进程退出回调
 */
function openVlcStream(options, callback,exitCallback) {
  options = Object.assign(optionsDefault, options);
  if (videoMonitorProcess && !videoMonitorProcess.killed) {
    console.log(`已开启摄像头RTSP推流,进程ID:${videoMonitorProcess.pid}`);
    if (callback) {
      workState.state = true;
      workState.message = '启动摄像头RTSP推流正常';
      workState.streamUrl = getStreamUrl(options);
      callback(workState);
    }
    setTimeoutCloseStream(options);
    return;
  }
  console.log(`准备启动摄像头RTSP推流，设备路径：${options.videoDevicePath}`);
  let vlcPathMess = `v4l2://${options.videoDevicePath}`;
  let pkill = 'pkill -f vlc';
  if (process.platform == 'win32') {
    vlcPathMess = `dshow://vdev=${options.videoDevicePath}`;
    pkill = ' taskkill /f /im vlc.exe';
  }
  let soutText = `:sout=#transcode{vcodec=mp4v,scale=Auto,vb=2048,width=320,height=240,acodec=none,scodec=none,fps=15}:rtp{sdp=rtsp://${options.localIp}:${options.port}/}`;
  if (options.streamType == 2) {
    soutText = `:sout=#transcode{vcodec=mp4v,marq-timeout=<10000,scale=Auto,vb=2048,width=320,height=240,acodec=none,scodec=none,fps=25}:standard{access=http,mux=ts,mime=video/ts,dst=:${options.port}}`;
  }
  let processObj = exec(pkill, function (error, stdout, stderr) {
    //用vlc直接启动需要将--sout '#transcode'改为:sout=#transcode,并且不能分割成两个参数传。
    let childProcess = execFile(
      'vlc',
      ['-vvv', vlcPathMess, soutText, '-I', 'dummy'],
      {
        maxBuffer: 1024 * 1024 * 2,
      },
      function (error, stdout, stderr) {
        console.log(`vlc rtsp server startup callback,error=${stderr}`);
      }
    );
    childProcess.on('exit', function () {
      console.log(`摄像头推流进程退出,进程ID:${childProcess.pid}`);
      if (exitCallback) {
        exitCallback(childProcess.pid)
      }
      
    });
    console.log(`启动摄像头RTSP推流,进程ID:${childProcess.pid}`);
    videoMonitorProcess = childProcess;
    setTimeoutCloseStream(options);
    setTimeout(function () {
      if (callback) {
        if (videoMonitorProcess && !videoMonitorProcess.killed) {
          workState.state = true;
          workState.message = '启动摄像头RTSP推流正常';
          workState.streamUrl = getStreamUrl(options);
          callback(workState);
        } else {
          workState.state = false;
          workState.message = '启动摄像头RTSP推流异常: ';
          workState.streamUrl = '';
          callback(workState);
        }
      }
    }, 4000);
  });
  console.log(`pkill vlc process id=${processObj.pid}`);
}

/**
 * 关闭视频流
 * 
 */
function closeCameraRTSP() {
  if (videoMonitorProcess) {
    let videoProcessObj = videoMonitorProcess;
    videoMonitorProcess = null;
    videoProcessObj.kill();
  }
}

/**
 * 获取视频流进程
 * @returns 
 */
function VideoMonitorProcess() {
  return videoMonitorProcess;
}

function getStreamUrl(options) {
  let streamUrl = `rtsp://${options.localIp}:${options.port}/`;
  if (options.streamType == 2) {
    streamUrl = `http://${options.localIp}:${options.port}/`;
  }
  return streamUrl;
}

function setTimeoutCloseStream(options) {
  if (vlcCloseTime) {
    clearTimeout(vlcCloseTime);
    vlcCloseTime = null;
  }
  if (options.autoCloseTime && options.autoCloseTime > 0) {
    vlcCloseTime = setTimeout(() => {
      closeCameraRTSP();
    }, options.autoCloseTime * 1000);
  }
}
module.exports = {
  openVlcStream,
  closeCameraRTSP,
  VideoMonitorProcess,
};
