This commit is contained in:
eric 2026-06-02 03:19:23 -05:00
commit bedd74d542
392 changed files with 126038 additions and 0 deletions

41
.gitignore vendored Normal file
View File

@ -0,0 +1,41 @@
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
# dependencies
/node_modules
/.pnp
.pnp.*
.yarn/*
!.yarn/patches
!.yarn/plugins
!.yarn/releases
!.yarn/versions
# testing
/coverage
# next.js
/.next/
/out/
# production
/build
# misc
.DS_Store
*.pem
# debug
npm-debug.log*
yarn-debug.log*
yarn-error.log*
.pnpm-debug.log*
# env files (can opt-in for committing if needed)
# .env*
# vercel
.vercel
# typescript
*.tsbuildinfo
next-env.d.ts

View File

13
d2ypp2/.dockerignore Normal file
View File

@ -0,0 +1,13 @@
.git
.github
**/__pycache__
**/*.pyc
.venv
venv
node_modules
web-console/node_modules
web-console/.next
*.log
.process_runner
.cursor
mobile

25
d2ypp2/.gitattributes vendored Normal file
View File

@ -0,0 +1,25 @@
*.sh text eol=lf
*.bash text eol=lf
*.py text eol=lf
*.md text eol=lf
install*.sh text eol=lf
start.sh text eol=lf
dev.sh text eol=lf
web.sh text eol=lf
doctor.sh text eol=lf
probe-live.sh text eol=lf
refresh-live-unit.sh text eol=lf
upgrade*.sh text eol=lf
uninstall.sh text eol=lf
services/neko/browser-launch.sh text eol=lf
requirements*.txt text eol=lf
Dockerfile text eol=lf
*.json text eol=lf
*.mjs text eol=lf
*.ts text eol=lf
*.tsx text eol=lf
*.css text eol=lf
*.yml text eol=lf
*.yaml text eol=lf
"services/neko/tampermonkey-seed/Default/Local Extension Settings/**" -text
"services/neko/tampermonkey-seed/Default/Managed Extension Settings/**" -text

194
d2ypp2/.gitignore vendored Normal file
View File

@ -0,0 +1,194 @@
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class
# C extensions
*.so
# Distribution / packaging
.Python
build/
develop-eggs/
# dist/
downloads/
eggs/
.eggs/
# 仅忽略仓库根目录的 lib(勿用 lib/ 否则会误伤 scripts/linux/lib)
/lib/
/lib64/
parts/
sdist/
var/
wheels/
share/python-wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST
# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec
# Installer logs
pip-log.txt
pip-delete-this-directory.txt
# Unit test / coverage reports
htmlcov/
.tox/
.nox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
*.py,cover
.hypothesis/
.pytest_cache/
cover/
# Translations
*.pot
# Django stuff:
*.log
local_settings.py
db.sqlite3
db.sqlite3-journal
# Flask stuff:
instance/
.webassets-cache
# Scrapy stuff:
.scrapy
# Sphinx documentation
docs/_build/
# PyBuilder
.pybuilder/
target/
# Jupyter Notebook
.ipynb_checkpoints
# IPython
profile_default/
ipython_config.py
# DouyinLiveRecord
backup_config/
logs/
node/
node-v*.zip
# pyenv
# For a library or package, you might want to ignore these files since the code is
# intended to run in multiple environments; otherwise, check them in:
.python-version
# pipenv
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
# However, in case of collaboration, if having platform-specific dependencies or dependencies
# having no cross-platform support, pipenv may install dependencies that don't work, or not
# install all needed dependencies.
#Pipfile.lock
# poetry
# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
# This is especially recommended for binary packages to ensure reproducibility, and is more
# commonly ignored for libraries.
# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
poetry.lock
# pdm
# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
#pdm.lock
# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
# in version control.
# https://pdm.fming.dev/#use-with-ide
.pdm.toml
# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
__pypackages__/
# Celery stuff
celerybeat-schedule
celerybeat.pid
# SageMath parsed files
*.sage.py
# Environments
.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/
# Spyder project settings
.spyderproject
.spyproject
# Rope project settings
.ropeproject
# mkdocs documentation
/site
# mypy
.mypy_cache/
.dmypy.json
dmypy.json
# Pyre type checker
.pyre/
# pytype static type analyzer
.pytype/
# Cython debug symbols
cython_debug/
# PyCharm
# JetBrains specific template is maintained in a separate JetBrains.gitignore that can
# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
# and can be added to the global gitignore or merged into this file. For a more nuclear
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
#.idea/
backup_config/
# 根目录 npm(concurrently 等)
node_modules/
# Next 开发缓存(静态导出目录 web-console/out 可纳入版本库以便无 Node 环境直接部署)
web-console/.next/
# scrcpy-server:由服务启动或 Docker 构建从 Genymobile Release 自动拉取(可纳入制品库而不提交)
vendor/scrcpy-server.jar
# Paramiko 部署本地日志(可能含敏感命令回显)
.deploy_logs/
# 无 PM2 时的本地进程状态
.process_runner/
# 本地排障/运行时生成物
tmp/
services/neko/docker-compose.generated.yml
# 本机端口/主机覆盖(从 config/runtime.env.example 复制)
config/runtime.env
config/system-stack.env
config/hardware.env
config/hardware-profile.json
config/hub_state.sqlite

31
d2ypp2/Dockerfile Normal file
View File

@ -0,0 +1,31 @@
# 生产镜像:ffmpeg + 多阶段构建 Next 静态页 + Python API(默认端口 8101,减少与同机 SRS/代理 冲突)
# docker compose up --build
FROM node:20-bookworm-slim AS console
WORKDIR /src/web-console
COPY web-console/package.json web-console/package-lock.json ./
RUN npm ci
COPY web-console/ ./
RUN npm run build
FROM python:3.12-slim-bookworm
WORKDIR /app
ENV PYTHONDONTWRITEBYTECODE=1 \
PIP_NO_CACHE_DIR=1 \
PORT=8101
RUN apt-get update \
&& apt-get install -y --no-install-recommends ffmpeg ca-certificates \
&& rm -rf /var/lib/apt/lists/* \
&& ffmpeg -version
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY . .
COPY --from=console /src/web-console/out ./web-console/out
# 构建期尝试拉取 scrcpy-server;失败不阻断构建(容器启动时 lifespan 会再试)
RUN sh -c "python -m src.scrcpy_vendor || echo '[docker] scrcpy-server: build-time fetch skipped'"
EXPOSE 8101
CMD ["sh", "-c", "exec python -m uvicorn web:app --host 0.0.0.0 --port ${PORT}"]

21
d2ypp2/LICENSE Normal file
View File

@ -0,0 +1,21 @@
MIT License
Copyright (c) 2025 Hmily
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

773
d2ypp2/README.md Normal file
View File

@ -0,0 +1,773 @@
![video_spider](https://socialify.git.ci/ihmily/DouyinLiveRecorder/image?font=Inter&forks=1&language=1&owner=1&pattern=Circuit%20Board&stargazers=1&theme=Light)
## 无人直播系统(Linux 一键部署,ARM / x86)
本项目当前定位不是单纯录播工具,而是面向 Linux 的无人直播一键部署栈。默认入口为 `http://live.local`,通过 Web 控制面板统一查看和操作 YouTube 无人转播、TikTok HDMI 硬件链路、SRS、Neko 浏览器、安卓与系统服务。
### 核心能力
- 抖音直播间 → YouTube Live:支持单频道 / 多频道同时推流,每个任务独立 `youtube.ini`、`URL_config` 与 PM2 进程
- TikTok 直播:支持视频流转发到硬件 HDMI,也可配合 SRS / OBS 接流后再转发
- Neko 浏览器:默认个人管理员模式,不挂 Chrome 企业策略、不禁用 Google Sync;保留管理员会话、开发者工具与 Tampermonkey 持久化;按 `NEKO_INSTANCE_COUNT` 动态生成独立容器,默认保底 2 个,YouTube PRO 频道保存会自动提升容量
- 兼容架构:Linux `x86_64` / `arm64`,使用一键脚本部署,控制面板默认域名 `live.local`
## Linux Unmanned Live Profiles
This fork now includes a modular Linux deployment layout for ARM and X86 nodes.
### Live Platform(四层架构)
- **配置中心**:`/opt/live/config`(模板见 `live-platform/config/defaults/`,开发时回退到仓库内同路径)
- **一键脚本**:`install.sh` 是远程 bootstrap 入口,负责源码获取、日志、锁、安装分发与验收;`./install-core.sh`(系统 + 基础服务,与业务解耦)、`./install-live.sh`(仅无人直播业务)、`./doctor.sh`(体检)
- **统一 API**:`GET /hub/dashboard`、`GET /hub/config` 等(见 [`docs/ARCHITECTURE.md`](docs/ARCHITECTURE.md))
- **产品级 Web**:根路径 `/` 为无人直播系统控制台;`/console` 为高级全功能页
- `install-hub.sh`: reusable Linux super hub with `live.local`, ShellCrash, WebTTY, Cockpit, File Browser, Homepage and Netdata
- `install-business.sh`: Douyin / YouTube / HDMI business module with ffmpeg, mpv, ADB, Chromium, web-scrcpy and SRS
- `install-all.sh`: installs both layers without tightly coupling them
### One-Line Install
Fresh Debian / Ubuntu / Armbian style hosts use the stream-safe bootstrapper:
```bash
curl -fsSL https://<public-bootstrap-host>/install.sh | bash
```
The checked-in `install.sh` is the production contract for that URL: it writes logs to `/var/log/shd2ypp2`, uses `/run/lock/shd2ypp2-install.lock` to prevent concurrent installs, syncs the project to `/opt/live/d2ypp`, dispatches `scripts/linux/install_stack.sh all`, waits for `/health`, runs `/deploy/check`, and then runs `tools/verify_local_install.py`.
The current GitLab remote at `gitlab.nomadro.com` requires authentication for raw file and clone access from a fresh machine. Publish the same `install.sh` behind an unauthenticated HTTPS endpoint, or pass a credentialed/public source explicitly:
```bash
LIVE_REPO_URL=http://gitlab.nomadro.com/gitlab-instance-0a899031/sh.git \
LIVE_REPO_REF=best \
curl -fsSL https://<public-bootstrap-host>/install.sh | bash -s -- --profile hub
```
Detailed docs:
- [`docs/ARCHITECTURE.md`](docs/ARCHITECTURE.md)
- [`docs/HOMELAB_OPTIMIZATION_PLAN.md`](docs/HOMELAB_OPTIMIZATION_PLAN.md)
- [`docs/install-profiles.md`](docs/install-profiles.md)
- [`docs/super-hub-architecture.md`](docs/super-hub-architecture.md)
### Default LAN Entrypoints
After `install-hub.sh` or `install-all.sh`, the default service map is:
- **`http://live.local`** (port 80, via **Caddy** `live-edge.service` + `live-edge-watch.service`) → same UI/API as the control plane
- `http://live.local:8001` for direct access to FastAPI (no edge proxy)
- `http://live.local/shellcrash` or `:8001/shellcrash` — ShellCrash 编辑器
- `http://live.local/android` or `:8001/android` — 安卓中心
- `http://live.local:3080` — Homepage 聚合(默认不再占用 80)
- `http://live.local:7681` for WebTTY
- `http://live.local:8082` for File Browser with `live / 12345678`
- `http://live.local:19999` for Netdata
### Install Acceptance
After deployment, validate the real delivery path instead of only checking one port:
- `sudo bash doctor.sh`
- `sudo bash probe-live.sh`
- `python3 tools/verify_local_install.py --install-dir /opt/live/d2ypp`
- `python3 tools/verify_live_console.py` with `LIVE_DEPLOY_HOST / LIVE_DEPLOY_USER / LIVE_DEPLOY_PASS` when verifying a remote node
The control plane exposes `GET /deploy/check` for a structured report covering `live.local`, `:80`, `:8001`, LAN IP binding, exported web assets, and `system-stack.env`.
### ShellCrash Web Control
ShellCrash is no longer treated as a jump back to the terminal menu. The control plane now exposes:
- direct service start, stop, and restart
- managed roots for `cfg`, `yaml`, `json`, `list`, and `env` files
- in-browser create, edit, delete, and import-or-replace flows for YAML and related config files
- one-click default profile apply plus a `web面板` shortcut that deploys ShellCrash's local zashboard UI and opens `http://<device-ip>:9999/ui/` for proxy selection
### Android Device Center
The Android panel now combines multiple layers instead of showing only raw `web-scrcpy`:
- ADB device discovery and overview
- screenshot-based preview with tap, double tap, and long press
- package search and app launch / stop / clear actions
- UI node extraction with quick jump actions
- embedded raw `web-scrcpy` for full interactive fallback
## 💡简介
[![Python Version](https://img.shields.io/badge/python-3.11.6-blue.svg)](https://www.python.org/downloads/release/python-3116/)
[![Supported Platforms](https://img.shields.io/badge/platforms-Windows%20%7C%20Linux-blue.svg)](https://github.com/ihmily/DouyinLiveRecorder)
[![Docker Pulls](https://img.shields.io/docker/pulls/ihmily/douyin-live-recorder?label=Docker%20Pulls&color=blue&logo=docker)](https://hub.docker.com/r/ihmily/douyin-live-recorder/tags)
![GitHub issues](https://img.shields.io/github/issues/ihmily/DouyinLiveRecorder.svg)
[![Latest Release](https://img.shields.io/github/v/release/ihmily/DouyinLiveRecorder)](https://github.com/ihmily/DouyinLiveRecorder/releases/latest)
[![Downloads](https://img.shields.io/github/downloads/ihmily/DouyinLiveRecorder/total)](https://github.com/ihmily/DouyinLiveRecorder/releases/latest)
一款**简易**的可循环值守的直播录制工具,基于FFmpeg实现多平台直播源录制,支持自定义配置录制以及直播状态推送。
</div>
## 😺已支持平台
- [x] 抖音
- [x] TikTok
- [x] 快手
- [x] 虎牙
- [x] 斗鱼
- [x] YY
- [x] B站
- [x] 小红书
- [x] bigo
- [x] blued
- [x] SOOP(原AfreecaTV)
- [x] 网易cc
- [x] 千度热播
- [x] PandaTV
- [x] 猫耳FM
- [x] Look直播
- [x] WinkTV
- [x] TTingLive(原Flextv)
- [x] PopkonTV
- [x] TwitCasting
- [x] 百度直播
- [x] 微博直播
- [x] 酷狗直播
- [x] TwitchTV
- [x] LiveMe
- [x] 花椒直播
- [x] 流星直播
- [x] ShowRoom
- [x] Acfun
- [x] 映客直播
- [x] 音播直播
- [x] 知乎直播
- [x] CHZZK
- [x] 嗨秀直播
- [x] vv星球直播
- [x] 17Live
- [x] 浪Live
- [x] 畅聊直播
- [x] 飘飘直播
- [x] 六间房直播
- [x] 乐嗨直播
- [x] 花猫直播
- [x] Shopee
- [x] Youtube
- [x] 淘宝
- [x] 京东
- [x] Faceit
- [x] 咪咕
- [x] 连接直播
- [x] 来秀直播
- [x] Picarto
- [ ] 更多平台正在更新中
</div>
## 🎈项目结构
```
.
└── DouyinLiveRecorder/
├── /config -> (config record)
├── /logs -> (save runing log file)
├── /backup_config -> (backup file)
├── /douyinliverecorder -> (package)
├── initializer.py-> (check and install nodejs)
├── spider.py-> (get live data)
├── stream.py-> (get live stream address)
├── utils.py -> (contains utility functions)
├── logger.py -> (logger handdle)
├── room.py -> (get room info)
├── ab_sign.py-> (generate dy token)
├── /javascript -> (some decrypt code)
├── main.py -> (main file)
├── ffmpeg_install.py -> (ffmpeg install script)
├── demo.py -> (call package test demo)
├── msg_push.py -> (send live status update message)
├── ffmpeg.exe -> (record video)
├── index.html -> (play m3u8 and flv video)
├── requirements.txt -> (library dependencies)
├── docker-compose.yaml -> (Container Orchestration File)
├── Dockerfile -> (Application Build Recipe)
├── StopRecording.vbs -> (stop recording script on Windows)
...
```
</div>
## 🌱使用说明
- 对于只想使用录制软件的小白用户,进入[Releases](https://github.com/ihmily/DouyinLiveRecorder/releases) 中下载最新发布的 zip压缩包即可,里面有打包好的录制软件。(有些电脑可能会报毒,直接忽略即可,如果下载时被浏览器屏蔽,请更换浏览器下载)
- 压缩包解压后,在 `config` 文件夹内的 `URL_config.ini` 中添加录制直播间地址,一行一个直播间地址。如果要自定义配置录制,可以修改`config.ini` 文件,推荐将录制格式修改为`ts`。
- 以上步骤都做好后,就可以运行`DouyinLiveRecorder.exe` 程序进行录制了。录制的视频文件保存在同目录下的 `downloads` 文件夹内。
- 另外,如果需要录制TikTok、AfreecaTV等海外平台,请在配置文件中设置开启代理并添加proxy_addr链接 如:`127.0.0.1:7890` (这只是示例地址,具体根据实际填写)。
- 假如`URL_config.ini`文件中添加的直播间地址,有个别直播间暂时不想录制又不想移除链接,可以在对应直播间的链接开头加上`#`,那么将停止该直播间的监测以及录制。
- 软件默认录制清晰度为 `原画` ,如果要单独设置某个直播间的录制画质,可以在添加直播间地址时前面加上画质即可,如`超清,https://live.douyin.com/745964462470` 记得中间要有`,` 分隔。
- 如果要长时间挂着软件循环监测直播,最好循环时间设置长一点(咱也不差没录制到的那几分钟),避免因请求频繁导致被官方封禁IP 。
- 要停止直播录制,Windows平台可执行StopRecording.vbs脚本文件,或者在录制界面使用 `Ctrl+C ` 组合键中断录制,若要停止其中某个直播间的录制,可在`URL_config.ini`文件中的地址前加#,会自动停止对应直播间的录制并正常保存已录制的视频。
- 最后,欢迎右上角给本项目一个star,同时也非常乐意大家提交pr。
&emsp;
直播间链接示例:
```
抖音:
https://live.douyin.com/745964462470
https://v.douyin.com/iQFeBnt/
https://live.douyin.com/yall1102 (链接+抖音号)
https://v.douyin.com/CeiU5cbX (主播主页地址)
TikTok:
https://www.tiktok.com/@pearlgaga88/live
快手:
https://live.kuaishou.com/u/yall1102
虎牙:
https://www.huya.com/52333
斗鱼:
https://www.douyu.com/3637778?dyshid=
https://www.douyu.com/topic/wzDBLS6?rid=4921614&dyshid=
YY:
https://www.yy.com/22490906/22490906
B站:
https://live.bilibili.com/320
小红书(直播间分享地址):
http://xhslink.com/xpJpfM
bigo直播:
https://www.bigo.tv/cn/716418802
buled直播:
https://app.blued.cn/live?id=Mp6G2R
SOOP:
https://play.sooplive.co.kr/sw7love
网易cc:
https://cc.163.com/583946984
千度热播:
https://qiandurebo.com/web/video.php?roomnumber=33333
PandaTV:
https://www.pandalive.co.kr/live/play/bara0109
猫耳FM:
https://fm.missevan.com/live/868895007
Look直播:
https://look.163.com/live?id=65108820&position=3
WinkTV:
https://www.winktv.co.kr/live/play/anjer1004
FlexTV(TTinglive)::
https://www.flextv.co.kr/channels/593127/live
PopkonTV:
https://www.popkontv.com/live/view?castId=wjfal007&partnerCode=P-00117
https://www.popkontv.com/channel/notices?mcid=wjfal007&mcPartnerCode=P-00117
TwitCasting:
https://twitcasting.tv/c:uonq
百度直播:
https://live.baidu.com/m/media/pclive/pchome/live.html?room_id=9175031377&tab_category
微博直播:
https://weibo.com/l/wblive/p/show/1022:2321325026370190442592
酷狗直播:
https://fanxing2.kugou.com/50428671?refer=2177&sourceFrom=
TwitchTV:
https://www.twitch.tv/gamerbee
LiveMe:
https://www.liveme.com/zh/v/17141543493018047815/index.html
花椒直播:
https://www.huajiao.com/l/345096174
流星直播:
https://www.7u66.com/100960
ShowRoom:
https://www.showroom-live.com/room/profile?room_id=480206 (主播主页地址)
Acfun:
https://live.acfun.cn/live/179922
映客直播:
https://www.inke.cn/liveroom/index.html?uid=22954469&id=1720860391070904
音播直播:
https://live.ybw1666.com/800002949
知乎直播:
https://www.zhihu.com/people/ac3a467005c5d20381a82230101308e9 (主播主页地址)
CHZZK:
https://chzzk.naver.com/live/458f6ec20b034f49e0fc6d03921646d2
嗨秀直播:
https://www.haixiutv.com/6095106
VV星球直播:
https://h5webcdn-pro.vvxqiu.com//activity/videoShare/videoShare.html?h5Server=https://h5p.vvxqiu.com&roomId=LP115924473&platformId=vvstar
17Live:
https://17.live/en/live/6302408
浪Live:
https://www.lang.live/en-US/room/3349463
畅聊直播:
https://live.tlclw.com/106188
飘飘直播:
https://m.pp.weimipopo.com/live/preview.html?uid=91648673&anchorUid=91625862&app=plpl
六间房直播:
https://v.6.cn/634435
乐嗨直播:
https://www.lehaitv.com/8059096
花猫直播:
https://h.catshow168.com/live/preview.html?uid=19066357&anchorUid=18895331
Shopee:
https://sg.shp.ee/GmpXeuf?uid=1006401066&session=802458
Youtube:
https://www.youtube.com/watch?v=cS6zS5hi1w0
淘宝(需cookie):
https://tbzb.taobao.com/live?liveId=532359023188
https://m.tb.cn/h.TWp0HTd
京东:
https://3.cn/28MLBy-E
Faceit:
https://www.faceit.com/zh/players/Compl1/stream
连接直播:
https://show.lailianjie.com/10000258
咪咕直播:
https://www.miguvideo.com/p/live/120000541321
来秀直播:
https://www.imkktv.com/h5/share/video.html?uid=1845195&roomId=1710496
Picarto:
https://www.picarto.tv/cuteavalanche
```
&emsp;
## 🎃源码运行
使用源码运行,可参考下面的步骤。
1.首先拉取或手动下载本仓库项目代码
```bash
git clone https://github.com/ihmily/DouyinLiveRecorder.git
```
2.进入项目文件夹,安装依赖
```bash
cd DouyinLiveRecorder
```
> [!TIP]
> - 不论你是否已安装 **Python>=3.10** 环境, 都推荐使用 [**uv**](https://github.com/astral-sh/uv) 运行, 因为它可以自动管理虚拟环境和方便地管理 **Python** 版本, **不过这完全是可选的**<br />
> 使用以下命令安装
> ```bash
> # 在 macOS 和 Linux 上安装 uv
> curl -LsSf https://astral.sh/uv/install.sh | sh
> ```
> ```powershell
> # 在 Windows 上安装 uv
> powershell -ExecutionPolicy ByPass -c "irm https://astral.sh/uv/install.ps1 | iex"
> ```
> - 如果安装依赖速度太慢, 你可以考虑使用国内 pip 镜像源:<br />
> 在 `pip` 命令使用 `-i` 参数指定, 如 `pip3 install -r requirements.txt -i https://pypi.tuna.tsinghua.edu.cn/simple`<br />
> 或者在 `uv` 命令 `--index` 选项指定, 如 `uv sync --index https://pypi.tuna.tsinghua.edu.cn/simple`
<details>
<summary>如果已安装 <b>Python>=3.10</b> 环境</summary>
- :white_check_mark: 在虚拟环境中安装 (推荐)
1. 创建虚拟环境
- 使用系统已安装的 Python, 不使用 uv
```bash
python -m venv .venv
```
- 使用 uv, 默认使用系统 Python, 你可以添加 `--python` 选项指定 Python 版本而不使用系统 Python [uv官方文档](https://docs.astral.sh/uv/concepts/python-versions/)
```bash
uv venv
```
2. 在终端激活虚拟环境 (在未安装 uv 或你想要手动激活虚拟环境时执行, 若已安装 uv, 可以跳过这一步, uv 会自动激活并使用虚拟环境)
**Bash** 中
```bash
source .venv/Scripts/activate
```
**Powershell** 中
```powershell
.venv\Scripts\activate.ps1
```
**Windows CMD** 中
```bat
.venv\Scripts\activate.bat
```
3. 安装依赖
```bash
# 使用 pip (若安装太慢或失败, 可使用 `-i` 指定镜像源)
pip3 install -U pip && pip3 install -r requirements.txt
# 或者使用 uv (可使用 `--index` 指定镜像源)
uv sync
# 或者
uv pip sync requirements.txt
```
- :x: 在系统 Python 环境中安装 (不推荐)
```bash
pip3 install -U pip && pip3 install -r requirements.txt
```
</details>
<details>
<summary>如果未安装 <b>Python>=3.10</b> 环境</summary>
你可以使用 [**uv**](https://github.com/astral-sh/uv) 安装依赖
```bash
# uv 将使用 3.10 及以上的最新 python 发行版自动创建并使用虚拟环境, 可使用 --python 选项指定 python 版本, 参见 https://docs.astral.sh/uv/reference/cli/#uv-sync--python 和 https://docs.astral.sh/uv/reference/cli/#uv-pip-sync--python
uv sync
# 或
uv pip sync requirements.txt
```
</details>
3.安装[FFmpeg](https://ffmpeg.org/download.html#build-linux),如果是Windows系统,这一步可跳过。对于Linux系统,执行以下命令安装
CentOS执行
```bash
yum install epel-release
yum install ffmpeg
```
Ubuntu则执行
```bash
apt update
apt install ffmpeg
```
macOS 执行
**如果已经安装 Homebrew 请跳过这一步**
```bash
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
```
```bash
brew install ffmpeg
```
4.运行程序
```python
python main.py
```
或
```bash
uv run main.py
```
其中Linux系统请使用`python3 main.py` 运行。
&emsp;
## 🐋容器运行
在运行命令之前,请确保您的机器上安装了 [Docker](https://docs.docker.com/get-docker/) 和 [Docker Compose](https://docs.docker.com/compose/install/)
1.快速启动
最简单方法是运行项目中的 [docker-compose.yaml](https://github.com/ihmily/DouyinLiveRecorder/blob/main/docker-compose.yaml) 文件,只需简单执行以下命令:
```bash
docker-compose up
```
可选 `-d` 在后台运行。
2.构建镜像(可选)
如果你只想简单的运行程序,则不需要做这一步。Docker镜像仓库中代码版本可能不是最新的,如果要运行本仓库主分支最新代码,可以本地自定义构建,通过修改 [docker-compose.yaml](https://github.com/ihmily/DouyinLiveRecorder/blob/main/docker-compose.yaml) 文件,如将镜像名修改为 `douyin-live-recorder:latest`,并取消 `# build: .` 注释,然后再执行
```bash
docker build -t douyin-live-recorder:latest .
docker-compose up
```
或者直接使用下面命令进行构建并启动
```bash
docker-compose -f docker-compose.yaml up
```
3.停止容器实例
```bash
docker-compose stop
```
4.注意事项
①在docker容器内运行本程序之前,请先在配置文件中添加要录制的直播间地址。
②在容器内时,如果手动中断容器运行停止录制,会导致正在录制的视频文件损坏!
**无论哪种运行方式,为避免手动中断或者异常中断导致录制的视频文件损坏的情况,推荐使用 `ts` 格式保存**。
&emsp;
## 🤖相关项目
- StreamCap: https://github.com/ihmily/StreamCap
- streamget: https://github.com/ihmily/streamget
&emsp;
## ❤️贡献者
&ensp;&ensp; [![Hmily](https://github.com/ihmily.png?size=50)](https://github.com/ihmily)
[![iridescentGray](https://github.com/iridescentGray.png?size=50)](https://github.com/iridescentGray)
[![annidy](https://github.com/annidy.png?size=50)](https://github.com/annidy)
[![wwkk2580](https://github.com/wwkk2580.png?size=50)](https://github.com/wwkk2580)
[![missuo](https://github.com/missuo.png?size=50)](https://github.com/missuo)
<a href="https://github.com/xueli12" target="_blank"><img src="https://github.com/xueli12.png?size=50" alt="xueli12" style="width:53px; height:51px;" /></a>
<a href="https://github.com/kaine1973" target="_blank"><img src="https://github.com/kaine1973.png?size=50" alt="kaine1973" style="width:53px; height:51px;" /></a>
<a href="https://github.com/yinruiqing" target="_blank"><img src="https://github.com/yinruiqing.png?size=50" alt="yinruiqing" style="width:53px; height:51px;" /></a>
<a href="https://github.com/Max-Tortoise" target="_blank"><img src="https://github.com/Max-Tortoise.png?size=50" alt="Max-Tortoise" style="width:53px; height:51px;" /></a>
[![justdoiting](https://github.com/justdoiting.png?size=50)](https://github.com/justdoiting)
[![dhbxs](https://github.com/dhbxs.png?size=50)](https://github.com/dhbxs)
[![wujiyu115](https://github.com/wujiyu115.png?size=50)](https://github.com/wujiyu115)
[![zhanghao333](https://github.com/zhanghao333.png?size=50)](https://github.com/zhanghao333)
<a href="https://github.com/gyc0123" target="_blank"><img src="https://github.com/gyc0123.png?size=50" alt="gyc0123" style="width:53px; height:51px;" /></a>
&ensp;&ensp; [![HoratioShaw](https://github.com/HoratioShaw.png?size=50)](https://github.com/HoratioShaw)
[![nov30th](https://github.com/nov30th.png?size=50)](https://github.com/nov30th)
[![727155455](https://github.com/727155455.png?size=50)](https://github.com/727155455)
[![nixingshiguang](https://github.com/nixingshiguang.png?size=50)](https://github.com/nixingshiguang)
[![1411430556](https://github.com/1411430556.png?size=50)](https://github.com/1411430556)
[![Ovear](https://github.com/Ovear.png?size=50)](https://github.com/Ovear)
&emsp;
## ⏳提交日志
- 20251024
- 修复抖音风控无法获取数据问题
- 新增soop.com录制支持
- 修复bigo录制
- 20250127
- 新增淘宝、京东、faceit直播录制
- 修复小红书直播流录制以及转码问题
- 修复畅聊、VV星球、flexTV直播录制
- 修复批量微信直播推送
- 新增email发送ssl和port配置
- 新增强制转h264配置
- 更新ffmpeg版本
- 重构包为异步函数!
- 20241130
- 新增shopee、youtube直播录制
- 新增支持自定义m3u8、flv地址录制
- 新增自定义执行脚本,支持python、bat、bash等
- 修复YY直播、花椒直播和小红书直播录制
- 修复b站标题获取错误
- 修复log日志错误
- 20241030
- 新增嗨秀直播、vv星球直播、17Live、浪Live、SOOP、畅聊直播(原时光直播)、飘飘直播、六间房直播、乐嗨直播、花猫直播等10个平台直播录制
- 修复小红书直播录制,支持小红书作者主页地址录制直播
- 新增支持ntfy消息推送,以及新增支持批量推送多个地址(逗号分隔多个推送地址)
- 修复Liveme直播录制、twitch直播录制
- 新增Windows平台一键停止录制VB脚本程序
- 20241005
- 新增邮箱和Bark推送
- 新增直播注释停止录制
- 优化分段录制
- 重构部分代码
- 20240928
- 新增知乎直播、CHZZK直播录制
- 修复音播直播录制
- 20240903
- 新增抖音双屏录制、音播直播录制
- 修复PandaTV、bigo直播录制
- 20240713
- 新增映客直播录制
- 20240705
- 新增时光直播录制
- 20240701
- 修复虎牙直播录制2分钟断流问题
- 新增自定义直播推送内容
- 20240621
- 新增Acfun、ShowRoom直播录制
- 修复微博录制、新增直播源线路
- 修复斗鱼直播60帧录制
- 修复酷狗直播录制
- 修复TikTok部分无法解析直播源
- 修复抖音无法录制连麦直播
- 20240510
- 修复部分虎牙直播间录制错误
- 20240508
- 修复花椒直播录制
- 更改文件路径解析方式 [@kaine1973](https://github.com/kaine1973)
- 20240506
- 修复抖音录制画质解析bug
- 修复虎牙录制 60帧最高画质问题
- 新增流星直播录制
- 20240427
- 新增LiveMe、花椒直播录制
- 20240425
- 新增TwitchTV直播录制
- 20240424
- 新增酷狗直播录制、优化PopkonTV直播录制
- 20240423
- 新增百度直播录制、微博直播录制
- 修复斗鱼录制直播回放的问题
- 新增直播源地址显示以及输出到日志文件设置
- 20240311
- 修复海外平台录制bug,增加画质选择,增强录制稳定性
- 修复虎牙录制bug (虎牙`一起看`频道 有特殊限制,有时无法录制)
- 20240309
- 修复虎牙直播、小红书直播和B站直播录制
- 新增5个直播平台录制,包括winktv、flextv、look、popkontv、twitcasting
- 新增部分海外平台账号密码配置,实现自动登录并更新配置文件中的cookie
- 新增自定义配置需要使用代理录制的平台
- 新增只推送开播消息不进行录制设置
- 修复了一些bug
- 20240209
- 优化AfreecaTV录制,新增账号密码登录获取cookie以及持久保存
- 修复了小红书直播因官方更新直播域名,导致无法录制直播的问题
- 修复了更新URL配置文件的bug
- 最后,祝大家新年快乐!
<details><summary>点击展开更多提交日志</summary>
- 20240129
- 新增猫耳FM直播录制
- 20240127
- 新增千度热播直播录制、新增pandaTV(韩国)直播录制
- 新增telegram直播状态消息推送,修复了某些bug
- 新增自定义设置不同直播间的录制画质(即每个直播间录制画质可不同)
- 修改录制视频保存路径为 `downloads` 文件夹,并且分平台进行保存。
- 20240114
- 新增网易cc直播录制,优化ffmpeg参数,修改AfreecaTV输入直播地址格式
- 修改日志记录器 @[iridescentGray](https://github.com/iridescentGray)
- 20240102
- 修复Linux上运行,新增docker配置文件
- 20231210
- 修复录制分段bug,修复bigo录制检测bug
- 新增自定义修改录制主播名
- 新增AfreecaTV直播录制,修复某些可能会发生的bug
- 20231207
- 新增blued直播录制,修复YY直播录制,新增直播结束消息推送
- 20231206
- 新增bigo直播录制
- 20231203
- 新增小红书直播录制(全网首发),目前小红书官方没有切换清晰度功能,因此直播录制也只有默认画质
- 小红书录制暂时无法循环监测,每次主播开启直播,都要重新获取一次链接
- 获取链接的方式为 将直播间转发到微信,在微信中打开后,复制页面的链接。
- 20231030
- 本次更新只是进行修复,没时间新增功能。
- 欢迎各位大佬提pr 帮忙更新维护
- 20230930
- 新增抖音从接口获取直播流,增强稳定性
- 修改快手获取直播流的方式,改用从官方接口获取
- 祝大家中秋节快乐!
- 20230919
- 修复了快手版本更新后录制出错的问题,增加了其自动获取cookie(~~稳定性未知~~)
- 修复了TikTok显示正在直播但不进行录制的问题
- 20230907
- 修复了因抖音官方更新了版本导致的录制出错以及短链接转换出错
- 修复B站无法录制原画视频的bug
- 修改了配置文件字段,新增各平台自定义设置Cookie
- 20230903
- 修复了TikTok录制时报644无法录制的问题
- 新增直播状态推送到钉钉和微信的功能,如有需要请看 [设置推送教程](https://d04vqdiqwr3.feishu.cn/docx/XFPwdDDvfobbzlxhmMYcvouynDh?from=from_copylink)
- 最近比较忙,其他问题有时间再更新
- 20230816
- 修复斗鱼直播(官方更新了字段)和快手直播录制出错的问题
- 20230814
- 新增B站直播录制
- 写了一个在线播放M3U8和FLV视频的网页源码,打开即可食用
- 20230812
- 新增YY直播录制
- 20230808
- 修复主播重新开播无法再次录制的问题
- 20230807
- 新增了斗鱼直播录制
- 修复显示录制完成之后会重新开始录制的问题
- 20230805
- 新增了虎牙直播录制,其暂时只能用flv视频流进行录制
- Web API 新增了快手和虎牙这两个平台的直播流解析(TikTok要代理)
- 20230804
- 新增了快手直播录制,优化了部分代码
- 上传了一个自动化获取抖音直播间页面Cookie的代码,可以用于录制
- 20230803
- 通宵更新
- 新增了国际版抖音TikTok的直播录制,去除冗余 简化了部分代码
- 20230724
- 新增了一个通过抖音直播间地址获取直播视频流链接的API接口,上传即可用
</details>
&emsp;
## 有问题可以提issue, 我会在这里持续添加更多直播平台的录制 欢迎Star
####

69
d2ypp2/StopRecording.vbs Normal file
View File

@ -0,0 +1,69 @@
'********************************************************************************************/
'* File Name : StopRecording.vbs
'* Created Date : 2024-10-15 01:50:30
'* Author : Hmily
'* GitHub : http://github.com/ihmily
'* Description : This script is designed to terminate the process of live recording
'********************************************************************************************/
Dim objWMIService, colProcesses, objProcess
Dim intResponse
strComputer = "."
On Error Resume Next
intResponse = MsgBox("确定要结束所有后台直播录制进程吗?", vbYesNo + vbQuestion, "确认结束进程")
If intResponse = vbYes Then
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
If Err.Number <> 0 Then
Err.Clear
End If
Set colProcesses = objWMIService.ExecQuery("Select * from Win32_Process Where Name = 'ffmpeg.exe'")
Set colProcesses2 = objWMIService.ExecQuery("Select * from Win32_Process Where Name = 'pythonw.exe'")
Set colProcesses3 = objWMIService.ExecQuery("Select * from Win32_Process Where Name = 'DouyinLiveRecorder.exe'")
If Err.Number <> 0 Then
Err.Clear
End If
If Not objWMIService Is Nothing And Not colProcesses Is Nothing And Not colProcesses2 Is Nothing Then
If colProcesses2.Count = 0 And colProcesses3.Count = 0 Then
MsgBox "没有找到录制程序的进程", vbExclamation, "提示信息"
WScript.Quit(1)
Else
For Each objProcess in colProcesses
objProcess.Terminate()
If Err.Number <> 0 Then
objShell.Run "taskkill /f /im " & objProcess.Name, 0, True
Err.Clear
End If
Next
End If
Else
objShell.Run "taskkill /f /im " & objProcess.Name, 0, True
End If
MsgBox "已成功结束正在录制直播的进程!" & vbCrLf & "关闭此窗口30秒后自动停止录制程序", vbInformation, "提示信息"
WScript.Sleep 10000
If colProcesses3.Count <> 0 Then
Set colProcesses_ = colProcesses3
Else
Set colProcesses_ = colProcesses2
End If
For Each objProcess in colProcesses_
objProcess.Terminate()
If Err.Number <> 0 Then
objShell.Run "taskkill /f /im " & objProcess.Name, 0, True
Err.Clear
End If
Next
Else
MsgBox "已取消结束录制操作", vbExclamation, "提示信息"
End If
On Error GoTo 0
Set objWMIService = Nothing
Set colProcesses = Nothing
Set colProcesses2 = Nothing
Set colProcesses3 = Nothing
Set objProcess = Nothing
Set objShell = Nothing

30
d2ypp2/audio Normal file
View File

@ -0,0 +1,30 @@
gpt的
"-af",
"arnndn=m=./arnndn-models/cb.rnnn:mix=0.88," # 人声增强
"afftdn=nf=-24:tn=1," # FFT 降噪,抹平音乐中频
"highpass=f=110,lowpass=f=4800," # 切掉低音鼓/高频镲
"equalizer=f=250:width_type=o:width=2:g=-9," # 衰减低中频,音乐基础弱化
"equalizer=f=800:width_type=o:width=1.5:g=-6," # 再衰减中频,人声外区域
"atempo=1.03," # 轻微加速 3%,节奏轻微错位
"asetrate=48000*1.02,aresample=48000," # 音高上移 ~1/2 半音
"afreqshift=shift=20," # 整体频率偏移 20Hz,破坏指纹
"acompressor=threshold=-28dB:ratio=5:attack=8:release=80:makeup=5," # 压缩动态,音乐更“扁”
"volume=1.15," # 补偿整体音量
"aresample=async=1:first_pts=0" # 保证音视频同步
grok的
"-af", "arnndn=m=./arnndn-models/cb.rnnn:mix=0.88,"
"afftdn=nf=-24:tn=1," # 强FFT降噪,进一步抹平音乐中频
"highpass=f=110,lowpass=f=4800," # 切掉低音鼓/高频镲,音乐能量大减
"equalizer=f=250:width_type=o:width=2:g=-9," # 衰减低中频(很多音乐基础)
"equalizer=f=800:width_type=o:width=1.5:g=-6," # 再衰减中频人声外区域
"atempo=1.06," # 轻微加速6%,节奏错位
"asetrate=48000*1.04,aresample=48000," # 音高上移约3/4半音
"aphaser=type=t:decay=0.5:speed=0.4:delay=2," # 相位扫,谱图模糊
"flanger=delay=4:depth=3:regen=35:width=60:speed=0.35," # 轻法兰杰,增加金属/扫频感
"afreqshift=shift=45," # 整体频率偏移45Hz,进一步乱指纹
"acompressor=threshold=-28dB:ratio=5:attack=8:release=80:makeup=5," # 压缩动态,让音乐更“扁”
"volume=1.15," # 补偿整体音量损失
"aresample=async=1:first_pts=0"

View File

@ -0,0 +1 @@
# 使 backup 成为显式包,便于 from backup.msg_push import ...

295
d2ypp2/backup/msg_push.py Normal file
View File

@ -0,0 +1,295 @@
# -*- coding: utf-8 -*-
"""
Author: Hmily
GitHub: https://github.com/ihmily
Date: 2023-09-03 19:18:36
Update: 2025-01-23 17:16:12
Copyright (c) 2023-2024 by Hmily, All Rights Reserved.
"""
from typing import Dict, Any
import json
import base64
import urllib.request
import urllib.error
import smtplib
from email.header import Header
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
no_proxy_handler = urllib.request.ProxyHandler({})
opener = urllib.request.build_opener(no_proxy_handler)
headers: Dict[str, str] = {'Content-Type': 'application/json'}
def dingtalk(url: str, content: str, number: str = None, is_atall: bool = False) -> Dict[str, Any]:
success = []
error = []
api_list = url.replace(',', ',').split(',') if url.strip() else []
for api in api_list:
json_data = {
'msgtype': 'text',
'text': {
'content': content,
},
"at": {
"atMobiles": [
number
],
"isAtAll": is_atall
},
}
try:
data = json.dumps(json_data).encode('utf-8')
req = urllib.request.Request(api, data=data, headers=headers)
response = opener.open(req, timeout=10)
json_str = response.read().decode('utf-8')
json_data = json.loads(json_str)
if json_data['errcode'] == 0:
success.append(api)
else:
error.append(api)
print(f'钉钉推送失败, 推送地址:{api}, {json_data["errmsg"]}')
except Exception as e:
error.append(api)
print(f'钉钉推送失败, 推送地址:{api}, 错误信息:{e}')
return {"success": success, "error": error}
def xizhi(url: str, title: str, content: str) -> Dict[str, Any]:
success = []
error = []
api_list = url.replace(',', ',').split(',') if url.strip() else []
for api in api_list:
json_data = {
'title': title,
'content': content
}
try:
data = json.dumps(json_data).encode('utf-8')
req = urllib.request.Request(api, data=data, headers=headers)
response = opener.open(req, timeout=10)
json_str = response.read().decode('utf-8')
json_data = json.loads(json_str)
if json_data['code'] == 200:
success.append(api)
else:
error.append(api)
print(f'微信推送失败, 推送地址:{api}, 失败信息:{json_data["msg"]}')
except Exception as e:
error.append(api)
print(f'微信推送失败, 推送地址:{api}, 错误信息:{e}')
return {"success": success, "error": error}
def send_email(email_host: str, login_email: str, email_pass: str, sender_email: str, sender_name: str,
to_email: str, title: str, content: str, smtp_port: str = None, open_ssl: bool = True) -> Dict[str, Any]:
receivers = to_email.replace(',', ',').split(',') if to_email.strip() else []
try:
message = MIMEMultipart()
send_name = base64.b64encode(sender_name.encode("utf-8")).decode()
message['From'] = f'=?UTF-8?B?{send_name}?= <{sender_email}>'
message['Subject'] = Header(title, 'utf-8')
if len(receivers) == 1:
message['To'] = receivers[0]
t_apart = MIMEText(content, 'plain', 'utf-8')
message.attach(t_apart)
if open_ssl:
smtp_port = int(smtp_port) or 465
smtp_obj = smtplib.SMTP_SSL(email_host, smtp_port)
else:
smtp_port = int(smtp_port) or 25
smtp_obj = smtplib.SMTP(email_host, smtp_port)
smtp_obj.login(login_email, email_pass)
smtp_obj.sendmail(sender_email, receivers, message.as_string())
return {"success": receivers, "error": []}
except smtplib.SMTPException as e:
print(f'邮件推送失败, 推送邮箱:{to_email}, 错误信息:{e}')
return {"success": [], "error": receivers}
def tg_bot(chat_id: int, token: str, content: str) -> Dict[str, Any]:
try:
json_data = {
"chat_id": chat_id,
'text': content
}
url = f'https://api.telegram.org/bot{token}/sendMessage'
data = json.dumps(json_data).encode('utf-8')
req = urllib.request.Request(url, data=data, headers=headers)
response = urllib.request.urlopen(req, timeout=15)
json_str = response.read().decode('utf-8')
_json_data = json.loads(json_str)
return {"success": [1], "error": []}
except Exception as e:
print(f'tg推送失败, 聊天ID:{chat_id}, 错误信息:{e}')
return {"success": [], "error": [1]}
def bark(api: str, title: str = "message", content: str = 'test', level: str = "active",
badge: int = 1, auto_copy: int = 1, sound: str = "", icon: str = "", group: str = "",
is_archive: int = 1, url: str = "") -> Dict[str, Any]:
success = []
error = []
api_list = api.replace(',', ',').split(',') if api.strip() else []
for _api in api_list:
json_data = {
"title": title,
"body": content,
"level": level,
"badge": badge,
"autoCopy": auto_copy,
"sound": sound,
"icon": icon,
"group": group,
"isArchive": is_archive,
"url": url
}
try:
data = json.dumps(json_data).encode('utf-8')
req = urllib.request.Request(_api, data=data, headers=headers)
response = opener.open(req, timeout=10)
json_str = response.read().decode("utf-8")
json_data = json.loads(json_str)
if json_data['code'] == 200:
success.append(_api)
else:
error.append(_api)
print(f'Bark推送失败, 推送地址:{_api}, 失败信息:{json_data["message"]}')
except Exception as e:
error.append(api)
print(f'Bark推送失败, 推送地址:{_api}, 错误信息:{e}')
return {"success": success, "error": error}
def ntfy(api: str, title: str = "message", content: str = 'test', tags: str = 'tada', priority: int = 3,
action_url: str = "", attach: str = "", filename: str = "", click: str = "", icon: str = "",
delay: str = "", email: str = "", call: str = "") -> Dict[str, Any]:
success = []
error = []
api_list = api.replace(',', ',').split(',') if api.strip() else []
tags = tags.replace(',', ',').split(',') if tags else ['partying_face']
actions = [{"action": "view", "label": "view live", "url": action_url}] if action_url else []
for _api in api_list:
server, topic = _api.rsplit('/', maxsplit=1)
json_data = {
"topic": topic,
"title": title,
"message": content,
"tags": tags,
"priority": priority,
"attach": attach,
"filename": filename,
"click": click,
"actions": actions,
"markdown": False,
"icon": icon,
"delay": delay,
"email": email,
"call": call
}
try:
data = json.dumps(json_data, ensure_ascii=False).encode('utf-8')
req = urllib.request.Request(server, data=data, headers=headers)
response = opener.open(req, timeout=10)
json_str = response.read().decode("utf-8")
json_data = json.loads(json_str)
if "error" not in json_data:
success.append(_api)
else:
error.append(_api)
print(f'ntfy推送失败, 推送地址:{_api}, 失败信息:{json_data["error"]}')
except urllib.error.HTTPError as e:
error.append(_api)
error_msg = e.read().decode("utf-8")
print(f'ntfy推送失败, 推送地址:{_api}, 错误信息:{json.loads(error_msg)["error"]}')
except Exception as e:
error.append(api)
print(f'ntfy推送失败, 推送地址:{_api}, 错误信息:{e}')
return {"success": success, "error": error}
def pushplus(token: str, title: str, content: str) -> Dict[str, Any]:
"""
PushPlus推送通知
API文档: https://www.pushplus.plus/doc/
"""
success = []
error = []
token_list = token.replace(',', ',').split(',') if token.strip() else []
for _token in token_list:
json_data = {
'token': _token,
'title': title,
'content': content
}
try:
url = 'https://www.pushplus.plus/send'
data = json.dumps(json_data).encode('utf-8')
req = urllib.request.Request(url, data=data, headers=headers)
response = opener.open(req, timeout=10)
json_str = response.read().decode('utf-8')
json_data = json.loads(json_str)
if json_data.get('code') == 200:
success.append(_token)
else:
error.append(_token)
print(f'PushPlus推送失败, Token:{_token}, 失败信息:{json_data.get("msg", "未知错误")}')
except Exception as e:
error.append(_token)
print(f'PushPlus推送失败, Token:{_token}, 错误信息:{e}')
return {"success": success, "error": error}
if __name__ == '__main__':
send_title = '直播通知' # 标题
send_content = '张三 开播了!' # 推送内容
# 钉钉推送通知
webhook_api = '' # 替换成自己Webhook链接,参考文档:https://open.dingtalk.com/document/robots/custom-robot-access
phone_number = '' # 被@用户的手机号码
is_atall = '' # 是否@全体
# dingtalk(webhook_api, send_content, phone_number)
# 微信推送通知
# 替换成自己的单点推送接口,获取地址:https://xz.qqoq.net/#/admin/one
# 当然也可以使用其他平台API 如server酱 使用方法一样
xizhi_api = 'https://xizhi.qqoq.net/xxxxxxxxx.send'
# xizhi(xizhi_api, send_content)
# telegram推送通知
tg_token = '' # tg搜索"BotFather"获取的token值
tg_chat_id = 000000 # tg搜索"userinfobot"获取的chat_id值,即可发送推送消息给你自己,如果下面的是群组id则发送到群
# tg_bot(tg_chat_id, tg_token, send_content)
# email_message(
# email_host="smtp.qq.com",
# login_email="",
# email_pass="",
# sender_email="",
# sender_name="",
# to_email="",
# title="",
# content="",
# )
bark_url = 'https://xxx.xxx.com/key/'
# bark(bark_url, send_title, send_content)
ntfy(
api="https://ntfy.sh/xxxxx",
title="直播推送",
content="xxx已开播",
)
# PushPlus推送通知
pushplus_token = '' # 替换成自己的PushPlus Token,获取地址:https://www.pushplus.plus/
# pushplus(pushplus_token, send_title, send_content)

View File

@ -0,0 +1,227 @@
# robust_relay.py
# 高稳定性 YouTube 转播模块(防误判下播 + 看门狗 + 自动重连 + token刷新)
# 作者:融合 A+B 代码精华,专为抖音/抖音国际版长期无人值守转播设计
import subprocess
import time
import threading
import os
import signal
import datetime
from typing import List, Optional, Callable
# ==================== 配置常量(可全局覆盖) ====================
WATCHDOG_SILENCE = 600 # 10分钟无输出 → 软重启
WATCHDOG_GRACE = 120 # 启动宽限期
REFRESH_URL_EVERY = 300 # 每5分钟强制刷新 real_url(防token过期)
OFFLINE_DEBOUNCE = 3 # 连续3次API返回下播才认为真下播
OFFLINE_WINDOW = 120 # 最近120秒有活跃就忽略下播信号
SOFT_RESTART_COOLDOWN = 90 # 软重启最小间隔
# ==================== 轻量探活 ====================
def _probe_alive(url: str, timeout: float = 5.0) -> bool:
if not url:
return False
try:
import urllib.request, contextlib
opener = urllib.request.build_opener()
if hasattr(urllib.request, 'getproxies'):
proxy = urllib.request.getproxies().get('http')
if proxy:
opener.add_handler(urllib.request.ProxyHandler({"http": proxy, "https": proxy}))
req = urllib.request.Request(url, headers={"User-Agent": "Mozilla/5.0"}, method="HEAD")
with contextlib.closing(opener.open(req, timeout=timeout)) as r:
if r.code >= 400:
return False
head = r.read(256)
if url.lower().endswith(".m3u8"):
return b"#EXTM3U" in head.upper()
if url.lower().endswith(".flv"):
return head.startswith(b"FLV")
return len(head) > 0
except:
return False
# ==================== 增强版 ffmpeg 启动器 ====================
def _launch_ffmpeg(
input_url: str,
youtube_rtmp: str,
anchor_name: str,
logger: Callable[[str], None],
extra_cmd: List[str] = None
) -> subprocess.Popen:
cmd = [
"ffmpeg", "-nostdin", "-hide_banner", "-stats", "-stats_period", "60", "-loglevel", "info",
# 输入端超强重连
"-reconnect", "1", "-reconnect_streamed", "1", "-reconnect_at_eof", "1",
"-reconnect_delay_max", "30", "-rw_timeout", "20000000",
# 极致低延迟 + 时间戳修复
"-fflags", "+genpts+igndts+flush_packets", "-flags", "+global_header",
"-thread_queue_size", "4096", "-analyzeduration", "0", "-probesize", "32",
"-i", input_url,
# copy 模式(质量无损)
"-c:v", "copy", "-c:a", "copy", "-bsf:a", "aac_adtstoasc",
"-map", "0:v?", "-map", "0:a?",
# YouTube 强制参数
"-f", "mpegts", "-g", "2", "-rtmp_buffer", "1000", "-rtmp_live", "live",
"-max_delay", "0", "-tune", "zerolatency", "-avoid_negative_ts", "make_zero",
"-muxdelay", "0", "-muxpreload", "0",
"-fflags", "+nobuffer+flush_packets", "-avioflags", "direct",
]
if extra_cmd:
cmd.extend(extra_cmd)
cmd.append(youtube_rtmp)
creationflags = 0
proc = subprocess.Popen(
cmd,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
bufsize=0,
creationflags=creationflags
)
# 用于看门狗
proc.last_output_ts = time.time()
def _reader():
try:
for line in proc.stdout: # type: ignore
if not line:
break
text = line.decode(errors="ignore").rstrip()
proc.last_output_ts = time.time()
if any(k in text for k in ["bitrate=", "frame=", "speed=", "fps="]):
logger(f"[{anchor_name}] {text}")
except:
pass
threading.Thread(target=_reader, daemon=True).start()
return proc
# ==================== 主函数:高稳定性转播(替代原 check_subprocess) ====================
def robust_youtube_relay(
anchor_name: str,
real_url: str,
youtube_rtmp: str,
logger: Callable[[str], None],
get_latest_stream_url: Callable[[], Optional[str]], # 用于刷新 real_url(如有token过期)
is_stream_still_live: Callable[[], bool], # 检查主播是否在播(API)
extra_ffmpeg_args: List[str] = None, # 可选:加 -f segment 分段保存
heartbeat_callback: Callable[[int], None] = None # 可选:每分钟回调已运行秒数
) -> bool:
"""
返回值:
True = 主播已下播(正常结束)
False = 发生未知错误(建议计数错误次数)
"""
proc: Optional[subprocess.Popen] = None
start_time = time.time()
last_refresh = 0.0
last_soft_restart = 0.0
offline_count = 0
last_live_ts = time.time()
try:
proc = _launch_ffmpeg(real_url, youtube_rtmp, anchor_name, logger, extra_ffmpeg_args)
logger(f"[{anchor_name}] 已开始高稳定性转播 → {youtube_rtmp.split('/')[-1]}")
while True:
now = time.time()
elapsed = int(now - start_time)
silence = now - proc.last_output_ts if proc else 0
# 1. 进程意外退出 → 重启
if proc and proc.poll() is not None:
logger(f"[{anchor_name}] ffmpeg 意外退出,3秒后重启...")
time.sleep(3)
proc = _launch_ffmpeg(real_url, youtube_rtmp, anchor_name, logger, extra_ffmpeg_args)
start_time = time.time()
continue
# 2. 看门狗:长时间无输出 → 软重启
if elapsed > WATCHDOG_GRACE and silence > WATCHDOG_SILENCE:
if now - last_soft_restart > SOFT_RESTART_COOLDOWN:
logger(f"[{anchor_name}] 检测到卡顿({silence:.0f}s无输出),软重启 ffmpeg...")
last_soft_restart = now
if proc and proc.stdin:
proc.stdin.write(b'q')
proc.stdin.flush()
time.sleep(4)
proc = _launch_ffmpeg(real_url, youtube_rtmp, anchor_name, logger, extra_ffmpeg_args)
start_time = time.time()
continue
# 3. 定期刷新播放地址(防token过期)
if now - last_refresh > REFRESH_URL_EVERY:
new_url = get_latest_stream_url()
if new_url and new_url != real_url:
logger(f"[{anchor_name}] 检测到新的播放地址,切换中...")
real_url = new_url
if proc and proc.stdin:
proc.stdin.write(b'q')
time.sleep(3)
proc = _launch_ffmpeg(real_url, youtube_rtmp, anchor_name, logger, extra_ffmpeg_args)
start_time = time.time()
last_refresh = now
# 4. 下播防抖判定(核心防误判)
try:
still_live = is_stream_still_live()
except:
still_live = True # 接口异常不判下播
if not still_live:
# 交叉验证:流还能访问 → 忽略API误判
if _probe_alive(real_url):
logger(f"[{anchor_name}] API判下播但流仍活跃,忽略本次误判")
still_live = True
last_live_ts = now
if still_live:
offline_count = 0
last_live_ts = now
else:
if now - last_live_ts < OFFLINE_WINDOW:
logger(f"[{anchor_name}] 短期掉线,忽略")
else:
offline_count += 1
if offline_count >= OFFLINE_DEBOUNCE:
logger(f"[{anchor_name}] 连续{offline_count}次确认下播,结束转播")
if proc and proc.stdin:
proc.stdin.write(b'q')
return True
else:
logger(f"[{anchor_name}] 疑似下播 {offline_count}/{OFFLINE_DEBOUNCE},继续观察")
# 5. 心跳日志 & 回调
if elapsed % 60 < 2:
h, m = divmod(elapsed // 60, 60)
logger(f"[{anchor_name}] 正在转播 {h:02d}:{m:02d}")
if heartbeat_callback:
heartbeat_callback(elapsed)
time.sleep(8)
except KeyboardInterrupt:
logger(f"[{anchor_name}] 手动终止转播")
return True
except Exception as e:
logger(f"[{anchor_name}] 严重错误: {e}")
return False
finally:
if proc:
try:
proc.stdin.write(b'q') if proc.stdin else None
proc.wait(timeout=8)
except:
proc.kill()

BIN
d2ypp2/codex-live-stack.tgz Normal file

Binary file not shown.

View File

@ -0,0 +1,2 @@
# 每行一条源站直播页 URL(如抖音直播间),由控制台保存或手工编辑
# 部署后请删除本注释并填入实际地址,或仅在 Web 控制台「直播地址列表」中填写

View File

@ -0,0 +1,2 @@
https://live.douyin.com/866853161480,主播: 小小咖啡老吴
https://live.douyin.com/866853161482

View File

@ -0,0 +1,3 @@
https://live.douyin.com/866853161480
https://live.douyin.com/866853161482
https://live.douyin.com/866853161483

View File

@ -0,0 +1 @@
https://live.douyin.com/866853111

131
d2ypp2/config/config.ini Normal file
View File

@ -0,0 +1,131 @@
[录制设置]
language(zh_cn/en) = zh_cn
是否跳过代理检测(是/否) = 是
直播保存路径(不填则默认) =
保存文件夹是否以作者区分 = 否
保存文件夹是否以时间区分 = 否
保存文件夹是否以标题区分 = 否
保存文件名是否包含标题 = 否
是否去除名称中的表情符号 = 是
视频保存格式ts|mkv|flv|mp4|mp3音频|m4a音频 = ts
原画|超清|高清|标清|流畅 = 原画
是否使用代理ip(是/否) = 否
代理地址 =
同一时间访问网络的线程数 = 3
循环时间(秒) = 300
排队读取网址时间(秒) = 0
是否显示循环秒数 = 否
是否显示直播源地址 = 是
分段录制是否开启 = 是
是否强制启用https录制 = 否
录制空间剩余阈值(gb) = 1.0
视频分段时间(秒) = 1800
录制完成后自动转为mp4格式 = 否
mp4格式重新编码为h264 = 否
追加格式后删除原文件 = 是
生成时间字幕文件 = 否
是否录制完成后执行自定义脚本 = 否
自定义脚本执行命令 =
使用代理录制的平台(逗号分隔) = tiktok, sooplive, pandalive, winktv, flextv, popkontv, twitch, liveme, showroom, chzzk, shopee, shp, youtu
额外使用代理录制的平台(逗号分隔) =
[推送配置]
# 可选微信|钉钉|tg|邮箱|bark|ntfy|pushplus 可填多个
直播状态推送渠道 =
钉钉推送接口链接 =
微信推送接口链接 =
bark推送接口链接 =
bark推送中断级别 = active
bark推送铃声 =
钉钉通知@对象(填手机号) =
钉钉通知@全体(是/否) = 否
tgapi令牌 =
tg聊天id(个人或者群组id) =
smtp邮件服务器 =
是否使用SMTP服务SSL加密(是/否) =
SMTP邮件服务器端口 =
邮箱登录账号 =
发件人密码(授权码) =
发件人邮箱 =
发件人显示昵称 =
收件人邮箱 =
ntfy推送地址 =
ntfy推送标签 = tada
ntfy推送邮箱 =
pushplus推送token =
自定义推送标题 =
自定义开播推送内容 =
自定义关播推送内容 =
只推送通知不录制(是/否) = 否
直播推送检测频率(秒) = 1800
开播推送开启(是/否) = 是
关播推送开启(是/否)= 否
[Cookie]
# 录制抖音必填
抖音cookie = ttwid=1%7CB1qls3GdnZhUov9o2NxOMxxYS2ff6OSvEWbv0ytbES4%7C1680522049%7C280d802d6d478e3e78d0c807f7c487e7ffec0ae4e5fdd6a0fe74c3c6af149511; my_rd=1; passport_csrf_token=3ab34460fa656183fccfb904b16ff742; passport_csrf_token_default=3ab34460fa656183fccfb904b16ff742; d_ticket=9f562383ac0547d0b561904513229d76c9c21; n_mh=hvnJEQ4Q5eiH74-84kTFUyv4VK8xtSrpRZG1AhCeFNI; store-region=cn-fj; store-region-src=uid; LOGIN_STATUS=1; __security_server_data_status=1; FORCE_LOGIN=%7B%22videoConsumedRemainSeconds%22%3A180%7D; pwa2=%223%7C0%7C3%7C0%22; download_guide=%223%2F20230729%2F0%22; volume_info=%7B%22isUserMute%22%3Afalse%2C%22isMute%22%3Afalse%2C%22volume%22%3A0.6%7D; strategyABtestKey=%221690824679.923%22; stream_recommend_feed_params=%22%7B%5C%22cookie_enabled%5C%22%3Atrue%2C%5C%22screen_width%5C%22%3A1536%2C%5C%22screen_height%5C%22%3A864%2C%5C%22browser_online%5C%22%3Atrue%2C%5C%22cpu_core_num%5C%22%3A8%2C%5C%22device_memory%5C%22%3A8%2C%5C%22downlink%5C%22%3A10%2C%5C%22effective_type%5C%22%3A%5C%224g%5C%22%2C%5C%22round_trip_time%5C%22%3A150%7D%22; VIDEO_FILTER_MEMO_SELECT=%7B%22expireTime%22%3A1691443863751%2C%22type%22%3Anull%7D; home_can_add_dy_2_desktop=%221%22; __live_version__=%221.1.1.2169%22; device_web_cpu_core=8; device_web_memory_size=8; xgplayer_user_id=346045893336; csrf_session_id=2e00356b5cd8544d17a0e66484946f28; odin_tt=724eb4dd23bc6ffaed9a1571ac4c757ef597768a70c75fef695b95845b7ffcd8b1524278c2ac31c2587996d058e03414595f0a4e856c53bd0d5e5f56dc6d82e24004dc77773e6b83ced6f80f1bb70627; __ac_nonce=064caded4009deafd8b89; __ac_signature=_02B4Z6wo00f01HLUuwwAAIDBh6tRkVLvBQBy9L-AAHiHf7; ttcid=2e9619ebbb8449eaa3d5a42d8ce88ec835; webcast_leading_last_show_time=1691016922379; webcast_leading_total_show_times=1; webcast_local_quality=sd; live_can_add_dy_2_desktop=%221%22; msToken=1JDHnVPw_9yTvzIrwb7cQj8dCMNOoesXbA_IooV8cezcOdpe4pzusZE7NB7tZn9TBXPr0ylxmv-KMs5rqbNUBHP4P7VBFUu0ZAht_BEylqrLpzgt3y5ne_38hXDOX8o=; msToken=jV_yeN1IQKUd9PlNtpL7k5vthGKcHo0dEh_QPUQhr8G3cuYv-Jbb4NnIxGDmhVOkZOCSihNpA2kvYtHiTW25XNNX_yrsv5FN8O6zm3qmCIXcEe0LywLn7oBO2gITEeg=; tt_scid=mYfqpfbDjqXrIGJuQ7q-DlQJfUSG51qG.KUdzztuGP83OjuVLXnQHjsz-BRHRJu4e986
快手cookie =
tiktok_cookie =
虎牙cookie =
斗鱼cookie =
yy_cookie =
b站cookie =
小红书cookie =
bigo_cookie =
blued_cookie =
sooplive_cookie =
netease_cookie =
千度热播_cookie =
pandatv_cookie =
猫耳fm_cookie =
winktv_cookie =
flextv_cookie =
look_cookie =
twitcasting_cookie =
baidu_cookie =
weibo_cookie =
kugou_cookie =
twitch_cookie =
liveme_cookie =
huajiao_cookie =
liuxing_cookie =
showroom_cookie =
acfun_cookie =
changliao_cookie =
yinbo_cookie =
yingke_cookie =
zhihu_cookie =
chzzk_cookie =
haixiu_cookie =
vvxqiu_cookie =
17live_cookie =
langlive_cookie =
pplive_cookie =
6room_cookie =
lehaitv_cookie =
huamao_cookie =
shopee_cookie =
youtube_cookie =
taobao_cookie =
jd_cookie =
faceit_cookie =
migu_cookie =
lianjie_cookie =
laixiu_cookie =
picarto_cookie =
[Authorization]
popkontv_token =
[账号密码]
sooplive账号 =
sooplive密码 =
flextv账号 =
flextv密码 =
popkontv账号 =
partner_code = P-00001
popkontv密码 =
twitcasting账号类型 = normal
twitcasting账号 =
twitcasting密码 =

View File

@ -0,0 +1,5 @@
{
"networkName": "",
"networkSecret": "",
"peerUrls": []
}

View File

@ -0,0 +1,10 @@
{
"redirect_uri": "http://127.0.0.1:8001/youtube/oauth/callback",
"web": {
"client_id": "",
"client_secret": "",
"auth_uri": "https://accounts.google.com/o/oauth2/auth",
"token_uri": "https://oauth2.googleapis.com/token",
"redirect_uris": ["http://127.0.0.1:8001/youtube/oauth/callback"]
}
}

View File

@ -0,0 +1,14 @@
# 复制为 config/hardware.env 或安装后由 scripts/hardware_probe.py --write 生成
# 抖音→YouTube 推流(douyin_youtube_ffplay.py)在 Linux 上会读取本文件中的 LIVE_VIDEO_ENCODER。
#
# —— ARM(RK3588 等)常见:h264_rkmpp(需 /dev/mpp_service 与 ffmpeg 含 rkmpp)
# —— ARM 通用 V4L2:h264_v4l2m2m
# —— x86_64 Intel/AMD 核显(VA-API):h264_vaapi(需 /dev/dri render 节点)
# —— x86_64 Intel Quick Sync:本项目默认不自动启用 h264_qsv;Linux 上优先走更稳的 h264_vaapi
# —— NVIDIA:一般无需写此处,推流脚本会自行检测 nvidia-smi + h264_nvenc
#
# LIVE_VIDEO_ENCODER=h264_v4l2m2m
# LIVE_HW_DECODER=cpu
# LIVE_HDMI_PLAYER=mpv-drm
# LIVE_BROWSER_HWACCEL=auto
# LIVE_STABILITY_MODE=safe

View File

@ -0,0 +1,7 @@
strict_chain
proxy_dns
tcp_read_time_out 30000
tcp_connect_time_out 8000
[ProxyList]
socks5 127.0.0.1 7890

View File

@ -0,0 +1,18 @@
# 复制本文件为同目录下的 runtime.env 后生效(已加入 .gitignore,不会提交)
# 启动器 scripts/launch.py 会自动加载 runtime.env 中的键(不覆盖已存在的环境变量)
# 局域网内任意浏览器访问控制台时,请保持 0.0.0.0
HOST=0.0.0.0
# Web 控制台(FastAPI + 静态页)端口;与同机 SRS / Clash / Neko 等冲突时请改成未占用端口,例如 8101、9200
# 若 Nginx/Caddy 反代出现 502,请核对 proxy_pass 端口与这里一致(Docker Compose 默认常为 8101,PM2 ecosystem 默认 8001)
PORT=8001
# 开发模式时 Next 端口(一般无需改)
# NEXT_DEV_PORT=3000
# scrcpy-server 自动下载(安卓 Web 真流):默认同版本走 GitHub;内网可镜像后设下列之一(支持 {tag} / {version})
# SCRCPY_SERVER_DOWNLOAD_URL=https://你的镜像/scrcpy-server-v{tag}
# SCRCPY_SERVER_DOWNLOAD_URLS=https://a/v{tag},https://b/v{tag}
# SCRCPY_SERVER_DOWNLOAD_NO_GITHUB=1
# SKIP_SCRCPY_SERVER_FETCH=1

View File

@ -0,0 +1,196 @@
# Copy to config/system-stack.env before first Linux deployment when you need custom values.
# Profile model:
# - install-hub.sh: base Linux super hub, web admin, ShellCrash, monitoring, beginner tools
# - install-business.sh: Douyin / YouTube / HDMI business module only
# - install-all.sh: hub first, then business module
# LAN identity
HOSTNAME_ALIAS=live
# Shared control plane
PORT=8001
# Caddy 将 :80 反代到 PORT(http://live.local 无端口验收)
ENABLE_LIVE_EDGE_PROXY=1
LIVE_EDGE_WATCH_INTERVAL=15
# Hub web services
WEBTTY_PORT=7681
# 默认 3080,避免与 Caddy 占用 80(live.local 无端口访问控制台)
HOMEPAGE_PORT=3080
FILEBROWSER_PORT=8082
NETDATA_PORT=19999
# Business streaming services
SRS_HTTP_PORT=8080
SRS_API_PORT=1985
SRS_RTMP_PORT=1935
SRS_SRT_PORT=10080
SRS_WEBRTC_PORT=8088
SRS_WEBRTC_UDP_PORT=8000
# ShellCrash
SHELLCRASH_DIR=/etc/ShellCrash
# Browser / Android lab
BROWSER_PROFILE_DIR=/var/lib/live-browser/profile
BROWSER_START_URL=https://www.tiktok.com/live
BROWSER_REMOTE_DEBUG_PORT=9222
BROWSER_LOCALE=zh-CN
# WebTTY credentials
WEBTTY_USER=live
WEBTTY_PASS=12345678
# File Browser credentials
FILEBROWSER_USER=live
FILEBROWSER_PASS=12345678
# Wi-Fi onboarding
WIFI_CONNECTION_NAME=live-wifi
WIFI_SSID=live
WIFI_PSK=12345678
DISABLE_IPV6=1
LIVE_DNS_SERVERS="223.5.5.5 119.29.29.29 1.1.1.1 8.8.8.8"
# ws-scrcpy 克隆地址(可改为 NetrisTV 上游:https://github.com/NetrisTV/ws-scrcpy.git)
# ANDROID_PANEL_GIT_URL=https://github.com/baixin1228/web-scrcpy.git
# 可选:Docker Neko 浏览器桌面(m1k1o/neko),与 SRS 8080 错开端口
# 默认策略:管理员口令可用、开发者工具开启、油猴强制安装并持久化;用户数据目录见 NEKO_PROFILE_HOST_DIR
# WebRTC 画面:NEKO_WEBRTC_NAT1TO1 必须为本机在局域网中的 IP(如 192.168.x.x),与参考机填网关 IP 同理
# 设为 1 才会安装/启动 Neko 容器;不需要浏览器桌面可改回 0
ENABLE_NEKO=1
NEKO_HTTP_PORT=9200
NEKO_HTTP_PORT_1=9200
NEKO_HTTP_PORT_2=9201
NEKO_HTTP_PORT_3=9202
NEKO_START_URL=https://accounts.google.com/ServiceLogin?continue=https://www.youtube.com/
# Optional explicit image override. When set, it takes precedence over NEKO_IMAGE_X86 / NEKO_IMAGE_ARM64.
# Example for slow GHCR networks: NEKO_IMAGE=ghcr.nju.edu.cn/m1k1o/neko/chromium:3.0.0
# ARM64 mirror example: NEKO_IMAGE=swr.cn-north-4.myhuaweicloud.com/ddn-k8s/ghcr.io/m1k1o/neko/chromium:3.0.6-linuxarm64
NEKO_IMAGE=
NEKO_IMAGE_X86=ghcr.io/m1k1o/neko/google-chrome:3.0.0
NEKO_IMAGE_ARM64=ghcr.io/m1k1o/neko/chromium:3.0.0
# Optional browser supervisor override. Empty means infer from the selected Neko image.
NEKO_BROWSER_SUPERVISOR_CONF=
# Seconds before install continues if the Neko image registry is slow. Set 0 to wait forever.
NEKO_INSTALL_TIMEOUT=900
NEKO_INSTANCE_COUNT=2
NEKO_MAX_INSTANCE_COUNT=64
NEKO_CONTAINER_USER=neko
NEKO_CONTAINER_HOME=/home/neko
NEKO_CONTAINER_UID=1000
NEKO_CONTAINER_GID=1000
NEKO_DISPLAY=:99.0
# Neko 浏览器登录:显示昵称可填 live / admin;密码与全站策略一致(默认 12345678)
NEKO_USER_PASS=12345678
NEKO_ADMIN_PASS=12345678
# 持久化 Chromium 配置(油猴、YouTube 登录、脚本、开发者数据);可从参考机 rsync 整个目录覆盖以迁移
NEKO_PROFILE_HOST_DIR=
NEKO_SHM_SIZE=512mb
NEKO_DESKTOP_SCREEN=1280x720@15
NEKO_MAX_FPS=15
NEKO_VIDEO_BITRATE=1200
NEKO_BROWSER_RENDER_MODE=auto
# Keep disabled by default: managed policies plus the seeded profile install Tampermonkey without Chromium wrapper --load-extension flags.
NEKO_EXTERNAL_EXTENSIONS=0
# 默认使用官方 Chrome policy 给 Tampermonkey 下发 YouTube 脚本,保证新建频道也自动可用。
# 如必须隐藏“由组织管理”提示,可改为 0;此时只保留个人 profile 种子,脚本导入为 best-effort。
NEKO_MANAGED_POLICIES=1
# 启动时重建 Tampermonkey 插件与脚本种子,修复 profile 中损坏/异常的油猴扩展。
NEKO_TAMPERMONKEY_REPAIR=1
NEKO_WEBRTC_EPR=52000-52099
NEKO_WEBRTC_EPR_1=52000-52099
NEKO_WEBRTC_EPR_2=52101-52199
NEKO_WEBRTC_EPR_3=52201-52299
NEKO_WEBRTC_UDP_RANGE=52000-52099
NEKO_WEBRTC_UDP_RANGE_1=52000-52099
NEKO_WEBRTC_UDP_RANGE_2=52101-52199
NEKO_WEBRTC_UDP_RANGE_3=52201-52299
NEKO_WEBRTC_ICELITE=0
NEKO_WEBRTC_TCPMUX=52300
NEKO_WEBRTC_TCPMUX_1=52300
NEKO_WEBRTC_TCPMUX_2=52301
NEKO_WEBRTC_TCPMUX_3=52302
NEKO_WEBRTC_UDPMUX=52300
NEKO_WEBRTC_UDPMUX_1=52300
NEKO_WEBRTC_UDPMUX_2=52301
NEKO_WEBRTC_UDPMUX_3=52302
NEKO_WEBRTC_NAT1TO1=
# WireGuard/EasyTier/Tailscale 等覆盖网络地址可显式填入 NEKO_WEBRTC_NAT1TO1(例如 10.88.0.2)。
# 留空时自动选择物理 LAN IP;显式填入本机覆盖网络 IP 时不会被 LAN watcher 覆盖。
NEKO_WIREGUARD_HOST=
NEKO_PUBLIC_HOST=
# 后台 watcher 会定期核对当前 LAN/显式 NAT1TO1;若板子切换 Wi‑Fi / DHCP 后 IP 变化,会自动重启 Neko 刷新 WebRTC NAT 地址
NEKO_IP_WATCH_INTERVAL=15
NEKO_PLUGINS_ENABLED=true
# Redroid Android 13(需要 binderfs 或 /dev/binder*;安装脚本会在支持的内核上自动准备)
ENABLE_REDROID=1
REDROID_DEFAULT_PORT=5555
REDROID_PORT_STEP=1
REDROID_INSTANCE_PREFIX=redroid13
REDROID_DEFAULT_COUNT=1
REDROID_DATA_PREFIX=/var/lib/live-redroid
REDROID_GPU_MODE=guest
REDROID_DEVICE_PROFILE=pixel-7-pro
REDROID_ADB_INSECURE=1
REDROID_BOOT_ARGS="androidboot.redroid_magisk=1 androidboot.redroid_gpu_mode=guest"
REDROID_EXPECT_GMS=1
REDROID_EXPECT_MAGISK=1
REDROID_WEB_CONSOLE_PORT=9010
REDROID_IMAGE_X86=fahaddz/redroid:13
REDROID_IMAGE_X86_ALT=fahaddz/redroid:13
REDROID_IMAGE_ARM64=fahaddz/redroid:13-arm-pi5
REDROID_IMAGE_ARM64_ALT=fahaddz/redroid:13-arm-pi5
# Seconds before install continues if Redroid image pull/create is slow. Set 0 to wait forever.
REDROID_INSTALL_TIMEOUT=900
# Android gateway mode(仅双网口直连安卓板时需要;单网口留空 ANDROID_DOWNLINK_IF 即可,控制台为「跳过」)
ANDROID_GATEWAY_NAME=live-android-gateway
ANDROID_UPLINK_IF=eth0
ANDROID_DOWNLINK_IF=
ANDROID_GATEWAY_CIDR=192.168.51.1/24
ANDROID_PANEL_PORT=5000
ANDROID_PANEL_DIR=/opt/live-modules/web-scrcpy
ANDROID_PANEL_VIDEO_BIT_RATE=1024000
# Optional modules
# Shared timeout for optional Docker modules during install. Set 0 to wait forever.
DOCKER_OPTIONAL_INSTALL_TIMEOUT=900
# Shared
ENABLE_SHELLCRASH=1
ENABLE_WEBTTY=1
ENABLE_BROWSER=1
ENABLE_MDNS=1
ENABLE_WIFI_PROFILE=1
ENABLE_ANDROID_PANEL=1
# Hub profile defaults
ENABLE_COCKPIT=1
ENABLE_FILEBROWSER=1
ENABLE_HOMEPAGE=1
ENABLE_NETDATA=1
ENABLE_MITMPROXY=1
MITMPROXY_WEB_PORT=8086
MITMPROXY_PROXY_PORT=8087
ENABLE_VSCODE_SERVER=1
VSCODE_SERVER_PORT=8440
VSCODE_SERVER_PASSWORD=12345678
ENABLE_UPTIME_KUMA=1
UPTIME_KUMA_PORT=3001
ENABLE_PULSEAUDIO=1
PULSEAUDIO_TCP_PORT=4713
ENABLE_KMSCUBE=1
KMSCUBE_AUTOSTART=0
KMSCUBE_DRM_DEVICE=/dev/dri/card0
ENABLE_OPENCLAW=1
OPENCLAW_IMAGE=ghcr.io/openclaw/openclaw:latest
OPENCLAW_GATEWAY_PORT=18789
OPENCLAW_BRIDGE_PORT=18790
OPENCLAW_GATEWAY_TOKEN=12345678
OPENCLAW_ALLOW_INSECURE_PRIVATE_WS=1
OPENCLAW_CONFIG_DIR=/var/lib/live-openclaw/config
OPENCLAW_WORKSPACE_DIR=/var/lib/live-openclaw/workspace
# Business profile defaults
ENABLE_SRS=1

View File

View File

@ -0,0 +1 @@
0.0.0.0

12
d2ypp2/config/youtube.ini Normal file
View File

@ -0,0 +1,12 @@
[youtube]
# 必填:YouTube 直播推流 key(在 YouTube 工作室 → 创建 → 流式传输 获取)
key =
# 可选:是否使用 RTMPS 加密推流,填 否 则用 RTMP(默认 RTMPS)
; rtmps = 否
# 可选:视频比特率 kbps,YouTube 推荐 4000-6000,默认 4500
; bitrate = 4500
# 可选:软编 speed 长期小于 1 时开启——轻量音频链(无 arnndn/长 EQ),减轻 CPU。填 1 或 是
; fast_audio = 1

View File

@ -0,0 +1,133 @@
[youtube]
key = x04z-564w-aks7-embw-30y4
rtmps = 是
fast_audio = 1
[录制设置]
language(zh_cn/en) = zh_cn
是否跳过代理检测(是/否) = 否
直播保存路径(不填则默认) =
保存文件夹是否以作者区分 = 是
保存文件夹是否以时间区分 = 否
保存文件夹是否以标题区分 = 否
保存文件名是否包含标题 = 否
是否去除名称中的表情符号 = 是
视频保存格式ts|mkv|flv|mp4|mp3音频|m4a音频 = ts
原画|超清|高清|标清|流畅 = 原画
是否使用代理ip(是/否) = 是
代理地址 =
同一时间访问网络的线程数 = 3
循环时间(秒) = 120
排队读取网址时间(秒) = 0
是否显示循环秒数 = 否
是否显示直播源地址 = 否
分段录制是否开启 = 否
是否强制启用https录制 = 否
录制空间剩余阈值(gb) = 1.0
视频分段时间(秒) = 1800
录制完成后自动转为mp4格式 = 否
mp4格式重新编码为h264 = 否
追加格式后删除原文件 = 否
生成时间字幕文件 = 否
是否录制完成后执行自定义脚本 = 否
使用代理录制的平台(逗号分隔) = tiktok, soop, pandalive, winktv, flextv, popkontv, twitch, liveme, showroom, chzzk, shopee, shp, youtu, faceit
额外使用代理录制的平台(逗号分隔) =
[推送配置]
直播状态推送渠道 =
钉钉推送接口链接 =
微信推送接口链接 =
bark推送接口链接 =
bark推送中断级别 = active
bark推送铃声 = bell
钉钉通知@对象(填手机号) =
钉钉通知@全体(是/否) = 否
tgapi令牌 =
tg聊天id(个人或者群组id) =
smtp邮件服务器 =
是否使用smtp服务ssl加密(是/否) = 是
smtp邮件服务器端口 =
邮箱登录账号 =
发件人密码(授权码) =
发件人邮箱 =
发件人显示昵称 =
收件人邮箱 =
ntfy推送地址 =
ntfy推送标签 = tada
ntfy推送邮箱 =
pushplus推送token =
自定义推送标题 = 直播间状态更新通知
自定义开播推送内容 =
自定义关播推送内容 =
只推送通知不录制(是/否) = 否
直播推送检测频率(秒) = 1800
开播推送开启(是/否) = 是
关播推送开启(是/否) = 否
[Cookie]
抖音cookie =
快手cookie =
tiktok_cookie =
虎牙cookie =
斗鱼cookie =
yy_cookie =
b站cookie =
小红书cookie =
bigo_cookie =
blued_cookie =
sooplive_cookie =
netease_cookie =
千度热播_cookie =
pandatv_cookie =
猫耳fm_cookie =
winktv_cookie =
flextv_cookie =
look_cookie =
twitcasting_cookie =
baidu_cookie =
weibo_cookie =
kugou_cookie =
twitch_cookie =
liveme_cookie =
huajiao_cookie =
liuxing_cookie =
showroom_cookie =
acfun_cookie =
changliao_cookie =
yinbo_cookie =
yingke_cookie =
zhihu_cookie =
chzzk_cookie =
haixiu_cookie =
vvxqiu_cookie =
17live_cookie =
langlive_cookie =
pplive_cookie =
6room_cookie =
lehaitv_cookie =
huamao_cookie =
shopee_cookie =
youtube_cookie =
taobao_cookie =
jd_cookie =
faceit_cookie =
migu_cookie =
lianjie_cookie =
laixiu_cookie =
picarto_cookie =
[Authorization]
popkontv_token =
[账号密码]
sooplive账号 =
sooplive密码 =
flextv账号 =
flextv密码 =
popkontv账号 =
partner_code = P-00001
popkontv密码 =
twitcasting账号类型 = normal
twitcasting账号 =
twitcasting密码 =

View File

@ -0,0 +1,12 @@
[youtube]
# YouTube 推流 key(工作室 → 直播 → 串流密钥)
key = x04z-564w-aks7-embw-30y4
# 使用 RTMPS;填 否 则 RTMP
rtmps = 是
# 视频比特率 kbps(可选)
# bitrate = 4000
# 轻量音频链,减轻 CPU:1 / 是
fast_audio = 1

View File

@ -0,0 +1,12 @@
[youtube]
# YouTube 推流 key(工作室 → 直播 → 串流密钥)
key = 23122112
# 使用 RTMPS;填 否 则 RTMP
rtmps = 是
# 视频比特率 kbps(可选)
# bitrate = 4000
# 轻量音频链,减轻 CPU:1 / 是
fast_audio = 0

View File

@ -0,0 +1,133 @@
[youtube]
key = ue78-1c3e-mr9g-14mz-9r4z
rtmps = 是
fast_audio = 1
[录制设置]
language(zh_cn/en) = zh_cn
是否跳过代理检测(是/否) = 否
直播保存路径(不填则默认) =
保存文件夹是否以作者区分 = 是
保存文件夹是否以时间区分 = 否
保存文件夹是否以标题区分 = 否
保存文件名是否包含标题 = 否
是否去除名称中的表情符号 = 是
视频保存格式ts|mkv|flv|mp4|mp3音频|m4a音频 = ts
原画|超清|高清|标清|流畅 = 原画
是否使用代理ip(是/否) = 是
代理地址 =
同一时间访问网络的线程数 = 3
循环时间(秒) = 120
排队读取网址时间(秒) = 0
是否显示循环秒数 = 否
是否显示直播源地址 = 否
分段录制是否开启 = 否
是否强制启用https录制 = 否
录制空间剩余阈值(gb) = 1.0
视频分段时间(秒) = 1800
录制完成后自动转为mp4格式 = 否
mp4格式重新编码为h264 = 否
追加格式后删除原文件 = 否
生成时间字幕文件 = 否
是否录制完成后执行自定义脚本 = 否
使用代理录制的平台(逗号分隔) = tiktok, soop, pandalive, winktv, flextv, popkontv, twitch, liveme, showroom, chzzk, shopee, shp, youtu, faceit
额外使用代理录制的平台(逗号分隔) =
[推送配置]
直播状态推送渠道 =
钉钉推送接口链接 =
微信推送接口链接 =
bark推送接口链接 =
bark推送中断级别 = active
bark推送铃声 = bell
钉钉通知@对象(填手机号) =
钉钉通知@全体(是/否) = 否
tgapi令牌 =
tg聊天id(个人或者群组id) =
smtp邮件服务器 =
是否使用smtp服务ssl加密(是/否) = 是
smtp邮件服务器端口 =
邮箱登录账号 =
发件人密码(授权码) =
发件人邮箱 =
发件人显示昵称 =
收件人邮箱 =
ntfy推送地址 =
ntfy推送标签 = tada
ntfy推送邮箱 =
pushplus推送token =
自定义推送标题 = 直播间状态更新通知
自定义开播推送内容 =
自定义关播推送内容 =
只推送通知不录制(是/否) = 否
直播推送检测频率(秒) = 1800
开播推送开启(是/否) = 是
关播推送开启(是/否) = 否
[Cookie]
抖音cookie =
快手cookie =
tiktok_cookie =
虎牙cookie =
斗鱼cookie =
yy_cookie =
b站cookie =
小红书cookie =
bigo_cookie =
blued_cookie =
sooplive_cookie =
netease_cookie =
千度热播_cookie =
pandatv_cookie =
猫耳fm_cookie =
winktv_cookie =
flextv_cookie =
look_cookie =
twitcasting_cookie =
baidu_cookie =
weibo_cookie =
kugou_cookie =
twitch_cookie =
liveme_cookie =
huajiao_cookie =
liuxing_cookie =
showroom_cookie =
acfun_cookie =
changliao_cookie =
yinbo_cookie =
yingke_cookie =
zhihu_cookie =
chzzk_cookie =
haixiu_cookie =
vvxqiu_cookie =
17live_cookie =
langlive_cookie =
pplive_cookie =
6room_cookie =
lehaitv_cookie =
huamao_cookie =
shopee_cookie =
youtube_cookie =
taobao_cookie =
jd_cookie =
faceit_cookie =
migu_cookie =
lianjie_cookie =
laixiu_cookie =
picarto_cookie =
[Authorization]
popkontv_token =
[账号密码]
sooplive账号 =
sooplive密码 =
flextv账号 =
flextv密码 =
popkontv账号 =
partner_code = P-00001
popkontv密码 =
twitcasting账号类型 = normal
twitcasting账号 =
twitcasting密码 =

227
d2ypp2/demo.py Normal file
View File

@ -0,0 +1,227 @@
# -*- coding: utf-8 -*-
import asyncio
from src.logger import logger
from src import spider
# 以下示例直播间链接不保证时效性,请自行查看链接是否能正常访问
# Please note that the following example live room links may not be up-to-date
LIVE_STREAM_CONFIG = {
"douyin": {
"url": "https://live.douyin.com/745964462470",
"func": spider.get_douyin_app_stream_data,
},
"tiktok": {
"url": "https://www.tiktok.com/@pearlgaga88/live",
"func": spider.get_tiktok_stream_data,
},
"kuaishou": {
"url": "https://live.kuaishou.com/u/yall1102",
"func": spider.get_kuaishou_stream_data,
},
"huya": {
"url": "https://www.huya.com/116",
"func": spider.get_huya_app_stream_url,
},
"douyu": {
"url": "https://www.douyu.com/topic/wzDBLS6?rid=4921614&dyshid=",
"func": spider.get_douyu_info_data,
},
"yy": {
"url": "https://www.yy.com/22490906/22490906",
"func": spider.get_yy_stream_data,
},
"bilibili": {
"url": "https://live.bilibili.com/21593109",
"func": spider.get_bilibili_stream_data,
},
"xhs": {
"url": "https://www.xiaohongshu.com/user/profile/6330049c000000002303c7ed?appuid=5f3f478a00000000010005b3",
"func": spider.get_xhs_stream_url,
},
"bigo": {
"url": "https://www.bigo.tv/cn/716418802",
"func": spider.get_bigo_stream_url,
},
"blued": {
"url": "https://app.blued.cn/live?id=Mp6G2R",
"func": spider.get_blued_stream_url,
},
"sooplive": {
"url": "https://play.sooplive.co.kr/sw7love",
"func": spider.get_sooplive_stream_data,
},
"netease": {
"url": "https://cc.163.com/583946984",
"func": spider.get_netease_stream_data,
},
"qiandurebo": {
"url": "https://qiandurebo.com/web/video.php?roomnumber=33333",
"func": spider.get_qiandurebo_stream_data,
},
"pandatv": {
"url": "https://www.pandalive.co.kr/live/play/bara0109",
"func": spider.get_pandatv_stream_data,
},
"maoerfm": {
"url": "https://fm.missevan.com/live/868895007",
"func": spider.get_maoerfm_stream_url,
},
"winktv": {
"url": "https://www.winktv.co.kr/live/play/anjer1004",
"func": spider.get_winktv_stream_data,
},
"flextv": {
"url": "https://www.ttinglive.com/channels/685479/live",
"func": spider.get_flextv_stream_data,
},
"looklive": {
"url": "https://look.163.com/live?id=65108820&position=3",
"func": spider.get_looklive_stream_url,
},
"popkontv": {
"url": "https://www.popkontv.com/live/view?castId=wjfal007&partnerCode=P-00117",
"func": spider.get_popkontv_stream_url,
},
"twitcasting": {
"url": "https://twitcasting.tv/c:uonq",
"func": spider.get_twitcasting_stream_url,
},
"baidu": {
"url": "https://live.baidu.com/m/media/pclive/pchome/live.html?room_id=9175031377&tab_category",
"func": spider.get_baidu_stream_data,
},
"weibo": {
"url": "https://weibo.com/u/7849520225",
"func": spider.get_weibo_stream_data,
},
"kugou": {
"url": "https://fanxing2.kugou.com/50428671?refer=2177&sourceFrom=",
"func": spider.get_kugou_stream_url,
},
"twitchtv": {
"url": "https://www.twitch.tv/gamerbee",
"func": spider.get_twitchtv_stream_data,
},
"liveme": {
"url": "https://www.liveme.com/zh/v/17141937295821012854/index.html",
"func": spider.get_liveme_stream_url,
},
"huajiao": {
"url": "https://www.huajiao.com/user/207446325",
"func": spider.get_huajiao_stream_url,
},
"showroom": {
"url": "https://www.showroom-live.com/room/profile?room_id=511033",
"func": spider.get_showroom_stream_data,
},
"acfun": {
"url": "https://live.acfun.cn/live/17912421",
"func": spider.get_acfun_stream_data,
},
"changliao": {
"url": "https://www.tlclw.com/801044397",
"func": spider.get_changliao_stream_url,
},
"yingke": {
"url": "https://www.inke.cn/liveroom/index.html?uid=710032101&id=1720857535354099",
"func": spider.get_yingke_stream_url,
},
"yinbo": {
"url": "https://live.ybw1666.com/800008687",
"func": spider.get_yinbo_stream_url,
},
"zhihu": {
"url": "https://www.zhihu.com/people/ac3a467005c5d20381a82230101308e9",
"func": spider.get_zhihu_stream_url,
},
"chzzk": {
"url": "https://chzzk.naver.com/live/458f6ec20b034f49e0fc6d03921646d2",
"func": spider.get_chzzk_stream_data,
},
"haixiu": {
"url": "https://www.haixiutv.com/6095106",
"func": spider.get_haixiu_stream_url,
},
"vvxqiu": {
"url": "https://h5webcdnp.vvxqiu.com//activity/videoShare/videoShare.html?h5Server=https://h5p.vvxqiu.com&"
"roomId=LP115664695&platformId=vvstar",
"func": spider.get_vvxqiu_stream_url,
},
"17live": {
"url": "https://17.live/en/live/6302408",
"func": spider.get_17live_stream_url,
},
"langlive": {
"url": "https://www.lang.live/en-US/room/3349463",
"func": spider.get_langlive_stream_url,
},
"pplive": {
"url": "https://m.pp.weimipopo.com/live/preview.html?uid=91648673&anchorUid=91625862&app=plpl",
"func": spider.get_pplive_stream_url,
},
"6room": {
"url": "https://v.6.cn/634435",
"func": spider.get_6room_stream_url,
},
"lehai": {
"url": "https://www.lehaitv.com/8059096",
"func": spider.get_haixiu_stream_url,
},
"huamao": {
"url": "https://h.catshow168.com/live/preview.html?uid=19066357&anchorUid=18895331",
"func": spider.get_pplive_stream_url,
},
"shopee": {
"url": "https://sg.shp.ee/GmpXeuf?uid=1006401066&session=802458",
"func": spider.get_shopee_stream_url,
},
"youtube": {
"url": "https://www.youtube.com/watch?v=cS6zS5hi1w0",
"func": spider.get_youtube_stream_url,
},
"taobao": {
"url": "https://m.tb.cn/h.TWp0HTd",
"func": spider.get_taobao_stream_url,
},
"jd": {
"url": "https://3.cn/28MLBy-E",
"func": spider.get_jd_stream_url,
},
"faceit": {
"url": "https://www.faceit.com/zh/players/Compl1/stream",
"func": spider.get_faceit_stream_data,
},
"lianjie": {
"url": "https://show.lailianjie.com/10000258",
"func": spider.get_lianjie_stream_url,
},
"migu": {
"url": "https://www.miguvideo.com/p/live/120000541321",
"func": spider.get_migu_stream_url,
},
"laixiu": {
"url": "https://www.imkktv.com/h5/share/video.html?uid=1845195&roomId=1710496",
"func": spider.get_laixiu_stream_url,
},
"picarto": {
"url": "https://www.picarto.tv/cuteavalanche",
"func": spider.get_picarto_stream_url,
}
}
def test_live_stream(platform_name: str, proxy_addr=None, cookies=None) -> None:
if platform_name in LIVE_STREAM_CONFIG:
config = LIVE_STREAM_CONFIG[platform_name]
try:
stream_data = asyncio.run(config['func'](config['url'], proxy_addr=proxy_addr, cookies=cookies))
logger.debug(f"Stream data for {platform_name}: {stream_data}")
except Exception as e:
logger.error(f"Error fetching stream data for {platform_name}: {e}")
else:
logger.warning(f"No configuration found for platform: {platform_name}")
if __name__ == "__main__":
platform = "douyin"
test_live_stream(platform)

6
d2ypp2/dev.bat Normal file
View File

@ -0,0 +1,6 @@
@echo off
cd /d "%~dp0"
if not defined PORT set "PORT=8001"
echo [dev] API+Next 开发模式 PORT=%PORT%
echo [dev] 浏览器打开 http://localhost:3000
python scripts\launch.py --dev --port %PORT%

12
d2ypp2/dev.sh Normal file
View File

@ -0,0 +1,12 @@
#!/usr/bin/env bash
# 开发:API(热重载) + Next dev;浏览器打开 http://localhost:3000
set -euo pipefail
cd "$(dirname "$0")"
export PORT="${PORT:-8001}"
if [[ -x ".venv/bin/python" ]]; then
PY=".venv/bin/python"
else
PY=python3
command -v python3 >/dev/null 2>&1 || PY=python
fi
exec "$PY" scripts/launch.py --dev --port "$PORT"

View File

@ -0,0 +1,16 @@
version: '3.8'
services:
app:
image: ihmily/douyin-live-recorder:latest
environment:
- TERM=xterm-256color
tty: true
stdin_open: true
#build: .
volumes:
- ./config:/app/config
- ./logs:/app/logs
- ./backup_config:/app/backup_config
- ./downloads:/app/downloads
restart: always

10
d2ypp2/docker-compose.yml Normal file
View File

@ -0,0 +1,10 @@
# 控制台默认 8101(与 SRS 8080/1985、Clash 7890 等错开);改端口请同步修改左侧宿主机映射
services:
live-console:
build: .
ports:
- "${LIVE_CONSOLE_PORT:-8101}:8101"
restart: unless-stopped
environment:
HOST: "0.0.0.0"
PORT: "8101"

View File

@ -0,0 +1,64 @@
# Live Platform 四层架构
Homelab 一键直播系统的具体优化路线图见 [`HOMELAB_OPTIMIZATION_PLAN.md`](HOMELAB_OPTIMIZATION_PLAN.md),该文档把 `live.local` 面板、YouTube 多频道 Pro、Neko、TikTok HDMI、安卓云控和网络代理拆成可验收的实施项。
## 分层
| 层 | 职责 | 代码/路径 |
|----|------|-----------|
| Core OS | 用户、SSH、mDNS、Wi‑Fi、WebTTY、Docker、systemd、日志 | `scripts/linux/install_hub.sh` 及系统包 |
| Infra Service | ShellCrash、Caddy、Netdata、SRS、Neko、ws-scrcpy、FRP、WireGuard 占位 | `services/*`、`scripts/linux/service_ctl.sh` |
| Business | 无人直播 douyinyoutube(FFmpeg/HDMI/推流),可脱离控制台运行 | 仓库根业务脚本、`install-live.sh` |
| Web Console | 仅通过 API 与配置中心「控制」,不实现业务算法 | `web.py`、`web-console`、`/hub/*` API |
## 配置中心
- 安装目标:`/opt/live/config/`
- 默认模板:`live-platform/config/defaults/`
- 文件:`system.json`、`network.json`、`services/*.json`、`business/*.json`
- 生成兼容层:`live-platform/tools/render_stack_env.py` → `/opt/live/generated/system-stack.env`(供现有 shell 读取,逐步淘汰分散 `.env`)
## 一键脚本(幂等)
| 脚本 | 作用 |
|------|------|
| `./install-core.sh` | 同步 JSON → `/opt/live/config`,生成 env,调用 `install_hub.sh`(无业务) |
| `./install-live.sh` | 仅业务模块,调用 `install_business.sh` |
| `./doctor.sh` | 网络、端口、adb、ffmpeg、docker、API 健康检查 |
## API
- `GET /hub/dashboard`:快照 + 服务 + 安卓 + 直播进程状态
- `GET /hub/config`:配置中心只读聚合
- `POST /hub/business/douyinyoutube`:业务元数据(如抖音 URL 声明)
- 既有:`/service_action`、`/android/*`、`/process_monitor`、`/save_url_config` 等
## 前端
- `/`:`LiveControlApp` 产品壳(总览、服务、直播、安卓、网络、设置)
- `/console`:高级遗留控制台(全功能)
- 开发:`middleware` 将 `/hub` 代理到本机 FastAPI
## live.local(无端口验收)
- **`install_hub.sh` 末尾**执行 **`install_live_edge_proxy`**:安装/启用 **`live-edge.service`(Caddy)**,将 **`http://live.local`(:80)** 反代到 **`127.0.0.1:${PORT}`**(默认 8001),并启用 **`live-edge-watch.service`** 自动拉起/修复 80 入口。
- **Homepage** 默认改绑 **`HOMEPAGE_PORT=3080`**,避免与 Caddy 抢 80。
- 仅更新反代:`sudo bash scripts/linux/reinstall_live_edge.sh`
- `ENABLE_LIVE_EDGE_PROXY=0` 可关闭(`system-stack.env`)。
## Neko 动态实例
- `scripts/linux/service_ctl.sh neko start|restart` 与安装流程都会先调用 `tools/render_neko_compose.py`,输出 `services/neko/docker-compose.generated.yml`,再由 Docker Compose 启动 `live-neko-1..N`。
- `NEKO_INSTANCE_COUNT` 最少为 2,`NEKO_MAX_INSTANCE_COUNT` 默认封顶 64;YouTube PRO 保存频道时由 `src/neko_capacity.py` 把实例数提升到频道数所需容量。
- 每个实例独立分配 profile、HTTP 端口、TCPMUX、UDPMUX 和 UDP range。第 4 个及以后实例从 `52400-52499` 起按百段分配 UDP range,避免与前 3 个实例的 mux 端口冲突。
- 默认 `NEKO_MANAGED_POLICIES=0`,Neko 不挂 Chrome enterprise policy,因此浏览器不应显示“由组织管理”,并且不会通过启动参数禁用 Google Sync。若必须强制下发 Tampermonkey/浏览器策略,可设为 `1`,但 Chrome 会按设计显示 managed by organization。
- 新 profile 启动前会调用 `seed_neko_tampermonkey_profile`,从 1 号健康 profile 补种 Tampermonkey 扩展目录、脚本存储和扩展设置;这样新频道新 Neko 不依赖 Chrome Web Store 当场下载,弱网/中国网络下也能看到默认脚本。
- `services/neko/browser-launch.sh` 必须保持可执行位;本地 verifier 会检查每个 Neko 里的 `google-chrome`/`chromium` supervisor 进程,防止只看到 Neko 容器健康但浏览器实际没启动。
- `services/neko/docker-compose.yml` 仅保留为兼容模板和排障参考;生产运行以生成文件为准。
- `live-neko-ip-watch.service` 监测 LAN IP 变化,更新 `NEKO_WEBRTC_NAT1TO1` 后重启 Neko,避免换网后 WebRTC、iframe 或局域网入口继续指向旧地址。
## 安卓 Web 控制
- `/android/screenshot` 提供 PNG 截图兜底,`/android/action` 支持 tap、double tap、long press、text、keyevent、swipe 等操作。
- 前端优先尝试 `/android/scrcpy/ws` 真流;WebSocket、WebCodecs 或 scrcpy-server 不可用时自动降级到截图轮询,仍可按截图坐标触控。
- Redroid 和真实 ADB 设备统一走 ADB 发现;Redroid 启动后自动尝试 `adb connect 127.0.0.1:5555`。

View File

@ -0,0 +1,211 @@
# Homelab 一键直播系统优化方案
本方案把 `/home/eric/sh/d2ypp2` 作为核心源码与发布来源,目标是在 x86_64 / arm64 Linux 主机上通过一键脚本安装统一服务,并在 `http://live.local` 提供可展示、可控制、可诊断的 Web 面板。
## 目标状态
- 一键安装:`install-all.sh` 可在 Debian / Ubuntu / Armbian 类系统上完成 Core OS、Infra Service、Business、Web Console 四层安装;`install-core.sh` 与 `install-live.sh` 可独立运行。
- 统一入口:`live.local` 由 Caddy `live-edge.service` 承接,默认反代到 `live-console.service`,并由 `live-edge-watch.service` 持续自愈,控制台无需记端口。
- 总览:展示硬件、软件、网络、直播业务状态,并给出健康检查、失败原因与下一步操作。
- 服务:展示 ShellCrash、SRS、Neko、Redroid、ADB、File Browser、Netdata、WebTTY 等服务的安装、运行、端口与控制按钮。
- YouTube 无人直播:单频道与多频道 Pro 共存。每条 Pro 线路独立保存 URL、推流密钥、PM2 进程、日志、Neko 工作室入口。
- TikTok 无人直播:视频源转发到设备 HDMI,面板可检测输出设备、预览命令、启动/停止链路。
- 安卓:Redroid 与真实手机都通过 ADB 识别;Web 面板可看屏、点按、长按、输入、安装 APK、批量执行命令。
- 网络:ShellCrash 解决单机代理上网,面板展示实时/累计上行下行、代理状态、DNS 与出口连通性。
## 源码与部署边界
当前说明里提到“核心源码”和“实际部署同步另一个文件夹”分离,后续必须固定一个发布流程:
- 源码目录只以 `/home/eric/sh/d2ypp2` 为准,实际部署目录不手工改代码。
- `upgrade-live.sh` 负责从源码构建前端、刷新 systemd 单元、同步配置模板、重启 `live-console` 与 `live-edge`。
- `/opt/live/config` 是设备上的运行配置中心;源码里的 `live-platform/config/defaults/` 只提供默认模板。
- 用户数据与账号态必须持久化到 `/opt/live/state`、`/opt/live/logs`、`/opt/live-modules/*`,不能随升级覆盖。
## P0:先修可用性闭环
### 1. 安卓 Web 画面与触控
现状:已有 `/android/screenshot`、`/android/action`、`/android/scrcpy/ws`,前端也有截图轮询和 scrcpy H.264 WebSocket。但在 scrcpy-server、WebCodecs、ADB forward、无线断连、Redroid 启动未完成时,界面容易表现为空白,用户误以为安卓不可控。
优化:
- WebSocket 真流失败时自动降级到 PNG 截图轮询,仍保留点按/双击/长按。
- 在安卓页显式展示 `adb devices -l`、scrcpy-server jar、WebCodecs、截图接口、触控接口的诊断结果。
- Redroid 启动后自动 `adb connect 127.0.0.1:5555`,真实手机则提示 USB 授权或无线配对。
- 触控坐标优先按截图/Canvas 实际像素映射;旋转后重新读取 `wm size` 与截图尺寸。
涉及文件:
- `web-console/components/live-product/LiveAndroidStreamConsole.tsx`
- `src/android_control.py`
- `src/scrcpy_stream.py`
- `src/redroid_control.py`
- `web.py`
验收:
- scrcpy-server 不存在或 WebSocket 失败时,安卓页仍能显示截图并可点按。
- Redroid、USB 手机、无线 ADB 至少各有一条诊断路径。
- `pytest tests/test_android_redroid.py` 通过,前端 `npm run build` 通过。
### 2. Neko 基线与 Google 友好
现状:Neko 运行路径已经改为动态生成 compose。`NEKO_INSTANCE_COUNT` 默认保底 2,最大受 `NEKO_MAX_INSTANCE_COUNT` 限制并封顶 64;每个实例都有独立 profile、HTTP/WebRTC 端口、Tampermonkey 持久化、开发者模式与 IP 变更 watchdog。默认是个人管理员浏览器模式,不挂 Chrome 企业策略、不禁用 Google Sync。
优化:
- 保底实例数为 2;多频道 Pro 线路数超过实例数时,保存频道会自动提升 `NEKO_INSTANCE_COUNT` 并后台重启 Neko。
- 每个实例独立 `NEKO_PROFILE_HOST_DIR_N`,账号态、Tampermonkey、YouTube Studio 页面保持持久化。
- 新建 profile 会从 1 号健康 profile 自动补种 Tampermonkey 扩展目录、脚本 LevelDB 与扩展设置,避免新频道新 Neko 依赖 Chrome Web Store 实时下载后才出现默认脚本。
- Neko 默认启用超级管理员入口,管理员密码来自 `NEKO_ADMIN_PASS`,普通观看/操作密码来自 `NEKO_USER_PASS`。
- 浏览器默认打开开发者模式。`NEKO_MANAGED_POLICIES=0` 时不挂企业策略,因此不会显示“由组织管理”;如必须强制安装/导入 Tampermonkey,可改为 `NEKO_MANAGED_POLICIES=1`,代价是 Chrome 会显示 managed by organization。
- 默认使用 Google/YouTube 登录入口,保留完整 ICE,避免更换 Wi-Fi 后 WebRTC 仍指向旧局域网 IP。
- Tampermonkey 默认脚本继续使用 `services/neko/provisioning/youtube-studio-auto-dismiss.user.js`,来源 URL 固定为 `https://greasyfork.org/en/scripts/557378-youtube-studio-auto-dismiss/code`;企业策略模式开启时会通过 Chrome policy 导入。
涉及文件:
- `services/neko/docker-compose.yml`
- `tools/render_neko_compose.py`
- `services/neko/browser-launch.sh`
- `services/neko/policies/policies.json`
- `services/neko/provisioning/*`
- `tools/render_tampermonkey_provisioning.py`
- `scripts/linux/neko_ip_watch.sh`
- `scripts/linux/service_ctl.sh`
验收:
- 新安装后至少有 `Neko 1`、`Neko 2` 两个入口。
- `service_ctl.sh neko restart` 会生成 `services/neko/docker-compose.generated.yml`,按 `NEKO_INSTANCE_COUNT` 启动 `live-neko-1..N`。
- `tools/verify_local_install.py` 会逐实例检查浏览器 supervisor、Tampermonkey provisioning server、默认脚本 payload 与脚本存储落盘。
- 切换局域网 IP 后 `live-neko-*` 重启并刷新 `NEKO_WEBRTC_NAT1TO1`。
- Chrome/Chromium 默认开发者模式可见,Tampermonkey 脚本已启用。
### 3. YouTube 多频道 Pro
现状:多频道列表已落盘 SQLite,每条线路可独立生成 `youtube.<pm2>.ini` 与 `URL_config.<pm2>.ini`,PM2 名使用 `youtube2__<channelId>`;保存频道时会调用 `src/neko_capacity.py` 保证 Neko 容量不小于频道数且最少 2 个。
优化:
- 新建线路保存成功后,自动保证对应配置文件存在,并在进程列表显示该线路。
- 新建线路保存成功后,自动保证存在对应 Neko 实例,动态 compose 按线路数生成 `Neko 1..N`。
- 线路和 Neko 实例建立稳定映射:线路 1 -> Neko 1,线路 2 -> Neko 2,线路 N -> Neko N;超过设备上限时进入“需要扩容硬件/降低实例数”的明确状态。
- 开始直播前校验:抖音 URL、YouTube key、FFmpeg、PM2、SRS/RTMP 端口、Neko 可达性。
- 日志按线路隔离,面板展示最近错误、推流中/等待上游/密钥异常/心跳过期。
涉及文件:
- `web-console/components/live-product/LiveYoutubeUnmannedView.tsx`
- `web-console/lib/youtubeProChannels.ts`
- `src/youtube_pro_runtime.py`
- `src/hub_kv_store.py`
- `web.py`
验收:
- 新增线路保存后刷新页面仍存在。
- 每条线路的 URL 与 key 不互相覆盖。
- 未填 key 或 URL 时不能启动,提示具体原因。
## P1:补齐设备与网络体验
### 4. TikTok HDMI 链路
优化:
- 自动探测 `/dev/dri/card*`、`/dev/fb*`、`/dev/video*`、USB HDMI 采集卡、EDID。
- 提供 `mpv --drm-*`、`ffmpeg -> kms/drm`、`v4l2loopback` 的候选命令与失败解释。
- 将视频源、输出接口、音频输出、分辨率、帧率、重试策略写入配置中心。
涉及文件:
- `web-console/components/live-product/LiveTiktokHdmiView.tsx`
- `src/hdmi_control.py`
- `scripts/srt_to_hdmi_drm.example.sh`
- `tiktok/tiktok.py`
验收:
- 有 HDMI/DRM 设备时面板显示推荐输出命令。
- 无设备时显示缺失项,不影响其他模块运行。
### 5. 网络与带宽统计
优化:
- 总览和网络页展示每个物理网卡的实时上行/下行、累计 RX/TX、链路速率、在线状态。
- ShellCrash 页保留配置编辑、启动/停止/重启、导入 YAML,并增加出口 IP / DNS / YouTube 连通性探测。
- 支持保存“代理健康检查”结果到 dashboard,业务启动前可选择是否强制检查代理。
涉及文件:
- `src/control_plane.py`
- `web-console/components/live-product/LiveControlApp.tsx`
- `web-console/components/OverviewCharts.tsx`
- `live-platform/config/defaults/services/shellcrash.json`
验收:
- `/hub/dashboard` 返回接口流量数据。
- 网络页无需 Netdata 也能看到基本带宽曲线。
## P2:工程化与长期维护
### 6. 动态 Neko 扩容
已实现由配置中心生成 compose:
- `NEKO_INSTANCE_COUNT=max(2, youtube_pro_lane_count)`。
- 每个实例自动分配 HTTP、TCPMUX、UDPMUX、UDP_RANGE、profile 目录。
- `service_ctl.sh neko restart` 使用生成后的 compose 启动所需实例并停掉多余实例。
- 生成器:`tools/render_neko_compose.py`。
- 输出文件:`services/neko/docker-compose.generated.yml`;旧 `services/neko/docker-compose.yml` 保留为兼容模板和人工排障参考。
### 7. 安装验收矩阵
为每次部署固定验收:
- `sudo bash doctor.sh`
- `sudo bash probe-live.sh`
- `python3 tools/verify_live_console.py`
- `pytest`
- `npm --prefix web-console run build`
硬件矩阵:
- x86_64 小主机:Intel/AMD + VAAPI。
- ARM64 开发板:RK3588 / Raspberry Pi 5 / Armbian。
- 安卓:Redroid、USB 手机、无线 ADB。
- 网络:中国大陆单机代理、普通海外网络、换 Wi-Fi 后 mDNS 与 Neko WebRTC。
### 8. 面板信息架构
保持当前 7 个一级页面:
- 总览:硬件/软件/业务摘要、健康检查、关键链路。
- 服务:基础服务安装与运行控制。
- YouTube 无人直播:单频道、多频道 Pro、Neko 工作室。
- TikTok 无人直播:HDMI 输出链路。
- 安卓:Redroid 与真实手机云控。
- 网络:ShellCrash、带宽、出口连通性。
- 设置:配置中心、升级、备份恢复。
## 实施优先级
1. P0-1:安卓真流失败自动降级截图,补诊断。
2. P0-3:YouTube Pro 新建线路后保证配置、进程、Neko 映射一致。
3. P0-2:Neko 基线验收,确认 Tampermonkey 脚本、profile、IP watcher。
4. P1-5:网络带宽统计与代理连通性。
5. P1-4:TikTok HDMI 探测和启动链路。
6. P2-6:动态 Neko compose 已落地;后续重点是按硬件资源给出容量建议和超载保护。
## 当前代码落点
- 一键入口:`install.sh`、`install-all.sh`、`install-core.sh`、`install-live.sh`
- Linux 脚本:`scripts/linux/lib/common.sh`、`scripts/linux/service_ctl.sh`
- 控制平面:`web.py`、`src/control_plane.py`、`src/hub_routes.py`
- 前端面板:`web-console/components/live-product/*`
- Neko:`services/neko/*`、`tools/render_neko_compose.py`、`src/neko_capacity.py`
- 安卓:`src/android_control.py`、`src/scrcpy_stream.py`、`src/redroid_control.py`
- YouTube Pro:`src/youtube_pro_runtime.py`、`web-console/lib/youtubeProChannels.ts`

View File

@ -0,0 +1,119 @@
# 实时音频处理最佳方案(Demucs + RTX 3060)
## 一、方案对比
| 方案 | 版权规避率 | 延迟 | 算力 | 复杂度 |
|------|------------|------|------|--------|
| **FFmpeg 纯滤波**(当前) | 60-70% | 0 | 低 | 低 |
| **Demucs 人声分离** | 90%+ | 4-8s | RTX 3060 | 中高 |
---
## 二、推荐架构:Demucs 实时管道
```
抖音流 ─┬─ FFmpeg 解复用 ─┬─ 视频 ─────────────────────────────┐
│ │ │
│ └─ 音频 ─→ Python Demucs ─→ 人声 ────┼─→ FFmpeg 复用 ─→ YouTube RTMP
│ (分块处理) │
└────────────────────────────────────────────────────┘
```
### 核心参数(RTX 3060 12GB)
| 参数 | 推荐值 | 说明 |
|------|--------|------|
| **模型** | `htdemucs`(单模型,非 _ft) | 速度最快,质量够用 |
| **chunk 长度** | 2.5-3 秒 | 延迟 ≈ 2×chunk ≈ 5-6s |
| **overlap** | 0.25 | 减少接缝,质量更好 |
| **shifts** | 0 | 降低算力,实时必需 |
| **segment** | 7.8(默认)或更小 | 显存不足时减小 |
### RTX 3060 算力
- 约 13 TFLOPS,高于 Demucs 实时所需 2 TFLOPS
- 12GB 显存足够 htdemucs(约 6-8GB)
- 预期:**2-4× 实时速度**,可满足直播
---
## 三、实现方式
### 方式 A:Python 自建管道(推荐)
```python
# 伪代码流程
# 1. FFmpeg 从抖音拉流,输出: -vn -acodec pcm_s16le -ar 44100 -ac 1 pipe:1
# 2. 主进程读取音频块(2.5s = 110250 samples @ 44.1kHz)
# 3. 调用 demucs.separate_audio(model, chunk) 得到 vocals
# 4. 人声写入 pipe,FFmpeg 另一进程读取并与视频复用推流
```
**依赖**:
```
demucs
torch
torchaudio
```
**模型加载**:
```python
from demucs.pretrained import get_model
model = get_model('htdemucs') # 单模型,非 htdemucs_ft
```
### 方式 B:GStreamer(若可用)
GStreamer 1.28+ 内置 demucs 元素,CPU 约 8× 实时:
```bash
# 需安装 gst-plugins-rs (含 demucs)
gst-launch-1.0 uridecodebin uri=抖音流 ! audioconvert ! demucs ! ...
```
---
## 四、分块处理要点
1. **重叠**:chunk 之间 25% 重叠,避免接缝
2. **队列**:双缓冲,一块处理时另一块接收
3. **采样率**:Demucs 默认 44100 Hz,与 FFmpeg 输出一致
4. **延迟**:总延迟 ≈ 2 × chunk 长度(约 5-6 秒可接受)
---
## 五、快速验证(离线测试)
```bash
# 安装
pip install demucs torch torchaudio
# 测试 30 秒音频分离速度
demucs -n htdemucs --two-stems=vocals -j 1 test_30s.mp3 -o output/
# 若 30s 在 10s 内完成 → 可实时
```
---
## 六、与当前方案的关系
- **当前**:`douyin_youtube_ffplay.py` 纯 FFmpeg,60-70% 规避率
- **升级**:可新增 `douyin_youtube_demucs.py`,集成 Demucs 管道
- **切换**:通过 config 选择 `mode = ffmpeg` 或 `mode = demucs`
---
## 七、配置建议(config/youtube.ini)
```ini
[youtube]
key = xxx
# 音频模式: ffmpeg | demucs
; audio_mode = ffmpeg
# Demucs 专用
; demucs_chunk = 2.5
; demucs_model = htdemucs
```

View File

@ -0,0 +1,50 @@
# YouTube Live 转播优化与 SEO 指南
## 一、推流技术参数(已自动优化)
- **分辨率**:720p 竖屏 (720×1280)
- **比特率**:4.5 Mbps(可在 config/youtube.ini 的 bitrate 调整)
- **关键帧**:2 秒(符合 YouTube 推荐)
- **音频**:AAC 128kbps 48kHz 立体声
- **协议**:RTMPS 加密推流(推荐)
- **防版权**:开源音频处理链(降噪 + 带通 + EQ + 相位扰动)
## 二、YouTube 直播 SEO 与推荐权重
直播标题、描述、标签在 **YouTube 工作室** 创建直播时设置,推流程序无法修改。以下为提升推荐权重的建议:
### 标题(前 60 字最关键)
- 主关键词放前面,如:`LIVE 摆摊日常 | 路边直播`
- 可加实时感词汇:LIVE、直播、实时、正在直播
- 避免堆砌关键词,保持可读性
### 描述(前 125 字影响搜索)
- 首段包含主关键词和内容概要
- 可说明:转播自抖音、直播内容类型、时间等
### 标签
- 5–15 个相关标签,如:live stream, 摆摊, 路边直播, 抖音转播
- 与标题、描述语义一致
### 算法相关因素
- **观看时长**:用户停留越久,推荐越高
- **互动**:点赞、评论、分享
- **画质与音质**:清晰稳定的流有助于留存
## 三、config/youtube.ini 配置说明
| 配置项 | 说明 | 示例 |
|--------|------|------|
| key | 必填,YouTube stream key | key = xxxx-xxxx-xxxx |
| rtmps | 是否用 RTMPS(默认是) | rtmps = 否 |
| bitrate | 视频比特率 kbps | bitrate = 4500 |
## 四、稳定性建议
1. 网络:上行带宽 ≥ 6 Mbps,建议有线
2. 推流前在 YouTube 工作室完成标题、描述、标签设置
3. 定期检查 config/youtube.ini 中的 stream key 是否有效

View File

@ -0,0 +1,88 @@
# EasyTier 组网运维记录
EasyTier 可作为 WireGuard 的补充方案,用于 NAT 穿透、P2P 优先连接和 TCP/KCP 兜底。当前生产访问 Neko 优先使用 WireGuard 腾讯云中继;EasyTier 保留为备用和实验链路。
## 适用场景
- 两端 NAT 条件较好,希望优先 P2P 直连。
- WireGuard Endpoint 被运营商或本地代理栈影响,需要另一条覆盖网络。
- 临时排查 Neko、ShellCrash、Windows 远控链路时,作为旁路验证。
不建议把 EasyTier 和 WireGuard 同时承担同一个网段的默认路由。两者共存时,只让其中一个负责 `10.88.0.0/24` 或 Neko 访问网段,另一条链路保持禁用路由或使用不同虚拟网段。
## 推荐参数
优先使用 UDP/P2P,必要时打开 KCP 或 TCP 兜底:
```toml
instance_name = "d2ypp2-neko"
ipv4 = "10.88.0.2"
dhcp = false
listeners = [
"udp://0.0.0.0:11010",
"tcp://0.0.0.0:11010"
]
rpc_portal = "127.0.0.1:15888"
enable_kcp_proxy = true
disable_p2p = false
```
Windows 端使用独立节点名和地址,例如:
```toml
instance_name = "d2ypp2-windows"
ipv4 = "10.88.0.6"
dhcp = false
peers = ["udp://<server>:11010", "tcp://<server>:11010"]
enable_kcp_proxy = true
```
## 端口
建议放行:
- `11010/udp`:P2P 和 UDP 中继。
- `11010/tcp`:TCP 兜底。
- `11011/udp`:如果拆分控制/数据端口,可作为第二监听端口。
如走公网中继,云安全组必须同步放行对应 TCP/UDP 端口。
## 与 ShellCrash 共存
ShellCrash/Mihomo TUN 可能劫持默认路由。EasyTier 只应承担覆盖网段路由,不应抢系统默认路由。出现以下现象时,优先查路由表:
- `ping 10.88.0.2` 延迟突然变成美国出口链路。
- Neko HTTP 可打开但 WebRTC 黑屏。
- ShellCrash 代理检测一直卡住。
排查命令:
```bash
ip route
ip addr
ss -lunpt | grep -E '11010|11011'
```
Windows:
```powershell
route print
Get-NetIPInterface -AddressFamily IPv4
```
## 与 WireGuard 的取舍
WireGuard 优点是内核态、稳定、可控,适合固定 VPS 中继和生产访问。EasyTier 优点是 P2P/NAT 穿透能力强,适合网络条件变化时快速试链路。
当前 Neko 生产建议:
- 主链路:WireGuard 腾讯云中继。
- 备用链路:EasyTier,网段不与主链路抢默认路由。
- WebRTC:`NEKO_WEBRTC_NAT1TO1` 必须填客户端实际可达的 Neko 地址;用 EasyTier 访问时填 EasyTier 地址,用 WireGuard 访问时填 WireGuard 地址。
## 常见故障
- 不能 P2P:检查两端 UDP 是否出站可达,必要时开启 KCP/TCP fallback。
- 能 ping 但 Neko 黑屏:检查 `NEKO_WEBRTC_NAT1TO1` 和 UDP mux/端口段。
- 访问慢:检查是否被本地 TUN 代理绕路;覆盖网络 Endpoint 应走物理网关。
- 代理检测卡住:在 Neko 容器内测试 `curl -x http://host.docker.internal:7890 https://www.youtube.com/`。

View File

@ -0,0 +1,150 @@
# Linux Install Profiles
## Quick Start
Use one of these entrypoints from the repo root on Debian, Ubuntu, or Armbian:
```bash
sudo bash install-hub.sh
sudo bash install-business.sh
sudo bash install-all.sh
```
### Acceptance After Install
On the target Linux node, run the built-in health checks:
```bash
sudo bash doctor.sh
sudo bash probe-live.sh
```
From a dev machine, you can also verify the remote node over SSH:
```bash
LIVE_DEPLOY_HOST=192.168.x.x python3 tools/verify_live_console.py
```
The control plane now exposes a structured acceptance report at:
```text
http://127.0.0.1:8001/deploy/check
```
It focuses on the real delivery path for this project:
- `127.0.0.1:8001/health`
- `127.0.0.1:80/health`
- `http://live.local/health`
- `http://live.local:8001/health`
- exported `web-console/out/index.html`
- `config/system-stack.env`
### After `git pull` (no full reinstall)
刷新依赖、重建前端、重启 `live-console` 与 `live-edge`(**不要**为此再跑 `install-all.sh`,除非你要重做整机栈):
```bash
cd /home/orangepi/d2ypp2-src # 或你的克隆路径
sudo bash upgrade-live.sh
```
若仓库只更新了 **`live-console.service` 模板**(例如 `StartLimitIntervalSec`),可单独刷新单元:
```bash
sudo bash refresh-live-unit.sh
```
## What Each Script Does
### `install-hub.sh`
Use this when the Linux device should become the reusable super hub first.
- Creates and refreshes the `live` account
- Installs the shared control plane runtime
- Enables `live.local`
- Creates the default Wi-Fi profile `live / 12345678` when `wlan0` exists
- Installs ShellCrash, WebTTY, Cockpit, File Browser, Homepage, and Netdata
- Installs the Android web panel based on `web-scrcpy`
- Builds the web console and enables `live-console.service`
### `install-business.sh`
Use this when the device should only run the Douyin or YouTube business stack.
- Creates and refreshes the `live` account
- Installs the shared control plane runtime
- Installs ffmpeg, mpv, ADB, Chromium
- Installs the Android web panel based on `web-scrcpy`
- Starts SRS
- Builds the web console and enables `live-console.service`
- Installs **Caddy** `live-edge.service` so **`http://live.local`** (port 80) reverse-proxies to the control plane (same as hub)
- Generates the hardware profile for adaptive ARM or X86 defaults
### `http://live.local` returns 502
502 means the edge proxy reached nothing usable on the upstream port (default `127.0.0.1:8001`).
1. Check the control plane: `sudo systemctl status live-console.service` and `journalctl -u live-console.service -n 80 --no-pager`.
2. Check the edge: `sudo systemctl status live-edge.service` and confirm `config/system-stack.env` **`PORT`** matches what Caddy uses (regenerate with `sudo bash scripts/linux/reinstall_live_edge.sh` from the repo root).
3. Quick probe: `curl -sf http://127.0.0.1:8001/health` — if this fails, fix `live-console` first (Python venv, `web-console/out`, or `scripts/launch.py` errors in the journal).
**Older business installs** (before `install_live_edge_proxy` was included) never installed Caddy; if you still see 502 on port 80, you likely had a prior hub/edge install—run `sudo bash scripts/linux/reinstall_live_edge.sh` after pulling the latest repo.
### Browser: `live.local` — **refused to connect** (not 502)
That means the TCP connection was **rejected or nothing listens** on the address you used (often **port 80** on the box’s IP).
1. On the **device**, run: `sudo bash probe-live.sh` (or `scripts/linux/probe_live_access.sh`) and read the `:80` / `:8001` lines.
2. If **`:8001` works** but **`:80` fails**: `live-edge` (Caddy) is down — `sudo systemctl restart live-edge.service` or `sudo bash scripts/linux/reinstall_live_edge.sh`.
3. If **both fail**: `live-console` is down — `sudo systemctl restart live-console.service` and `journalctl -u live-console.service -n 80`.
4. From a **laptop/phone**, open **`http://<device-LAN-IP>:8001/`** first (same Wi‑Fi). If that works but `http://live.local` does not, the problem is **mDNS** (Windows often needs Bonjour) or you’re not on the same LAN — use the IP bookmark.
5. **Firewall** (nftables/ufw) blocking **80/8001** from Wi‑Fi will also show as “refused” from other hosts while loopback still works.
### PM2:单频道与多频道 Pro(Linux ARM / x86_64)
- **单频道**:在项目根启用一个业务进程即可,例如取消注释 `ecosystem.config.cjs` 里的 `youtube` 或 `tiktok`,执行 `pm2 start ecosystem.config.cjs && pm2 save`。
- **多频道 Pro**:每路直播需要**独立的** `config/youtube.ini` 与 `config/URL_config.ini`(或整份独立工作目录)。为第二路及以后各复制一份目录(或符号链接脚本外的配置),在 PM2 里为每个 app 设置不同的 `cwd`,`name` 与 Web 控制台 Pro 线路建议名一致(如 `youtube2__<channelId>`)。
- **硬件编码**:`sudo python3 scripts/hardware_probe.py --write` 会写入 `config/hardware.env` 与 `hardware-profile.json`;推流侧可选 `LIVE_VIDEO_ENCODER`(RKMPP / V4L2M2M / VA-API / QSV 等,见 `config/hardware.env.example`)。NVIDIA 一般由 `douyin_youtube_ffplay.py` 自动走 NVENC。
- **音频链**:与 GitLab 分支 `ffmpegAudioRMFoode` 中 `douyin_youtube_ffplay.py` 的 FFmpeg 处理思路一致(`fast_audio`、arnndn、EQ 等);当前主线在 Linux 上还包含板载编码探测与推流稳定性增强,以前端无需对齐 Electron 为准。
### `install-all.sh`
Use this when the node should be both the super hub and the livestream business node.
- Runs `install-hub.sh`
- Runs `install-business.sh`
- Reuses shared modules instead of replacing them
## Shared Config
All install profiles read the same shared file:
- `config/system-stack.env`
If the file does not exist, the installer copies:
- `config/system-stack.env.example`
This keeps host identity, ports, Wi-Fi, ShellCrash path, and module toggles centralized.
## Default Access URLs
With the default hostname and ports, a fresh hub exposes:
- `http://live.local:8001` main control plane
- `http://live.local:8001/shellcrash` ShellCrash editor route
- `http://live.local:8001/android` Android device center route
- `http://live.local:7681` WebTTY
- `http://live.local:8082` File Browser, default login `live / 12345678`
- `http://live.local:19999` Netdata
The ShellCrash and Android pages are separate routes on purpose, so they can be bookmarked directly instead of sharing the same tabbed root URL.
## Separation Rules
- The hub profile must keep working without SRS.
- The business profile must keep working without Cockpit, Homepage, File Browser, or Netdata.
- The control plane should show degraded modules as unavailable instead of crashing.
- Every service must be removable by systemd or compose boundaries.

View File

@ -0,0 +1,103 @@
# Super Hub Architecture
## Goal
Build the ARM or X86 node as a reusable Linux super hub instead of a single-purpose
streaming box. The Douyin or YouTube workflow is one optional business module that can
be installed alone or layered on top of the hub later.
## Install Profiles
- `install-hub.sh`
- Base Linux super hub
- Web control plane
- mDNS `live.local`
- Wi-Fi onboarding profile
- ShellCrash
- WebTTY
- Cockpit
- File Browser
- Homepage
- Netdata
- Hardware probe
- `install-business.sh`
- Shared control plane runtime
- ffmpeg, mpv, ADB, Chromium
- SRS
- Hardware probe and adaptive decode defaults
- Douyin or YouTube business orchestration
- `install-all.sh`
- Runs the hub profile first
- Runs the business profile second
- Safe to rerun because the shared pieces are idempotent
## Layers
1. Base Node
- Debian / Ubuntu / Armbian
- `live` user
- mDNS with `live.local`
- Wi-Fi bootstrap
- hardware probe and graceful degradation
2. Control Plane
- FastAPI backend
- Next.js panel
- managed config roots
- service registry and status polling
3. Hub Modules
- ShellCrash
- WebTTY
- Cockpit
- File Browser
- Homepage
- Netdata
- Android Web Panel
4. Business Modules
- Douyin / YouTube relay app
- SRS
- HDMI playback bridge
- Android / ADB integration
- Chromium persistent profile
- Browser-based device control via web-scrcpy
5. Future Modules
- Caddy
- WireGuard
- FRP
- Matrix
- Uptime Kuma
- n8n
- AI and media workloads
## Design Rules
- `install-hub.sh` must never hard-depend on business services such as SRS.
- `install-business.sh` must work on a clean Linux system without requiring the hub profile first.
- If the hub profile already exists, the business profile must reuse it instead of replacing it.
- Each service stays in its own systemd unit or compose file so it can be removed without breaking unrelated modules.
- The control plane edits only managed roots and never exposes arbitrary filesystem write access.
- ARM and X86 share one control plane, then diverge only through the generated hardware profile.
## Current Implementation
- `scripts/linux/lib/common.sh` contains the shared install functions used by every profile.
- `scripts/linux/install_hub.sh` installs the reusable Linux super hub.
- `scripts/linux/install_business.sh` installs the Douyin or YouTube business module.
- `scripts/linux/install_stack.sh` remains as a compatibility entrypoint for `hub`, `business`, and `all`.
- `src/control_plane.py` exposes managed roots, hardware profile loading, and service actions.
- `scripts/hardware_probe.py` generates safe runtime defaults for ARM and X86.
- `services/` keeps dockerized modules isolated instead of merging them into one monolith.
## Recommended Next Modules
- Caddy for unified reverse proxy and TLS
- wg-easy for WireGuard mesh management
- FRP panel for tunnel management
- Uptime Kuma for alerting
- n8n for workflow automation
- Matrix plus Element for messaging and operations collaboration

View File

@ -0,0 +1,92 @@
# wg-easy / WireGuard 组网运维记录
本文档记录无人直播栈当前采用的 WireGuard 中继方案,以及和 Neko、ShellCrash、Windows Mihomo/TUN 共存时的固定处理方式。
## 当前拓扑
- 腾讯云 VPS:`129.204.21.129`,作为中国方向 WireGuard 中继。
- WireGuard 端口:`51820/udp`,云防火墙和系统防火墙都需要放行。
- Neko 主机:`10.88.0.2`。
- Windows 客户端:`10.88.0.6/32`。
- Neko Web:`http://10.88.0.2:9201/`,本地 LAN 和 WireGuard 网络都应能访问。
腾讯云仅负责中继内网段流量,不承载 ShellCrash 代理。Neko 容器内访问 Google/YouTube 仍走 Neko 主机上的 ShellCrash HTTP 代理。
## 2026-06-02 生产校验
- wandaA:`wgeasy` 使用 `Endpoint = 129.204.21.129:51820`,`Address = 10.88.0.4/32`,`MTU = 1360`,`PersistentKeepalive = 25`;切回 `107.172.77.34:51820` 时未握手。
- wandaB:`wgeasy` 使用 `Endpoint = 129.204.21.129:51820`,`Address = 10.88.0.2/32`;到 `10.88.0.1` 的延迟约 25ms。
- Neko 访问优先级:WireGuard `10.88.0.0/24` 优先,frp 公网端口兜底,EasyTier `10.126.126.0/24` 作为备用运维链路。
## 推荐参数
WireGuard peer 推荐:
```ini
MTU = 1360
PersistentKeepalive = 25
Endpoint = 129.204.21.129:51820
```
VPS 内核和链路优化:
```bash
sysctl -w net.core.default_qdisc=fq
sysctl -w net.ipv4.tcp_congestion_control=bbr
sysctl -w net.core.rmem_max=2500000
sysctl -w net.core.wmem_max=2500000
iptables -t mangle -A FORWARD -p tcp --tcp-flags SYN,RST SYN -j TCPMSS --clamp-mss-to-pmtu
```
## Windows 与 Mihomo/TUN 共存
如果 Windows 上有 Mihomo、Clash、ShellCrash TUN 抢默认路由,WireGuard 的 VPS Endpoint 可能被送进代理出口,导致绕路和高延迟。必须给 VPS 公网 IP 加一条物理网关旁路路由:
```powershell
route -p add 129.204.21.129 mask 255.255.255.255 192.168.2.1 metric 1 if 21
```
参数说明:
- `129.204.21.129`:WireGuard VPS Endpoint。
- `192.168.2.1`:Windows 当前物理局域网网关。
- `if 21`:Windows 物理网卡 ifIndex,用 `Get-NetIPInterface -AddressFamily IPv4` 查看。
删除命令:
```powershell
route delete 129.204.21.129
```
## Neko 黑屏和 NAT1TO1
Neko WebRTC 候选地址必须是访问端可达的地址。当前跨 WireGuard 访问时应设置:
```env
NEKO_WEBRTC_NAT1TO1=10.88.0.2
NEKO_WEBRTC_EPR=52101-52199
NEKO_WEBRTC_TCPMUX=52301
NEKO_WEBRTC_UDPMUX=52301
```
不要把旧公网 IP 写入 `NEKO_WEBRTC_NAT1TO1`。源码已调整为:显式填入本机 WireGuard/Tailscale/EasyTier 地址时,Neko LAN watcher 不会再把它覆盖成物理 LAN IP;留空才自动选择物理 LAN IP。
## Web 控制台导入
无人直播 Web 的「网络」模块支持导入 VPS 的 WireGuard `.conf`:
- 配置会保存到 `config/wireguard/imports/<name>.conf`。
- 返回结果会脱敏 `PrivateKey`、`PublicKey`、`PresharedKey`。
- 页面会生成 Windows Endpoint 旁路路由模板。
导入功能只做解析和保存,不直接执行系统级 `wg-quick` 或 Windows 隧道安装命令,避免从 Web 表单执行未审计的网络配置。
## 旧 Endpoint 排障
旧 VPS Endpoint 只保留作排障记录。2026-06-02 校验时,wandaA 指向该端点无法握手,不应作为生产首选:
```ini
Endpoint = 107.172.77.34:51820
```
只有确认旧 VPS 的 wg-easy 容器、UDP `51820` 入站、防火墙和客户端出口都正常后,才临时切换到该端点。同时删除 Windows 上指向腾讯云的持久路由,或改成旧 Endpoint 对应的物理旁路路由。

4
d2ypp2/doctor.sh Normal file
View File

@ -0,0 +1,4 @@
#!/usr/bin/env bash
set -euo pipefail
ROOT_DIR="$(cd "$(dirname "$0")" && pwd)"
exec bash "$ROOT_DIR/live-platform/scripts/doctor.sh" "$@"

View File

@ -0,0 +1,978 @@
# douyin_youtube_ffplay.py
# Linux:仓库内推流实现,编码由 config/hardware.env(LIVE_VIDEO_ENCODER)与可选 NVENC 探测决定。
import queue
import unicodedata
import platform
import traceback
import time
import datetime
import subprocess
import threading
import re
import os
import glob
import configparser
import socket
import shutil
from urllib.parse import urlparse
from src.youtube_runtime import resolve_live_video_encoder
class StreamEnded(Exception):
"""主播真实下播的专用异常"""
pass
_FFMPEG_STATS_PERIOD_OK: dict[str, bool] = {}
_FFMPEG_FILTERS_CACHE: dict[str, str] = {}
_FFMPEG_STATIC_CACHE: dict[str, bool] = {}
_FFMPEG_PROTOCOLS_CACHE: dict[str, str] = {}
def _ffmpeg_display_name(ffmpeg_bin: str) -> str:
return ffmpeg_bin or "ffmpeg"
def _ffmpeg_resolved_path(ffmpeg_bin: str) -> str:
ffmpeg_bin = (ffmpeg_bin or "ffmpeg").strip()
if os.path.sep in ffmpeg_bin or (os.path.altsep and os.path.altsep in ffmpeg_bin):
return ffmpeg_bin
return shutil.which(ffmpeg_bin) or ffmpeg_bin
def _ffmpeg_supports_stats_period(ffmpeg_bin: str = "ffmpeg") -> bool:
key = _ffmpeg_resolved_path(ffmpeg_bin)
if key in _FFMPEG_STATS_PERIOD_OK:
return _FFMPEG_STATS_PERIOD_OK[key]
try:
r = subprocess.run(
[ffmpeg_bin, "-hide_banner", "-h", "full"],
capture_output=True,
text=True,
timeout=30,
)
blob = (r.stdout or "") + (r.stderr or "")
ok = "-stats_period" in blob
except FileNotFoundError:
_FFMPEG_STATS_PERIOD_OK[key] = False
raise RuntimeError("未找到 ffmpeg,请先安装。") from None
except Exception as e:
print(f"[WARN] 无法检测 {_ffmpeg_display_name(ffmpeg_bin)} 是否支持 -stats_period: {e}")
ok = True
_FFMPEG_STATS_PERIOD_OK[key] = ok
return ok
def _ffmpeg_stats_args(ffmpeg_bin: str = "ffmpeg") -> list[str]:
if _ffmpeg_supports_stats_period(ffmpeg_bin):
return ["-stats", "-stats_period", "1"]
print(f"[WARN] {_ffmpeg_display_name(ffmpeg_bin)} 不支持 -stats_period,已降级为 -stats")
return ["-stats"]
def _require_ffmpeg_stats_period(ffmpeg_bin: str = "ffmpeg") -> None:
"""推流依赖 -stats_period(ffmpeg 约 4.4+);Debian 11 默认 4.3 需升级。"""
if _ffmpeg_supports_stats_period(ffmpeg_bin):
return
raise RuntimeError(
"ffmpeg 不支持 -stats_period(需约 4.4+)。板端执行: sudo bash scripts/linux/upgrade_ffmpeg_newer.sh"
)
def _ffmpeg_filters(ffmpeg_bin: str = "ffmpeg") -> str:
key = _ffmpeg_resolved_path(ffmpeg_bin)
if key in _FFMPEG_FILTERS_CACHE:
return _FFMPEG_FILTERS_CACHE[key]
try:
r = subprocess.run(
[ffmpeg_bin, "-hide_banner", "-filters"],
capture_output=True,
text=True,
timeout=8,
)
blob = (r.stdout or "") + (r.stderr or "")
except Exception as e:
print(f"[WARN] 无法检测 {_ffmpeg_display_name(ffmpeg_bin)} filters: {e}")
blob = ""
_FFMPEG_FILTERS_CACHE[key] = blob
return blob
def _ffmpeg_has_filter(ffmpeg_bin: str, name: str) -> bool:
blob = _ffmpeg_filters(ffmpeg_bin)
return bool(re.search(rf"(^|\s){re.escape(name)}\s", blob))
def sanitize_title(text: str, max_len: int = 120) -> str:
if not text:
return ""
text = unicodedata.normalize("NFKC", text)
text = ''.join(ch for ch in text if unicodedata.category(ch)[0] != 'C')
text = ''.join(ch for ch in text if ord(ch) <= 0xFFFF)
return text.strip()[:max_len]
def _stderr_reader_thread(proc, q):
try:
while True:
line = proc.stderr.readline()
if not line:
break
q.put(line)
except Exception as e:
try:
q.put(f"__ERR__READER__:{e}")
except Exception:
pass
finally:
try:
q.put(None)
except Exception:
pass
def cleanup_proc(proc):
try:
if proc and proc.poll() is None:
try:
proc.terminate()
proc.wait(timeout=5)
except Exception:
if proc.poll() is None:
try:
proc.kill()
except Exception:
pass
except Exception:
pass
def _live_pm2_name() -> str:
return (os.environ.get("LIVE_PM2_PROCESS_NAME") or os.environ.get("PM2_SERVICE_NAME") or "").strip()
def _resolve_youtube_push_config_file(config_file: str | None = None, *, base_dir: str | None = None) -> str:
root_dir = os.path.abspath(base_dir or os.path.dirname(os.path.abspath(__file__)))
if config_file:
cfg = str(config_file).strip()
if cfg:
return cfg if os.path.isabs(cfg) else os.path.join(root_dir, cfg)
legacy = os.path.join(root_dir, "config", "youtube.ini")
pm2 = _live_pm2_name()
if pm2:
low = pm2.lower()
if low.startswith("youtube") or low.startswith("douyin_youtube"):
safe = re.sub(r"[^a-zA-Z0-9_.-]", "_", pm2)
managed = os.path.join(root_dir, "config", f"youtube.{safe}.ini")
if os.path.isfile(managed):
return managed
return legacy
def _load_youtube_push_settings(config_file: str) -> dict[str, str | bool]:
settings: dict[str, str | bool] = {
"use_rtmps": True,
"b_v": "4000k",
"maxrate": "4500k",
"bufsize": "8000k",
"stream_key": "",
"fast_audio": False,
}
if not os.path.exists(config_file):
return settings
config = configparser.ConfigParser()
config.read(config_file, encoding="utf-8-sig")
if not config.has_section("youtube"):
return settings
for k, v in config.items("youtube"):
v = (v or "").strip()
if k == "rtmps" and v.lower() in ("0", "false", "否"):
settings["use_rtmps"] = False
elif k == "fast_audio":
settings["fast_audio"] = v.lower() in ("1", "true", "yes", "是", "开", "on")
elif k == "bitrate" and v:
try:
n = int(v)
settings["b_v"] = f"{n}k"
settings["maxrate"] = f"{min(n * 12 // 10, 8000)}k"
settings["bufsize"] = f"{n * 2}k"
except ValueError:
pass
elif (k == "key" or k == "stream_key") and v and not v.startswith("#"):
settings["stream_key"] = v
return settings
def _is_local_tcp_open(host: str, port: int, timeout: float = 0.35) -> bool:
try:
with socket.create_connection((host, port), timeout=timeout):
return True
except OSError:
return False
def _redact_proxy_url(value: str) -> str:
return re.sub(r"(://[^:/@\s]+:)[^@/\s]+(@)", r"\1<redacted>\2", value)
def _is_disabled_value(value: str) -> bool:
return (value or "").strip().lower() in {"0", "false", "no", "off", "none", "direct"}
def _normalize_push_proxy_mode(configured: str | None = None) -> str:
value = (
configured
or os.environ.get("YOUTUBE_PUSH_PROXY_MODE")
or os.environ.get("LIVE_YOUTUBE_PUSH_PROXY_MODE")
or "auto"
)
low = (value or "").strip().lower()
if low in {"0", "false", "no", "off", "none", "direct"}:
return "off"
if low in {"env", "environment", "http_proxy", "https_proxy"}:
return "env"
if low in {"proxychains", "proxychains4", "chain"}:
return "proxychains"
return "auto"
def _resolve_youtube_push_proxy(configured: str | None = None) -> str:
candidates = [
configured,
os.environ.get("YOUTUBE_PUSH_PROXY"),
os.environ.get("LIVE_YOUTUBE_PUSH_PROXY"),
os.environ.get("https_proxy"),
os.environ.get("http_proxy"),
os.environ.get("HTTPS_PROXY"),
os.environ.get("HTTP_PROXY"),
]
for value in candidates:
value = (value or "").strip()
if _is_disabled_value(value):
return ""
if value:
return value
auto = os.environ.get("YOUTUBE_PUSH_PROXY_AUTO", "1").strip().lower()
if auto not in {"0", "false", "no", "off"} and _is_local_tcp_open("127.0.0.1", 7890):
return "http://127.0.0.1:7890"
return ""
def _ffmpeg_env_with_push_proxy(push_proxy: str) -> dict[str, str] | None:
push_proxy = (push_proxy or "").strip()
if not push_proxy:
return None
env = os.environ.copy()
for key in ("http_proxy", "https_proxy", "all_proxy", "HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY"):
env[key] = push_proxy
return env
def _should_use_proxychains(push_proxy: str, proxy_mode: str = "auto") -> bool:
if not push_proxy:
return False
mode = _normalize_push_proxy_mode(proxy_mode)
if mode in {"off", "env"}:
return False
return bool(shutil.which("proxychains4"))
def _proxychains_proxy_line(push_proxy: str) -> str | None:
value = (push_proxy or "").strip()
if not value:
return None
parsed = urlparse(value if "://" in value else f"socks5://{value}")
host = parsed.hostname
port = parsed.port
if not host or not port:
return None
scheme = (parsed.scheme or "socks5").lower()
if scheme in {"socks", "socks5", "socks5h"}:
proxy_type = "socks5"
elif scheme == "socks4":
proxy_type = "socks4"
elif scheme in {"http", "https"}:
proxy_type = "http"
else:
return None
parts = [proxy_type, host, str(port)]
if parsed.username:
parts.append(parsed.username)
if parsed.password:
parts.append(parsed.password)
return " ".join(parts)
def _proxychains_config_for_push(push_proxy: str) -> str | None:
explicit = (
os.environ.get("YOUTUBE_PROXYCHAINS_CONF")
or os.environ.get("LIVE_YOUTUBE_PROXYCHAINS_CONF")
or ""
).strip()
if explicit and os.path.isfile(explicit):
return explicit
proxy_line = _proxychains_proxy_line(push_proxy)
if proxy_line:
root = os.path.dirname(os.path.abspath(__file__))
runtime_dir = os.path.join(root, ".process_runner")
try:
os.makedirs(runtime_dir, exist_ok=True)
conf = os.path.join(runtime_dir, "proxychains-youtube.conf")
with open(conf, "w", encoding="utf-8") as fh:
fh.write(
"strict_chain\n"
"proxy_dns\n"
"tcp_read_time_out 30000\n"
"tcp_connect_time_out 8000\n\n"
"[ProxyList]\n"
f"{proxy_line}\n"
)
try:
os.chmod(conf, 0o600)
except OSError:
pass
return conf
except OSError as e:
print(f"[WARN] 无法写入 proxychains runtime 配置: {e}")
conf = os.path.join(os.path.dirname(os.path.abspath(__file__)), "config", "proxychains-youtube.conf")
if os.path.isfile(conf):
return conf
return None
def _ffmpeg_is_static_binary(ffmpeg_bin: str) -> bool:
path = _ffmpeg_resolved_path(ffmpeg_bin)
if path in _FFMPEG_STATIC_CACHE:
return _FFMPEG_STATIC_CACHE[path]
if platform.system().lower() != "linux":
_FFMPEG_STATIC_CACHE[path] = False
return False
ldd = shutil.which("ldd")
if not ldd or not os.path.exists(path):
_FFMPEG_STATIC_CACHE[path] = False
return False
try:
r = subprocess.run([ldd, path], capture_output=True, text=True, timeout=5)
blob = ((r.stdout or "") + (r.stderr or "")).lower()
is_static = "not a dynamic executable" in blob or "statically linked" in blob
except Exception:
is_static = False
_FFMPEG_STATIC_CACHE[path] = is_static
return is_static
def _ffmpeg_protocols(ffmpeg_bin: str) -> str:
key = _ffmpeg_resolved_path(ffmpeg_bin)
if key in _FFMPEG_PROTOCOLS_CACHE:
return _FFMPEG_PROTOCOLS_CACHE[key]
try:
r = subprocess.run(
[ffmpeg_bin, "-hide_banner", "-protocols"],
capture_output=True,
text=True,
timeout=8,
)
blob = (r.stdout or "") + (r.stderr or "")
except Exception:
blob = ""
_FFMPEG_PROTOCOLS_CACHE[key] = blob
return blob
def _ffmpeg_supports_youtube_output(ffmpeg_bin: str) -> bool:
protocols = _ffmpeg_protocols(ffmpeg_bin)
return "rtmp" in protocols and "rtmps" in protocols
def _candidate_ffmpeg_binaries(preferred: str = "ffmpeg") -> list[str]:
raw = [
os.environ.get("YOUTUBE_PUSH_FFMPEG"),
os.environ.get("LIVE_YOUTUBE_PUSH_FFMPEG"),
os.environ.get("FFMPEG_PROXYCHAINS_BIN"),
os.environ.get("LIVE_FFMPEG_BIN"),
os.environ.get("FFMPEG_BIN"),
preferred,
shutil.which(preferred or "ffmpeg"),
shutil.which("ffmpeg"),
"/usr/bin/ffmpeg",
"/bin/ffmpeg",
"/usr/local/bin/ffmpeg",
]
out: list[str] = []
seen: set[str] = set()
for item in raw:
value = (item or "").strip()
if not value:
continue
key = _ffmpeg_resolved_path(value)
if key in seen:
continue
seen.add(key)
out.append(value)
return out
def _resolve_youtube_push_ffmpeg(preferred: str, push_proxy: str, proxy_mode: str = "auto") -> tuple[str, str]:
base = (
os.environ.get("LIVE_FFMPEG_BIN")
or os.environ.get("FFMPEG_BIN")
or preferred
or "ffmpeg"
).strip()
if not _should_use_proxychains(push_proxy, proxy_mode):
return base, ""
if not _ffmpeg_is_static_binary(base):
return base, ""
base_path = _ffmpeg_resolved_path(base)
for candidate in _candidate_ffmpeg_binaries(base):
if _ffmpeg_resolved_path(candidate) == base_path:
continue
if not os.path.exists(_ffmpeg_resolved_path(candidate)):
continue
if _ffmpeg_is_static_binary(candidate):
continue
if not _ffmpeg_supports_youtube_output(candidate):
continue
return (
candidate,
f"proxychains4 cannot hook static ffmpeg ({base_path}); using dynamic ffmpeg {candidate}",
)
return (
base,
f"proxychains4 cannot hook static ffmpeg ({base_path}); no dynamic ffmpeg fallback found",
)
def _proxychains_command(ffmpeg_command: list[str], push_proxy: str, proxy_mode: str = "auto") -> list[str] | None:
if not _should_use_proxychains(push_proxy, proxy_mode):
return None
conf = _proxychains_config_for_push(push_proxy)
if not conf:
return None
return ["proxychains4", "-q", "-f", conf, *ffmpeg_command]
def start_douyin_youtube_ffplay(
title: str,
anchor_name: str,
real_url: str,
rec_info: str,
record_name: str,
recording: set,
recording_time_list: dict,
running_list: list,
clear_record_info,
color_obj,
config_file: str | None = None,
):
"""
抖音 → YouTube 推流主函数(单路推流)
只从 config/youtube.ini 读取一个 stream key(取第一个有效值)
"""
# ====================== 读取 YouTube 配置 ======================
config_file = _resolve_youtube_push_config_file(config_file)
rtmps_base = os.environ.get("YOUTUBE_RTMPS_BASE", "rtmps://a.rtmps.youtube.com/live2/")
rtmp_base = os.environ.get("YOUTUBE_RTMP_BASE", "rtmp://a.rtmp.youtube.com/live2/")
use_rtmps = True
# 720p 竖屏,符合 YouTube 推荐:4–6 Mbps、2s 关键帧、AAC 128k
b_v, maxrate, bufsize = "4000k", "4500k", "8000k"
stream_key = None
push_proxy = ""
push_proxy_mode = ""
fast_audio = False # 默认恢复强化音频链,必要时可在配置里开启轻量模式
if os.path.exists(config_file):
config = configparser.ConfigParser()
config.read(config_file, encoding="utf-8-sig")
if config.has_section("youtube"):
for k, v in config.items("youtube"):
v = (v or "").strip()
if k == "rtmps" and v.lower() in ("0", "false", "否"):
use_rtmps = False
elif k in ("rtmps_base", "rtmps_url_base") and v:
rtmps_base = v
elif k in ("rtmp_base", "rtmp_url_base") and v:
rtmp_base = v
elif k in ("push_proxy", "youtube_push_proxy") and v:
push_proxy = v
elif k in ("push_proxy_mode", "youtube_push_proxy_mode") and v:
push_proxy_mode = v
elif k == "fast_audio":
fast_audio = v.lower() in ("1", "true", "yes", "是", "开", "on")
elif k == "bitrate" and v:
try:
n = int(v)
b_v, maxrate, bufsize = f"{n}k", f"{min(n * 12 // 10, 8000)}k", f"{n * 2}k"
except ValueError:
pass
elif (k == "key" or k == "stream_key") and v and not v.startswith("#"):
stream_key = v
if stream_key:
if stream_key.startswith("rtmp://") or stream_key.startswith("rtmps://"):
youtube_rtmp = stream_key
else:
youtube_rtmp = (rtmps_base if use_rtmps else rtmp_base) + stream_key
if youtube_rtmp.startswith("rtmps://a.rtmp.youtube.com/"):
youtube_rtmp = youtube_rtmp.replace(
"rtmps://a.rtmp.youtube.com/",
"rtmps://a.rtmps.youtube.com/",
1,
)
print(f"[INFO] 从 {config_file} 读取 YouTube 推流地址")
else:
raise ValueError(f"请在 {config_file} 中配置 key=你的stream_key")
# ====================== 常量配置 ======================
push_proxy = _resolve_youtube_push_proxy(push_proxy)
push_proxy_mode = _normalize_push_proxy_mode(push_proxy_mode)
if push_proxy:
print(f"[INFO] YouTube push proxy ({push_proxy_mode}): {_redact_proxy_url(push_proxy)}")
ffmpeg_bin, ffmpeg_note = _resolve_youtube_push_ffmpeg("ffmpeg", push_proxy, push_proxy_mode)
if ffmpeg_note:
print(f"[WARN] {ffmpeg_note}")
if ffmpeg_bin != "ffmpeg":
print(f"[INFO] YouTube push ffmpeg: {ffmpeg_bin}")
MAX_RETRY_DELAY = 90
INITIAL_RETRY_DELAY = 3
STDERR_QUEUE_TIMEOUT = 1.0
NO_FRAME_TIMEOUT = 120
START_CHECK_AFTER = 25
STALE_OUTPUT_SECONDS = 40
RECONNECT_DELAY_MAX = 10
# 明确结束 / 平台拒绝:停止整条转推(与瞬时网络错误区分)
TERMINAL_KEYWORDS = [
"live has ended",
"server returned 404",
"ingestion error",
"access denied",
"server returned 403",
"client disconnected",
]
# 瞬时错误:结束当前 ffmpeg 进程后由外层循环退避重连
TRANSIENT_KEYWORDS = [
"connection reset by peer",
"failed to write trailer",
"invalid data found",
"server returned 500",
"packet too short",
"no route to host",
"connection timed out",
"connection refused",
"error writing output",
"broken pipe",
"i/o error",
]
douyin_headers = (
"User-Agent: Mozilla/5.0 (iPhone; CPU iPhone OS 18_1 like Mac OS X) AppleWebKit/605.1.15\r\n"
"Referer: https://live.douyin.com/\r\n"
"Origin: https://live.douyin.com\r\n"
)
# ====================== 标题处理 ======================
timestamp_str = time.strftime("%Y-%m-%d_%H-%M-%S", time.localtime())
clean_title = sanitize_title(title)
stream_title = sanitize_title(f"{anchor_name}{('_' + clean_title) if clean_title else ''}_{timestamp_str}")
print(f"[INFO] {rec_info} 开始推流到 YouTube: {stream_title}")
# ====================== 视频编码:hardware.env(ARM)→ NVENC → libx264 ======================
def _load_simple_env(path: str) -> dict[str, str]:
out: dict[str, str] = {}
if not os.path.isfile(path):
return out
with open(path, "r", encoding="utf-8-sig", errors="ignore") as fh:
for line in fh:
line = line.strip()
if not line or line.startswith("#") or "=" not in line:
continue
k, _, v = line.partition("=")
key = k.strip()
if key.startswith("#"):
continue
out[key] = v.strip().strip('"').strip("'")
return out
codec_v = "libx264"
video_args = [
"-preset", "ultrafast", "-tune", "zerolatency", "-profile:v", "high", "-level", "4.0",
"-b:v", b_v, "-maxrate", maxrate, "-bufsize", bufsize,
]
_config_dir = os.path.dirname(os.path.abspath(config_file))
_hw_env = _load_simple_env(os.path.join(_config_dir, "hardware.env"))
_want_enc = (_hw_env.get("LIVE_VIDEO_ENCODER") or "").strip()
_hw_enc_active = False
_encoders_blob = ""
_machine = platform.machine().lower()
_vaapi_device = ""
for _candidate in ("/dev/dri/renderD128", "/dev/dri/renderD129", "/dev/dri/renderD130"):
if os.path.exists(_candidate):
_vaapi_device = _candidate
break
def _ffmpeg_encoder_smoke_test(name: str) -> bool:
if not name:
return False
cmd = [
ffmpeg_bin, "-hide_banner", "-loglevel", "error",
"-f", "lavfi", "-i", "testsrc2=size=128x128:rate=1",
"-frames:v", "1", "-an",
]
if name == "h264_vaapi":
if not _vaapi_device:
return False
cmd = [
ffmpeg_bin, "-hide_banner", "-loglevel", "error",
"-vaapi_device", _vaapi_device,
"-f", "lavfi", "-i", "testsrc2=size=128x128:rate=1",
"-vf", "format=nv12,hwupload",
"-frames:v", "1", "-an",
]
cmd += ["-c:v", name, "-f", "null", "-"]
try:
probe = subprocess.run(
cmd,
capture_output=True,
text=True,
timeout=8,
)
except Exception as e:
print(f"[WARN] Encoder smoke test failed for {name}: {e}")
return False
if probe.returncode == 0:
return True
detail = ((probe.stderr or "") + (probe.stdout or "")).strip().splitlines()
suffix = f": {detail[-1][:180]}" if detail else ""
print(f"[WARN] Encoder smoke test rejected {name}{suffix}")
return False
if platform.system().lower() == "linux":
try:
enc = subprocess.run(
[ffmpeg_bin, "-hide_banner", "-encoders"],
capture_output=True,
text=True,
timeout=6,
)
_encoders_blob = (enc.stdout or "") + (enc.stderr or "")
_probe_names: list[str] = []
for _name in ("h264_rkmpp", "h264_v4l2m2m", "h264_vaapi", _want_enc):
if _name and _name.startswith("h264_") and _name in _encoders_blob and _name not in _probe_names:
_probe_names.append(_name)
_usable_encoders = {
_name for _name in _probe_names
if _ffmpeg_encoder_smoke_test(_name)
}
_selected_enc, _enc_note = resolve_live_video_encoder(
_want_enc,
_encoders_blob,
_machine,
has_mpp_service=os.path.exists("/dev/mpp_service"),
has_render_node=bool(_vaapi_device),
has_v4l2_device=bool(glob.glob("/dev/video*")),
usable_encoders=_usable_encoders,
)
if _enc_note:
print(f"[WARN] {_enc_note}")
if _selected_enc:
codec_v = _selected_enc
video_args = ["-b:v", b_v, "-maxrate", maxrate, "-bufsize", bufsize]
_hw_enc_active = True
print(f"[INFO] 使用 config/hardware.env LIVE_VIDEO_ENCODER={codec_v}(板载硬件编码)")
except Exception as e:
print(f"[WARN] LIVE_VIDEO_ENCODER 校验失败: {e}")
if not _hw_enc_active:
try:
if platform.system().lower() == "linux":
check = subprocess.run(["nvidia-smi"], capture_output=True, timeout=5)
if check.returncode == 0:
enc = subprocess.run(
[ffmpeg_bin, "-hide_banner", "-encoders"],
capture_output=True,
text=True,
timeout=5,
)
if "h264_nvenc" in (enc.stdout or ""):
codec_v = "h264_nvenc"
video_args = [
"-profile:v", "high", "-level", "4.0",
"-tune", "ll", "-rc", "cbr", "-b:v", b_v,
"-maxrate", maxrate, "-bufsize", bufsize,
]
print("[INFO] 检测到 NVIDIA GPU → 使用 NVENC 硬件加速")
except Exception as e:
print(f"[WARN] NVENC 检测失败,回退软件编码: {e}")
_filter_threads = "4"
# ====================== 开源音频处理:背景音乐弱化 + 防版权 ======================
_script_dir = os.path.dirname(os.path.abspath(__file__))
_ffmpeg_cwd = None
if fast_audio:
print("[INFO] fast_audio=开:使用轻量音频链")
_af_chain = "afftdn=nf=-26:tn=1,aresample=async=1:first_pts=0"
else:
# 优先 RNNoise(arnndn),无模型则用 afftdn;aphaser 相位扰动可干扰 Content ID 指纹
_arnndn_paths = [
os.path.join(_script_dir, "arnndn-models", "cb.rnnn"),
os.path.join(os.path.dirname(_script_dir), "arnndn-models", "cb.rnnn"),
"arnndn-models/cb.rnnn",
]
_arnndn_model = None
for _p in _arnndn_paths:
if os.path.isfile(_p):
_arnndn_model = os.path.normpath(_p)
break
if _arnndn_model and _ffmpeg_has_filter(ffmpeg_bin, "arnndn"):
print(f"[INFO] 使用 RNNoise 降噪模型: {_arnndn_model}")
_arnndn_base = os.path.dirname(os.path.dirname(os.path.abspath(_arnndn_model)))
_af_denoise = "arnndn=m=arnndn-models/cb.rnnn:mix=0.82,"
_ffmpeg_cwd = _arnndn_base
else:
if _arnndn_model:
print(f"[WARN] {_ffmpeg_display_name(ffmpeg_bin)} 不支持 arnndn,改用 afftdn")
print("[INFO] 未找到 arnndn 模型,使用 afftdn 降噪(可克隆 richardpl/arnndn-models 到 arnndn-models/)")
_af_denoise = "afftdn=nf=-26:tn=1,"
# 强化版:收紧带通 + 频率偏移 + 音高微调 + 多段 EQ + 相位扰动
_freq_shift = "afreqshift=shift=22," if _ffmpeg_has_filter(ffmpeg_bin, "afreqshift") else ""
if not _freq_shift:
print(f"[WARN] {_ffmpeg_display_name(ffmpeg_bin)} 不支持 afreqshift,跳过频率偏移滤镜")
_af_chain = (
_af_denoise
+ "highpass=f=200,lowpass=f=3800,"
+ "equalizer=f=150:width_type=o:width=2.5:g=-14,"
+ "equalizer=f=350:width_type=o:width=2:g=-10,"
+ "equalizer=f=600:width_type=o:width=1.8:g=-8,"
+ "equalizer=f=1000:width_type=o:width=1.5:g=-6,"
+ "equalizer=f=2500:width_type=o:width=1.2:g=-4,"
+ "acompressor=threshold=-26dB:ratio=5:attack=8:release=80:makeup=5,"
+ _freq_shift
+ "asetrate=48000*1.035,aresample=48000,"
+ "aphaser=type=t:decay=0.4:delay=3:speed=0.7,"
+ "volume=1.12,"
+ "aresample=async=1:first_pts=0"
)
_video_mid = ["-vsync", "cfr", "-g", "60", "-keyint_min", "60", "-r", "30",
"-bf", "0", "-sc_threshold", "0"]
if codec_v == "libx264":
_video_mid += ["-x264-params", "force-cfr=1:scenecut=0:open_gop=0:sync-lookahead=0"]
# -re:按源时间戳节奏拉流,避免突发过快;不用 realtime/arealtime(输入抖动时易让 YouTube 判为数据不足)
_vf_pad = (
"fps=30,scale=720:1280:force_original_aspect_ratio=decrease:flags=bilinear,"
"pad=720:1280:(ow-iw)/2:(oh-ih)/2:black"
)
_ffmpeg_pre_input = []
_pix_fmt = "yuv420p"
if codec_v == "h264_vaapi":
if _vaapi_device:
_ffmpeg_pre_input = ["-vaapi_device", _vaapi_device]
_vf_pad = f"{_vf_pad},format=nv12,hwupload"
_pix_fmt = "vaapi"
print(f"[INFO] 使用 VAAPI 设备: {_vaapi_device}")
else:
print("[WARN] h264_vaapi 缺少 /dev/dri/renderD*,回退到 libx264")
codec_v = "libx264"
video_args = [
"-preset", "ultrafast", "-tune", "zerolatency", "-profile:v", "high", "-level", "4.0",
"-b:v", b_v, "-maxrate", maxrate, "-bufsize", bufsize,
]
_hw_enc_active = False
_input_path = os.path.normpath(os.path.expanduser(real_url))
_input_is_file = os.path.isfile(_input_path)
_stats_args = _ffmpeg_stats_args(ffmpeg_bin)
if _input_is_file:
ffmpeg_command = [
ffmpeg_bin, "-y", "-loglevel", "info", "-nostdin",
*_stats_args,
"-fflags", "+genpts+discardcorrupt",
"-err_detect", "ignore_err",
"-thread_queue_size", "2048",
"-filter_threads", _filter_threads,
*_ffmpeg_pre_input,
"-re",
"-i", _input_path,
"-vf", _vf_pad,
"-c:v", codec_v,
*video_args,
*_video_mid,
"-pix_fmt", _pix_fmt,
"-c:a", "aac", "-b:a", "128k", "-ar", "48000", "-ac", "2",
"-af", _af_chain,
"-flags", "+global_header",
"-flvflags", "no_duration_filesize",
"-f", "flv", youtube_rtmp,
]
else:
ffmpeg_command = [
ffmpeg_bin, "-y", "-loglevel", "info", "-nostdin",
*_stats_args,
"-rw_timeout", "50000000",
"-reconnect", "1", "-reconnect_at_eof", "1", "-reconnect_streamed", "1",
"-reconnect_delay_max", str(RECONNECT_DELAY_MAX),
"-fflags", "+genpts+discardcorrupt",
"-err_detect", "ignore_err",
"-max_delay", "500000",
"-thread_queue_size", "2048",
"-filter_threads", _filter_threads,
*_ffmpeg_pre_input,
"-headers", douyin_headers,
"-re",
"-i", real_url,
# bilinear 比 lanczos 轻很多,利于 speed 稳定在 ≥1.0x
"-vf", _vf_pad,
"-c:v", codec_v,
*video_args,
*_video_mid,
"-pix_fmt", _pix_fmt,
"-c:a", "aac", "-b:a", "128k", "-ar", "48000", "-ac", "2",
"-af", _af_chain,
"-flags", "+global_header",
"-flvflags", "no_duration_filesize",
"-f", "flv", youtube_rtmp,
]
proc = None
stderr_q = None
reader_t = None
retry_delay = INITIAL_RETRY_DELAY
try:
while True:
try:
if retry_delay > INITIAL_RETRY_DELAY:
print(f"[WARN] 防风控等待 {retry_delay}s 后重新连接抖音源...")
time.sleep(retry_delay)
cleanup_proc(proc)
stderr_q = queue.Queue()
print(f"[INFO][{datetime.datetime.now():%H:%M:%S}] 启动 YouTube 推流 → {stream_title}")
_popen_kw = dict(
stdin=subprocess.DEVNULL,
stdout=subprocess.DEVNULL,
stderr=subprocess.PIPE,
text=True,
bufsize=1,
universal_newlines=True,
)
if _ffmpeg_cwd:
_popen_kw["cwd"] = _ffmpeg_cwd
ffmpeg_exec = _proxychains_command(ffmpeg_command, push_proxy, push_proxy_mode)
if ffmpeg_exec is None:
ffmpeg_exec = ffmpeg_command
_ffmpeg_env = _ffmpeg_env_with_push_proxy(push_proxy)
if _ffmpeg_env:
_popen_kw["env"] = _ffmpeg_env
proc = subprocess.Popen(ffmpeg_exec, **_popen_kw)
proc.last_out_ts = time.time()
reader_t = threading.Thread(target=_stderr_reader_thread, args=(proc, stderr_q))
reader_t.daemon = True
reader_t.start()
start_time = last_frame_time = time.time()
while True:
try:
try:
line = stderr_q.get(timeout=STDERR_QUEUE_TIMEOUT)
except queue.Empty:
if time.time() - getattr(proc, "last_out_ts", time.time()) > STALE_OUTPUT_SECONDS:
print("[WARN] 长时间无任何日志,强制重启进程")
cleanup_proc(proc)
break
continue
if line is None:
if proc.poll() is not None:
break
continue
line = line.strip()
if line.startswith("__ERR__READER__"):
print(f"[ERROR] stderr reader 异常: {line}")
continue
if line:
proc.last_out_ts = time.time()
print(f"[FFmpeg] {line}")
line_lower = line.lower()
if any(kw in line_lower for kw in TERMINAL_KEYWORDS):
print("[ERROR] 判定直播结束或平台明确拒绝,停止推流")
cleanup_proc(proc)
raise StreamEnded()
if any(kw in line_lower for kw in TRANSIENT_KEYWORDS):
print(f"[WARN] 瞬时错误,将退避重试: {line[:160]}")
cleanup_proc(proc)
retry_delay = min(max(retry_delay, INITIAL_RETRY_DELAY) * 2, MAX_RETRY_DELAY)
break
if re.search(r'frame=\s*\d+', line_lower) or "fps=" in line_lower:
last_frame_time = time.time()
retry_delay = INITIAL_RETRY_DELAY
if time.time() - start_time > START_CHECK_AFTER:
if time.time() - last_frame_time > NO_FRAME_TIMEOUT:
print(f"[WARN] 连续 {NO_FRAME_TIMEOUT}s 无新帧,判定主播已下播")
cleanup_proc(proc)
raise StreamEnded()
except StreamEnded:
raise
except Exception as e:
print(f"[ERROR] 内层异常: {e}")
traceback.print_exc()
cleanup_proc(proc)
retry_delay = min(retry_delay * 2, MAX_RETRY_DELAY)
break
continue
except StreamEnded:
print(f"[INFO] 主播已下播,停止 YouTube 转推 → {record_name}")
break
except Exception as e:
print(f"[ERROR] 外层异常: {e}")
traceback.print_exc()
retry_delay = min(retry_delay * 2, MAX_RETRY_DELAY)
continue
except Exception as e:
print(f"[FATAL] YouTube 推流最外层异常: {e}")
traceback.print_exc()
finally:
cleanup_proc(proc)
try:
recording_time_list.pop(record_name, None)
# 统一由 clear_record_info 维护 running_list / monitoring / url_comments
clear_record_info(record_name, real_url)
except Exception:
pass
color_obj.print_colored(f"[{record_name}] YouTube 推流已彻底停止并清理完毕\n", color_obj.GREEN)
if __name__ == "__main__":
# 兼容旧 PM2/脚本名:实际业务入口为 youtube.py(监控 URL_config + 调用本模块推流)
import runpy
from pathlib import Path
_root = Path(__file__).resolve().parent
runpy.run_path(str(_root / "youtube.py"), run_name="__main__")

View File

@ -0,0 +1,51 @@
/**
* PM2:在项目根执行 `pm2 start ecosystem.config.cjs` 后 `pm2 save`
* web 使用 scripts/launch.py:若缺少 web-console/out 会自动 npm build 再起 uvicorn
*
* 单频道:通常只启一个 youtube.py(或 tiktok.py)+ web。
* 多频道 Pro:同一项目根下按 PM2 名拆分文件:config/youtube.<name>.ini 与 config/URL_config.<name>.ini(控制台保存时自动创建)。
* PM2 进程名须与控制台线路一致(如 youtube2__ch_xxx),并在 env 中设置 LIVE_PM2_PROCESS_NAME 与同名字符串,供 youtube.py 读取正确 ini。
* 音频处理链与 GitLab 分支 ffmpegAudioRMFoode 中 douyin_youtube_ffplay 对齐;Linux ARM/x86 编码由 config/hardware.env 与硬件探测辅助。
*/
const path = require("path");
const root = __dirname;
const py = process.env.PYTHON || "python3";
module.exports = {
apps: [
{
name: "web",
cwd: root,
script: path.join(root, "scripts", "launch.py"),
interpreter: py,
env: {
HOST: "0.0.0.0",
PORT: process.env.PORT || "8001",
},
},
// —— 单频道直播(Linux ARM/x86 通用,二选一或按需启用)——
// {
// name: "youtube",
// cwd: root,
// script: "youtube.py",
// interpreter: py,
// env: { PYTHONUNBUFFERED: "1" },
// },
// {
// name: "tiktok",
// cwd: root,
// script: "tiktok.py",
// interpreter: py,
// env: { PYTHONUNBUFFERED: "1" },
// },
// —— Pro 第二路示例:与 web 控制台「多频道 Pro」线路 PM2 名一致 ——
// {
// name: "youtube2__lane2",
// cwd: root,
// script: "youtube.py",
// interpreter: py,
// env: { PYTHONUNBUFFERED: "1", LIVE_PM2_PROCESS_NAME: "youtube2__lane2" },
// },
// { name: "obs", cwd: root, script: "bash", args: `-lc ${JSON.stringify(path.join(root, "obs.sh"))}` },
],
};

121
d2ypp2/ffmpeg_install.py Normal file
View File

@ -0,0 +1,121 @@
# -*- coding: utf-8 -*-
"""
Author: Hmily
GitHub: https://github.com/ihmily
Copyright (c) 2024 by Hmily, All Rights Reserved.
"""
from __future__ import annotations
import os
import subprocess
import sys
import platform
from src.logger import logger
current_platform = platform.system()
execute_dir = os.path.split(os.path.realpath(sys.argv[0]))[0]
current_env_path = os.environ.get("PATH") or ""
ffmpeg_path = os.path.join(execute_dir, "ffmpeg")
def install_ffmpeg_linux():
is_RHS = True
try:
logger.warning("ffmpeg is not installed.")
logger.debug("Trying to install the stable version of ffmpeg")
result = subprocess.run(['yum', '-y', 'update'], capture_output=True)
if result.returncode != 0:
logger.error("Failed to update package lists using yum.")
return False
result = subprocess.run(['yum', 'install', '-y', 'ffmpeg'], capture_output=True)
if result.returncode == 0:
logger.debug("ffmpeg installation was successful using yum. Restart for changes to take effect.")
return True
logger.error(result.stderr.decode('utf-8').strip())
except FileNotFoundError:
logger.debug("yum command not found, trying to install using apt...")
is_RHS = False
except Exception as e:
logger.error(f"An error occurred while trying to install ffmpeg using yum: {e}")
if not is_RHS:
try:
logger.debug("Trying to install the stable version of ffmpeg for Linux using apt...")
result = subprocess.run(['apt', 'update'], capture_output=True)
if result.returncode != 0:
logger.error("Failed to update package lists using apt")
return False
result = subprocess.run(['apt', 'install', '-y', 'ffmpeg'], capture_output=True)
if result.returncode == 0:
logger.debug("ffmpeg installation was successful using apt. Restart for changes to take effect.")
return True
else:
logger.error(result.stderr.decode('utf-8').strip())
except FileNotFoundError:
logger.error("apt command not found, unable to install ffmpeg. Please manually install ffmpeg by yourself")
except Exception as e:
logger.error(f"An error occurred while trying to install ffmpeg using apt: {e}")
logger.error("Manual installation of ffmpeg is required. Please manually install ffmpeg by yourself.")
return False
def install_ffmpeg() -> bool:
if current_platform == "Linux":
return install_ffmpeg_linux()
logger.debug("ffmpeg 自动安装仅支持 Linux,请使用系统包管理器安装 ffmpeg。")
return False
def ensure_ffmpeg_installed(func):
def wrapper(*args, **kwargs):
try:
result = subprocess.run(['ffmpeg', '-version'], capture_output=True)
version = result.stdout.strip()
if result.returncode == 0 and version:
return func(*args, **kwargs)
except FileNotFoundError:
pass
return False
def wrapped_func(*args, **kwargs):
if sys.version_info >= (3, 7):
res = wrapper(*args, **kwargs)
else:
res = wrapper(*args, **kwargs)
if not res:
install_ffmpeg()
res = wrapper(*args, **kwargs)
if not res:
raise RuntimeError("ffmpeg is not installed.")
return func(*args, **kwargs)
return wrapped_func
def check_ffmpeg_installed() -> bool:
try:
result = subprocess.run(['ffmpeg', '-version'], capture_output=True)
version = result.stdout.strip()
if result.returncode == 0 and version:
return True
except FileNotFoundError:
pass
except OSError as e:
print(f"OSError occurred: {e}. ffmpeg may not be installed correctly or is not available in the system PATH.")
print("Please delete the ffmpeg and try to download and install again.")
except Exception as e:
print(f"An unexpected error occurred: {e}")
return False
def check_ffmpeg() -> bool:
if not check_ffmpeg_installed():
return install_ffmpeg()
return True

32
d2ypp2/i18n.py Normal file
View File

@ -0,0 +1,32 @@
import os
import sys
import gettext
import inspect
import builtins
from pathlib import Path
def init_gettext(locale_dir, locale_name):
gettext.bindtextdomain('zh_CN', locale_dir)
gettext.textdomain('zh_CN')
os.environ['LANG'] = f'{locale_name}.utf8'
return gettext.gettext
execute_dir = os.path.split(os.path.realpath(sys.argv[0]))[0]
if os.path.exists(Path(execute_dir) / '_internal/i18n'):
locale_path = Path(execute_dir) / '_internal/i18n'
else:
locale_path = Path(execute_dir) / 'i18n'
_tr = init_gettext(locale_path, 'zh_CN')
original_print = builtins.print
package_name = 'src'
def translated_print(*args, **kwargs):
for arg in args:
if package_name in inspect.stack()[1].filename:
translated_arg = _tr(str(arg))
else:
translated_arg = str(arg)
original_print(translated_arg, **kwargs)

View File

Binary file not shown.

View File

@ -0,0 +1,85 @@
# DouyinLiveRecorder.
# Copyright (C) 2024 Hmily
# This file is distributed under the same license as the DouyinLiveRecorder package.
#
#, fuzzy
msgid ""
msgstr ""
"Project-Id-Version: 4.0.1\n"
"POT-Creation-Date: 2024-10-20 00:00+0800\n"
"PO-Revision-Date: 2024-11-09 03:05+0800\n"
"Last-Translator: Hmily <EMAIL@ADDRESS>\n"
"Language-Team: Chinese\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"Language: zh_CN\n"
"Plural-Forms: nplurals=1; plural=0;\n"
#: douyinliverecorder/spider.py
msgid "IP banned. Please change device or network."
msgstr "IP被禁止 请更换设备或网络"
msgid "The anchor did not start broadcasting."
msgstr "主播并未开播"
msgid "sooplive platform login successful! Starting to fetch live streaming data..."
msgstr "sooplive平台登录成功!开始获取直播数据..."
msgid "sooplive live stream failed to retrieve, the live stream just ended."
msgstr "sooplive直播获取失败,该直播间刚结束直播"
msgid "sooplive live stream retrieval failed, the live needs 19+, you are not logged in."
msgstr "soop直播获取失败,该直播间需要年龄19+观看,您尚未登录"
msgid "Attempting to log in to the sooplive live streaming platform with your account and password, please ensure it is configured."
msgstr "正在尝试使用您的账号和密码登录soop直播平台,请确保已在config配置文件中配置"
msgid "error message:Please check if the input sooplive live room address is correct."
msgstr "错误信息:请检查输入的sooplive直播间地址是否正确"
msgid "Please check if the FlexTV account and password in the configuration file are correct."
msgstr "请检查配置文件中的FlexTV账号和密码是否正确"
msgid "FlexTV live stream retrieval failed [not logged in]: 19+ live streams are only available for logged-in adults."
msgstr "FlexTV直播获取失败[未登录]: 19+直播需要登录后是成人才可观看"
msgid "Attempting to log in to the FlexTV live streaming platform, please ensure your account and password are correctly filled in the configuration file."
msgstr "正在尝试登录FlexTV直播平台,请确保已在配置文件中填写好您的账号和密码"
msgid "Logging into FlexTV platform..."
msgstr "FlexTV平台登录中..."
msgid "Logged into FlexTV platform successfully! Starting to fetch live streaming data..."
msgstr "FlexTV平台登录成功!开始获取直播数据..."
msgid "Look live currently only supports audio live streaming, not video live streaming!"
msgstr "Look直播暂时只支持音频直播,不支持Look视频直播!"
msgid "Failed to retrieve popkontv live stream [token does not exist or has expired]: Please log in to watch."
msgstr "popkontv直播获取失败[token不存在或者已过期]: 请登录后观看"
msgid "Attempting to log in to the popkontv live streaming platform, please ensure your account and password are correctly filled in the configuration file."
msgstr "正在尝试登录popkontv直播平台,请确保已在配置文件中填写好您的账号和密码"
msgid "Logging into popkontv platform..."
msgstr "popkontv平台登录中..."
msgid "Logged into popkontv platform successfully! Starting to fetch live streaming data..."
msgstr "popkontv平台登录成功!开始获取直播数据..."
msgid "Attempting to log in to TwitCasting..."
msgstr "TwitCasting正在尝试登录..."
msgid "TwitCasting login successful! Starting to fetch data..."
msgstr "TwitCasting 登录成功!开始获取数据..."
msgid "Failed to retrieve TwitCasting data, attempting to log in..."
msgstr "获取TwitCasting数据失败,正在尝试登录..."
msgid "Failed to retrieve live room data, the Huajiao live room address is not fixed, please manually change the address for recording."
msgstr "获取直播间数据失败,花椒直播间地址是非固定的,请手动更换地址进行录制"
msgid "Fetch shopee live data failed, please update the address of the live broadcast room and try again."
msgstr "获取shopee直播间数据失败,请手动更换直播录制地址后重试"

338
d2ypp2/index.html Normal file
View File

@ -0,0 +1,338 @@
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>多进程录制控制台</title>
<style>
:root{--bg:#1a237e;--accent:#283593;--text:#fff;--card:#fff;--card-text:#000}
@media(prefers-color-scheme:dark){:root{--card:#1e1e1e;--card-text:#fff}}
body{margin:0;font-family:system-ui,-apple-system,sans-serif;background:linear-gradient(135deg,var(--bg),#283593,#4a148c);color:var(--text);min-height:100vh;display:flex;justify-content:center;padding:20px;box-sizing:border-box}
.container{max-width:720px;width:100%;background:var(--card);color:var(--card-text);border-radius:12px;padding:24px;box-shadow:0 8px 32px rgba(0,0,0,.4)}
h1{margin:0 0 24px;font-size:1.6em;display:flex;align-items:center;gap:12px}
#processSelect{padding:8px;border-radius:8px;border:1px solid #ddd;font-size:1em}
#statusIndicator{font-size:1.2em;font-weight:600}
h2{margin:24px 0 12px;font-size:1.4em}
h3{margin:16px 0 8px;font-size:1.2em}
input,button,textarea{width:100%;padding:12px;margin:8px 0;border-radius:8px;border:none;box-sizing:border-box;font-size:1em}
input,textarea{background:#f5f5f5;color:#000;border:1px solid #ddd;font-family:monospace;overflow:hidden;resize:none;min-height:100px}
button{background:var(--accent);color:#fff;cursor:pointer;font-weight:600;transition:.2s}
button:hover{background:#1a237e}
button.loading{opacity:.7;pointer-events:none}
button.loading::after{content:" ⏳";animation:spin 1s linear infinite}
#pm2Buttons{display:grid;grid-template-columns:repeat(auto-fit,minmax(100px,1fr));gap:8px;margin:12px 0}
#pm2Log{background:#000;color:#0f0;padding:12px;height:320px;overflow-y:auto;font-family:monospace;font-size:.9em;border-radius:8px;white-space:pre-wrap;word-break:break-all}
.configButtons{display:grid;grid-template-columns:repeat(auto-fit,minmax(120px,1fr));gap:8px;margin:12px 0}
.configStatus{color:#0f0;margin-top:8px;font-family:monospace;font-size:0.9em}
#obsAddress{background:#f0f0f0;padding:12px;border-radius:8px;font-family:monospace;font-size:1.1em;margin:8px 0;word-break:break-all}
@keyframes spin{to{transform:rotate(360deg)}}
</style>
</head>
<body>
<div class="container">
<h1>
进程:
<select id="processSelect"></select>
<span id="statusIndicator">⚪ 加载中...</span>
</h1>
<p id="processScriptNote" style="font-size:0.88em;margin:-12px 0 20px;opacity:0.88;font-family:ui-monospace,monospace"></p>
<!-- YouTube 专属配置(仅 youtube 时显示) -->
<div id="youtubeOnlySection" style="display:none;">
<h2>YouTube 配置编辑 (youtube.ini)</h2>
<div class="configEditor">
<h3>youtube.ini</h3>
<textarea id="youtubeConfig"></textarea>
<div class="configButtons">
<button id="loadYoutubeBtn">加载配置</button>
<button id="saveYoutubeBtn">保存配置</button>
</div>
<pre class="configStatus" id="youtubeStatus">就绪</pre>
</div>
</div>
<!-- URL_config.ini 共享配置(youtube 或 tiktok 时显示) -->
<div id="urlConfigSection" style="display:none;">
<h2>URL 配置编辑 (URL_config.ini)</h2>
<div class="configEditor">
<h3>URL_config.ini</h3>
<textarea id="urlConfig"></textarea>
<div class="configButtons">
<button id="loadUrlBtn">加载配置</button>
<button id="saveUrlBtn">保存配置</button>
</div>
<pre class="configStatus" id="urlStatus">就绪</pre>
</div>
</div>
<!-- OBS 推流地址区(仅 obs 时显示) -->
<div id="obsSection" style="display:none;">
<h2>OBS 直播推流地址</h2>
<p>请在 OBS → 设置 → 推流 → 服务选择“自定义”,服务器填写以下地址:</p>
<div id="obsAddress">srt://live.local:10080/live/obs</div>
<p>密钥(Stream Key)留空即可。</p>
</div>
<h2>PM2 进程控制</h2>
<div id="pm2Buttons">
<button data-action="start">启动</button>
<button data-action="stop">停止</button>
<button data-action="restart">重启</button>
<button data-action="status">手动刷新</button>
</div>
<h2>实时日志(自动每秒刷新)</h2>
<pre id="pm2Log">正在加载状态与日志...</pre>
</div>
<script>
/** 进程列表来自 GET /process_monitor(web.py 扫描根目录);PM2 名 = 脚本主文件名(无扩展名)。 */
let PROCESS_MONITOR = [];
function pm2NameFromScript(script) {
const base = String(script).split(/[/\\]/).pop() || '';
const i = base.lastIndexOf('.');
return i > 0 ? base.slice(0, i) : base;
}
function isYoutubeScript(script) {
if (!/\.py$/i.test(script)) return false;
var s = pm2NameFromScript(script).toLowerCase();
return s.startsWith('youtube') || s.startsWith('douyin_youtube');
}
function isTiktokScript(script) {
return /\.py$/i.test(script) && pm2NameFromScript(script).startsWith('tiktok');
}
function isObsScript(script) {
return pm2NameFromScript(script).startsWith('obs');
}
async function loadProcessMonitor() {
const res = await fetch('/process_monitor');
if (!res.ok) throw new Error(String(res.status));
const data = await res.json();
const entries = data.entries || [];
PROCESS_MONITOR = entries.map((e) => ({
script: e.script,
label: e.label || e.script,
pm2: e.pm2 || pm2NameFromScript(e.script),
}));
}
function getEntryByPm2(name) {
return PROCESS_MONITOR.find((e) => e.pm2 === name) || null;
}
function fillProcessSelect() {
processSelect.innerHTML = '';
PROCESS_MONITOR.forEach((e) => {
const opt = document.createElement('option');
opt.value = e.pm2;
opt.textContent = `${e.label}(${e.script})`;
processSelect.appendChild(opt);
});
}
const logEl = document.getElementById('pm2Log');
const statusIndicator = document.getElementById('statusIndicator');
const processSelect = document.getElementById('processSelect');
let currentProcess = '';
// 各专属区域
const youtubeOnlySection = document.getElementById('youtubeOnlySection');
const urlConfigSection = document.getElementById('urlConfigSection');
const obsSection = document.getElementById('obsSection');
// youtube.ini 编辑(youtube 专属)
const youtubeConfig = document.getElementById('youtubeConfig');
const loadYoutubeBtn = document.getElementById('loadYoutubeBtn');
const saveYoutubeBtn = document.getElementById('saveYoutubeBtn');
const youtubeStatus = document.getElementById('youtubeStatus');
// URL_config.ini 编辑(youtube 和 tiktok 共享)
const urlConfig = document.getElementById('urlConfig');
const loadUrlBtn = document.getElementById('loadUrlBtn');
const saveUrlBtn = document.getElementById('saveUrlBtn');
const urlStatus = document.getElementById('urlStatus');
function refreshProcessScriptNote() {
const el = document.getElementById('processScriptNote');
const ent = getEntryByPm2(currentProcess);
el.textContent = ent ? `脚本: ${ent.script} · PM2 名: ${ent.pm2}` : '';
}
processSelect.addEventListener('change', () => {
currentProcess = processSelect.value;
refreshProcessScriptNote();
fetchStatus();
updateSectionsVisibility();
});
function updateSectionsVisibility() {
const ent = getEntryByPm2(currentProcess);
const s = ent ? ent.script : '';
const isYoutube = ent && isYoutubeScript(s);
const isTiktok = ent && isTiktokScript(s);
const isObs = ent && isObsScript(s);
youtubeOnlySection.style.display = isYoutube ? 'block' : 'none';
urlConfigSection.style.display = (isYoutube || isTiktok) ? 'block' : 'none';
obsSection.style.display = isObs ? 'block' : 'none';
if (isYoutube) loadYoutubeConfig();
if (isYoutube || isTiktok) loadUrlConfig();
}
// textarea 高度自适应
function autoResize(textarea) {
textarea.style.height = 'auto';
textarea.style.height = (textarea.scrollHeight) + 'px';
}
[youtubeConfig, urlConfig].forEach(ta => {
ta.addEventListener('input', () => autoResize(ta));
autoResize(ta);
});
// 通用加载/保存
async function loadConfig(endpoint, textarea, statusEl) {
statusEl.textContent = '加载中...';
try {
const res = await fetch(`${endpoint}?process=${currentProcess}`);
if (!res.ok) throw new Error(`HTTP ${res.status}`);
const data = await res.json();
textarea.value = data.content || '';
autoResize(textarea);
statusEl.textContent = '加载成功';
} catch (err) {
statusEl.textContent = `加载失败: ${err.message}`;
}
}
async function saveConfig(endpoint, textarea, statusEl, saveBtn) {
statusEl.textContent = '保存中...';
const content = textarea.value;
try {
const res = await fetch(`${endpoint}?process=${currentProcess}`, {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({content})
});
if (!res.ok) throw new Error(`HTTP ${res.status}`);
const data = await res.json();
statusEl.textContent = data.message || '保存成功';
} catch (err) {
statusEl.textContent = `保存失败: ${err.message}`;
} finally {
if (saveBtn) saveBtn.classList.remove('loading');
}
}
// youtube.ini(仅 youtube)
function loadYoutubeConfig() { loadConfig('/get_config', youtubeConfig, youtubeStatus); }
function saveYoutubeConfig() {
saveYoutubeBtn.classList.add('loading');
saveConfig('/save_config', youtubeConfig, youtubeStatus, saveYoutubeBtn);
}
loadYoutubeBtn.onclick = loadYoutubeConfig;
saveYoutubeBtn.onclick = saveYoutubeConfig;
// URL_config.ini(youtube 和 tiktok 共享)
function loadUrlConfig() { loadConfig('/get_url_config', urlConfig, urlStatus); }
function saveUrlConfig() {
saveUrlBtn.classList.add('loading');
saveConfig('/save_url_config', urlConfig, urlStatus, saveUrlBtn);
}
loadUrlBtn.onclick = loadUrlConfig;
saveUrlBtn.onclick = saveUrlConfig;
function scrollLog(){logEl.scrollTop = logEl.scrollHeight}
function updateStatus(process_status){
let emoji = '⚪', text = '未知';
if(process_status === 'online'){ emoji = '🟢'; text = '运行中'; }
else if(process_status === 'stopped'){ emoji = '🔴'; text = '已停止'; }
else if(process_status === 'errored'){ emoji = '🔴'; text = '错误'; }
else if(process_status === 'launching' || process_status === 'starting'){ emoji = '🟡'; text = '启动中'; }
else if(process_status === 'waiting restart'){ emoji = '🟡'; text = '等待重启'; }
else if(process_status === 'not_found'){ emoji = '❌'; text = '未注册到 PM2'; }
statusIndicator.innerHTML = `${emoji} ${text}`;
}
async function pm2Action(action){
const btn = document.querySelector(`[data-action="${action}"]`);
if(btn) btn.classList.add('loading');
const url = `/${action}?process=${currentProcess}`;
try{
const res = await fetch(url);
if(!res.ok) throw new Error('网络错误');
const data = await res.json();
if(action === 'status'){
updateStatus(data.process_status);
let logText = `【PM2 全状态表格】(${new Date().toLocaleTimeString()})\n${data.raw_status}\n\n`;
if(data.process_status === 'not_found'){
const ent = getEntryByPm2(currentProcess);
const hint = ent ? `${ent.script}(PM2 名: ${ent.pm2})` : currentProcess;
logText += `【提示】未在 PM2 中找到: ${hint}\n`;
}else{
logText += `【实时输出日志】`;
if(data.recent_log.includes('不存在') || data.recent_log.includes('无日志路径')){
logText += `\n${data.recent_log}`;
}else{
logText += `(最近 ${data.recent_log.trim().split('\n').length} 行)\n${data.recent_log || '无新输出'}`;
}
logText += `\n\n【实时错误日志】`;
if(data.recent_error.includes('不存在') || data.recent_error.includes('无日志路径')){
logText += `\n${data.recent_error}`;
}else{
logText += `(最近 ${data.recent_error.trim().split('\n').length} 行)\n${data.recent_error || '无错误'}`;
}
}
logEl.textContent = logText;
scrollLog();
}else{
const ent = getEntryByPm2(currentProcess);
const who = ent ? `${ent.script} (${ent.pm2})` : currentProcess;
logEl.textContent = `操作: ${action} → ${who}\n${data.output || '成功'}\n\n正在刷新状态...`;
scrollLog();
setTimeout(fetchStatus, 1500);
}
}catch(err){
logEl.textContent = `请求失败: ${err.message}`;
scrollLog();
updateStatus('unknown');
}finally{
if(btn) btn.classList.remove('loading');
}
}
async function fetchStatus(){ pm2Action('status'); }
// 按钮事件委托
document.getElementById('pm2Buttons').addEventListener('click', e=>{
const btn = e.target.closest('button');
if(!btn) return;
const action = btn.dataset.action;
if(action && action !== 'status') pm2Action(action);
});
(async function boot() {
try {
await loadProcessMonitor();
} catch (e) {
logEl.textContent = '无法加载 /process_monitor(请用本服务打开的页面访问,或检查 web.py / uvicorn 是否已启动)\n' + (e && e.message ? e.message : '');
statusIndicator.textContent = '❌ 未连接';
return;
}
if (!PROCESS_MONITOR.length) {
logEl.textContent = '未发现任何入口脚本(项目根应有 tiktok*.py / youtube*.py / douyin_youtube*.py / obs 脚本,且含 web.py)';
return;
}
fillProcessSelect();
currentProcess = PROCESS_MONITOR[0].pm2;
processSelect.value = currentProcess;
refreshProcessScriptNote();
setInterval(fetchStatus, 1000);
fetchStatus();
updateSectionsVisibility();
})();
</script>
</body>
</html>

4
d2ypp2/install-all.sh Normal file
View File

@ -0,0 +1,4 @@
#!/usr/bin/env bash
set -euo pipefail
ROOT_DIR="$(cd "$(dirname "$0")" && pwd)"
exec bash "$ROOT_DIR/scripts/linux/install_stack.sh" all "$@"

View File

@ -0,0 +1,4 @@
#!/usr/bin/env bash
set -euo pipefail
ROOT_DIR="$(cd "$(dirname "$0")" && pwd)"
exec bash "$ROOT_DIR/scripts/linux/install_business.sh" "$@"

4
d2ypp2/install-core.sh Normal file
View File

@ -0,0 +1,4 @@
#!/usr/bin/env bash
set -euo pipefail
ROOT_DIR="$(cd "$(dirname "$0")" && pwd)"
exec bash "$ROOT_DIR/live-platform/scripts/install-core.sh" "$@"

4
d2ypp2/install-hub.sh Normal file
View File

@ -0,0 +1,4 @@
#!/usr/bin/env bash
set -euo pipefail
ROOT_DIR="$(cd "$(dirname "$0")" && pwd)"
exec bash "$ROOT_DIR/scripts/linux/install_hub.sh" "$@"

4
d2ypp2/install-live.sh Normal file
View File

@ -0,0 +1,4 @@
#!/usr/bin/env bash
set -euo pipefail
ROOT_DIR="$(cd "$(dirname "$0")" && pwd)"
exec bash "$ROOT_DIR/live-platform/scripts/install-live.sh" "$@"

View File

@ -0,0 +1,47 @@
#!/usr/bin/env bash
# 一键安装入口:Ubuntu/Debian 系 + 常见 ARM/x86_64,再调用现有 install-all(hub + business)
set -euo pipefail
ROOT_DIR="$(cd "$(dirname "$0")" && pwd)"
log() {
printf '[oneclick] %s\n' "$*"
}
if [ ! -f /etc/os-release ]; then
log "未找到 /etc/os-release,仅支持 Debian/Ubuntu 系。"
exit 1
fi
# shellcheck source=/dev/null
. /etc/os-release
ID_LIKE="${ID_LIKE:-}"
if ! echo "${ID:-} ${ID_LIKE}" | grep -qiE 'debian|ubuntu'; then
log "当前发行版: ${PRETTY_NAME:-unknown}"
log "脚本仅在 Debian/Ubuntu 及其衍生版上测试;如需其它系统请直接阅读 scripts/linux/*.sh 手工执行。"
exit 1
fi
ARCH="$(uname -m 2>/dev/null || true)"
case "${ARCH}" in
x86_64 | amd64 | aarch64 | arm64 | armv7l | armv6l) ;;
*)
log "未识别的机器架构: ${ARCH:-?},将继续尝试安装(请自行确认依赖是否可用)。"
;;
esac
log "ROOT_DIR=${ROOT_DIR}"
log "架构=${ARCH} 系统=${PRETTY_NAME:-$ID}"
INSTALL_ALL="${ROOT_DIR}/install-all.sh"
if [ ! -f "${INSTALL_ALL}" ]; then
log "缺少 install-all.sh"
exit 1
fi
if [ ! -x "${INSTALL_ALL}" ]; then
log "install-all.sh 未设置执行位,改用 bash 直接执行"
fi
exec bash "${INSTALL_ALL}" "$@"

426
d2ypp2/install.sh Normal file
View File

@ -0,0 +1,426 @@
#!/usr/bin/env bash
# SHD2YPP2 remote bootstrapper.
#
# Supported entrypoints:
# curl -fsSL http://<host>/install.sh | bash
# curl -fsSL http://<host>/install.sh | bash -s -- --profile all
# sudo bash install.sh --profile hub
#
# The heavy OS/service installation stays in scripts/linux/install_stack.sh.
# This file owns the production bootstrap contract: source acquisition, locking,
# logging, privilege handling, profile dispatch, and post-install verification.
set -Eeuo pipefail
PRODUCT_NAME="SHD2YPP2"
DEFAULT_REPO_URL="http://gitlab.nomadro.com/gitlab-instance-0a899031/sh.git"
DEFAULT_REPO_REF="best"
DEFAULT_REPO_SUBDIR="d2ypp2"
DEFAULT_INSTALL_DIR="/opt/live/d2ypp"
DEFAULT_LOG_DIR="/var/log/shd2ypp2"
DEFAULT_LOCK_FILE="/run/lock/shd2ypp2-install.lock"
PROFILE="all"
REPO_URL="${LIVE_REPO_URL:-$DEFAULT_REPO_URL}"
REPO_REF="${LIVE_REPO_REF:-$DEFAULT_REPO_REF}"
REPO_SUBDIR="${LIVE_REPO_SUBDIR:-$DEFAULT_REPO_SUBDIR}"
INSTALL_DIR="${LIVE_INSTALL_DIR:-$DEFAULT_INSTALL_DIR}"
LOG_DIR="${LIVE_INSTALL_LOG_DIR:-$DEFAULT_LOG_DIR}"
LOCK_FILE="${LIVE_INSTALL_LOCK_FILE:-$DEFAULT_LOCK_FILE}"
VERIFY=1
LOCAL_ONLY=0
KEEP_SOURCE=0
ASSUME_YES=1
SELF_PATH="${BASH_SOURCE[0]:-$0}"
START_TS="$(date +%Y%m%d-%H%M%S)"
LOG_FILE="$LOG_DIR/install-$START_TS.log"
log() {
printf '[install] %s\n' "$*" >&2
}
die() {
log "ERROR: $*"
exit 1
}
usage() {
cat <<USAGE
$PRODUCT_NAME one-click installer
Usage:
curl -fsSL <url>/install.sh | bash
bash install.sh [options]
Options:
--profile all|hub|core|business|live Install profile. Default: all
--repo URL Git repository URL. Default: $DEFAULT_REPO_URL
--ref REF Git branch/tag/commit. Default: $DEFAULT_REPO_REF
--subdir PATH Project subdir inside repo. Default: $DEFAULT_REPO_SUBDIR
--dir PATH Runtime source directory. Default: $DEFAULT_INSTALL_DIR
--no-verify Skip post-install health probes
--local-only Require running from an existing project checkout
--keep-source Keep temporary clone directory for debugging
-h, --help Show this help
Environment overrides:
LIVE_REPO_URL, LIVE_REPO_REF, LIVE_REPO_SUBDIR, LIVE_INSTALL_DIR
HOSTNAME_ALIAS, PORT and other config/system-stack.env values
USAGE
}
parse_args() {
while [ "$#" -gt 0 ]; do
case "$1" in
--profile)
PROFILE="${2:-}"
shift 2
;;
--profile=*)
PROFILE="${1#*=}"
shift
;;
--repo)
REPO_URL="${2:-}"
shift 2
;;
--repo=*)
REPO_URL="${1#*=}"
shift
;;
--ref)
REPO_REF="${2:-}"
shift 2
;;
--ref=*)
REPO_REF="${1#*=}"
shift
;;
--subdir)
REPO_SUBDIR="${2:-}"
shift 2
;;
--subdir=*)
REPO_SUBDIR="${1#*=}"
shift
;;
--dir)
INSTALL_DIR="${2:-}"
shift 2
;;
--dir=*)
INSTALL_DIR="${1#*=}"
shift
;;
--no-verify)
VERIFY=0
shift
;;
--local-only)
LOCAL_ONLY=1
shift
;;
--keep-source)
KEEP_SOURCE=1
shift
;;
-y|--yes)
ASSUME_YES=1
shift
;;
-h|--help)
usage
exit 0
;;
*)
die "Unknown argument: $1"
;;
esac
done
case "$PROFILE" in
all|full) PROFILE="all" ;;
hub|core|sh) PROFILE="hub" ;;
business|live|app|sh2) PROFILE="business" ;;
*) die "Unsupported profile: $PROFILE" ;;
esac
[ -n "$REPO_URL" ] || die "--repo cannot be empty"
[ -n "$REPO_REF" ] || die "--ref cannot be empty"
[ -n "$INSTALL_DIR" ] || die "--dir cannot be empty"
}
have() {
command -v "$1" >/dev/null 2>&1
}
root_prefix() {
if [ "$(id -u)" -eq 0 ]; then
return 0
fi
if ! have sudo; then
die "sudo is required when not running as root. Use: curl -fsSL <url>/install.sh | sudo -E bash"
fi
sudo -n true 2>/dev/null || sudo -v
}
run_root() {
if [ "$(id -u)" -eq 0 ]; then
"$@"
else
sudo -E "$@"
fi
}
run_root_shell() {
if [ "$(id -u)" -eq 0 ]; then
bash -lc "$*"
else
sudo -E bash -lc "$*"
fi
}
setup_logging() {
root_prefix
run_root mkdir -p "$LOG_DIR" "$(dirname "$LOCK_FILE")"
run_root chmod 0755 "$LOG_DIR"
if [ "$(id -u)" -eq 0 ]; then
exec > >(tee -a "$LOG_FILE") 2>&1
else
exec > >(sudo -E tee -a "$LOG_FILE") 2>&1
fi
log "$PRODUCT_NAME bootstrap started at $START_TS"
log "Log file: $LOG_FILE"
}
detect_platform() {
[ -r /etc/os-release ] || die "/etc/os-release not found; Debian/Ubuntu/Armbian are supported"
# shellcheck source=/dev/null
. /etc/os-release
local family="${ID:-} ${ID_LIKE:-}"
if ! printf '%s' "$family" | grep -qiE 'debian|ubuntu'; then
die "Unsupported distribution: ${PRETTY_NAME:-unknown}. Use Debian, Ubuntu, Armbian, Raspberry Pi OS, or a compatible derivative."
fi
local arch
arch="$(uname -m 2>/dev/null || true)"
case "$arch" in
x86_64|amd64|aarch64|arm64|armv7l|armv6l) ;;
*) log "WARN: untested architecture: ${arch:-unknown}; continuing with best-effort install" ;;
esac
log "Platform: ${PRETTY_NAME:-$family}; arch=$arch; kernel=$(uname -r)"
}
apt_install_bootstrap_deps() {
local need_apt=0
for cmd in git curl rsync flock; do
have "$cmd" || need_apt=1
done
[ "$need_apt" = 1 ] || return 0
log "Installing bootstrap dependencies"
run_root env DEBIAN_FRONTEND=noninteractive apt-get update
run_root env DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends \
ca-certificates curl git rsync util-linux sudo
}
acquire_lock() {
run_root touch "$LOCK_FILE"
if [ "$(id -u)" -ne 0 ]; then
run_root chown "$(id -u):$(id -g)" "$LOCK_FILE"
fi
exec 9>"$LOCK_FILE"
if ! flock -n 9; then
die "Another installer is already running. Lock: $LOCK_FILE"
fi
}
is_project_dir() {
local dir="$1"
[ -f "$dir/scripts/linux/install_stack.sh" ] && [ -f "$dir/web.py" ] && [ -d "$dir/web-console" ]
}
local_project_dir() {
local candidate
if [ -n "$SELF_PATH" ] && [ -f "$SELF_PATH" ]; then
candidate="$(cd "$(dirname "$SELF_PATH")" && pwd)"
if is_project_dir "$candidate"; then
printf '%s\n' "$candidate"
return 0
fi
fi
candidate="$(pwd)"
if is_project_dir "$candidate"; then
printf '%s\n' "$candidate"
return 0
fi
return 1
}
clone_source() {
local clone_root project_dir
clone_root="/opt/live/src/shd2ypp2-$START_TS"
log "Fetching source: repo=$REPO_URL ref=$REPO_REF subdir=$REPO_SUBDIR"
run_root mkdir -p "$(dirname "$clone_root")"
run_root git clone --depth 1 --branch "$REPO_REF" "$REPO_URL" "$clone_root" || {
log "Shallow clone failed; retrying full fetch"
run_root rm -rf "$clone_root"
run_root git clone "$REPO_URL" "$clone_root"
run_root git -C "$clone_root" checkout "$REPO_REF"
}
if [ -n "$REPO_SUBDIR" ]; then
project_dir="$clone_root/$REPO_SUBDIR"
else
project_dir="$clone_root"
fi
is_project_dir "$project_dir" || die "Fetched source does not contain SHD2YPP2 project at: $project_dir"
printf '%s\n' "$project_dir"
}
sync_to_install_dir() {
local source_dir="$1"
local target="$INSTALL_DIR"
log "Syncing source to $target"
run_root mkdir -p "$target"
run_root rsync -a --delete \
--exclude '.git/' \
--exclude '.venv/' \
--exclude '.next/' \
--exclude 'node_modules/' \
--exclude 'web-console/node_modules/' \
--exclude 'web-console/.next/' \
--exclude 'logs/' \
--exclude 'downloads/' \
--exclude 'backup_config/' \
--exclude '.pm2/' \
--exclude '.process_runner/' \
--exclude 'services/neko/data/' \
--exclude 'config/system-stack.env' \
"$source_dir/" "$target/"
run_root chown -R live:live "$target" 2>/dev/null || true
printf '%s\n' "$target"
}
resolve_project_dir() {
local project=""
if project="$(local_project_dir 2>/dev/null)"; then
log "Using local project checkout: $project"
project="$(sync_to_install_dir "$project")"
printf '%s\n' "$project"
return 0
fi
if [ "$LOCAL_ONLY" = 1 ]; then
die "--local-only was set, but current directory is not a SHD2YPP2 checkout"
fi
apt_install_bootstrap_deps
local fetched
fetched="$(clone_source)"
sync_to_install_dir "$fetched"
if [ "$KEEP_SOURCE" != 1 ]; then
run_root rm -rf "$(dirname "$fetched")"
else
log "Keeping fetched source at $(dirname "$fetched")"
fi
}
install_profile() {
local project_dir="$1"
local stack="$project_dir/scripts/linux/install_stack.sh"
[ -f "$stack" ] || die "Missing installer: $stack"
log "Dispatching install profile: $PROFILE"
run_root chmod +x "$stack" "$project_dir"/install-*.sh "$project_dir"/start.sh 2>/dev/null || true
run_root env \
LIVE_STACK_REPO_ROOT="$INSTALL_DIR" \
LIVE_INSTALL_LOG_FILE="$LOG_FILE" \
ASSUME_YES="$ASSUME_YES" \
bash "$stack" "$PROFILE"
}
post_verify() {
[ "$VERIFY" = 1 ] || {
log "Post-install verification skipped by --no-verify"
return 0
}
local port="${PORT:-8001}"
if [ -f "$INSTALL_DIR/config/system-stack.env" ]; then
# shellcheck source=/dev/null
. "$INSTALL_DIR/config/system-stack.env" || true
port="${PORT:-8001}"
fi
log "Waiting for control plane on 127.0.0.1:$port"
local ok=0 i
for i in $(seq 1 90); do
if curl -fsS -m 3 "http://127.0.0.1:$port/health" >/dev/null 2>&1; then
ok=1
break
fi
sleep 2
done
if [ "$ok" != 1 ]; then
run_root journalctl -u live-console.service -n 120 --no-pager || true
die "Control plane did not become healthy on 127.0.0.1:$port"
fi
log "Control plane health OK"
if curl -fsS -m 8 "http://127.0.0.1:$port/deploy/check" >/tmp/shd2ypp2-deploy-check.json 2>/dev/null; then
python3 - <<'PY'
from __future__ import annotations
import json
from pathlib import Path
data = json.loads(Path("/tmp/shd2ypp2-deploy-check.json").read_text(encoding="utf-8"))
status = "READY" if data.get("ready") else "DEGRADED"
print(f"[install] deploy/check: {status} ({data.get('pass_count', 0)}/{data.get('total_count', 0)})")
for item in data.get("failing_checks") or []:
label = item.get("label") or item.get("id") or "check"
detail = item.get("detail") or item.get("error") or ""
print(f"[install] FAIL {label}: {detail}")
for hint in data.get("hints") or []:
print(f"[install] hint: {hint}")
PY
else
log "WARN: /deploy/check unavailable; /health passed"
fi
local verifier="$INSTALL_DIR/tools/verify_local_install.py"
if [ -f "$verifier" ]; then
log "Running local production verifier"
run_root chmod +x "$verifier" 2>/dev/null || true
run_root python3 "$verifier" --install-dir "$INSTALL_DIR" --timeout 6
else
log "WARN: local verifier not found at $verifier"
fi
}
print_finish() {
local host_alias="${HOSTNAME_ALIAS:-live}"
local port="${PORT:-8001}"
if [ -f "$INSTALL_DIR/config/system-stack.env" ]; then
# shellcheck source=/dev/null
. "$INSTALL_DIR/config/system-stack.env" || true
host_alias="${HOSTNAME_ALIAS:-live}"
port="${PORT:-8001}"
fi
cat <<EOF
[install] $PRODUCT_NAME install finished.
[install] Web console: http://${host_alias}.local
[install] Direct URL: http://${host_alias}.local:${port}
[install] Runtime dir: $INSTALL_DIR
[install] Log file: $LOG_FILE
EOF
}
main() {
parse_args "$@"
setup_logging
acquire_lock
detect_platform
apt_install_bootstrap_deps
local project_dir
project_dir="$(resolve_project_dir)"
install_profile "$project_dir"
post_verify
print_finish
}
main "$@"

View File

@ -0,0 +1,19 @@
{
"id": "douyinyoutube",
"name": "无人直播(抖音/TikTok → YouTube / SRS / HDMI)",
"enabled": true,
"layer": "business",
"install_marker": "/opt/live/business/douyinyoutube/.installed",
"ffmpeg": {
"template_id": "default",
"auto_restart": true,
"retry_seconds": 15
},
"streams": {
"douyin_input_url": "",
"youtube_rtmp_key": "",
"srs_publish_url": "",
"hdmi_device": ""
},
"note": "具体推流参数仍可由 PM2 脚本与 config/*.ini 管理;此处为声明式元数据,供控制台与恢复策略使用"
}

View File

@ -0,0 +1,24 @@
{
"version": 1,
"wifi": {
"enabled": true,
"connection_name": "live-wifi",
"ssid": "live",
"psk": "12345678"
},
"ipv6": {
"disable": true
},
"android_proxy": {
"mode": "gateway_optional",
"description": "可选透明网关或 ShellCrash 规则;具体由 ShellCrash 与 network 脚本实现"
},
"remote_access": {
"neko": {
"lan": true,
"wireguard": true,
"nat1to1_env": "NEKO_WEBRTC_NAT1TO1",
"wireguard_host_env": "NEKO_WIREGUARD_HOST"
}
}
}

View File

@ -0,0 +1,12 @@
{
"id": "android_panel",
"layer": "infra",
"enabled": true,
"manager": "systemd",
"ports": { "http": 5000 },
"env": {
"ENABLE_ANDROID_PANEL": "1",
"ANDROID_PANEL_PORT": "5000",
"ANDROID_PANEL_DIR": "/opt/live-modules/web-scrcpy"
}
}

View File

@ -0,0 +1,9 @@
{
"id": "caddy",
"layer": "infra",
"enabled": false,
"manager": "systemd",
"description": "可选:统一 live.local:80 入口,反代控制台静态 + /api → FastAPI",
"ports": { "http": 80, "https": 443 },
"template": "/opt/live/templates/Caddyfile"
}

View File

@ -0,0 +1,13 @@
{
"id": "filebrowser",
"layer": "infra",
"enabled": true,
"manager": "docker",
"ports": { "http": 8082 },
"env": {
"ENABLE_FILEBROWSER": "1",
"FILEBROWSER_PORT": "8082",
"FILEBROWSER_USER": "live",
"FILEBROWSER_PASS": "12345678"
}
}

View File

@ -0,0 +1,8 @@
{
"id": "frp",
"layer": "infra",
"enabled": false,
"manager": "systemd",
"description": "占位:内网穿透,由运维填入 frpc 配置后启用",
"ports": {}
}

View File

@ -0,0 +1,8 @@
{
"id": "homepage",
"layer": "infra",
"enabled": true,
"manager": "docker",
"ports": { "http": 3080 },
"env": { "ENABLE_HOMEPAGE": "1", "HOMEPAGE_PORT": "3080" }
}

View File

@ -0,0 +1,33 @@
{
"id": "neko",
"layer": "infra",
"enabled": true,
"manager": "systemd",
"ports": { "http": 9200 },
"env": {
"ENABLE_NEKO": "1",
"NEKO_INSTANCE_COUNT": "2",
"NEKO_HTTP_PORT": "9200",
"NEKO_HTTP_PORT_1": "9200",
"NEKO_HTTP_PORT_2": "9201",
"NEKO_HTTP_PORT_3": "9202",
"NEKO_PROFILE_HOST_DIR": "/opt/live-modules/neko-profile",
"NEKO_SHM_SIZE": "512mb",
"NEKO_DESKTOP_SCREEN": "1280x720@15",
"NEKO_MAX_FPS": "15",
"NEKO_VIDEO_BITRATE": "1200",
"NEKO_BROWSER_RENDER_MODE": "auto",
"NEKO_WEBRTC_UDP_RANGE": "52000-52099",
"NEKO_WEBRTC_UDP_RANGE_1": "52000-52099",
"NEKO_WEBRTC_UDP_RANGE_2": "52101-52199",
"NEKO_WEBRTC_UDP_RANGE_3": "52201-52299",
"NEKO_WEBRTC_TCPMUX": "52300",
"NEKO_WEBRTC_TCPMUX_1": "52300",
"NEKO_WEBRTC_TCPMUX_2": "52301",
"NEKO_WEBRTC_TCPMUX_3": "52302",
"NEKO_WEBRTC_UDPMUX": "52300",
"NEKO_WEBRTC_UDPMUX_1": "52300",
"NEKO_WEBRTC_UDPMUX_2": "52301",
"NEKO_WEBRTC_UDPMUX_3": "52302"
}
}

View File

@ -0,0 +1,8 @@
{
"id": "netdata",
"layer": "infra",
"enabled": true,
"manager": "native",
"ports": { "http": 19999 },
"env": { "NETDATA_PORT": "19999", "ENABLE_NETDATA": "1" }
}

View File

@ -0,0 +1,11 @@
{
"id": "shellcrash",
"layer": "infra",
"enabled": true,
"manager": "systemd",
"ports": {},
"env": {
"SHELLCRASH_DIR": "/etc/ShellCrash",
"ENABLE_SHELLCRASH": "1"
}
}

View File

@ -0,0 +1,16 @@
{
"id": "srs",
"layer": "infra",
"enabled": true,
"manager": "docker",
"ports": {
"http": 8080,
"rtmp": 1935,
"api": 1985
},
"env": {
"SRS_HTTP_PORT": "8080",
"SRS_RTMP_PORT": "1935",
"SRS_API_PORT": "1985"
}
}

View File

@ -0,0 +1,13 @@
{
"id": "webtty",
"layer": "core",
"enabled": true,
"manager": "systemd",
"ports": { "http": 7681 },
"env": {
"ENABLE_WEBTTY": "1",
"WEBTTY_PORT": "7681",
"WEBTTY_USER": "live",
"WEBTTY_PASS": "12345678"
}
}

View File

@ -0,0 +1,14 @@
{
"id": "wireguard",
"layer": "infra",
"enabled": false,
"manager": "systemd",
"description": "WireGuard 覆盖网络配置导入;与 ShellCrash/Mihomo TUN 并存时需为 VPS Endpoint 添加物理出口旁路路由",
"ports": { "udp": 51820 },
"config": {
"imports_dir": "config/wireguard/imports",
"default_mtu": 1360,
"persistent_keepalive": 25,
"windows_endpoint_route_required": true
}
}

View File

@ -0,0 +1,21 @@
{
"version": 1,
"platform": {
"arch": "auto",
"description": "auto = detect via uname -m (aarch64/arm64/x86_64)"
},
"identity": {
"hostname_alias": "live",
"mdns_enabled": true
},
"paths": {
"state_dir": "/opt/live/state",
"logs_dir": "/opt/live/logs",
"generated_dir": "/opt/live/generated"
},
"web_console": {
"api_port": 8001,
"public_host": "live.local",
"note": "生产环境由 Caddy :80 反代到静态资源与 API"
}
}

View File

@ -0,0 +1,13 @@
# 将本文件复制到 /opt/live/templates/Caddyfile 并按实际路径修改
# 目标:http://live.local → 静态控制台 + /api/* → FastAPI
{$LIVE_DOMAIN:live.local} {
encode gzip
# 静态(Next export 由 web.py 同端口托管时可改为 reverse_proxy)
handle_path /api/* {
reverse_proxy 127.0.0.1:8001
}
handle {
reverse_proxy 127.0.0.1:8001
}
}

View File

@ -0,0 +1,121 @@
#!/usr/bin/env bash
# 一键体检:网络 / 端口 / adb / ffmpeg / docker / 服务状态(模块化输出)
set -euo pipefail
ROOT="$(cd "$(dirname "$0")/../.." && pwd)"
REPO="$ROOT"
# shellcheck source=/dev/null
source "$ROOT/live-platform/scripts/lib/common.sh"
STACK_ENV="$REPO/config/system-stack.env"
if [[ -f "$STACK_ENV" ]]; then
set -a
# shellcheck source=/dev/null
. "$STACK_ENV"
set +a
fi
echo "=== Live Platform Doctor ==="
echo "arch: $(detect_arch)"
echo "hostname: $(hostname -f 2>/dev/null || hostname)"
section() { echo ""; echo "--- $1 ---"; }
section "loopback / DNS"
ping -c1 -W2 127.0.0.1 >/dev/null 2>&1 && echo "ping 127.0.0.1: ok" || echo "ping 127.0.0.1: fail"
MDNS_HOST="${HOSTNAME_ALIAS:-live}.local"
getent hosts "$MDNS_HOST" >/dev/null 2>&1 && echo "$MDNS_HOST resolves: yes" || echo "$MDNS_HOST resolves: fail"
section "config"
if [[ -f "$REPO/config/system-stack.env" ]]; then
echo "repo stack env: present ($REPO/config/system-stack.env)"
else
echo "repo stack env: missing"
fi
if [[ -f /opt/live/config/system.json ]]; then
echo "system.json: present"
elif [[ -f "$REPO/config/system-stack.env" ]]; then
echo "system.json: not used by repo-managed install"
else
echo "system.json: MISSING (run install-core)"
fi
if [[ -f /opt/live/generated/system-stack.env ]]; then
echo "generated env: present"
elif [[ -f "$REPO/config/system-stack.env" ]]; then
echo "generated env: repo-managed via config/system-stack.env"
else
echo "generated env: missing"
fi
section "ports (LISTEN)"
command -v ss >/dev/null 2>&1 && ss -tlnp 2>/dev/null | head -n 40 || netstat -tlnp 2>/dev/null | head -n 40 || true
section "adb"
if command -v adb >/dev/null 2>&1; then
adb devices -l || true
else
echo "adb not installed"
fi
section "ffmpeg"
command -v ffmpeg >/dev/null 2>&1 && ffmpeg -version | head -n1 || echo "ffmpeg missing"
section "docker"
if command -v docker >/dev/null 2>&1; then
docker info >/dev/null 2>&1 && echo "docker: daemon ok" || echo "docker: daemon unreachable"
else
echo "docker not installed"
fi
section "proxy hint (ShellCrash)"
if [[ -d /etc/ShellCrash ]]; then
echo "ShellCrash dir: /etc/ShellCrash"
else
echo "ShellCrash dir: not found"
fi
if [[ -f "$REPO/web.py" ]] && command -v curl >/dev/null 2>&1; then
section "API"
PORT="${PORT:-8001}"
curl -sS -m 3 "http://127.0.0.1:${PORT}/health" && echo "" || echo "health check failed on :$PORT"
section "Port 80 (live-edge / Caddy)"
systemctl is-active live-edge.service 2>/dev/null || echo "live-edge.service: inactive"
curl -sS -m 5 -o /dev/null -w "GET http://127.0.0.1/ → http_code=%{http_code}\n" "http://127.0.0.1/" || echo "curl :80 failed"
section "Deployment Acceptance"
deploy_json="$(curl -fsS -m 10 "http://127.0.0.1:${PORT}/deploy/check" 2>/dev/null || true)"
if [[ -n "$deploy_json" ]]; then
DEPLOY_JSON="$deploy_json" python3 - <<'PY'
import json
import os
import sys
raw = os.environ.get("DEPLOY_JSON", "").strip()
if not raw:
raise SystemExit(0)
data = json.loads(raw)
status = "READY" if data.get("ready") else "DEGRADED"
print(f"status: {status} ({data.get('pass_count', 0)}/{data.get('total_count', 0)} checks passed)")
for item in data.get("checks") or []:
mark = "OK" if item.get("ok") else "FAIL"
label = item.get("label") or item.get("id") or "check"
detail = item.get("detail") or ""
print(f"{mark:4} {label}: {detail}")
hints = data.get("hints") or []
if hints:
print("hints:")
for line in hints:
print(f"- {line}")
urls = data.get("urls") or {}
if urls:
print("urls:")
for key in ("mdns_root", "mdns_control", "lan_root", "lan_control", "loopback_api"):
value = urls.get(key)
if value:
print(f"- {key}: {value}")
PY
else
echo "deploy/check unavailable on :$PORT"
fi
fi
echo ""
echo "=== Doctor finished ==="

View File

@ -0,0 +1,42 @@
#!/usr/bin/env bash
# 幂等:同步配置中心默认 JSON → /opt/live/config,生成 system-stack.env,安装 Hub(无业务模块)
set -euo pipefail
ROOT="$(cd "$(dirname "$0")/../.." && pwd)"
REPO="$(cd "$ROOT/.." && pwd)"
# shellcheck source=/dev/null
source "$ROOT/scripts/lib/common.sh"
ARCH="$(detect_arch)"
echo "[live-platform] install-core arch=$ARCH"
ensure_live_dirs
if [[ ! -f /opt/live/config/system.json ]]; then
cp -a "$ROOT/config/defaults/system.json" /opt/live/config/system.json
fi
if [[ ! -f /opt/live/config/network.json ]]; then
cp -a "$ROOT/config/defaults/network.json" /opt/live/config/network.json
fi
if command -v rsync >/dev/null 2>&1; then
rsync -a --ignore-existing "$ROOT/config/defaults/services/" /opt/live/config/services/
rsync -a --ignore-existing "$ROOT/config/defaults/business/" /opt/live/config/business/
else
cp -n "$ROOT/config/defaults/services/"*.json /opt/live/config/services/ 2>/dev/null || true
cp -n "$ROOT/config/defaults/business/"*.json /opt/live/config/business/ 2>/dev/null || true
fi
export LIVE_CONFIG_ROOT="${LIVE_CONFIG_ROOT:-/opt/live/config}"
python3 "$ROOT/tools/render_stack_env.py" /opt/live/generated/system-stack.env
if [[ -n "${LINK_REPO_CONFIG:-}" ]]; then
mkdir -p "$REPO/config"
ln -sf /opt/live/generated/system-stack.env "$REPO/config/system-stack.env"
fi
if [[ -x "$REPO/scripts/linux/install_hub.sh" ]]; then
bash "$REPO/scripts/linux/install_hub.sh" "$@"
else
echo "[live-platform] WARN: scripts/linux/install_hub.sh missing, skip hub packages"
fi
echo "[live-platform] install-core done. Env: /opt/live/generated/system-stack.env"

View File

@ -0,0 +1,16 @@
#!/usr/bin/env bash
# 幂等:仅无人直播业务模块(与 install-core 解耦)
set -euo pipefail
ROOT="$(cd "$(dirname "$0")/../.." && pwd)"
REPO="$(cd "$ROOT/.." && pwd)"
if [[ -x "$REPO/scripts/linux/install_business.sh" ]]; then
bash "$REPO/scripts/linux/install_business.sh" "$@"
else
echo "[live-platform] ERROR: scripts/linux/install_business.sh not found"
exit 1
fi
mkdir -p /opt/live/business/douyinyoutube
touch /opt/live/business/douyinyoutube/.installed
echo "[live-platform] install-live done"

View File

@ -0,0 +1,29 @@
# shellcheck shell=bash
# 被 install-core / install-live / doctor 引用;禁止写业务逻辑,仅路径与权限。
live_platform_root() {
local here
here="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
printf '%s\n' "$here"
}
repo_root() {
local lp
lp="$(live_platform_root)"
cd "$lp/.." && pwd
}
detect_arch() {
case "$(uname -m)" in
aarch64|arm64) echo "arm64" ;;
x86_64|amd64) echo "amd64" ;;
*) echo "generic" ;;
esac
}
ensure_live_dirs() {
sudo mkdir -p /opt/live/config/services /opt/live/config/business \
/opt/live/generated /opt/live/state /opt/live/logs /opt/live/templates 2>/dev/null || \
mkdir -p /opt/live/config/services /opt/live/config/business \
/opt/live/generated /opt/live/state /opt/live/logs /opt/live/templates
}

View File

@ -0,0 +1,46 @@
#!/usr/bin/env python3
"""生成 Caddy 配置:HTTP :80 → 本机 FastAPI+静态(PORT,默认 8001)。"""
from __future__ import annotations
import json
import sys
from pathlib import Path
def main() -> int:
alias = "live"
port = "8001"
out = Path("/opt/live/generated/Caddyfile")
cfg = Path("/opt/live/config/system.json")
if cfg.is_file():
data = json.loads(cfg.read_text(encoding="utf-8"))
ident = data.get("identity") or {}
web = data.get("web_console") or {}
alias = str(ident.get("hostname_alias") or alias)
if web.get("api_port") is not None:
port = str(web["api_port"])
if len(sys.argv) >= 2:
alias = sys.argv[1]
if len(sys.argv) >= 3:
port = sys.argv[2]
if len(sys.argv) >= 4:
out = Path(sys.argv[3])
host = f"{alias}.local"
body = f"""# Generated by live-platform/tools/render_caddyfile.py - do not hand-edit
# http://{host}/ and http://<LAN-IP>/ -> 127.0.0.1:{port}
{host}:80, :80 {{
\treverse_proxy 127.0.0.1:{port}
}}
"""
out.parent.mkdir(parents=True, exist_ok=True)
out.write_text(body, encoding="utf-8")
print(str(out))
return 0
if __name__ == "__main__":
raise SystemExit(main())

View File

@ -0,0 +1,97 @@
#!/usr/bin/env python3
"""从 /opt/live/config(或 LIVE_CONFIG_ROOT)JSON 配置生成 system-stack.env,供现有 service_ctl / install 脚本读取。"""
from __future__ import annotations
import json
import os
import sys
from pathlib import Path
def config_root() -> Path:
env = os.environ.get("LIVE_CONFIG_ROOT", "").strip()
if env:
return Path(env)
if Path("/opt/live/config/system.json").is_file():
return Path("/opt/live/config")
here = Path(__file__).resolve()
return here.parent.parent / "config" / "defaults"
def load_json(path: Path) -> dict:
if not path.is_file():
return {}
return json.loads(path.read_text(encoding="utf-8"))
def collect_env(root: Path) -> dict[str, str]:
lines: dict[str, str] = {}
sys_j = load_json(root / "system.json")
web = sys_j.get("web_console") or {}
ident = sys_j.get("identity") or {}
if ident.get("hostname_alias"):
lines["HOSTNAME_ALIAS"] = str(ident["hostname_alias"])
if web.get("api_port") is not None:
lines["PORT"] = str(web["api_port"])
net = load_json(root / "network.json")
wifi = net.get("wifi") or {}
if wifi.get("connection_name"):
lines["WIFI_CONNECTION_NAME"] = str(wifi["connection_name"])
if wifi.get("ssid"):
lines["WIFI_SSID"] = str(wifi["ssid"])
if wifi.get("psk"):
lines["WIFI_PSK"] = str(wifi["psk"])
if net.get("ipv6", {}).get("disable"):
lines["DISABLE_IPV6"] = "1"
svc_dir = root / "services"
if svc_dir.is_dir():
for f in sorted(svc_dir.glob("*.json")):
data = load_json(f)
env = data.get("env") or {}
if not isinstance(env, dict):
continue
for k, v in env.items():
if v is not None and str(v) != "":
lines[str(k)] = str(v)
ports = {}
if svc_dir.is_dir():
for f in sorted(svc_dir.glob("*.json")):
data = load_json(f)
pid = data.get("id") or f.stem
pr = data.get("ports") or {}
if isinstance(pr, dict) and "http" in pr:
ports[pid] = pr["http"]
# 固定映射:homepage 使用 HOMEPAGE_PORT
if "homepage" in ports:
lines.setdefault("HOMEPAGE_PORT", str(ports["homepage"]))
lines.setdefault("ENABLE_MDNS", "1")
lines.setdefault("ENABLE_WIFI_PROFILE", "1")
lines.setdefault("ENABLE_BROWSER", "1")
lines.setdefault("ENABLE_COCKPIT", "1")
return lines
def main() -> int:
root = config_root()
out = Path(os.environ.get("LIVE_ENV_OUT", "/opt/live/generated/system-stack.env"))
if len(sys.argv) > 1:
out = Path(sys.argv[1])
lines = collect_env(root)
out.parent.mkdir(parents=True, exist_ok=True)
body = "\n".join(f"{k}={v}" for k, v in sorted(lines.items())) + "\n"
out.write_text(
"# Generated by live-platform/tools/render_stack_env.py — do not hand-edit\n" + body,
encoding="utf-8",
)
# 开发树:可选同步到仓库 config(由 install 脚本 ln -sf)
print(str(out))
return 0
if __name__ == "__main__":
raise SystemExit(main())

2213
d2ypp2/main.py Normal file

File diff suppressed because it is too large Load Diff

17
d2ypp2/obs.bat Normal file
View File

@ -0,0 +1,17 @@
@echo off
setlocal EnableDelayedExpansion
REM Windows:从本机 SRS 拉 SRT 并用 ffplay 播放(需已安装 ffmpeg 且 ffplay 在 PATH)
REM 下方 SRS_SRT_URL 里的端口是 SRS 的 SRT 端口,与 Web 控制台端口(config\runtime.env)无关。
if not defined SRS_SRT_URL (
set "SRS_SRT_URL=srt://127.0.0.1:10080?streamid=#!::r=live/livestream,m=request^&latency=10"
)
where ffplay >nul 2>&1
if errorlevel 1 (
echo ffplay not found. Install ffmpeg and add to PATH.
exit /b 1
)
ffplay -nostats -hide_banner -fflags nobuffer -flags low_delay -framedrop -probesize 32 -analyzeduration 0 -sync ext -infbuf -vf "setpts=PTS-STARTPTS" "%SRS_SRT_URL%"
endlocal

53
d2ypp2/obs.sh Normal file
View File

@ -0,0 +1,53 @@
#!/usr/bin/env bash
set -euo pipefail
ROOT_DIR="$(cd "$(dirname "$0")" && pwd)"
[ -f "$ROOT_DIR/config/system-stack.env" ] && set -a && . "$ROOT_DIR/config/system-stack.env" && set +a
[ -f "$ROOT_DIR/config/hardware.env" ] && set -a && . "$ROOT_DIR/config/hardware.env" && set +a
: "${SRS_SRT_URL:=srt://127.0.0.1:10080?streamid=#!::r=live/livestream,m=request&latency=10}"
try_mpv_drm() {
command -v mpv >/dev/null 2>&1 || return 1
[[ -e /dev/dri/card0 ]] || return 1
exec mpv \
--no-config \
--profile=low-latency \
--fullscreen \
--osc=no \
--osd-level=0 \
--no-audio \
--untimed \
--cache=no \
--vo=gpu \
--gpu-context=drm \
--hwdec=auto-safe \
"$SRS_SRT_URL"
}
try_ffplay_gui() {
command -v ffplay >/dev/null 2>&1 || return 1
export DISPLAY="${DISPLAY:-:0}"
if [[ -n "${FFPLAY_SDL_DRIVER:-}" ]]; then
export SDL_VIDEODRIVER="${FFPLAY_SDL_DRIVER}"
fi
exec ffplay -fs -nostats -hide_banner \
-fflags nobuffer -flags low_delay -framedrop \
-probesize 32 -analyzeduration 0 -sync ext -infbuf \
-vf "setpts=PTS-STARTPTS" \
"$SRS_SRT_URL"
}
case "${LIVE_HDMI_PLAYER:-auto}" in
mpv-drm)
try_mpv_drm
;;
ffplay-x11)
try_ffplay_gui
;;
esac
try_mpv_drm || try_ffplay_gui
echo "No compatible HDMI playback stack found. Install mpv for DRM/KMS or ffplay + X11." >&2
exit 1

327
d2ypp2/package-lock.json generated Normal file
View File

@ -0,0 +1,327 @@
{
"name": "douyinyoutube",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "douyinyoutube",
"devDependencies": {
"concurrently": "^9.1.2"
}
},
"node_modules/ansi-regex": {
"version": "5.0.1",
"resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz",
"integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=8"
}
},
"node_modules/ansi-styles": {
"version": "4.3.0",
"resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz",
"integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==",
"dev": true,
"license": "MIT",
"dependencies": {
"color-convert": "^2.0.1"
},
"engines": {
"node": ">=8"
},
"funding": {
"url": "https://github.com/chalk/ansi-styles?sponsor=1"
}
},
"node_modules/chalk": {
"version": "4.1.2",
"resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz",
"integrity": "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==",
"dev": true,
"license": "MIT",
"dependencies": {
"ansi-styles": "^4.1.0",
"supports-color": "^7.1.0"
},
"engines": {
"node": ">=10"
},
"funding": {
"url": "https://github.com/chalk/chalk?sponsor=1"
}
},
"node_modules/chalk/node_modules/supports-color": {
"version": "7.2.0",
"resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz",
"integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==",
"dev": true,
"license": "MIT",
"dependencies": {
"has-flag": "^4.0.0"
},
"engines": {
"node": ">=8"
}
},
"node_modules/cliui": {
"version": "8.0.1",
"resolved": "https://registry.npmjs.org/cliui/-/cliui-8.0.1.tgz",
"integrity": "sha512-BSeNnyus75C4//NQ9gQt1/csTXyo/8Sb+afLAkzAptFuMsod9HFokGNudZpi/oQV73hnVK+sR+5PVRMd+Dr7YQ==",
"dev": true,
"license": "ISC",
"dependencies": {
"string-width": "^4.2.0",
"strip-ansi": "^6.0.1",
"wrap-ansi": "^7.0.0"
},
"engines": {
"node": ">=12"
}
},
"node_modules/color-convert": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz",
"integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==",
"dev": true,
"license": "MIT",
"dependencies": {
"color-name": "~1.1.4"
},
"engines": {
"node": ">=7.0.0"
}
},
"node_modules/color-name": {
"version": "1.1.4",
"resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz",
"integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==",
"dev": true,
"license": "MIT"
},
"node_modules/concurrently": {
"version": "9.2.1",
"resolved": "https://registry.npmjs.org/concurrently/-/concurrently-9.2.1.tgz",
"integrity": "sha512-fsfrO0MxV64Znoy8/l1vVIjjHa29SZyyqPgQBwhiDcaW8wJc2W3XWVOGx4M3oJBnv/zdUZIIp1gDeS98GzP8Ng==",
"dev": true,
"license": "MIT",
"dependencies": {
"chalk": "4.1.2",
"rxjs": "7.8.2",
"shell-quote": "1.8.3",
"supports-color": "8.1.1",
"tree-kill": "1.2.2",
"yargs": "17.7.2"
},
"bin": {
"conc": "dist/bin/concurrently.js",
"concurrently": "dist/bin/concurrently.js"
},
"engines": {
"node": ">=18"
},
"funding": {
"url": "https://github.com/open-cli-tools/concurrently?sponsor=1"
}
},
"node_modules/emoji-regex": {
"version": "8.0.0",
"resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz",
"integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==",
"dev": true,
"license": "MIT"
},
"node_modules/escalade": {
"version": "3.2.0",
"resolved": "https://registry.npmjs.org/escalade/-/escalade-3.2.0.tgz",
"integrity": "sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=6"
}
},
"node_modules/get-caller-file": {
"version": "2.0.5",
"resolved": "https://registry.npmjs.org/get-caller-file/-/get-caller-file-2.0.5.tgz",
"integrity": "sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==",
"dev": true,
"license": "ISC",
"engines": {
"node": "6.* || 8.* || >= 10.*"
}
},
"node_modules/has-flag": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz",
"integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=8"
}
},
"node_modules/is-fullwidth-code-point": {
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz",
"integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=8"
}
},
"node_modules/require-directory": {
"version": "2.1.1",
"resolved": "https://registry.npmjs.org/require-directory/-/require-directory-2.1.1.tgz",
"integrity": "sha512-fGxEI7+wsG9xrvdjsrlmL22OMTTiHRwAMroiEeMgq8gzoLC/PQr7RsRDSTLUg/bZAZtF+TVIkHc6/4RIKrui+Q==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=0.10.0"
}
},
"node_modules/rxjs": {
"version": "7.8.2",
"resolved": "https://registry.npmjs.org/rxjs/-/rxjs-7.8.2.tgz",
"integrity": "sha512-dhKf903U/PQZY6boNNtAGdWbG85WAbjT/1xYoZIC7FAY0yWapOBQVsVrDl58W86//e1VpMNBtRV4MaXfdMySFA==",
"dev": true,
"license": "Apache-2.0",
"dependencies": {
"tslib": "^2.1.0"
}
},
"node_modules/shell-quote": {
"version": "1.8.3",
"resolved": "https://registry.npmjs.org/shell-quote/-/shell-quote-1.8.3.tgz",
"integrity": "sha512-ObmnIF4hXNg1BqhnHmgbDETF8dLPCggZWBjkQfhZpbszZnYur5DUljTcCHii5LC3J5E0yeO/1LIMyH+UvHQgyw==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">= 0.4"
},
"funding": {
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/string-width": {
"version": "4.2.3",
"resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz",
"integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==",
"dev": true,
"license": "MIT",
"dependencies": {
"emoji-regex": "^8.0.0",
"is-fullwidth-code-point": "^3.0.0",
"strip-ansi": "^6.0.1"
},
"engines": {
"node": ">=8"
}
},
"node_modules/strip-ansi": {
"version": "6.0.1",
"resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz",
"integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==",
"dev": true,
"license": "MIT",
"dependencies": {
"ansi-regex": "^5.0.1"
},
"engines": {
"node": ">=8"
}
},
"node_modules/supports-color": {
"version": "8.1.1",
"resolved": "https://registry.npmjs.org/supports-color/-/supports-color-8.1.1.tgz",
"integrity": "sha512-MpUEN2OodtUzxvKQl72cUF7RQ5EiHsGvSsVG0ia9c5RbWGL2CI4C7EpPS8UTBIplnlzZiNuV56w+FuNxy3ty2Q==",
"dev": true,
"license": "MIT",
"dependencies": {
"has-flag": "^4.0.0"
},
"engines": {
"node": ">=10"
},
"funding": {
"url": "https://github.com/chalk/supports-color?sponsor=1"
}
},
"node_modules/tree-kill": {
"version": "1.2.2",
"resolved": "https://registry.npmjs.org/tree-kill/-/tree-kill-1.2.2.tgz",
"integrity": "sha512-L0Orpi8qGpRG//Nd+H90vFB+3iHnue1zSSGmNOOCh1GLJ7rUKVwV2HvijphGQS2UmhUZewS9VgvxYIdgr+fG1A==",
"dev": true,
"license": "MIT",
"bin": {
"tree-kill": "cli.js"
}
},
"node_modules/tslib": {
"version": "2.8.1",
"resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz",
"integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==",
"dev": true,
"license": "0BSD"
},
"node_modules/wrap-ansi": {
"version": "7.0.0",
"resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-7.0.0.tgz",
"integrity": "sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q==",
"dev": true,
"license": "MIT",
"dependencies": {
"ansi-styles": "^4.0.0",
"string-width": "^4.1.0",
"strip-ansi": "^6.0.0"
},
"engines": {
"node": ">=10"
},
"funding": {
"url": "https://github.com/chalk/wrap-ansi?sponsor=1"
}
},
"node_modules/y18n": {
"version": "5.0.8",
"resolved": "https://registry.npmjs.org/y18n/-/y18n-5.0.8.tgz",
"integrity": "sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA==",
"dev": true,
"license": "ISC",
"engines": {
"node": ">=10"
}
},
"node_modules/yargs": {
"version": "17.7.2",
"resolved": "https://registry.npmjs.org/yargs/-/yargs-17.7.2.tgz",
"integrity": "sha512-7dSzzRQ++CKnNI/krKnYRV7JKKPUXMEh61soaHKg9mrWEhzFWhFnxPxGl+69cD1Ou63C13NUPCnmIcrvqCuM6w==",
"dev": true,
"license": "MIT",
"dependencies": {
"cliui": "^8.0.1",
"escalade": "^3.1.1",
"get-caller-file": "^2.0.5",
"require-directory": "^2.1.1",
"string-width": "^4.2.3",
"y18n": "^5.0.5",
"yargs-parser": "^21.1.1"
},
"engines": {
"node": ">=12"
}
},
"node_modules/yargs-parser": {
"version": "21.1.1",
"resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-21.1.1.tgz",
"integrity": "sha512-tVpsJW7DdjecAiFpbIB1e3qxIQsE6NoPc5/eTdrbbIC4h0LVsWhnoa3g+m2HclBIujHzsxZ4VJVA+GUuc2/LBw==",
"dev": true,
"license": "ISC",
"engines": {
"node": ">=12"
}
}
}
}

17
d2ypp2/package.json Normal file
View File

@ -0,0 +1,17 @@
{
"name": "douyinyoutube",
"private": true,
"description": "直播推流控制台:一键开发/构建脚本入口(核心逻辑见 scripts/launch.py)",
"scripts": {
"dev": "python scripts/launch.py --dev",
"dev:api": "python -m uvicorn web:app --host 0.0.0.0 --port 8001 --reload",
"dev:console": "python scripts/launch.py --dev",
"build": "python scripts/launch.py --build-only",
"start": "python scripts/launch.py",
"start:api": "python scripts/launch.py --api-only",
"preview": "python scripts/launch.py --skip-build"
},
"devDependencies": {
"concurrently": "^9.1.2"
}
}

4
d2ypp2/probe-live.sh Normal file
View File

@ -0,0 +1,4 @@
#!/usr/bin/env bash
set -euo pipefail
ROOT_DIR="$(cd "$(dirname "$0")" && pwd)"
exec bash "$ROOT_DIR/scripts/linux/probe_live_access.sh" "$@"

24
d2ypp2/pyproject.toml Normal file
View File

@ -0,0 +1,24 @@
[project]
name = "DouyinLiveRecorder"
version = "4.0.7"
description = "可循环值守和多人录制的直播录制软件, 支持抖音、TikTok、Youtube、快手、虎牙、斗鱼、B站、小红书、pandatv、sooplive、flextv、popkontv、twitcasting、winktv、百度、微博、酷狗、17Live、Twitch、Acfun、CHZZK、shopee等40+平台直播录制"
readme = "README.md"
authors = [{name = "Hmily"}]
license = { text = "MIT" }
requires-python = ">=3.10"
dependencies = [
"requests>=2.31.0",
"loguru>=0.7.3",
"pycryptodome>=3.20.0",
"distro>=1.9.0",
"tqdm>=4.67.1",
"httpx[http2]>=0.28.1",
"PyExecJS>=1.5.1",
"PyYAML>=5.4.1"
]
[project.urls]
"Homepage" = "https://github.com/ihmily/DouyinLiveRecorder"
"Documentation" = "https://github.com/ihmily/DouyinLiveRecorder"
"Repository" = "https://github.com/ihmily/DouyinLiveRecorder"
"Issues" = "https://github.com/ihmily/DouyinLiveRecorder/issues"

41
d2ypp2/readme2.txt Normal file
View File

@ -0,0 +1,41 @@
项目修复记录(2026-05-17)
1. 本次实际修复的 bug
- 单频道 YouTube / 抖音转 YouTube:
旧逻辑只要检测到任意一个托管配置文件存在,就会把 `youtube.ini` 和 `URL_config.ini` 整对切到托管路径;当只生成了一半托管文件时,会把另一半旧配置绕掉,导致推流 key 或房间 URL 丢失。现已改为“按文件粒度回退”。
- 多频道 Pro:
前端从服务端拉取频道列表时,空列表会被误判成“拉取失败”,随后回退到浏览器本地缓存,导致页面继续显示旧频道。现已把“成功拉到空列表”和“请求失败”区分开。
- 进程重启:
`web.py` 的重启接口原先在 `restart()` 之后再 `force_kill_ffmpeg()`,会把刚拉起的新 ffmpeg 一并杀掉。现已改为先清理旧 ffmpeg,再执行重启。
- PM2 状态污染:
PM2 `start/stop/restart/resurrect` 失败时,旧代码仍会把进程标记成期望运行并保存状态,控制台会显示假在线。现已改为只有返回码为 0 才更新 desired 状态。
- PM2 自恢复卡死:
`src/web_process_backend.py` 把一些很小的本地文件读写放进 `asyncio.to_thread()`;在当前环境里这条路径会卡住,导致 PM2 进程表恢复逻辑不返回。现已改为直接同步执行这些轻量操作。
- Neko 浏览器:
`DeveloperToolsAvailability` 原来是 `2`,会直接禁用开发者工具;同时启动参数带 `--bwsi`,会破坏扩展持久化和 Tampermonkey 行为。现已改为允许 DevTools,并移除 `--bwsi`。
2. 本次改动的关键文件
- 后端:
`src/youtube_config_paths.py`
`youtube.py`
`src/web_process_backend.py`
`web.py`
- 前端:
`web-console/lib/youtubeProChannels.ts`
`web-console/components/live-product/LiveYoutubeUnmannedView.tsx`
`web-console/out/*`(已重新构建静态产物)
- Neko:
`services/neko/policies/policies.json`
`services/neko/google-chrome.conf`
`services/neko/chromium.conf`
`services/neko/browser-launch.sh`
3. 验证结果
- 已通过:
`python -m compileall -q src web.py youtube.py douyin_youtube_ffplay.py tests`
`python -m unittest -q tests.test_web_process_backend tests.test_web_dynamic_processes tests.test_youtube_config_paths tests.test_neko_config tests.test_youtube_push_config tests.test_youtube_pro_runtime`
- 前端已使用 Node 20 重新执行 `web-console` 构建,新的 `web-console/out` 已生成。
4. 部署注意
- `live.local` 实际运行目录不是当前仓库 `/home/eric/sh/d2ypp2`,而是 `/home/eric/d2ypp`。
- 如果只改当前目录而不把修复同步到 `/home/eric/d2ypp`,`live.local` 不会生效。

View File

@ -0,0 +1,4 @@
#!/usr/bin/env bash
set -euo pipefail
ROOT_DIR="$(cd "$(dirname "$0")" && pwd)"
exec bash "$ROOT_DIR/scripts/linux/refresh_live_console_unit.sh" "$@"

14
d2ypp2/requirements.txt Normal file
View File

@ -0,0 +1,14 @@
requests>=2.31.0
loguru>=0.7.3
pycryptodome>=3.20.0
distro>=1.9.0
tqdm>=4.67.1
httpx[http2]>=0.28.1,<0.29.0
PyExecJS>=1.5.1
fastapi>=0.115.0,<0.116.0
starlette>=0.40.0,<0.47.0
pydantic>=2.9.0,<3.0.0
eval-type-backport>=0.2.0
uvicorn[standard]>=0.30.0,<0.36.0
python-multipart>=0.0.9
PyYAML>=5.4.1

120
d2ypp2/scripts/env_check.py Normal file
View File

@ -0,0 +1,120 @@
# -*- coding: utf-8 -*-
"""启动前环境分析:Python 依赖、ffmpeg、Node/npm、端口提示(Linux)。"""
from __future__ import annotations
import importlib.util
import shutil
import socket
import subprocess
import sys
def _has_module(name: str) -> bool:
return importlib.util.find_spec(name) is not None
def _local_ips() -> list[str]:
out: list[str] = []
try:
hostname = socket.gethostname()
for info in socket.getaddrinfo(hostname, None, family=socket.AF_INET):
ip = info[4][0]
if ip and not ip.startswith("127.") and ip not in out:
out.append(ip)
except OSError:
pass
return out[:4]
def _node_major() -> tuple[int | None, str | None]:
node = shutil.which("node")
if not node:
return None, None
try:
raw = subprocess.check_output([node, "-v"], stderr=subprocess.STDOUT, text=True).strip()
except Exception:
return None, node
try:
major = int(raw.lstrip("v").split(".", 1)[0])
except Exception:
major = None
return major, f"{node} ({raw})"
def print_env_report(
*,
dev: bool,
need_npm: bool,
host: str,
port: str,
next_port: str = "3000",
) -> None:
print()
print("┌── 环境检测 ─────────────────────────────────────────")
print(f"│ 系统: {sys.platform} Python: {sys.version.split()[0]}")
ok = True
for mod, label in (
("fastapi", "FastAPI"),
("uvicorn", "Uvicorn"),
):
if _has_module(mod):
print(f"│ ✓ {label} 已安装")
else:
print(f"│ ✕ 缺少 {label},请执行: pip install -r requirements.txt")
ok = False
ff = shutil.which("ffmpeg")
fp = shutil.which("ffplay")
if ff:
print(f"│ ✓ ffmpeg: {ff}")
else:
print("│ ⚠ 未找到 ffmpeg(推流/录制/OBS 拉流会失败;Docker 镜像已内置)")
ok = False
if fp:
print(f"│ ✓ ffplay: {fp}")
else:
print("│ ⚠ 未找到 ffplay(HDMI 全屏播放需要完整 ffmpeg 套件)")
if need_npm:
major, node_desc = _node_major()
npm = shutil.which("npm")
docker = shutil.which("docker")
if node_desc:
if major is not None and major < 18:
print(f"│ ⚠ Node: {node_desc}(Next.js 推荐 Node 18+;可自动尝试 Docker 兜底)")
else:
print(f"│ ✓ Node: {node_desc}")
else:
print("│ ✕ 未找到 Node.js(Next.js 构建/开发需要 Node 18+ 或 Docker 兜底)")
ok = False
if npm:
print(f"│ ✓ npm: {npm}")
else:
print("│ ⚠ 未找到 npm(若有 Node 18+ 通常可用;否则请安装完整 Node 或启用 Docker)")
if docker:
print(f"│ ✓ Docker: {docker}")
elif major is None or (major is not None and major < 18):
print("│ ⚠ 无 Docker 时,Node 过低会依赖本机升级才能构建前端")
print("│")
print("│ 同机端口提示(若冲突请在 config/runtime.env 修改 PORT):")
print("│ 本控制台 API/Web 使用环境变量 PORT(默认见 launch.py)")
print("│ SRS 常见: 1935/1985/8080/10080 等;代理常见: 7890/9090;Chrome 远程: 9222")
print("│")
print(f"│ 监听: {host}:{port}")
if dev:
ips = _local_ips()
print(f"│ 开发 UI: 0.0.0.0:{next_port}(局域网可用本机 IP 访问)")
if ips:
print(f"│ 示例: http://{ips[0]}:{next_port}/")
else:
if host == "0.0.0.0":
ips = _local_ips()
if ips:
print(f"│ 局域网访问示例: http://{ips[0]}:{port}/")
else:
print("│ 局域网访问: http://<本机IP>:%s/" % port)
print("└────────────────────────────────────────────────────")
print()
if not ok and not dev:
print("[env] 存在警告,仍可尝试启动;若运行失败请按上述提示补全依赖。\n")

View File

@ -0,0 +1,388 @@
#!/usr/bin/env python3
from __future__ import annotations
import argparse
import json
import os
import platform
import re
import shutil
import socket
import subprocess
from pathlib import Path
ROOT = Path(__file__).resolve().parent.parent
CONFIG_DIR = ROOT / "config"
JSON_PATH = CONFIG_DIR / "hardware-profile.json"
ENV_PATH = CONFIG_DIR / "hardware.env"
def run_text(cmd: list[str]) -> str:
try:
proc = subprocess.run(
cmd,
capture_output=True,
text=True,
encoding="utf-8",
errors="ignore",
timeout=8,
check=False,
)
except (OSError, subprocess.TimeoutExpired):
return ""
return (proc.stdout or proc.stderr or "").strip()
def read_optional_text(path: Path) -> str:
if not path.is_file():
return ""
try:
return path.read_text(encoding="utf-8", errors="replace").strip()
except OSError:
return ""
def run_probe(cmd: list[str], timeout: int = 8) -> tuple[int, str]:
try:
proc = subprocess.run(
cmd,
capture_output=True,
text=True,
encoding="utf-8",
errors="ignore",
timeout=timeout,
check=False,
)
except (OSError, subprocess.TimeoutExpired) as exc:
return 124, str(exc)
return proc.returncode, ((proc.stdout or "") + (proc.stderr or "")).strip()
def ffmpeg_encoder_smoke_test(name: str, *, vaapi_device: str = "") -> bool:
if not shutil.which("ffmpeg") or not name:
return False
cmd = [
"ffmpeg", "-hide_banner", "-loglevel", "error",
"-f", "lavfi", "-i", "testsrc2=size=128x128:rate=1",
"-frames:v", "1", "-an",
]
if name == "h264_vaapi":
if not vaapi_device:
return False
cmd = [
"ffmpeg", "-hide_banner", "-loglevel", "error",
"-vaapi_device", vaapi_device,
"-f", "lavfi", "-i", "testsrc2=size=128x128:rate=1",
"-vf", "format=nv12,hwupload",
"-frames:v", "1", "-an",
]
cmd += ["-c:v", name, "-f", "null", "-"]
code, _ = run_probe(cmd)
return code == 0
def detect_ffmpeg_hwaccels() -> list[str]:
if not shutil.which("ffmpeg"):
return []
text = run_text(["ffmpeg", "-hide_banner", "-hwaccels"])
accels: list[str] = []
for line in text.splitlines():
item = line.strip()
if not item or item.lower().startswith("hardware acceleration methods"):
continue
if item not in accels:
accels.append(item)
return accels
def detect_gpu() -> dict:
dri_dir = Path("/dev/dri")
render_nodes = sorted(str(path) for path in dri_dir.glob("renderD*")) if dri_dir.is_dir() else []
cards = sorted(str(path) for path in dri_dir.glob("card*")) if dri_dir.is_dir() else []
driver = ""
if cards:
card0 = Path(cards[0])
driver_link = Path(f"/sys/class/drm/{card0.name}/device/driver")
if driver_link.exists():
try:
driver = driver_link.resolve().name
except OSError:
driver = driver_link.name
return {
"present": bool(cards or render_nodes),
"cards": cards,
"render_nodes": render_nodes,
"driver": driver,
"vainfo": bool(shutil.which("vainfo")),
}
def detect_npu() -> dict:
hints = []
for path in (
Path("/dev/rknpu"),
Path("/dev/npu"),
Path("/dev/galcore"),
Path("/sys/class/misc/rknpu"),
Path("/sys/class/misc/verisilicon-npu"),
):
if path.exists():
hints.append(str(path))
return {
"present": bool(hints),
"devices": hints,
}
def detect_kernel_features() -> dict:
features = {
"drm": Path("/dev/dri/card0").exists(),
"render_node": any(Path("/dev/dri").glob("renderD*")) if Path("/dev/dri").is_dir() else False,
"v4l2loopback": Path("/sys/module/v4l2loopback").exists(),
"kvm": Path("/dev/kvm").exists(),
"nvidia": shutil.which("nvidia-smi") is not None,
}
return features
def detect_video_capture() -> dict:
if platform.system().lower() != "linux":
return {
"video_devices": [],
"v4l2_devices": [],
"usb_capture_matches": [],
"ready": False,
}
video_nodes = sorted(str(path) for path in Path("/dev").glob("video*"))
v4l2_raw = run_text(["v4l2-ctl", "--list-devices"]) if shutil.which("v4l2-ctl") else ""
v4l2_devices: list[dict] = []
if v4l2_raw:
current_name = ""
current_nodes: list[str] = []
for raw in v4l2_raw.splitlines():
line = raw.rstrip()
if not line.strip():
if current_name or current_nodes:
v4l2_devices.append({"name": current_name or "unknown", "nodes": current_nodes[:]})
current_name = ""
current_nodes = []
continue
if not line.startswith("\t") and not line.startswith(" "):
current_name = line.rstrip(":")
continue
node = line.strip()
if node.startswith("/dev/"):
current_nodes.append(node)
if current_name or current_nodes:
v4l2_devices.append({"name": current_name or "unknown", "nodes": current_nodes[:]})
lsusb_raw = run_text(["lsusb"]) if shutil.which("lsusb") else ""
capture_pat = re.compile(r"(capture|video|uvc|hdmi|elgato|macrosilicon|ezcap|cam\slink)", re.IGNORECASE)
usb_capture_matches = [line for line in lsusb_raw.splitlines() if capture_pat.search(line)]
ready = bool(video_nodes) and bool(shutil.which("ffmpeg"))
return {
"video_devices": video_nodes,
"v4l2_devices": v4l2_devices,
"usb_capture_matches": usb_capture_matches,
"v4l2_available": bool(shutil.which("v4l2-ctl")),
"ready": ready,
}
def detect_network() -> dict:
interfaces: list[dict] = []
route_raw = run_text(["ip", "-j", "route", "show", "default"]) if shutil.which("ip") else ""
addr_raw = run_text(["ip", "-j", "-4", "addr", "show", "scope", "global"]) if shutil.which("ip") else ""
default_iface = ""
gateway = ""
if route_raw:
try:
routes = json.loads(route_raw)
except json.JSONDecodeError:
routes = []
if routes:
default_iface = str(routes[0].get("dev", "") or "")
gateway = str(routes[0].get("gateway", "") or "")
if addr_raw:
try:
addr_rows = json.loads(addr_raw)
except json.JSONDecodeError:
addr_rows = []
for row in addr_rows:
name = str(row.get("ifname", "") or "").strip()
if not name or name.startswith(("docker", "br-", "veth", "virbr", "lo")):
continue
speed_path = Path("/sys/class/net") / name / "speed"
operstate_path = Path("/sys/class/net") / name / "operstate"
speed = None
try:
speed = int(read_optional_text(speed_path))
except ValueError:
speed = None
addresses = [
str(item.get("local", "")).strip()
for item in (row.get("addr_info") or [])
if str(item.get("local", "")).strip()
]
interfaces.append(
{
"name": name,
"addresses": addresses,
"speed_mbps": speed if speed and speed > 0 else None,
"operstate": read_optional_text(operstate_path) or "unknown",
"default_route": name == default_iface,
}
)
online = False
if gateway:
online = True
else:
try:
with socket.create_connection(("1.1.1.1", 53), timeout=1.2):
online = True
except OSError:
online = False
return {
"default_iface": default_iface,
"gateway": gateway,
"interfaces": interfaces,
"online": online,
}
def recommend(profile: dict) -> dict:
hwaccels = set(profile["ffmpeg_hwaccels"])
gpu = profile["gpu"]
capture = profile.get("video_capture") or {}
kernel_features = profile.get("kernel_features") or {}
browser_hw = "auto" if gpu["present"] else "disabled"
decoder = "cpu"
if "vaapi" in hwaccels and gpu["render_nodes"]:
decoder = "vaapi"
elif "v4l2m2m" in hwaccels:
decoder = "v4l2m2m"
elif ("cuda" in hwaccels or "nvdec" in hwaccels) and kernel_features.get("nvidia"):
decoder = "cuda"
hdmi_player = "cpu"
if shutil.which("mpv") and gpu["cards"]:
hdmi_player = "mpv-drm"
elif shutil.which("ffplay") and (os.environ.get("DISPLAY") or shutil.which("startx")):
hdmi_player = "ffplay-x11"
risk = []
if not gpu["present"]:
risk.append("No DRM/VA render node detected, browser and HDMI playback will stay on conservative settings")
if decoder == "cpu":
risk.append("No safe hardware decoder detected, ffmpeg workloads will remain on CPU")
if hdmi_player == "cpu":
risk.append("No direct HDMI playback stack detected, install mpv or X11+ffplay for full-screen output")
if not capture.get("video_devices"):
risk.append("No /dev/video capture input detected, TikTok HDMI ingest cannot start yet")
return {
"video_decoder": decoder,
"browser_hwaccel": browser_hw,
"hdmi_player": hdmi_player,
"stability_mode": "safe" if risk else "balanced",
"degradation_reasons": risk,
}
def build_profile() -> dict:
profile = {
"status": "ok",
"arch": platform.machine(),
"kernel": platform.release(),
"platform": platform.platform(),
"ffmpeg_hwaccels": detect_ffmpeg_hwaccels(),
"gpu": detect_gpu(),
"npu": detect_npu(),
"kernel_features": detect_kernel_features(),
"video_capture": detect_video_capture(),
"network": detect_network(),
}
profile["recommendation"] = recommend(profile)
return profile
def suggest_video_encoder(profile: dict) -> str:
"""在 Linux 上根据 ffmpeg 能力与探测结果给出可选硬件编码器名(供 douyin→YouTube 读取 LIVE_VIDEO_ENCODER)。
优先级:RKMPP(常见 ARM SoC)→ V4L2M2M(通用 ARM/部分板)→ VA-API(x86 核显)。
NVIDIA 由 douyin_youtube_ffplay 内单独检测 h264_nvenc,此处不重复写入。
QSV 在部分 Linux 发行版上需要额外的设备/滤镜链路,本项目默认不自动启用,以优先保证跨机兼容性。
"""
if platform.system().lower() != "linux":
return ""
text = run_text(["ffmpeg", "-hide_banner", "-encoders"])
if not text:
return ""
hwaccels = set(profile.get("ffmpeg_hwaccels") or [])
gpu = profile.get("gpu") or {}
render_nodes = list(gpu.get("render_nodes") or [])
render_ok = bool(render_nodes)
vaapi_device = str(render_nodes[0]) if render_nodes else ""
machine = platform.machine().lower()
has_v4l2_device = any(Path("/dev").glob("video*"))
if machine in ("aarch64", "arm64", "armv7l", "armv8l"):
if (
"h264_rkmpp" in text
and Path("/dev/mpp_service").exists()
and ffmpeg_encoder_smoke_test("h264_rkmpp")
):
return "h264_rkmpp"
if (
"h264_v4l2m2m" in text
and has_v4l2_device
and ffmpeg_encoder_smoke_test("h264_v4l2m2m")
):
return "h264_v4l2m2m"
return ""
if (
"h264_vaapi" in text
and render_ok
and "vaapi" in hwaccels
and ffmpeg_encoder_smoke_test("h264_vaapi", vaapi_device=vaapi_device)
):
return "h264_vaapi"
return ""
def write_outputs(profile: dict) -> None:
CONFIG_DIR.mkdir(parents=True, exist_ok=True)
JSON_PATH.write_text(json.dumps(profile, indent=2, ensure_ascii=False), encoding="utf-8")
enc = suggest_video_encoder(profile)
env_lines = [
f"LIVE_HW_DECODER={profile['recommendation']['video_decoder']}",
f"LIVE_HDMI_PLAYER={profile['recommendation']['hdmi_player']}",
f"LIVE_BROWSER_HWACCEL={profile['recommendation']['browser_hwaccel']}",
f"LIVE_STABILITY_MODE={profile['recommendation']['stability_mode']}",
]
if enc:
env_lines.append(f"LIVE_VIDEO_ENCODER={enc}")
else:
env_lines.append("# LIVE_VIDEO_ENCODER= # optional: h264_v4l2m2m / h264_rkmpp when ffmpeg supports it")
ENV_PATH.write_text("\n".join(env_lines) + "\n", encoding="utf-8")
def main() -> None:
parser = argparse.ArgumentParser(description="Probe Linux hardware capabilities for safe runtime defaults")
parser.add_argument("--write", action="store_true", help="Write JSON and env files into config/")
args = parser.parse_args()
profile = build_profile()
if args.write:
write_outputs(profile)
print(json.dumps(profile, ensure_ascii=False))
if __name__ == "__main__":
main()

608
d2ypp2/scripts/launch.py Normal file
View File

@ -0,0 +1,608 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
一键启动 Web 控制台:
生产:构建 web-console(若需要)+ 仅 uvicorn(单端口托管 API + 静态页)
开发:uvicorn + Next dev(默认绑定 0.0.0.0,局域网可访问)
自动加载 config/runtime.env(若存在,不覆盖已有环境变量)。
用法:
python scripts/launch.py
python scripts/launch.py --dev
python scripts/launch.py --port 8101
python scripts/launch.py --skip-build
python scripts/launch.py --no-env-check
环境变量: HOST, PORT, NEXT_DEV_PORT, WEB_STACK=api, API_PROXY_TARGET(开发)
"""
from __future__ import annotations
import argparse
import hashlib
import json
import os
import re
import shutil
import subprocess
import sys
import time
from dataclasses import dataclass
from pathlib import Path
if hasattr(sys.stdout, "reconfigure"):
try:
sys.stdout.reconfigure(encoding="utf-8")
sys.stderr.reconfigure(encoding="utf-8")
except Exception:
pass
ROOT = Path(__file__).resolve().parent.parent
SCRIPTS_DIR = Path(__file__).resolve().parent
CONSOLE = ROOT / "web-console"
OUT_INDEX = CONSOLE / "out" / "index.html"
OUT_STAMP = CONSOLE / "out" / ".build-stamp.json"
MIN_WEB_NODE_MAJOR = 18
DOCKER_NODE_IMAGE = os.environ.get("WEB_CONSOLE_NODE_IMAGE", "node:20-bookworm-slim")
sys.path.insert(0, str(ROOT))
sys.path.insert(0, str(SCRIPTS_DIR))
import env_check # noqa: E402
from src.runtime_bootstrap import ensure_runtime_layout, raise_nofile_limit # noqa: E402
def load_runtime_env() -> None:
path = ROOT / "config" / "runtime.env"
if not path.is_file():
return
for raw in path.read_text(encoding="utf-8").splitlines():
line = raw.strip()
if not line or line.startswith("#"):
continue
if "=" not in line:
continue
k, _, v = line.partition("=")
k, v = k.strip(), v.strip().strip('"').strip("'")
if k and k not in os.environ:
os.environ[k] = v
@dataclass(frozen=True)
class NodeRuntime:
node: Path
major: int
npm: Path | None
source: str
def _node_version_major(node_bin: str | Path) -> int | None:
try:
raw = subprocess.check_output([str(node_bin), "-v"], stderr=subprocess.STDOUT, text=True).strip()
except Exception:
return None
match = re.match(r"v(\d+)\.", raw)
if not match:
return None
return int(match.group(1))
def _candidate_node_bins() -> list[Path]:
seen: set[str] = set()
out: list[Path] = []
def add(path_like: str | Path | None) -> None:
if not path_like:
return
p = Path(path_like).expanduser()
if p.is_dir():
p = p / "node"
key = str(p.resolve() if p.exists() else p)
if key in seen or not p.exists():
return
seen.add(key)
out.append(p)
add(shutil.which("node"))
for name in ("node22", "node20", "node18", "node"):
add(shutil.which(name))
nvm_bin = os.environ.get("NVM_BIN")
if nvm_bin:
add(Path(nvm_bin) / "node")
for env_var in ("VOLTA_HOME", "MISE_INSTALL_PATH"):
base = os.environ.get(env_var)
if base:
add(Path(base) / "bin" / "node")
home = Path.home()
for p in [
home / ".nvm" / "versions" / "node",
home / ".asdf" / "installs" / "nodejs",
home / ".local" / "share" / "mise" / "installs" / "node",
Path("/usr/local/bin/node"),
Path("/opt/homebrew/bin/node"),
Path("/usr/bin/node"),
]:
if p.is_dir():
for c in sorted(p.glob("*/bin/node")):
add(c)
else:
add(p)
return out
def _pick_node_runtime(min_major: int = MIN_WEB_NODE_MAJOR) -> NodeRuntime | None:
best: NodeRuntime | None = None
for node in _candidate_node_bins():
major = _node_version_major(node)
if major is None:
continue
npm = node.with_name("npm")
if not npm.exists():
npm = shutil.which("npm", path=str(node.parent))
npm = Path(npm) if npm else None
runtime = NodeRuntime(node=node, major=major, npm=npm, source="local")
if major >= min_major:
return runtime
if best is None or major > best.major:
best = runtime
return best
def _runtime_env(runtime: NodeRuntime, extra: dict[str, str] | None = None) -> dict[str, str]:
env = os.environ.copy()
path = env.get("PATH", "")
node_dir = str(runtime.node.parent)
env["PATH"] = f"{node_dir}{os.pathsep}{path}" if path else node_dir
env.setdefault("NEXT_TELEMETRY_DISABLED", "1")
if runtime.npm is not None:
env["npm_config_script_shell"] = env.get("npm_config_script_shell", "/bin/sh")
if extra:
env.update(extra)
return env
def _console_source_paths() -> list[Path]:
roots = [
CONSOLE / "app",
CONSOLE / "components",
CONSOLE / "lib",
]
files = [
CONSOLE / "middleware.ts",
CONSOLE / "next.config.mjs",
CONSOLE / "package.json",
CONSOLE / "package-lock.json",
CONSOLE / "pnpm-lock.yaml",
CONSOLE / "postcss.config.mjs",
CONSOLE / "tailwind.config.ts",
CONSOLE / "tsconfig.json",
CONSOLE / "README.md",
]
source_paths = [path for path in files if path.is_file()]
for root in roots:
if not root.exists():
continue
source_paths.extend(path for path in root.rglob("*") if path.is_file())
return sorted(source_paths, key=lambda item: item.relative_to(CONSOLE).as_posix())
def _console_sources_mtime() -> float:
latest = 0.0
for path in _console_source_paths():
latest = max(latest, path.stat().st_mtime)
return latest
def _console_sources_hash() -> str:
digest = hashlib.sha256()
for path in _console_source_paths():
rel = path.relative_to(CONSOLE).as_posix()
digest.update(rel.encode("utf-8", "surrogateescape"))
digest.update(b"\0")
try:
digest.update(path.read_bytes())
except OSError:
digest.update(b"<unreadable>")
digest.update(b"\0")
return digest.hexdigest()
def _read_console_stamp() -> dict[str, object] | None:
if not OUT_STAMP.is_file():
return None
try:
return json.loads(OUT_STAMP.read_text(encoding="utf-8"))
except Exception:
return None
def _console_needs_rebuild() -> bool:
if not OUT_INDEX.is_file():
return True
stamp = _read_console_stamp()
if not stamp:
return True
source_hash = str(stamp.get("source_hash") or "")
if source_hash and source_hash == _console_sources_hash():
return False
try:
src_mtime = float(stamp.get("source_mtime") or 0.0)
except Exception:
return True
return _console_sources_mtime() > src_mtime + 0.5
def _write_console_stamp(*, toolchain: str, major: int | None = None) -> None:
try:
OUT_STAMP.parent.mkdir(parents=True, exist_ok=True)
payload = {
"built_at": time.time(),
"source_mtime": _console_sources_mtime(),
"source_hash": _console_sources_hash(),
"toolchain": toolchain,
"node_major": major,
}
OUT_STAMP.write_text(json.dumps(payload, ensure_ascii=False, indent=2), encoding="utf-8")
except Exception:
pass
def _docker_available() -> str | None:
return shutil.which("docker")
def _run_console_cmd(cmd: list[str], *, cwd: Path, env: dict[str, str]) -> int:
return subprocess.call(cmd, cwd=cwd, env=env)
def _npm_cmd(runtime: NodeRuntime | None = None) -> str:
if runtime and runtime.npm is not None:
return str(runtime.npm)
return shutil.which("npm") or "npm"
def _try_local_console_build() -> tuple[bool, str]:
runtime = _pick_node_runtime()
if runtime is None:
return False, "未找到可用 Node.js"
if runtime.major < MIN_WEB_NODE_MAJOR:
return False, f"当前 Node {runtime.major} 过低"
if runtime.npm is None:
return False, f"找到 Node {runtime.node},但未找到同目录 npm"
env = _runtime_env(runtime)
npm = _npm_cmd(runtime)
print(f"[launch] 使用本机 Node {runtime.major} 构建 Web 控制台: {runtime.node}")
rebuild = _console_needs_rebuild()
if not rebuild:
print("[launch] 控制台产物已是最新。")
return True, "up-to-date"
print("[launch] 正在构建 Web 控制台…")
for path in (CONSOLE / "node_modules", CONSOLE / ".next"):
if path.exists():
shutil.rmtree(path, ignore_errors=True)
lock = CONSOLE / "package-lock.json"
if lock.is_file():
rc = _run_console_cmd([npm, "ci"], cwd=CONSOLE, env=env)
if rc != 0:
print("[launch] npm ci 失败,尝试 npm install…")
rc = _run_console_cmd([npm, "install"], cwd=CONSOLE, env=env)
if rc != 0:
return False, "npm install 失败"
else:
rc = _run_console_cmd([npm, "install"], cwd=CONSOLE, env=env)
if rc != 0:
return False, "npm install 失败"
rc = _run_console_cmd([npm, "run", "build"], cwd=CONSOLE, env=env)
if rc != 0:
return False, "npm run build 失败"
_write_console_stamp(toolchain="local", major=runtime.major)
print("[launch] 前端构建完成。")
return True, "built"
def _docker_console_build() -> bool:
docker = _docker_available()
if not docker:
return False
print(f"[launch] 本机 Node 不足,改用 Docker 构建: {DOCKER_NODE_IMAGE}")
script = (
"set -e; "
"rm -rf /tmp/web-console; "
"mkdir -p /tmp/web-console; "
"cd /workspace/web-console; "
"tar --exclude=node_modules --exclude=.next --exclude=out -cf - . | tar -C /tmp/web-console -xf -; "
"cd /tmp/web-console; "
"rm -rf node_modules .next out; "
"export HOME=/tmp npm_config_cache=/tmp/npm-cache; "
"if [ -f package-lock.json ]; then npm ci || npm install; else npm install; fi; "
"test -x node_modules/.bin/next; "
"npm run build; "
"rm -rf /workspace/web-console/out; "
"cp -a out /workspace/web-console/out"
)
cmd = [
docker,
"run",
"--rm",
"-u",
f"{os.getuid()}:{os.getgid()}",
"-e",
"HOME=/tmp",
"-e",
"npm_config_cache=/tmp/npm-cache",
"-v",
f"{ROOT}:/workspace",
"-w",
"/workspace",
DOCKER_NODE_IMAGE,
"sh",
"-lc",
script,
]
rc = subprocess.call(cmd, cwd=ROOT)
if rc != 0:
return False
_write_console_stamp(toolchain="docker", major=20)
print("[launch] Docker 构建完成。")
return True
def ensure_console_built(*, skip: bool, strict: bool = False) -> bool:
"""返回是否已存在可托管的静态 index。"""
if skip:
return OUT_INDEX.is_file()
if not CONSOLE.is_dir():
print("[launch] 未找到 web-console,将仅使用根目录 index.html(若存在)。")
return False
if not _console_needs_rebuild():
return True
ok, reason = _try_local_console_build()
if ok:
return True
if _docker_console_build():
return True
if OUT_INDEX.is_file() and not strict:
print(
f"[launch] {reason},但检测到已有 web-console/out/index.html,将继续启动。"
" 如需刷新,请安装 Node 18+ 或 Docker 后重新构建。",
)
return True
print(
f"[launch] {reason},且未能通过 Docker 兜底构建 Web 控制台。"
" 请安装 Node 18+ / pnpm 或启用 Docker。",
)
sys.exit(1)
def _terminate_process(p: subprocess.Popen | None) -> None:
if p is None or p.poll() is not None:
return
p.terminate()
try:
p.wait(timeout=8)
except subprocess.TimeoutExpired:
p.kill()
p.wait(timeout=3)
def _console_dev_runtime() -> NodeRuntime | None:
runtime = _pick_node_runtime()
if runtime is None:
return None
if runtime.major < MIN_WEB_NODE_MAJOR or runtime.npm is None:
return None
return runtime
def _start_local_console_dev(*, host: str, port: str, next_port: str) -> subprocess.Popen | None:
runtime = _console_dev_runtime()
if runtime is None:
return None
env = _runtime_env(runtime, {"API_PROXY_TARGET": f"http://127.0.0.1:{port}"})
npm = _npm_cmd(runtime)
node_modules = CONSOLE / "node_modules"
if not node_modules.exists():
lock = CONSOLE / "package-lock.json"
print("[launch] 未检测到 web-console/node_modules,先安装依赖…")
install_cmd = [npm, "ci"] if lock.is_file() else [npm, "install"]
if _run_console_cmd(install_cmd, cwd=CONSOLE, env=env) != 0:
print("[launch] 依赖安装失败,准备尝试 Docker 兜底。")
return None
cmd = [npm, "run", "dev", "--", "--hostname", "0.0.0.0", "--port", next_port]
return subprocess.Popen(cmd, cwd=CONSOLE, env=env)
def _start_docker_console_dev(*, host: str, port: str, next_port: str) -> subprocess.Popen | None:
docker = _docker_available()
if not docker:
return None
proxy_target = f"http://host.docker.internal:{port}"
script = (
"set -e; "
"cd /workspace/web-console; "
"if [ ! -x node_modules/.bin/next ]; then rm -rf node_modules .next; fi; "
"if [ ! -d node_modules ]; then "
"if [ -f package-lock.json ]; then npm ci || npm install; else npm install; fi; "
"fi; "
"npm run dev -- --hostname 0.0.0.0 --port 3000"
)
cmd = [
docker,
"run",
"--rm",
"--add-host",
"host.docker.internal:host-gateway",
"-p",
f"{next_port}:3000",
"-e",
f"API_PROXY_TARGET={proxy_target}",
"-e",
"HOME=/tmp",
"-e",
"npm_config_cache=/tmp/npm-cache",
"-e",
"HOST=0.0.0.0",
"-e",
"PORT=3000",
"-e",
"WATCHPACK_POLLING=true",
"-e",
"CHOKIDAR_USEPOLLING=true",
"-e",
"NEXT_TELEMETRY_DISABLED=1",
"-v",
f"{ROOT}:/workspace",
"-w",
"/workspace",
DOCKER_NODE_IMAGE,
"sh",
"-lc",
script,
]
print(f"[launch] 本机 Node 不足,改用 Docker 开发容器: {DOCKER_NODE_IMAGE}")
return subprocess.Popen(cmd, cwd=ROOT)
def run_dev(host: str, port: str, next_port: str) -> None:
api_url = f"http://127.0.0.1:{port}"
api_cmd = [
sys.executable,
"-m",
"uvicorn",
"web:app",
"--host",
host,
"--port",
port,
"--reload",
]
os.chdir(ROOT)
api: subprocess.Popen | None = None
ui: subprocess.Popen | None = None
try:
api = subprocess.Popen(api_cmd, cwd=ROOT)
time.sleep(0.6)
if api.poll() is not None:
print("[launch] API 进程异常退出,请检查端口是否被占用。")
sys.exit(api.returncode or 1)
ui = _start_local_console_dev(host=host, port=port, next_port=next_port)
if ui is None:
ui = _start_docker_console_dev(host=host, port=port, next_port=next_port)
if ui is None:
print("[launch] 未找到可用的 Node 18+ 或 Docker,无法启动 Next dev。")
print("[launch] 仅起 API 请用: python scripts/launch.py --api-only --reload")
sys.exit(1)
print()
print(" —— 开发模式(局域网可访问)——")
print(f" 控制台界面: http://0.0.0.0:{next_port} 或用本机 IP + 端口")
print(f" API: http://{host}:{port}/ (Next 已代理同名接口到 {api_url})")
print(" 按 Ctrl+C 可同时结束前后端")
if host == "0.0.0.0":
print(" 提示: 绑定 0.0.0.0 时请勿把管理端口暴露到公网")
print()
while True:
time.sleep(0.5)
if api.poll() is not None:
print("[launch] API 已退出")
break
if ui and ui.poll() is not None:
print("[launch] Next 已退出")
break
except KeyboardInterrupt:
print("\n[launch] 正在关闭…")
finally:
_terminate_process(ui)
_terminate_process(api)
def run_api_only(host: str, port: str, reload: bool) -> None:
os.chdir(ROOT)
cmd = [sys.executable, "-m", "uvicorn", "web:app", "--host", host, "--port", port]
if reload:
cmd.append("--reload")
os.execvp(sys.executable, cmd)
def run_prod(host: str, port: str, skip_build: bool, reload: bool) -> None:
ensure_console_built(skip=skip_build)
run_api_only(host, port, reload)
def main() -> None:
load_runtime_env()
raise_nofile_limit()
runtime_issues = ensure_runtime_layout(ROOT)
if runtime_issues:
print("[launch] warning: some runtime directories are not writable by the current user:", file=sys.stderr)
for issue in runtime_issues:
print(f"[launch] - {issue}", file=sys.stderr)
print(
"[launch] hint: fix deployment ownership for runtime dirs such as config/logs/backup_config/.pm2/.process_runner/downloads/backup",
file=sys.stderr,
)
default_port = os.environ.get("PORT", "8001")
ap = argparse.ArgumentParser(description="直播控制台一键启动")
ap.add_argument("--dev", action="store_true", help="开发:API + Next(需 Node)")
ap.add_argument(
"--api-only",
action="store_true",
help="仅 uvicorn,不构建、不启动 Next",
)
ap.add_argument("--host", default=None, help="监听地址(默认生产 0.0.0.0,可经 HOST 环境变量)")
ap.add_argument("--port", default=None, help="端口(默认 PORT 或 8001)")
ap.add_argument("--skip-build", action="store_true", help="跳过前端构建检测")
ap.add_argument("--build-only", action="store_true", help="只构建 web-console,不启动 API")
ap.add_argument("--reload", action="store_true", help="uvicorn --reload(生产慎用)")
ap.add_argument("--no-env-check", action="store_true", help="跳过环境分析")
args = ap.parse_args()
if os.environ.get("WEB_STACK", "").lower() == "api":
args.api_only = True
port = str(args.port if args.port is not None else default_port)
next_port = os.environ.get("NEXT_DEV_PORT", "3000")
if args.dev:
host = args.host or os.environ.get("HOST") or "0.0.0.0"
else:
host = args.host or os.environ.get("HOST") or "0.0.0.0"
os.environ["HOST"] = host
os.environ["PORT"] = port
need_npm = bool(args.dev or args.build_only or (not args.skip_build and not args.api_only and _console_needs_rebuild()))
if not args.no_env_check:
env_check.print_env_report(
dev=bool(args.dev),
need_npm=need_npm,
host=host,
port=port,
next_port=next_port,
)
if args.dev:
run_dev(host, port, next_port)
return
if args.build_only:
ensure_console_built(skip=False, strict=True)
return
if args.api_only:
run_api_only(host, port, args.reload)
return
run_prod(host, port, skip_build=args.skip_build, reload=args.reload)
if __name__ == "__main__":
main()

View File

@ -0,0 +1,46 @@
#!/usr/bin/env bash
set -euo pipefail
SELF_DIR="$(cd "$(dirname "$0")" && pwd)"
INSTALL_TAG="all"
. "$SELF_DIR/lib/common.sh"
ensure_root "$@"
load_env
ensure_live_user
normalize_repo_root
ensure_runtime_dirs_owned_by_live
install_base_packages
install_media_packages
configure_adb_udev
install_nodejs
install_docker_stack
install_android_panel
prepare_python_runtime
prepare_web_console
install_live_console_service
configure_sudoers
configure_mdns
configure_wifi_profile
install_shellcrash
install_browser_stack
install_neko_browser
install_neko_ip_watch_service
install_redroid
prepare_mitmproxy
prepare_vscode_server
prepare_uptime_kuma
prepare_openclaw
install_pulseaudio_service
install_kmscube_service
install_webtty
install_cockpit
install_netdata
prepare_homepage
prepare_filebrowser
prepare_srs
run_hardware_probe
install_live_edge_proxy
ensure_runtime_dirs_owned_by_live
print_summary "all"

View File

@ -0,0 +1,46 @@
#!/usr/bin/env bash
set -euo pipefail
SELF_DIR="$(cd "$(dirname "$0")" && pwd)"
INSTALL_TAG="business"
. "$SELF_DIR/lib/common.sh"
ensure_root "$@"
load_env
# Keep the business profile focused on the livestream stack.
ENABLE_HOMEPAGE=0
ENABLE_FILEBROWSER=0
ENABLE_COCKPIT=0
ENABLE_NETDATA=0
ensure_live_user
normalize_repo_root
ensure_runtime_dirs_owned_by_live
install_base_packages
install_media_packages
configure_adb_udev
install_nodejs
install_docker_stack
install_android_panel
prepare_python_runtime
prepare_web_console
install_live_console_service
configure_sudoers
configure_mdns
install_browser_stack
install_neko_browser
install_neko_ip_watch_service
install_redroid
prepare_mitmproxy
prepare_vscode_server
prepare_uptime_kuma
prepare_openclaw
install_pulseaudio_service
install_kmscube_service
prepare_srs
run_hardware_probe
# 与 install-hub 一致:装 Caddy live-edge,http://live.local:80 → 本机控制平面 PORT(默认 8001)
install_live_edge_proxy
ensure_runtime_dirs_owned_by_live
print_summary "business"

View File

@ -0,0 +1,48 @@
#!/usr/bin/env bash
set -euo pipefail
SELF_DIR="$(cd "$(dirname "$0")" && pwd)"
INSTALL_TAG="hub"
. "$SELF_DIR/lib/common.sh"
ensure_root "$@"
load_env
# Keep the hub profile independent from the livestream business stack.
ENABLE_SRS=0
ensure_live_user
normalize_repo_root
ensure_runtime_dirs_owned_by_live
install_base_packages
install_media_packages
configure_adb_udev
install_nodejs
install_docker_stack
install_android_panel
prepare_python_runtime
prepare_web_console
install_live_console_service
configure_sudoers
configure_mdns
configure_wifi_profile
install_shellcrash
install_browser_stack
install_neko_browser
install_neko_ip_watch_service
install_redroid
prepare_mitmproxy
prepare_vscode_server
prepare_uptime_kuma
prepare_openclaw
install_pulseaudio_service
install_kmscube_service
install_webtty
install_cockpit
install_netdata
prepare_homepage
prepare_filebrowser
run_hardware_probe
install_live_edge_proxy
ensure_runtime_dirs_owned_by_live
print_summary "hub"

View File

@ -0,0 +1,26 @@
#!/usr/bin/env bash
set -euo pipefail
ROOT_DIR="$(cd "$(dirname "$0")/../.." && pwd)"
PROFILE="${1:-all}"
case "$PROFILE" in
hub|core|sh)
exec bash "$ROOT_DIR/scripts/linux/install_hub.sh" "${@:2}"
;;
business|app|sh2)
exec bash "$ROOT_DIR/scripts/linux/install_business.sh" "${@:2}"
;;
all|full)
exec bash "$ROOT_DIR/scripts/linux/install_all.sh" "${@:2}"
;;
*)
cat <<USAGE
Usage:
scripts/linux/install_stack.sh hub
scripts/linux/install_stack.sh business
scripts/linux/install_stack.sh all
USAGE
exit 1
;;
esac

View File

@ -0,0 +1,64 @@
#!/usr/bin/env bash
set -euo pipefail
ROOT_DIR="$(cd "$(dirname "$0")/../.." && pwd)"
CONFIG_DIR="$ROOT_DIR/config"
[ -f "$CONFIG_DIR/system-stack.env" ] && set -a && . "$CONFIG_DIR/system-stack.env" && set +a
[ -f "$CONFIG_DIR/hardware.env" ] && set -a && . "$CONFIG_DIR/hardware.env" && set +a
case "$(uname -m)" in
x86_64|amd64)
browser_bin="$(
command -v google-chrome 2>/dev/null \
|| command -v google-chrome-stable 2>/dev/null \
|| command -v chromium 2>/dev/null \
|| command -v chromium-browser 2>/dev/null \
|| true
)"
;;
*)
browser_bin="$(
command -v chromium 2>/dev/null \
|| command -v chromium-browser 2>/dev/null \
|| command -v google-chrome 2>/dev/null \
|| command -v google-chrome-stable 2>/dev/null \
|| true
)"
;;
esac
if [ -z "$browser_bin" ]; then
echo "MESSAGE=Chromium or Google Chrome is not installed"
exit 1
fi
profile_dir="${BROWSER_PROFILE_DIR:-$HOME/.local/share/live-browser/profile}"
start_url="${BROWSER_START_URL:-https://www.tiktok.com/live}"
locale="${BROWSER_LOCALE:-zh-CN}"
debug_port="${BROWSER_REMOTE_DEBUG_PORT:-9222}"
mkdir -p "$profile_dir"
args=(
"--user-data-dir=$profile_dir"
"--password-store=basic"
"--lang=$locale"
"--no-first-run"
"--restore-last-session"
"--remote-debugging-port=$debug_port"
"--start-maximized"
"--ozone-platform-hint=auto"
)
if [ "${LIVE_BROWSER_HWACCEL:-auto}" = "disabled" ]; then
args+=("--disable-gpu")
fi
if [ -n "${BROWSER_EXTRA_FLAGS:-}" ]; then
# shellcheck disable=SC2206
extra_flags=(${BROWSER_EXTRA_FLAGS})
args+=("${extra_flags[@]}")
fi
exec "$browser_bin" "${args[@]}" "$start_url"

Some files were not shown because too many files have changed in this diff Show More