# coding: utf-8

import subprocess
import threading
import time
import os

VIDEO_PATH = "video"                   #自动推流视频目录
# PUSH_URL = "rtmp://192.168.0.108:1935/live/room"
PUSH_URL = "rtmp://10.100.12.50:1935/live/room"       #推流服务地址
pushThread = {}
isLoop = 1                             #是否循环推流：0：不循环  1：循环

#############################################
#          读取当前目录文件
#############################################
def readVideoFile(path=VIDEO_PATH):
    videoFiles = os.listdir(VIDEO_PATH)
    return videoFiles

#############################################
#          推流方法，被线程调用
#############################################
def pushStream(fi,url):
    print(fi + "----推流开始   ")
    m_command = ["ffmpeg.exe",
                 "-re",
                 "-i", fi,
                 "-vcodec", "copy",
                 "-f",
                 "flv", url]
    print(m_command)
    subprocess.run(m_command)
    print(fi + "----推流结束   ")
    if isLoop == 1:
        time.sleep(0.5)
        pushStream(fi,url)
    else:
        pushThread.pop(fi)


#############################################
#          开始推流启动多个线程去推流(使用VIDEO_PATH目录下的有所文件)
#############################################
def startPush():
    v_files = readVideoFile()
    i = 1
    for fi in v_files:
        pushFile = VIDEO_PATH + "/" + fi
        pushUrl = PUSH_URL + str(i)
        td = threading.Thread(target=pushStream,args=[pushFile,pushUrl])
        td.start()
        i = i + 1
        pushThread[pushFile] = pushUrl
        time.sleep(1)

    while len(pushThread) > 0:
        for key in pushThread:
            print(key + "  的播放地址为：" + pushThread[key])
        time.sleep(5)
        print("\n")
    print("所有推流全部结束")

#############################################
#          开始推流(使用写死的文件地址)
#############################################
def pushStreamFixedFile():
    m_command = ["ffmpeg.exe",
                 "-re",
                 "-i","E:\视频\舞蹈\【かや】Doja Cat - Say So _ KAYA Ver.【踊ってみた】.mp4",
                 # "-i", "【かや】thank u, next _ Ariana Grande【踊ってみた _ KAYA Ver.】.mp4",
                 "-vcodec", "copy",
                 "-f",
                 "flv", "rtmp://10.100.12.50:1935/live/room1"]
    subprocess.run(m_command)

if __name__ == "__main__":
    # startPush()
    pushStreamFixedFile()
