#coding:utf-8
import binascii
import time
import socket

from xml.dom.minidom import parse

#http://10.100.11.125:8085/live?port=1985&app=vandyo&stream=013146201116-4

# host = "10.100.11.125"

# host = "10.16.15.85"
host = "localhost"

port = 1078
BUF_SIZE = 2048
isLoop = 0     #是否循环发送视频流）0：不   1：是
SIM = "013146201117"
channel = "03"

def readFile_M(fileName):
    with open(fileName, 'r') as f1:
        f_content = f1.readlines()
        for con in f_content:
            # print(con)
            with open("temp/res.txt", 'a') as f2:
                f2.write(con.replace("\n",""))

#####################################################
# 从帧数据中获取帧类型
#####################################################
def getFrameType(data):
    # 0x67 (0 11 00111) SPS    非常重要       type = 7
    # 0x68 (0 11 01000) PPS     非常重要       type = 8
    # 0x65 (0 11 00101) IDR帧  关键帧  非常重要 type = 5
    # 0x61 (0 11 00001) I帧        重要         type=1    非IDR的I帧 不大常见
    # 0x41 (0 10 00001) P帧      重要         type = 1
    # 0x01 (0 00 00001) B帧     不重要        type = 1
    # 0x06 (0 00 00110) SEI     不重要        type = 6
    frameTypeHex = data[68:70]
    return frameTypeHex

def readFile_M2(fileName):
    with open(fileName, 'r') as f1:
        f_content = f1.read()
        f_content = f_content.split("30316364")
        # print(len(f_content))
        client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        client.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)  # 在客户端开启心跳
        client.connect((host, port))
        for i in range(2,len(f_content)):
            msg = "30316364" + f_content[i]
            msg = msg[:16] + SIM + channel + msg[30:]
            if getFrameType(msg) == "61":
                print("关键帧")
            client.send(binascii.a2b_hex(msg))
            time.sleep(0.01)
            print(msg)
    print("\n\n\n\n   第一波推流完成 --------------------------------")
    client.close()
    time.sleep(5)
    if isLoop == 1:
        readFile_M2("temp/res.txt")

def paseXml():
    domTree = parse("xml/frame.xml")
    rootNode = domTree.documentElement
    frameSizes = []

    # 所有顾客
    customers = rootNode.getElementsByTagName("frame")
    for customer in customers:
        frameSizes.append(int(customer.getAttribute("pkt_size")))

    with open("aac/aaa.aac", 'rb') as f1:
        client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        client.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)  # 在客户端开启心跳
        client.connect((host, port))
        for i in frameSizes:
            msg = f1.read(i)
            msg = msg.hex()
            print(msg)
            client.send(binascii.a2b_hex(msg))
            time.sleep(0.001)
    client.close()



if __name__ == "__main__":
    # readFile_M("temp/tmp1.txt")
    # readFile_M2("temp/res.txt")

    # readFile_M("temp/video.txt")
    # readFile_M2("temp/res.txt")
    paseXml()