# -*- coding: utf-8 -*-
import os
import time
import socket
import random
import logging

BLUR_RANGE = [2, 8]
INTERVAL_RANGE = [5, 10]
X_OFFSET_RANGE = [0, 100]
Y_OFFSET_RANGE = [0, 100]


if __name__ == '__main__':
    logging.basicConfig(format='[%(asctime)s] %(message)s')
    logging.warning(f'背景视频mp4文件放在C:\\mixinmp4，叠加视频切分成png子文件夹，抠绿幕后把子文件夹放在C:\\mixinpng')
    logging.warning(f'目录中不要放其他文件，支持多个大背景mp4及多组叠加视频png子文件夹')
    logging.warning(f'当前参数：BLUR_RANGE={BLUR_RANGE}, INTERVAL_RANGE={INTERVAL_RANGE}, '
                    f'X_OFFSET_RANGE={X_OFFSET_RANGE}, Y_OFFSET_RANGE={Y_OFFSET_RANGE}')
    logging.warning(f'程序已初始化...\n\n')

    mixin_dir_list = []
    for dir_name in os.listdir('C:\\mixinpng'):
        dir_path = f'C:\\mixinpng\\{dir_name}'
        if os.path.isdir(dir_path):
            png_count = len(os.listdir(dir_path))
            if png_count > 0:
                mixin_dir_list.append(dir_path)
                logging.warning(f'找到叠加png目录：{dir_path}，叠加时长{png_count * 0.04}s')

    logging.warning('打开摄像头画面')
    while True:
        try:
            os.system(f'start C:\\vcam.bat')
            sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            sock.connect(('127.0.0.1', 9029))
            while True:
                # png目录
                mixin_dir = mixin_dir_list[random.randint(0, len(mixin_dir_list) - 1)]
                # 间隔时间、间隔帧数
                interval = random.randint(INTERVAL_RANGE[0], INTERVAL_RANGE[1])
                interval_frame_count = interval * 25
                # 模糊等级
                blur = random.randint(BLUR_RANGE[0], BLUR_RANGE[1])
                if blur % 2 == 0:
                    blur -= 1
                # 偏移量
                x_offset = random.randint(X_OFFSET_RANGE[0], X_OFFSET_RANGE[1])
                y_offset = random.randint(Y_OFFSET_RANGE[0], Y_OFFSET_RANGE[1])

                logging.warning(f'{interval}s后插入叠加：{mixin_dir}，模糊等级{blur}，偏移量({x_offset},{y_offset})')
                for _ in range(interval_frame_count):
                    frame_path = f'0'
                    sock.sendall(frame_path.encode() + b'\0')
                    time.sleep(0.02)

                logging.warning(f'开始插入叠加')
                for png_name in os.listdir(mixin_dir):
                    if not png_name.endswith('.png'):
                        continue

                    path = os.path.join(mixin_dir, png_name)
                    frame_path = f'{path}+{x_offset},{y_offset},{blur}'
                    sock.sendall(frame_path.encode() + b'\0')
                    time.sleep(0.02)
        except Exception as e:
            logging.warning(f'摄像头模块通讯异常，5s后重新建立连接：{e}')
            time.sleep(5)
