#!/bin/bash

set -e

# GStreamer相机预览脚本
usage() {
	echo "Usage: $0 -d /dev/video0 -f YUYV -s 640x480 -r 30"
	echo "  -d            set video device (default: /dev/video0)"
	echo "  -f            set format of frame (YUYV / YUYV2UYVY, default: YUYV)"
	echo "  -s            set video size (default: 1920x1080)"
	echo "  -r            set framerate (default: 30)"
	echo "  -v            show verbose"
	echo "  -h            show help"
    echo ""
    echo "  comments: YUYV2UYVY用于声明的格式是 YUYV , 实际格式为 UYVY 的相机"
}

# 获取参数
VIDEO_DEVICE="/dev/video0"
FORMAT="YUYV"
VERBOSE=""
width=1920
height=1080
framerate=30

while getopts ":hf:p:t:s:r:b:d:v" opt; do
	case $opt in
	h)
		usage
		exit 0
		;;
	d)
		VIDEO_DEVICE="$OPTARG"
		;;
	f)
		FORMAT=$(echo "$OPTARG" | awk '{print tolower($0)}')
		;;
	s)
		size=$OPTARG
		IFS='x' read -r width height <<<"$size"
		;;
	r)
		framerate=$OPTARG
		;;
	v)
		VERBOSE="-vv"
		;;
	\?)
		echo "Invalid option: -$OPTARG" >&2
		usage
		exit 1
		;;
	:)
		echo "Option -$OPTARG requires an argument." >&2
		usage
		exit 1
		;;
	esac
done

# 检查设备是否存在
if [ ! -e "$VIDEO_DEVICE" ]; then
	echo "错误: 视频设备 '$VIDEO_DEVICE' 不存在"
	exit 1
fi

# 检查设备是否可访问
if [ ! -r "$VIDEO_DEVICE" ]; then
	echo "错误: 无法访问视频设备 '$VIDEO_DEVICE'，请检查权限"
	exit 1
fi

echo "=========================================="
echo "GStreamer 相机预览"
echo "=========================================="
echo "视频设备: $VIDEO_DEVICE"
echo "帧格式: $FORMAT"
echo "分辨率:   ${width}x${height}"
echo "帧率:     ${framerate}fps"
echo "=========================================="
echo "按 Ctrl+C 停止预览"
echo ""

rawvideoparse=""
if [ "$FORMAT" = "yuyv2uyvy" ]; then
	rawvideoparse="rawvideoparse format=uyvy width=${width} height=${height} framerate=${framerate}/1 !"
fi

command=$(cat <<EOF
gst-launch-1.0 ${VERBOSE} -e v4l2src device=${VIDEO_DEVICE} ! \
	video/x-raw,width=${width},height=${height},framerate=${framerate}/1 ! \
	${rawvideoparse} \
    nvvidconv ! 'video/x-raw(memory:NVMM),format=NV12' ! \
    nv3dsink
EOF
)

if [ -n "${VERBOSE}" ]; then
	echo $command
fi

echo $command
eval "$command"
