This commit is contained in:
eric
2025-09-16 17:02:16 +08:00
parent 2c4b0547f3
commit 696e00a144
2 changed files with 132 additions and 109 deletions

View File

@@ -121,7 +121,7 @@ class DouyinToYouTubeStreamer:
self.proc.wait()
if not self.stop_flag.is_set():
logging.warning(f"[{self.room_name}] FFmpeg 退出 (返回码: {self.proc.returncode})5秒后重启...")
logging.warning(f"[{self.room_name}] FFmpeg 退出 (返回码: {self.proc.returncode})1秒后重启...")
self.pushing = False
except Exception as e:
logging.error(f"[{self.room_name}] FFmpeg 启动异常: {e}")
@@ -129,12 +129,12 @@ class DouyinToYouTubeStreamer:
if self.proc and self.proc.poll() is None:
self.proc.terminate()
try:
self.proc.wait(timeout=5)
self.proc.wait(timeout=1)
except subprocess.TimeoutExpired:
self.proc.kill()
self.proc = None
if not self.stop_flag.is_set():
time.sleep(5)
time.sleep(1)
def _monitor_thread(self):
term_width, _ = shutil.get_terminal_size()
@@ -157,7 +157,7 @@ class DouyinToYouTubeStreamer:
if self.proc and self.proc.poll() is None:
self.proc.terminate()
try:
self.proc.wait(timeout=5)
self.proc.wait(timeout=1)
except subprocess.TimeoutExpired:
self.proc.kill()
@@ -188,8 +188,8 @@ def start_douyin_to_youtube(record_url, youtube_key, room_name=None, proxy_addr=
# ----------------- Main Program -----------------
if __name__ == "__main__":
DOUYIN_URL = "https://live.douyin.com/642534242822"
YOUTUBE_KEY = "ue78-1c3e-mr9g-14mz-9r4z"
DOUYIN_URL = "https://live.douyin.com/112633436109"
YOUTUBE_KEY = "qxvb-r47b-r5ju-6ud3-6k7z"
hls_instance = start_douyin_to_youtube(DOUYIN_URL, YOUTUBE_KEY)
if not hls_instance:

217
live.py
View File

@@ -6,7 +6,6 @@ import uuid
import time
import signal
import sys
import shutil
import logging
import spider
import stream
@@ -18,10 +17,12 @@ logging.basicConfig(
datefmt="%H:%M:%S"
)
# ----------------- Low-Latency Douyin to YouTube Streamer -----------------
# ----------------- Douyin to YouTube Streamer -----------------
class DouyinToYouTubeStreamer:
def __init__(self, bitrate=5000, audio_bitrate=128, resolution='720x1280', fps=30, gop=60):
self.proc = None
def __init__(self, bitrate=5000, audio_bitrate=128, resolution='720x1280',
fps=30, gop=60, max_minutes=8):
self.push_proc = None
self.record_proc = None
self.stop_flag = threading.Event()
self.bitrate = bitrate
self.audio_bitrate = audio_bitrate
@@ -30,152 +31,174 @@ class DouyinToYouTubeStreamer:
self.gop = gop
self.start_time = None
self.room_name = None
self.semaphore = threading.Semaphore(1)
self.pushing = False # 是否正在推流
self.pushing = False
self.out_file = None
self.max_minutes = max_minutes
os.makedirs("records", exist_ok=True)
def start_stream(self, real_url, youtube_key, room_name=None):
self.room_name = room_name or f"抖音_{str(uuid.uuid4())[:8]}"
logging.info(f"[{self.room_name}] 启动低延迟推流,目标 YouTube Key: {youtube_key}")
threading.Thread(target=self._run_ffmpeg_loop, args=(real_url, youtube_key), daemon=True).start()
threading.Thread(target=self._run_stream_loop,
args=(real_url, youtube_key), daemon=True).start()
threading.Thread(target=self._monitor_thread, daemon=True).start()
def _build_ffmpeg_cmd(self, real_url, youtube_key):
user_agent = ("Mozilla/5.0 (Linux; Android 11; SAMSUNG SM-G973U) AppleWebKit/537.36 "
"(KHTML, like Gecko) SamsungBrowser/14.2 Chrome/87.0.4280.141 Mobile Safari/537.36")
# ----------------- 构建命令 -----------------
def _build_push_cmd(self, real_url, youtube_key):
user_agent = ("Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
"AppleWebKit/537.36 (KHTML, like Gecko) Chrome/140.0.0.0 Safari/537.36")
headers = "Referer: https://www.douyin.com/\r\nOrigin: https://www.douyin.com\r\n"
cmd = [
'ffmpeg', '-y', '-v', 'error', '-hide_banner',
'ffmpeg', '-y',
'-rw_timeout', '10000000',
'-analyzeduration', '1000000',
'-probesize', '5000000',
'-thread_queue_size', '512',
'-user_agent', user_agent,
'-headers', headers,
'-protocol_whitelist', 'file,pipe,http,https,tcp,tls,udp,rtp,crypto',
'-fflags', '+discardcorrupt+genpts',
'-flags', 'low_delay',
'-http_seekable', '0',
'-avioflags', 'direct',
'-reconnect', '1',
'-reconnect_at_eof', '1',
'-reconnect_streamed', '1',
'-reconnect_delay_max', '5',
'-flush_packets', '1',
'-i', real_url,
'-c:v', 'libx264',
'-preset', 'veryfast',
'-tune', 'zerolatency',
'-crf', '23',
'-pix_fmt', 'yuv420p',
'-profile:v', 'main',
'-level', '3.1',
'-x264-params', f'keyint={self.gop}:scenecut=0:min-keyint={self.gop//2}',
'-g', str(self.gop),
'-r', str(self.fps),
'-s', self.resolution,
'-c:v', 'libx264', '-preset', 'veryfast', '-tune', 'zerolatency',
'-b:v', f'{self.bitrate}k',
'-maxrate', f'{self.bitrate}k',
'-bufsize', f'{self.bitrate * 2}k',
'-c:a', 'aac',
'-b:a', f'{self.audio_bitrate}k',
'-ar', '44100',
'-ac', '2',
'-strict', '-2',
'-avoid_negative_ts', 'make_zero',
'-r', str(self.fps),
'-g', str(self.gop),
'-c:a', 'aac', '-b:a', f'{self.audio_bitrate}k', '-ar', '44100', '-ac', '2',
'-f', 'flv',
f'rtmp://a.rtmp.youtube.com/live2/{youtube_key}'
]
return cmd
def _run_ffmpeg_loop(self, real_url, youtube_key):
def _build_record_cmd(self, real_url):
base_name = f"{self.room_name}_{int(time.time())}.mp4"
self.out_file = os.path.join("records", base_name).replace("\\", "/")
cmd = [
'ffmpeg', '-y',
'-i', real_url,
'-c:v', 'copy',
'-c:a', 'copy',
self.out_file
]
return cmd
# ----------------- 推流循环 -----------------
def _run_stream_loop(self, real_url, youtube_key):
while not self.stop_flag.is_set():
try:
with self.semaphore:
cmd = self._build_ffmpeg_cmd(real_url, youtube_key)
self.proc = subprocess.Popen(
cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE,
bufsize=0, universal_newlines=False
)
self.start_time = time.time()
self.pushing = False
logging.info(f"[{self.room_name}] FFmpeg 启动成功 (PID: {self.proc.pid})")
def read_stderr():
# ---- 启动推流 ----
push_cmd = self._build_push_cmd(real_url, youtube_key)
self.push_proc = subprocess.Popen(
push_cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE
)
# ---- 启动本地录制 ----
record_cmd = self._build_record_cmd(real_url)
self.record_proc = subprocess.Popen(
record_cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE
)
logging.info(f"[{self.room_name}] 本地录制开始: {self.out_file}")
logging.info(f"[{self.room_name}] 推流进程 PID: {self.push_proc.pid}")
# ---- 监控 stderr ----
def monitor_proc(proc, name):
try:
for line in iter(self.proc.stderr.readline, b''):
for line in iter(proc.stderr.readline, b''):
if self.stop_flag.is_set():
break
if line:
decoded = line.decode('utf-8', errors='ignore').strip()
logging.info(f"[{self.room_name} FFmpeg]: {decoded}")
# 判断推流是否成功
if not self.pushing and "frame=" in decoded and "fps=" in decoded:
if name == "push" and not self.pushing and "frame=" in decoded and "fps=" in decoded:
self.pushing = True
logging.info(f"[{self.room_name}] 推流到 YouTube 成功")
logging.debug(f"[{self.room_name} {name}]: {decoded}")
except Exception as e:
logging.error(f"[{self.room_name}] stderr线程异常: {e}")
logging.error(f"[{self.room_name} {name} stderr异常: {e}")
stderr_thread = threading.Thread(target=read_stderr, daemon=True)
stderr_thread.start()
threading.Thread(target=monitor_proc, args=(self.push_proc, "push"), daemon=True).start()
threading.Thread(target=monitor_proc, args=(self.record_proc, "record"), daemon=True).start()
self.proc.wait()
if not self.stop_flag.is_set():
logging.warning(f"[{self.room_name}] FFmpeg 退出 (返回码: {self.proc.returncode})2秒后重启...")
self.pushing = False
except Exception as e:
logging.error(f"[{self.room_name}] FFmpeg 启动异常: {e}")
finally:
if self.proc and self.proc.poll() is None:
self.proc.terminate()
try:
self.proc.wait(timeout=2)
except subprocess.TimeoutExpired:
self.proc.kill()
self.proc = None
if not self.stop_flag.is_set():
time.sleep(2)
def _monitor_thread(self):
term_width, _ = shutil.get_terminal_size()
bar_width = min(50, term_width - 30)
# ---- 循环检查 ----
while not self.stop_flag.is_set():
if self.proc:
uptime = time.time() - self.start_time if self.start_time else 0
uptime_str = f"{int(uptime // 60):02d}:{int(uptime % 60):02d}"
status = "推流中" if self.pushing else "启动中"
bar_len = bar_width if self.pushing else 0
bar = "#" * bar_len + "-" * (bar_width - bar_len)
print(f"\r[{self.room_name}] [{bar}] {status} | 运行时间: {uptime_str} | 码率: {self.bitrate}k", end="")
else:
print(f"\r[{self.room_name}] FFmpeg 未运行", end="")
elapsed = time.time() - self.start_time
if elapsed >= self.max_minutes * 60:
logging.warning(f"[{self.room_name}] 超过 {self.max_minutes} 分钟,自动停止推流和录制")
self.stop()
break
if self.push_proc.poll() is not None or self.record_proc.poll() is not None:
logging.warning(f"[{self.room_name}] FFmpeg 进程退出1秒后重启...")
break
time.sleep(2)
def stop(self):
logging.info(f"[{self.room_name}] 停止推流...")
self.stop_flag.set()
if self.proc and self.proc.poll() is None:
self.proc.terminate()
except Exception as e:
logging.error(f"[{self.room_name}] FFmpeg异常: {e}")
finally:
self._terminate_procs()
self._finalize_recording()
if not self.stop_flag.is_set():
time.sleep(1)
def _terminate_procs(self):
for proc in [self.push_proc, self.record_proc]:
if proc and proc.poll() is None:
proc.terminate()
try:
self.proc.wait(timeout=2)
proc.wait(timeout=1)
except subprocess.TimeoutExpired:
self.proc.kill()
proc.kill()
self.push_proc, self.record_proc = None, None
# ----------------- 监控线程 -----------------
def _monitor_thread(self):
while not self.stop_flag.is_set():
uptime = int(time.time() - self.start_time) if self.start_time else 0
m, s = divmod(uptime, 60)
status = "推流中" if self.pushing else "启动中"
print(f"\r[{self.room_name}] {status} | 运行时间: {m:02d}:{s:02d} | 码率: {self.bitrate}k", end="")
time.sleep(2)
# ----------------- 停止 -----------------
def stop(self):
logging.info(f"[{self.room_name}] 停止推流和录制...")
self.stop_flag.set()
self._terminate_procs()
self._finalize_recording()
def _finalize_recording(self):
if self.out_file and os.path.exists(self.out_file) and self.start_time:
elapsed = int(time.time() - self.start_time)
suffix = f"_{elapsed // 60}min" if elapsed >= 60 else f"_{elapsed}s"
new_name = self.out_file.replace(".mp4", f"{suffix}.mp4")
os.rename(self.out_file, new_name)
size_mb = os.path.getsize(new_name) / (1024 * 1024)
logging.info(f"[{self.room_name}] 本地录制已结束: {new_name} | 大小: {size_mb:.2f} MB")
# ----------------- Douyin Stream Parsing -----------------
async def get_douyin_real_url(record_url, record_quality="原画", proxy_addr=None, cookies=''):
try:
if 'v.douyin.com' not in record_url and '/user/' not in record_url:
json_data = await spider.get_douyin_stream_data(url=record_url, proxy_addr=proxy_addr, cookies=cookies)
json_data = await spider.get_douyin_stream_data(url=record_url,
proxy_addr=proxy_addr, cookies=cookies)
else:
json_data = await spider.get_douyin_app_stream_data(url=record_url, proxy_addr=proxy_addr, cookies=cookies)
json_data = await spider.get_douyin_app_stream_data(url=record_url,
proxy_addr=proxy_addr, cookies=cookies)
port_info = await stream.get_douyin_stream_url(json_data, record_quality, proxy_addr)
return port_info.get("record_url")
except Exception as e:
logging.error(f"获取抖音真实流失败: {e}")
return None
def start_douyin_to_youtube(record_url, youtube_key, room_name=None, proxy_addr=None, cookies='', bitrate=5000):
def start_douyin_to_youtube(record_url, youtube_key, room_name=None,
proxy_addr=None, cookies='', bitrate=5000):
real_url = asyncio.run(get_douyin_real_url(record_url, proxy_addr, cookies))
if not real_url:
logging.error("获取真实直播流失败")
@@ -188,17 +211,17 @@ def start_douyin_to_youtube(record_url, youtube_key, room_name=None, proxy_addr=
# ----------------- Main Program -----------------
if __name__ == "__main__":
DOUYIN_URL = "https://live.douyin.com/642534242822"
YOUTUBE_KEY = "ue78-1c3e-mr9g-14mz-9r4z"
DOUYIN_URL = "https://live.douyin.com/24113884853"
YOUTUBE_KEY = "qxvb-r47b-r5ju-6ud3-6k7z"
hls_instance = start_douyin_to_youtube(DOUYIN_URL, YOUTUBE_KEY)
if not hls_instance:
streamer_instance = start_douyin_to_youtube(DOUYIN_URL, YOUTUBE_KEY)
if not streamer_instance:
logging.error("推流实例创建失败,程序退出")
sys.exit(1)
def signal_handler(sig, frame):
if hls_instance:
hls_instance.stop()
if streamer_instance:
streamer_instance.stop()
sys.exit(0)
signal.signal(signal.SIGINT, signal_handler)