import subprocess
import os
import sys
import http.server
import socketserver
import threading
import time

# ================= 配置区 =================
RTSP_URL = "rtsp://wowzaec2demo.streamlock.net/vod/mp4:BigBuckBunny_115k.mov"
OUTPUT_DIR = "hls_output"    
M3U8_FILENAME = "stream.m3u8" 
PORT = 8000                  
# ==========================================

def get_ffmpeg_path():
    """
    获取 FFmpeg 的绝对路径。
    兼容本地直接运行和 PyInstaller 打包后的运行环境。
    """
    if getattr(sys, 'frozen', False):
        # 如果是打包后的可执行文件运行，去临时目录找
        base_path = sys._MEIPASS
    else:
        # 如果是原生 Python 脚本运行，去当前脚本所在目录找
        base_path = os.path.dirname(os.path.abspath(__file__))
    
    # 区分操作系统后缀
    ffmpeg_exe_name = 'ffmpeg.exe' if os.name == 'nt' else 'ffmpeg'
    
    # 核心改动：拼接 'ffmpeg' 文件夹路径
    ffmpeg_path = os.path.join(base_path, 'ffmpeg', ffmpeg_exe_name)
    
    return ffmpeg_path

def start_ffmpeg():
    """使用 FFmpeg 将 RTSP 转为 HLS"""
    if not os.path.exists(OUTPUT_DIR):
        os.makedirs(OUTPUT_DIR)
    
    output_path = os.path.join(OUTPUT_DIR, M3U8_FILENAME)
    ffmpeg_bin = get_ffmpeg_path()
    
    if not os.path.exists(ffmpeg_bin):
        print(f"[错误] 找不到 FFmpeg 组件，请检查路径: {ffmpeg_bin}")
        sys.exit(1)

    command = [
        ffmpeg_bin,
        '-rtsp_transport', 'tcp',
        '-i', RTSP_URL,
        '-c:v', 'copy',
        '-c:a', 'copy',
        '-f', 'hls',
        '-hls_time', '2',
        '-hls_list_size', '5',
        '-hls_flags', 'delete_segments',
        output_path
    ]

    print(f"[*] 正在启动 FFmpeg: {ffmpeg_bin}")
    process = subprocess.Popen(command, stdout=subprocess.DEVNULL, stderr=subprocess.STDOUT)
    return process

def start_http_server():
    """启动本地 HTTP 服务器"""
    os.chdir(OUTPUT_DIR)
    Handler = http.server.SimpleHTTPRequestHandler
    
    # 使用 SO_REUSEADDR 允许重启时快速重用端口
    socketserver.TCPServer.allow_reuse_address = True
    
    with socketserver.TCPServer(("", PORT), Handler) as httpd:
        print(f"[*] HTTP 服务器已启动: http://localhost:{PORT}")
        print(f"[*] 请使用播放器打开: http://localhost:{PORT}/{M3U8_FILENAME}")
        httpd.serve_forever()

if __name__ == '__main__':
    # 1. 启动 HTTP 服务
    server_thread = threading.Thread(target=start_http_server, daemon=True)
    server_thread.start()
    time.sleep(1)

    # 2. 启动转码进程
    ffmpeg_process = start_ffmpeg()

    try:
        while True:
            time.sleep(1)
            if ffmpeg_process.poll() is not None:
                print("[!] FFmpeg 进程意外退出。")
                break
    except KeyboardInterrupt:
        print("\n[*] 接收到停止信号，正在关闭服务...")
        ffmpeg_process.terminate()
        print("[*] 服务已停止。")