#!/bin/bash
# Mac 屏幕录制推流到 Cloudflare Stream
# 使用方法: ./scripts/stream-screen.sh

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
CONFIG_FILE="$SCRIPT_DIR/../config/stream.env"

# 检查配置文件
if [ ! -f "$CONFIG_FILE" ]; then
    echo "错误: 配置文件不存在"
    echo "请复制 config/stream.env.example 为 config/stream.env 并填写配置"
    exit 1
fi

# 加载配置
source "$CONFIG_FILE"

# 屏幕录制参数
SCREEN_DEVICE="${SCREEN_DEVICE:-1}"  # 屏幕设备号（通常是1）
AUDIO_DEVICE="${AUDIO_DEVICE:-0}"
FPS="${FPS:-30}"
BITRATE="${BITRATE:-3000k}"

# 检查必要配置
if [ -z "$RTMP_URL" ] || [ -z "$STREAM_KEY" ]; then
    echo "错误: 请在 config/stream.env 中配置 RTMP_URL 和 STREAM_KEY"
    exit 1
fi

# 检查 ffmpeg
if ! command -v ffmpeg &> /dev/null; then
    echo "错误: ffmpeg 未安装"
    echo "请运行: brew install ffmpeg"
    exit 1
fi

echo "======================================"
echo "    Cloudflare Stream 屏幕推流"
echo "======================================"
echo ""
echo "配置信息:"
echo "  屏幕设备: $SCREEN_DEVICE"
echo "  音频设备: $AUDIO_DEVICE"
echo "  帧率:     $FPS fps"
echo "  码率:     $BITRATE"
echo ""
echo "按 Ctrl+C 停止推流"
echo "======================================"
echo ""

# 开始屏幕推流
ffmpeg -f avfoundation \
    -framerate "$FPS" \
    -capture_cursor 1 \
    -i "$SCREEN_DEVICE:$AUDIO_DEVICE" \
    -c:v libx264 \
    -preset veryfast \
    -maxrate "$BITRATE" \
    -bufsize 6000k \
    -pix_fmt yuv420p \
    -g 60 \
    -c:a aac \
    -b:a 128k \
    -ar 44100 \
    -f flv \
    "${RTMP_URL}/${STREAM_KEY}"
