QQ浏览器视频文件夹下m3u8的转码和合并

QQ浏览器视频文件夹下的m3u8文件转码和合并

import os
import re
from Crypto.Cipher import AES
from natsort import natsorted

# 解密函数
def decrypt_ts_file(key, iv, input_file, output_file):
    cipher = AES.new(key, AES.MODE_CBC, iv)
    with open(input_file, 'rb') as f_in:
        ciphertext = f_in.read()
    plaintext = cipher.decrypt(ciphertext)
    with open(output_file, 'wb') as f_out:
        f_out.write(plaintext)

# 解析 M3U8 文件以获取 TS 文件夹路径
def parse_m3u8_file(m3u8_file):
    folder_paths = set()
    with open(m3u8_file, 'r', encoding='utf-8') as file:
        for line in file:
            if line.startswith("file:///"):
                match = re.search(r'/(\.[^/]+)/', line)
                if match:
                    folder_paths.add(match.group(1))
    return list(folder_paths)

# 处理每个 M3U8 文件
def process_m3u8_file(m3u8_file):
    folder_paths = parse_m3u8_file(m3u8_file)

    for folder in folder_paths:
        folder_path = os.path.join('.', folder)
        key_path = os.path.join(folder_path, '0.key')
        
        if not os.path.isdir(folder_path):
            print(f"文件夹 {folder_path} 不存在,跳过")
            continue
        if not os.path.isfile(key_path):
            print(f"密钥文件 {key_path} 不存在,跳过")
            continue

        with open(key_path, 'rb') as key_file:
            key = key_file.read()

        # 获取并排序文件夹中的所有 TS 文件
        ts_files = natsorted([f for f in os.listdir(folder_path) if f.endswith('.ts')])
        
        # 打印排序后的文件列表
        print(f"排序后的 TS 文件列表 ({folder_path}):")
        for ts_file in ts_files:
            print(ts_file)

        # 初始化向量,通常为全零
        iv = bytes([0] * 16)

        # 解密每个 TS 文件
        decrypted_files = []
        for ts_file in ts_files:
            input_file = os.path.join(folder_path, ts_file)
            decrypted_file = f'decrypted_{ts_file}'
            decrypt_ts_file(key, iv, input_file, decrypted_file)
            decrypted_files.append(decrypted_file)

        # 合并解密后的 TS 文件
        output_file_name = os.path.splitext(m3u8_file)[0] + '.ts'
        with open(output_file_name, 'wb') as output_file:
            for decrypted_file in decrypted_files:
                with open(decrypted_file, 'rb') as f:
                    output_file.write(f.read())

        # 清理解密过程中生成的文件
        for decrypted_file in decrypted_files:
            os.remove(decrypted_file)

        print(f"解密完成,生成的文件为:{output_file_name}")

# 列出当前目录中的所有 M3U8 文件
m3u8_files = [f for f in os.listdir('.') if f.endswith('.m3u8')]

# 处理每个 M3U8 文件
for m3u8_file in m3u8_files:
    process_m3u8_file(m3u8_file)

 

posted @ 2024-08-08 13:53  Easy C#  阅读(142)  评论(0)    收藏  举报