Skip to content

armgit / peach

Public Imported from GitHub
0

Peach: Local-first video metadata scraper and media manager.

feat(media): 设置里统一成按媒体库的媒体修复,缺索引的 MP4 用 untrunc 重建

longmeidao39eea19b6a12
diff --git a/docs/PRODUCT_BACKLOG.md b/docs/PRODUCT_BACKLOG.md
index 5287395d3..702464359 100644
--- a/docs/PRODUCT_BACKLOG.md
+++ b/docs/PRODUCT_BACKLOG.md
@@ -82,7 +82,7 @@ shuffle_key 改变随机浏览的序列语义,先测关系筛选收益再决
32. **系统清理与瘦身**:一个统一入口,先按类别列出各自占多少、删掉会失去什么,再由用户挑着清。可清的有头像与 Logo 的候选缓存(`provider-cache/` 下的 `objects/`、`requests/`)、抽帧与九宫格、HLS 分片与转码产物、复核 CSV 与标注图、日志与 state 快照。分档判据是「删了之后要重做一遍什么」:请求快照删了只是下次重取,`evidence/` 是「这个人用过哪些图」的历史、删了换头像就再也找不回旧图,两者不能同档。账本、真实媒体、备份和 `avatars-superseded/` 不在清理范围内。
起因是换头像功能把取到的每一张图都留在候选缓存里,盘上只增不减;但入口本身要按上面整张清单做,不是只清头像。
-33. **闲置时段跑后台任务**:判定用户此刻没在用 Peach,把不赶时间的活挪到那段时间自己跑,用户回来就让出资源。现在这类任务都要手点一下才动,播放兼容修复是第一个(`src/peach/web_media_repair.py`),抽帧、九宫格补齐、封面重探、probe 补时长都是同一类。要定的是闲不闲怎么判(最近一次播放与请求的间隔、是否有别的长跑任务在占盘)、哪些任务愿意进这个队列、抢占之后怎么记断点,以及计费来源要不要单独设闸。
+33. **闲置时段跑后台任务**:判定用户此刻没在用 Peach,把不赶时间的活挪到那段时间自己跑,用户回来就让出资源。现在这类任务都要手点一下才动,媒体修复是第一个(`src/peach/web_media_repair.py`),抽帧、九宫格补齐、封面重探、probe 补时长都是同一类。要定的是闲不闲怎么判(最近一次播放与请求的间隔、是否有别的长跑任务在占盘)、哪些任务愿意进这个队列、抢占之后怎么记断点,以及计费来源要不要单独设闸。
34. **文件发现改成推**:本地来源接 watchdog 事件、CloudDrive2 来源接它的 webhook,文件一落地就登记,不必等下一次全量扫描。云端路径按「云端前缀 → 挂载盘符」的映射翻译,不能拿本机 `pathlib` 解析 webhook 里那个路径——那是 CloudDrive2 自己的命名空间,在本机不存在。定期全量扫描保留为兜底:事件会丢(服务没起、挂载断开、webhook 投递失败),而「少登记了一个文件」这件事没有任何征兆。前置是来源类型字段(见第 10 条),本地与云端两条通道按类型分流。
合计:**41 项开放需求**,其中 7 项已有骨架,34 项尚未实现。已完成的需求不在这里留痕,去 Git 历史查。
diff --git a/docs/REUSE.md b/docs/REUSE.md
index 279683336..0d21a1979 100644
--- a/docs/REUSE.md
+++ b/docs/REUSE.md
@@ -251,6 +251,7 @@ CloudDrive 为外部应用,本项目不捆绑其二进制或依赖其管理 AP
| 已确认厂牌的目录归位 | Javinizer-Go v1.5.2 organizer 只作冲突预检、模板化目录和回滚边界参考,不让它持有 Peach ledger | `rehome_unknown_jav.py` 只消费人工确认映射;先出逐文件 CSV,拒绝扁平化重名与厂牌冲突,SQLite 备份后移动文件并同步 Peach 路径/实体 provenance |
| FC2 目录元数据与跨号证据 | 已缓存的 fc2cmadb Inertia `article`/评论收获;Javinizer-Go v1.5.2 的 FC2 解析器只作官方商品页字段边界参考 | 2026-08-31 登录态实测旧文章仍提供标题、原始标签、日期、时长、卖家、FC2 CDN 封面与 `comments`;Peach 只把无歧义标签翻译成现有词表,标题/标签进入 `/review`,实测 `w1200` 封面经尺寸与解码门槛落生成产物;稳定 pair、合集/分片保护、hash/时长/尺寸佐证、库外 evidence、健康统计和人工复核仍由 Peach 管,不依赖 FC2-Leak-Detector/JavSP,也不把镜像候选直写 ledger |
| 媒体探测/转码 | Peach 管理的 FFmpeg/ffprobe;Windows 已实测 FFmpeg 9.0.1 full build 的 CUDA/NVDEC、`scale_cuda` 与 NVENC,现有二进制启用 GPL/version3。CI 复用 `FedericoCarboni/setup-ffmpeg@v3`(MIT)并固定 FFmpeg 9.0.1;Gyan 官方 x64 full build 的 7z 为 165,742,351 字节,Python 3.12/3.14 的 Windows runner 共用同一版本。默认 `release` 会访问 Gyan 易失的 `release-version` 端点,2026-09-19 实测返回空响应并让两组 Windows 测试在执行前失败;固定版本改从 GyanD/codexffmpeg 的精确 GitHub release 资产下载。 | 任务策略和 Media Engine 编排:容器与内部编码分别检查,MP4/M4V 的 H.264 8-bit 与兼容音轨可直出;其余容器中的 H.264 8-bit 优先只换 MP4 封装;其余 Windows 输入依次尝试 CUDA→H.264 NVENC、软件解码→NVENC、原 `libx264` 回退,macOS 保持封装复制或软件转码。2026-09-05 的 JBS-023 原片为 MPEG-4 Part 2/AAC,12 秒样本经既有 FFmpeg 链路在 2.42 秒输出 H.264/AAC 并通过画面解码;兼容性依据为 MDN Web video codec guide 与 ffprobe 官方 stream 文档。真实 CloudDrive POC 中,H.264/AAC 的 30 秒片段封装耗时 0.64 秒,1080p HEVC 的 30 秒 CUDA/NVENC 转码耗时 1.60 秒;不新增 Python 依赖,不改生产、原媒体或 ledger。 |
+| 缺索引 MP4 重建 | untrunc(anthwlock,GPL-2.0,用户自行解压到 `<数据根>/tools/untrunc/`,也认 `PEACH_UNTRUNC` 与 PATH),按 `-n -s -dst` 借一部同编码器的完整片子当参照切 `mdat`;不随 Peach 分发,「运行信息」给下载入口 | `src/peach/mp4recover.py` 挑参照(同目录按文件名挨得最近的先试,最多 4 部)、验收(解码错误不超过 3 行、音视频时长差不超过 5%)、换回原路径并把坏原件改名成同目录的 `.文件名.peach-original` 留着;缺整个 `moov` 的片子在任何播放器里都打不开,所以结果替换原文件,不像缺 `ctts` 那样另存头。2026-09-23 实测 115 上 5 部:同日期、同分辨率的邻居参照能整部或 73%~100% 切回,参照分辨率不对时每帧报宏块错误,找不到同编码参数的参照就修不了 |
| HTML5/HLS/DASH 播放 | Video.js 8.24.1 + 内置 VHS(Apache-2.0,本地固定版本) | 流方案、授权、稳定时长、回退顺序和统计面板;详情不兼容片源复用 HlsSegmentService 与 FFmpeg 按六秒编码 H.264/AAC,独立缓存、绝对时间轴及会话取消;JBS-023 首段 0.67 秒、十分钟处 1.96 秒,YRH-097 首段 1.01 秒,无整片预转码 |
| 播放器设置与影院布局 | Video.js 8.24.1 的 `playbackRate`、既有 QualityLevel、原生 tooltip 与控制栏插槽;YouTube `e937390a` 实际 DOM/CSS/JS 提供可复现的几何、状态、动画和图形证据 | Peach 在现有 DOM 上组合氛围模式、播放速度、真实清晰度和影院模式,并复用 59 px 两排控制栏、40→111 px 横向音量、4→6 px 进度动画、右侧共享胶囊、整行悬停的 274 px 设置菜单和视口级全屏;普通视图 `contain` 保全片源,全屏用 `cover` 铺满视口,接受非等比例片源的边缘裁切。全屏命中同时使用 Video.js/原生类和 `isFullscreen()` 同步的 `data-peach-fullscreen`,并覆盖 `body.vjs-full-window` 回退,不能再靠单个 CSS 类推断运行态;标准、WebKit、Gecko 等浏览器专用伪类必须放进 forgiving `:is(...)` 或拆成独立规则,不能在普通 selector list 混写后让某浏览器因未知伪类废掉整组声明。要求图形精准的设置项、radio 选中勾、菜单箭头、中央 bezel 与 loading 只 vendoring 当前锁定版本的 SVG path/spinner 结构,音量 hover 与滑轨中心沿用上游外层伪元素和 50% 几何,tooltip 仅补 Peach 两排控制栏需要的显式层级与越界可见;不复制播放器控制逻辑、不迁移到 Video.js 10 Menu,也不引入重复现有质量选择的插件 |
| 播放器时刻预览 | Video.js 原生进度控件 + Peach 自己的 `/timeline?id=&s=`(10×10 接触印相),取不到时退到既有 `/poster?id=&c=0…8` 九宫格切片 | 时间轴图由 `peach.timeline_sheets` 按每 10 或 30 秒一帧预先铺好,只覆盖 `location='local'`:网盘上的每抽一帧都要回源拉一次,实测 115 单文件抽九帧约 285 MB,两万部按每 10 秒一帧算流量以 TB 计。没铺到的片子和在线视频退回九宫格,那九格是全片九等分、只给近似时刻。抽帧与拼图命令与九宫格脚本共用 `peach.frame_capture`,不另起一份裸 ffmpeg 调用。`videojs-vtt-thumbnails` 与 `videojs-sprite-thumbnails` 都要求另建 sprite/VTT 契约并多一层运行时依赖,而格子位置的换算在 Peach 这边是一行整除,所以不引入 |
diff --git a/frontend/src/react/settings/maintenance-settings.tsx b/frontend/src/react/settings/maintenance-settings.tsx
index 7272724e5..5cbc586ca 100644
--- a/frontend/src/react/settings/maintenance-settings.tsx
+++ b/frontend/src/react/settings/maintenance-settings.tsx
@@ -1,4 +1,4 @@
-/* 「更新与维护」分组:自动更新、检查更新、播放兼容修复、运行信息、重开安装教程,卸载排在最后。 */
+/* 「更新与维护」分组:自动更新、检查更新、媒体修复、运行信息、重开安装教程,卸载排在最后。 */
import { useState, type FormEvent } from 'react';
import { confirmModal } from '@peach/legacy/ui';
diff --git a/frontend/src/react/settings/media-repair.tsx b/frontend/src/react/settings/media-repair.tsx
index c91faa777..30617cc15 100644
--- a/frontend/src/react/settings/media-repair.tsx
+++ b/frontend/src/react/settings/media-repair.tsx
@@ -1,34 +1,44 @@
-/* 播放兼容修复:把缺时间戳表的 MP4 批量修好,修完这类片子起播就走原片。
+/* 媒体修复:选一个媒体库,把里面播不了或播不顺的 MP4 批量修好。
*
* 一轮要跑几十分钟到几小时,所以这里只负责起停和看进度;跑到哪一步由服务自己记,
* 页面关掉再回来照样接得上。跑动时两秒问一次,空闲时不问。 */
import { useEffect, useState } from 'react';
+import { confirmModal } from '@peach/legacy/ui';
+import { SettingsRow } from '@/components/application/settings/settings-rows';
import { Button } from '@/components/base/buttons/button';
-import { Checkbox } from '@/components/base/checkbox/checkbox';
+import { Select, SelectItem } from '@/components/base/select/select';
import { apiGet, apiSend } from '../../api';
import { Note } from '../components/note';
import { Progress } from '../components/progress';
-import { ErrorText, Footer, Help, Section, Stack } from './section';
+import { ErrorText, Footer, Rows, Section, Stack } from './section';
import { busyProps, useAction } from './use-action';
export interface MediaRepairState {
status: string;
+ library: string;
stage: string;
checked: number;
total: number;
found: number;
repaired: number;
failed: number;
+ missing_tool: number;
skipped: number;
message: string;
error?: string;
}
+export interface RepairLibrary {
+ id: string;
+ name: string;
+ metered: boolean;
+}
+
const IDLE: MediaRepairState = {
- status: 'idle', stage: '', checked: 0, total: 0, found: 0,
- repaired: 0, failed: 0, skipped: 0, message: '',
+ status: 'idle', library: '', stage: '', checked: 0, total: 0, found: 0,
+ repaired: 0, failed: 0, missing_tool: 0, skipped: 0, message: '',
};
const count = (value: number) => Number(value).toLocaleString();
@@ -49,12 +59,24 @@ function statusLine(state: MediaRepairState): string {
return '';
}
-export function MediaRepair({ initial }: { initial?: MediaRepairState }) {
+export function MediaRepair({ initial, initialLibraries }: {
+ initial?: MediaRepairState; initialLibraries?: RepairLibrary[];
+}) {
const [state, setState] = useState<MediaRepairState>(initial || IDLE);
- const [metered, setMetered] = useState(false);
+ const [libraries, setLibraries] = useState<RepairLibrary[]>(initialLibraries || []);
+ const [chosen, setChosen] = useState('');
const action = useAction();
const running = state.status === 'running';
+ useEffect(() => {
+ if (initialLibraries) return undefined;
+ const controller = new AbortController();
+ apiGet<{ libraries: RepairLibrary[] }>('/api/libraries', controller.signal)
+ .then((result) => { if (!controller.signal.aborted) setLibraries(result.libraries || []); })
+ .catch(() => undefined);
+ return () => controller.abort();
+ }, [initialLibraries]);
+
useEffect(() => {
const controller = new AbortController();
let timer: ReturnType<typeof setTimeout>;
@@ -72,33 +94,55 @@ export function MediaRepair({ initial }: { initial?: MediaRepairState }) {
return () => { controller.abort(); clearTimeout(timer); };
}, [running]);
- const start = () => void action.run('start',
- (signal) => apiSend<MediaRepairState>('/api/media-repair',
- { allow_metered: metered, restart: true }, 'POST', signal), setState);
+ // 跑着的那一轮握着下拉框;空闲时是人选的那个,没选过就是上一轮修的库,再没有就是第一个。
+ const selected = libraries.find((row) => row.id === (running ? state.library : chosen))
+ ?? libraries.find((row) => row.id === state.library) ?? libraries[0];
+
+ const start = () => {
+ if (!selected) return;
+ void confirmModal({
+ title: `修复媒体库「${selected.name}」`,
+ body: '缺时间戳表的片子另存一份修好的头,原文件不动;缺索引的片子重建后替换原文件,'
+ + '坏原件改名成同目录的隐藏文件(.文件名.peach-original)留着。'
+ + (selected.metered ? '这个库在计费来源上,每修一部都要把片子完整拉一遍。' : ''),
+ confirmLabel: '修复媒体库',
+ onConfirm: async () => setState(await apiSend<MediaRepairState>('/api/media-repair',
+ { library: selected.id, restart: true })),
+ });
+ };
const stop = () => void action.run('stop',
(signal) => apiSend<MediaRepairState>('/api/media-repair', { stop: true }, 'POST', signal), setState);
const progress = state.total ? Math.round((state.checked / state.total) * 100) : 0;
+ const complete = state.status === 'complete';
+ const notes = [
+ running ? <Progress key="progress" label="修复进度" value={progress} /> : null,
+ complete && !state.repaired && !state.failed
+ ? <Note key="clean" tone="info" title="没有要修的">这个库里的片子都能直接播。</Note>
+ : null,
+ complete && state.missing_tool
+ ? <Note key="tool" tone="warning" title="缺少 untrunc">
+ {`${count(state.missing_tool)} 部缺索引的片子要装上 untrunc 才修得了,下载入口在「运行信息」里。`}
+ </Note>
+ : null,
+ action.error || state.error ? <ErrorText key="error">{action.error || state.error}</ErrorText> : null,
+ ].filter(Boolean);
return (
- <Section title="播放兼容修复">
- <Stack>
- <Help>
- 有些 MP4 少了一张时间戳表,浏览器按容器给的时刻排帧,会把其中一部分丢掉,看着就是卡顿。
- 修好之后这类片子起播直接用原片,不再实时转码。原始文件不改动,修好的头另存在缓存里。
- </Help>
- <Checkbox isSelected={metered} isDisabled={running} onChange={setMetered}>
- 连 PikPak 上的一起修(要把片子完整拉一遍,走流量)
- </Checkbox>
- {running ? <Progress label="修复进度" value={progress} /> : null}
- {state.status === 'complete' && !state.repaired && !state.failed
- ? <Note tone="info" title="没有要修的">库里的片子都能直接播,没找到缺时间戳表的。</Note>
- : null}
- {action.error || state.error ? <ErrorText>{action.error || state.error}</ErrorText> : null}
- </Stack>
+ <Section title="媒体修复">
+ <Rows>
+ <SettingsRow label="媒体库"
+ description="修缺时间戳表(播放卡顿)和缺索引(打不开)的 MP4。常看的片子先修。">
+ <Select aria-label="媒体库" selectedKey={selected?.id ?? null} isDisabled={running || !libraries.length}
+ onSelectionChange={(key) => { if (key !== null) setChosen(String(key)); }}>
+ {libraries.map((row) => <SelectItem key={row.id} id={row.id}>{row.name}</SelectItem>)}
+ </Select>
+ </SettingsRow>
+ </Rows>
+ {notes.length ? <Stack divided>{notes}</Stack> : null}
<Footer status={statusLine(state) ? <p role="status">{statusLine(state)}</p> : null}>
{running
? <Button onClick={stop} {...busyProps(action.busy === 'stop')}>停止</Button>
- : <Button onClick={start} {...busyProps(action.busy === 'start')}>开始修复</Button>}
+ : <Button onClick={start} disabled={!selected}>开始修复</Button>}
</Footer>
</Section>
);
diff --git a/frontend/test/react/configuration.test.tsx b/frontend/test/react/configuration.test.tsx
index 5448518ba..fd5b91fd7 100644
--- a/frontend/test/react/configuration.test.tsx
+++ b/frontend/test/react/configuration.test.tsx
@@ -29,7 +29,7 @@ const startup = {
available: true, enabled: false, silent: true, message: '', desktop: false, desktop_message: '',
};
-/** 除了配置本身,页面上还有按自己节律问的块(播放兼容修复)。按路径应答,别的路径直接空转。 */
+/** 除了配置本身,页面上还有按自己节律问的块(媒体修复)。按路径应答,别的路径直接空转。 */
function serve(config: ConfigurationData) {
const calls: string[] = [];
const fetcher = vi.fn(async (path: string) => {
diff --git a/frontend/test/react/maintenance-settings.test.tsx b/frontend/test/react/maintenance-settings.test.tsx
index 5a0b49f6c..5c810f09c 100644
--- a/frontend/test/react/maintenance-settings.test.tsx
+++ b/frontend/test/react/maintenance-settings.test.tsx
@@ -16,7 +16,9 @@ const release: ReleaseState = {
};
const uninstall = { available: true, full_available: true, message: '', data_root: 'fixture', directories: ['fixture', 'fixture/cache'] };
-it('分区依次是自动更新、检查更新、播放兼容修复、运行信息、安装教程、卸载;缺依赖的那条运行信息带下载链接', async () => {
+it('分区依次是自动更新、检查更新、媒体修复、运行信息、安装教程、卸载;缺依赖的那条运行信息带下载链接', async () => {
+ // 媒体修复一挂上就去问有哪些库,这里只看分区顺序,给它一个空库表。
+ vi.stubGlobal('fetch', fetchMock(200, { libraries: [] }));
const data: ConfigurationData = {
editable: true, notice: '', revision: 'r', media_dirs: [], port: 9123,
automatic_updates: automatic, updates: release, uninstall,
@@ -27,7 +29,7 @@ it('分区依次是自动更新、检查更新、播放兼容修复、运行信
};
const host = await mount(<MaintenanceSettings data={data} receipt={vi.fn()} reopenTutorial={vi.fn()} />);
expect([...host.firstElementChild!.children].map((node) => node.getAttribute('aria-label')))
- .toEqual(['自动更新', '检查更新', '播放兼容修复', '运行信息', '安装教程', '卸载 Peach']);
+ .toEqual(['自动更新', '检查更新', '媒体修复', '运行信息', '安装教程', '卸载 Peach']);
const facts = section(host, '运行信息')!;
expect([...facts.querySelectorAll('dt')].map((dt) => dt.textContent)).toEqual(['版本', 'FFmpeg']);
const link = facts.querySelector('a[href="https://ffmpeg.org/download.html"]');
diff --git a/frontend/test/react/media-repair.test.tsx b/frontend/test/react/media-repair.test.tsx
index 14615c943..16922180b 100644
--- a/frontend/test/react/media-repair.test.tsx
+++ b/frontend/test/react/media-repair.test.tsx
@@ -1,34 +1,67 @@
import { expect, it, vi } from 'vitest';
+import * as legacyUi from '@peach/legacy/ui';
-import { MediaRepair, type MediaRepairState } from '../../src/react/settings/media-repair';
-import { buttonNamed, click, fetchMock, mount, sentBody, settle } from './render';
+import { MediaRepair, type MediaRepairState, type RepairLibrary } from '../../src/react/settings/media-repair';
+import { buttonNamed, choose, click, fetchMock, mount, sentBody, settle } from './render';
const idle: MediaRepairState = {
- status: 'idle', stage: '', checked: 0, total: 0, found: 0, repaired: 0, failed: 0, skipped: 0, message: '',
+ status: 'idle', library: '', stage: '', checked: 0, total: 0, found: 0,
+ repaired: 0, failed: 0, missing_tool: 0, skipped: 0, message: '',
};
+const libraries: RepairLibrary[] = [
+ { id: '网盘', name: '网盘', metered: false },
+ { id: 'PikPak', name: 'PikPak', metered: true },
+];
-it('开始修复把要不要连计费来源一起发过去,随后按服务端的进度报扫描到哪一部', async () => {
+type Confirmation = Parameters<typeof legacyUi.confirmModal>[0];
+
+/** 确认弹层直接点确认,并记下弹层上写的是什么。 */
+function confirmEverything() {
+ const seen: Confirmation[] = [];
+ vi.spyOn(legacyUi, 'confirmModal').mockImplementation((async (options: Confirmation) => {
+ seen.push(options);
+ await options.onConfirm?.();
+ return { confirmed: true };
+ }) as typeof legacyUi.confirmModal);
+ return seen;
+}
+
+it('开始修复先确认,确认后把选中的库发过去,随后按服务端的进度报扫描到哪一部', async () => {
vi.useFakeTimers();
- const fetcher = fetchMock(200, { ...idle, status: 'running', stage: '扫描', checked: 3, total: 12 });
+ const seen = confirmEverything();
+ const fetcher = fetchMock(200, { ...idle, status: 'running', library: 'PikPak', stage: '扫描', checked: 3, total: 12 });
vi.stubGlobal('fetch', fetcher);
- const host = await mount(<MediaRepair initial={idle} />);
- await click(host.querySelector('input[type="checkbox"]'));
+ const host = await mount(<MediaRepair initial={idle} initialLibraries={libraries} />);
+ await choose(host.querySelector('[aria-haspopup="listbox"]'), 'PikPak');
await click(buttonNamed('开始修复', host));
await settle();
- expect(fetcher).toHaveBeenCalledTimes(1);
+ expect(seen[0]?.title).toBe('修复媒体库「PikPak」');
+ expect(seen[0]?.confirmLabel).toBe('修复媒体库');
+ expect(seen[0]?.body).toContain('每修一部都要把片子完整拉一遍');
expect(fetcher.mock.calls[0]?.[0]).toBe('/api/media-repair');
- expect(sentBody(fetcher)).toEqual({ allow_metered: true, restart: true });
+ expect(sentBody(fetcher)).toEqual({ library: 'PikPak', restart: true });
expect(host.querySelector('[role="progressbar"]')?.getAttribute('aria-valuenow')).toBe('25');
expect(host.querySelector('p[role="status"]')?.textContent).toBe('扫描 3 / 12');
expect(buttonNamed('停止', host)).not.toBeNull();
});
+it('不在计费来源上的库,确认正文不提流量', async () => {
+ const seen = confirmEverything();
+ vi.stubGlobal('fetch', fetchMock(200, idle));
+ const host = await mount(<MediaRepair initial={idle} initialLibraries={libraries} />);
+ await click(buttonNamed('开始修复', host));
+ await settle();
+ expect(seen[0]?.title).toBe('修复媒体库「网盘」');
+ expect(seen[0]?.body).toContain('坏原件改名成同目录的隐藏文件');
+ expect(seen[0]?.body).not.toContain('拉一遍');
+});
+
it('修复阶段点名当前这部片,停止之后回到可以再开始的样子', async () => {
vi.useFakeTimers();
- const fetcher = fetchMock(200, { ...idle, status: 'complete', stage: '完成', repaired: 2 });
+ const fetcher = fetchMock(200, { ...idle, status: 'complete', library: '网盘', stage: '完成', repaired: 2 });
vi.stubGlobal('fetch', fetcher);
- const host = await mount(<MediaRepair initial={{
- ...idle, status: 'running', stage: '修复', checked: 1, total: 2, found: 2, message: 'FC2-PPV-1.mp4',
+ const host = await mount(<MediaRepair initialLibraries={libraries} initial={{
+ ...idle, status: 'running', library: '网盘', stage: '修复', checked: 1, total: 2, found: 2, message: 'FC2-PPV-1.mp4',
}} />);
expect(host.querySelector('p[role="status"]')?.textContent).toBe('修复 1 / 2 · FC2-PPV-1.mp4');
await click(buttonNamed('停止', host));
@@ -38,8 +71,18 @@ it('修复阶段点名当前这部片,停止之后回到可以再开始的样
expect(buttonNamed('开始修复', host)).not.toBeNull();
});
-it('一部都没找到时说清楚是库里的片子都能直接播', async () => {
+it('一部都没找到时说清楚这个库里的片子都能直接播', async () => {
vi.useFakeTimers();
- const host = await mount(<MediaRepair initial={{ ...idle, status: 'complete', stage: '完成' }} />);
- expect(host.textContent).toContain('库里的片子都能直接播');
+ const host = await mount(<MediaRepair initialLibraries={libraries}
+ initial={{ ...idle, status: 'complete', library: '网盘', stage: '完成' }} />);
+ expect(host.textContent).toContain('这个库里的片子都能直接播');
+});
+
+it('缺索引的片子卡在没装 untrunc 上时,指明去运行信息里下载', async () => {
+ vi.useFakeTimers();
+ const host = await mount(<MediaRepair initialLibraries={libraries} initial={{
+ ...idle, status: 'complete', library: '网盘', stage: '完成', found: 2, failed: 2, missing_tool: 2,
+ }} />);
+ expect(host.querySelector('p[role="status"]')?.textContent).toBe('修好 0 部,2 部修不了');
+ expect(host.textContent).toContain('2 部缺索引的片子要装上 untrunc 才修得了');
});
diff --git a/scripts/test_runner.py b/scripts/test_runner.py
index cf73d8d8e..5a4f72e6e 100644
--- a/scripts/test_runner.py
+++ b/scripts/test_runner.py
@@ -59,7 +59,7 @@ SCOPES: dict[str, tuple[str, ...]] = {
"test_frame_capture.py", "test_timeline_sheets.py",
"test_web_timeline_thumbnails.py",
"test_interaction.py", "test_media.py", "test_mp4repair.py",
- "test_web_media_repair.py",
+ "test_mp4recover.py", "test_web_media_repair.py",
"test_previews.py",
"test_providers.py", "test_segments.py", "test_streaming.py",
"test_subtitles.py", "test_transcodes.py"),
@@ -188,7 +188,8 @@ AUTO_SCOPE_PREFIXES: tuple[tuple[str, str | tuple[str, ...]], ...] = (
# 关键帧与 ctts 都从 moov 读,测试住在 `test_segments.py` 里。
("src/peach/mp4index.py", "media"),
("src/peach/mp4repair.py", "media"),
- # 批量修头是播放链路的任务,但住在 web 层,两个域都要跑到。
+ ("src/peach/mp4recover.py", "media"),
+ # 批量修复是播放链路的任务,但住在 web 层,两个域都要跑到。
("src/peach/web_media_repair.py", ("media", "web")),
("src/peach/desktop_startup.py", "tooling"),
("src/peach/desktop_uninstall.py", "tooling"),
diff --git a/src/peach/mp4recover.py b/src/peach/mp4recover.py
new file mode 100644
index 000000000..38081e99c
--- /dev/null
+++ b/src/peach/mp4recover.py
@@ -0,0 +1,179 @@
+"""缺 `moov` 的 MP4:借同来源一部完好的片子当参照,用 untrunc 从 `mdat` 里重建索引。
+
+下载或录制没写完的 MP4 只有 `ftyp` 和 `mdat`,每一帧在哪、多大、什么时刻都记在
+`moov` 里,它缺了就没有播放器打得开。码流本身还在,untrunc 拿参照片的编码参数把
+`mdat` 逐帧切开,再写出一份带索引的新文件。
+
+参照必须和坏片出自同一台编码器、同一套参数,否则切出来的帧解不开。所以候选按目录
+与文件名远近排:同目录里名字挨着的最先试(同一批下载、同一天发布),实测命中率最高。
+修出来的文件整片解码一遍才算数,解码报错多于几行、音画时长对不上的一律不收。
+
+修好的文件换到原路径,坏原件改名成同目录的隐藏文件留着。和 `ctts` 那类只存边车不同:
+缺索引的片子在哪都打不开,时长、缩略图也都生成不了,只修 Peach 里的播放不够。
+"""
+from __future__ import annotations
+
+import os
+import shutil
+import subprocess
+from dataclasses import dataclass
+from pathlib import Path, PureWindowsPath
+
+from .mp4repair import RepairUnavailable, _top_level
+
+UNTRUNC_ENV = "PEACH_UNTRUNC"
+#: 一部坏片最多试几个参照。每试一个都要把坏片完整读一遍,网盘上是实打实的流量。
+REFERENCE_LIMIT = 4
+#: 整片解码允许的报错行数。截断处最后一帧常常不完整,实测修好的片子恰好报 1 行。
+DECODE_ERROR_LIMIT = 3
+#: 音频与视频时长差出这个比例,就是参照的采样率或帧率对不上,切出来的时间轴是错的。
+DURATION_DRIFT = 0.05
+#: 恢复出的数据到这个比例就不必再换参照了。
+GOOD_ENOUGH = 0.99
+RUN_TIMEOUT_SECONDS = 4 * 3600
+ORIGINAL_SUFFIX = ".peach-original"
+
+
+@dataclass(frozen=True)
+class Recovery:
+ path: Path
+ reference: Path
+ duration: float
+ #: 修好的片子里的媒体数据占坏片 `mdat` 的比例;片尾接了一段参数不同的内容时会明显小于 1。
+ coverage: float
+
+
+def untrunc_path(tools_root: Path) -> Path | None:
+ """环境变量指定的、Peach 托管目录里的、PATH 上的,依次找。"""
+ configured = os.environ.get(UNTRUNC_ENV)
+ if configured and Path(configured).expanduser().is_file():
+ return Path(configured).expanduser().resolve()
+ managed = Path(tools_root) / "untrunc" / f"untrunc{'.exe' if os.name == 'nt' else ''}"
+ if managed.is_file():
+ return managed.resolve()
+ found = shutil.which("untrunc")
+ return Path(found).resolve() if found else None
+
+
+def _payload_size(path: Path) -> int:
+ with open(path, "rb") as handle:
+ return sum(end - body for kind, _start, body, end in _top_level(handle) if kind == b"mdat")
+
+
+def missing_index(source: Path) -> bool:
+ """顶层有 `mdat` 却没有 `moov`。只读每个顶层盒子的头,不碰码流。"""
+ with open(source, "rb") as handle:
+ kinds = {kind for kind, *_ in _top_level(handle)}
+ return b"mdat" in kinds and b"moov" not in kinds
+
+
+def pick_references(broken: str, candidates: list[str], limit: int = REFERENCE_LIMIT) -> list[str]:
+ """候选参照按远近排:同目录优先,其次按文件名排序后离坏片有多远。
+
+ 路径是账本口径(Windows 形态)。坏片自己不在候选里。
+ """
+ target = PureWindowsPath(broken)
+ ordered = sorted({*candidates, broken}, key=lambda raw: str(PureWindowsPath(raw)).casefold())
+ rank = {raw: index for index, raw in enumerate(ordered)}
+ others = [raw for raw in candidates if raw != broken]
+ others.sort(key=lambda raw: (PureWindowsPath(raw).parent != target.parent,
+ abs(rank[raw] - rank[broken])))
+ return others[:limit]
+
+
+def _run(command: list[str], timeout: float) -> subprocess.CompletedProcess:
+ return subprocess.run(command, capture_output=True, stdin=subprocess.DEVNULL, timeout=timeout)
+
+
+def _stream_durations(ffprobe: Path, path: Path) -> dict[str, float]:
+ completed = _run([str(ffprobe), "-v", "error", "-show_entries", "stream=codec_type,duration",
+ "-of", "csv=p=0", str(path)], 120)
+ durations: dict[str, float] = {}
+ for line in completed.stdout.decode("utf-8", "replace").splitlines():
+ kind, _, value = line.strip().partition(",")
+ try:
+ durations.setdefault(kind, float(value))
+ except ValueError:
+ continue
+ return durations
+
+
+def _decode_errors(ffmpeg: Path, path: Path) -> int:
+ completed = _run([str(ffmpeg), "-v", "error", "-threads", "0", "-i", str(path), "-f", "null", "-"],
+ RUN_TIMEOUT_SECONDS)
+ lines = completed.stderr.decode("utf-8", "replace").splitlines()
+ return sum(1 for line in lines if "error while decoding" in line or "corrupt" in line)
+
+
+def acceptable(durations: dict[str, float], errors: int) -> bool:
+ """修出来的片子能不能收:有视频、解码几乎不报错、音画时长对得上。"""
+ video = durations.get("video", 0.0)
+ if video < 1 or errors > DECODE_ERROR_LIMIT:
+ return False
+ audio = durations.get("audio")
+ return audio is None or abs(audio - video) <= DURATION_DRIFT * video
+
+
+def recover(source: Path, references: list[Path], *, untrunc: Path, ffmpeg: Path, ffprobe: Path,
+ work: Path) -> Recovery:
+ """逐个参照试,收恢复得最多的那一份。一份都收不了就抛 `RepairUnavailable`。"""
+ work.mkdir(parents=True, exist_ok=True)
+ total = _payload_size(source)
+ best: Recovery | None = None
+ for index, reference in enumerate(references):
+ output = work / f"recovered-{index}.mp4"
+ output.unlink(missing_ok=True)
+ try:
+ # `-s` 跳过认不出的数据段接着往下切,不在第一处对不上的地方就收手。
+ _run([str(untrunc), "-n", "-s", "-dst", str(output), str(reference), str(source)],
+ RUN_TIMEOUT_SECONDS)
+ except (OSError, subprocess.TimeoutExpired):
+ output.unlink(missing_ok=True)
+ continue
+ if not output.is_file():
+ continue
+ durations = _stream_durations(ffprobe, output)
+ if not acceptable(durations, _decode_errors(ffmpeg, output)):
+ output.unlink()
+ continue
+ found = Recovery(output, reference, durations["video"],
+ _payload_size(output) / total if total else 0.0)
+ if best is None or found.coverage > best.coverage:
+ if best is not None:
+ best.path.unlink(missing_ok=True)
+ best = found
+ else:
+ output.unlink()
+ if best.coverage >= GOOD_ENOUGH:
+ break
+ if best is None:
+ raise RepairUnavailable("没有一个参照切得出能解码的片子")
+ return best
+
+
+def replace_original(source: Path, repaired: Path) -> Path:
+ """修好的文件换到原路径,坏原件改名成同目录的隐藏文件;返回留档的路径。
+
+ 先把新文件完整写成同目录的临时名,再做两次同目录改名:网盘上改名是服务端操作,
+ 中途失败时原件还在原路径或留档名上,不会两头落空。
+ """
+ kept = source.with_name(f".{source.name}{ORIGINAL_SUFFIX}")
+ if kept.exists():
+ raise RepairUnavailable(f"同目录已有一份留档:{kept.name}")
+ staged = source.with_name(f".{source.name}.peach-repair.tmp")
+ try:
+ shutil.copyfile(repaired, staged)
+ if staged.stat().st_size != repaired.stat().st_size:
+ raise OSError("写到原目录的副本大小不对")
+ os.replace(source, kept)
+ except BaseException:
+ staged.unlink(missing_ok=True)
+ raise
+ try:
+ os.replace(staged, source)
+ except BaseException:
+ os.replace(kept, source)
+ staged.unlink(missing_ok=True)
+ raise
+ repaired.unlink(missing_ok=True)
+ return kept
diff --git a/src/peach/routes_api.py b/src/peach/routes_api.py
index 355e8de10..7ab88c76d 100644
--- a/src/peach/routes_api.py
+++ b/src/peach/routes_api.py
@@ -92,7 +92,10 @@ def source_health(request: Request, args: dict[str, str] = Depends(require_auth)
@router.get("/api/libraries")
def media_library_list(request: Request, args: dict[str, str] = Depends(require_auth)):
from . import media_libraries, settings_file
- return {"libraries": [{"id": row["id"], "name": row["name"], "icon": row["icon"], "folders": len(row["roots"])}
+ from .jobs import SourceAccessPolicy
+ metered = SourceAccessPolicy().metered_locations
+ return {"libraries": [{"id": row["id"], "name": row["name"], "icon": row["icon"], "folders": len(row["roots"]),
+ "metered": any(root["location"] in metered for root in row["roots"])}
for row in media_libraries.libraries(settings_file.active())]}
diff --git a/src/peach/task_runs.py b/src/peach/task_runs.py
index f964c3f44..df396bc01 100644
--- a/src/peach/task_runs.py
+++ b/src/peach/task_runs.py
@@ -81,7 +81,7 @@ TASK_LABELS = {
"resource-apply": "资源对账执行",
"empty-folders": "空文件夹与失效条目清理",
"scraping-cover": "封面采集",
- "media-repair": "播放兼容修复",
+ "media-repair": "媒体修复",
"organize": "按模板整理",
"batch": "批量操作",
"scrape-codes": "番号资料刮削",
diff --git a/src/peach/web_entry.py b/src/peach/web_entry.py
index c500b3728..629f00e56 100644
--- a/src/peach/web_entry.py
+++ b/src/peach/web_entry.py
@@ -220,9 +220,11 @@ def runtime_facts(config) -> tuple[tuple[str, str], ...]:
from . import __version__
import platform as system_platform
from .ffmpeg import FFmpegResolver
+ from .mp4recover import untrunc_path
available = FFmpegResolver(config.directory("tools") / "ffmpeg").ffmpeg() is not None
ffmpeg = "可用" if available else "未安装;MP4 可直接播放,转码和缩略图需要安装 FFmpeg。"
+ untrunc = "可用" if untrunc_path(config.directory("tools")) else "未安装;缺索引的 MP4 需要它才修得了。"
return (
("版本", __version__),
("操作系统", system_platform.system()),
@@ -230,6 +232,7 @@ def runtime_facts(config) -> tuple[tuple[str, str], ...]:
("设置文件", str(config.path)),
("日志目录", str(config.directory("logs"))),
("FFmpeg", ffmpeg),
+ ("untrunc", untrunc),
)
@@ -244,4 +247,9 @@ def runtime_fact_entries(config) -> list[dict[str, str]]:
entry = next(row for row in entries if row["term"] == "FFmpeg")
entry.update(value="未找到 " + "、".join(missing) + ";转码、媒体信息与缩略图需要 FFmpeg 工具包。",
download_url="https://ffmpeg.org/download.html", download_label="下载 FFmpeg")
+ untrunc = next(row for row in entries if row["term"] == "untrunc")
+ if untrunc["value"] != "可用":
+ untrunc.update(value=untrunc["value"] + f"解压到 {config.directory('tools') / 'untrunc'}。",
+ download_url="https://github.com/anthwlock/untrunc/releases",
+ download_label="下载 untrunc")
return entries
diff --git a/src/peach/web_media_repair.py b/src/peach/web_media_repair.py
index 6e1e3b390..f5d02dbde 100644
--- a/src/peach/web_media_repair.py
+++ b/src/peach/web_media_repair.py
@@ -1,36 +1,46 @@
-"""批量把缺 `ctts` 的 MP4 头修好,让这类片子起播就走原片直发。
+"""批量修一个媒体库里播不了或播不顺的 MP4。两类毛病,一个入口:
-有 B 帧却没有 `ctts` 的片源,浏览器按容器时间戳丢帧,只能退回 HLS 实时转码。
-`mp4repair` 能重建一份头存成边车,但那是起播时后台补的:一部片要等下一次打开才
-享受得到。这里把同一件事做成一次可以在后台跑完的批量任务。
+- **缺 `ctts`**:有 B 帧却没有时间戳表,浏览器按容器时间戳丢帧,只能退回 HLS 实时转码。
+ `mp4repair` 重建一份头存成边车,原文件一个字节不动。
+- **缺 `moov`**:下载或录制没写完,整个索引都没有,在哪都打不开。`mp4recover` 借同来源
+ 的完好片子重建,修好的文件换回原路径,坏原件改名留在同目录。
两段走,因为两段的瓶颈不是一回事:
-1. **筛**:读每个片子的 `moov` 判断它是不是这一类。一次判定只读头,但 115 上就是
- 一次网络往返,所以并发做。判完的结论按「资产 + 大小 + 改动时间」落盘,下次再点
- 就不必把整个库重读一遍。
-2. **修**:整片解码一遍才问得出显示顺序,CPU 和读盘都吃满,所以串行做,并且按播放
- 次数排序——常看的先修好,中途停下也已经换来了体感。
+1. **筛**:探不出时长的片子先看顶层有没有 `moov`,其余读头判断缺不缺 `ctts`。一次判定
+ 只读头,但 115 上就是一次网络往返。判完的结论按「资产 + 大小 + 改动时间」落盘,下次
+ 再点就不必把整个库重读一遍。
+2. **修**:两类都要把整片读一遍,CPU 和读盘都吃满,所以串行做,并且按播放次数排序——
+ 常看的先修好,中途停下也已经换来了体感。
-计费来源默认不碰(`SourceAccessPolicy`):PikPak 上一部片要完整拉一遍才修得了。
+一轮只修一个库,由用户点名。选中计费来源(PikPak)上的库就是同意走流量:一部片要完整
+拉一遍才修得了。
"""
from __future__ import annotations
import json
+import shutil
+import subprocess
import time
-from pathlib import Path
+from pathlib import Path, PureWindowsPath
-from .jobs import SourceAccessPolicy
+from . import media_libraries, media_probe, mp4recover, settings_file
+from .mp4repair import RepairUnavailable
from .platform import translate_ledger_path
#: 判定结论的落盘位置,放在边车自己的目录里:它们同生同灭,清缓存时一起走。
SCAN_CACHE_NAME = "mp4-repair-scan.json"
-#: 只有这两个结论值得记:需要修的当场就修了,修完有边车为证。
+#: 只有这两个结论值得记:需要修的当场就修了,修完有边车或新文件为证。
CLEAN = "clean"
UNAVAILABLE = "unavailable"
-POLICY = SourceAccessPolicy()
+#: 缺时间戳表,修的是边车。
+HEADER = "header"
+#: 缺整个索引,修的是文件本身。
+INDEX = "index"
+
+_MP4 = "(lower({0}path) LIKE '%.mp4' OR lower({0}path) LIKE '%.m4v')"
def _cache_path(contract) -> Path:
@@ -64,27 +74,41 @@ def _key(asset_id: int, source: Path) -> str:
return f"{asset_id}-{stat.st_size}-{stat.st_mtime_ns}"
-def _candidates(contract, allow_metered: bool) -> list[tuple[int, Path]]:
- """库里所有还在的 MP4,常看的排前面。"""
- condition, parameters = POLICY.sql_filter(None, allow_metered)
+def _library_filter(library: str) -> tuple[str, list]:
+ condition, parameters = media_libraries.predicate(settings_file.active(), library)
+ if condition == "0":
+ raise ValueError("没有这个媒体库")
+ return condition, parameters
+
+
+def _candidates(contract, scope: tuple[str, list]) -> list[tuple[int, str, float | None]]:
+ """这个库里所有还在的 MP4,常看的排前面。"""
+ condition, parameters = scope
with contract.read_connection() as connection:
rows = connection.execute(
- "SELECT id,path FROM asset "
- "WHERE path IS NOT NULL AND COALESCE(disposal,'')!='trash' "
- "AND (lower(path) LIKE '%.mp4' OR lower(path) LIKE '%.m4v')" + condition
- + " ORDER BY play_count DESC, COALESCE(last_played,0) DESC, id",
+ "SELECT a.id,a.path,a.duration FROM asset a "
+ "WHERE a.path IS NOT NULL AND COALESCE(a.disposal,'')!='trash' "
+ f"AND {_MP4.format('a.')} AND {condition} "
+ "ORDER BY a.play_count DESC, COALESCE(a.last_played,0) DESC, a.id",
parameters).fetchall()
- return [(row["id"], translate_ledger_path(row["path"])) for row in rows]
+ return [(row["id"], row["path"], row["duration"]) for row in rows]
+
+def _diagnose(contract, source: Path, duration: float | None) -> str | None:
+ """这部片缺的是什么;什么都不缺回 None。"""
+ if (duration is None or duration < 0) and mp4recover.missing_index(source):
+ return INDEX
+ return HEADER if contract.transcode_service.decode_order_timestamps(source) else None
-def _survey(contract, job, job_id: str, rows, cache: dict[str, str]) -> list[tuple[int, Path]]:
+
+def _survey(contract, job, job_id: str, rows, cache: dict[str, str]) -> list[tuple[int, str, str]]:
"""筛出需要修的那些。结论边判边进缓存,中途停下也不白读。"""
store = contract.header_repairs
- transcodes = contract.transcode_service
- found: list[tuple[int, Path]] = []
- for index, (asset_id, source) in enumerate(rows, start=1):
+ found: list[tuple[int, str, str]] = []
+ for index, (asset_id, raw, duration) in enumerate(rows, start=1):
if job.snapshot() is None:
break
+ source = translate_ledger_path(raw)
try:
key = _key(asset_id, source)
except OSError:
@@ -93,11 +117,11 @@ def _survey(contract, job, job_id: str, rows, cache: dict[str, str]) -> list[tup
_advance(job, job_id, index, skipped=True)
continue
try:
- affected = transcodes.decode_order_timestamps(source)
+ kind = _diagnose(contract, source, duration)
except OSError:
- affected = False
- if affected:
- found.append((asset_id, source))
+ kind = None
+ if kind:
+ found.append((asset_id, raw, kind))
else:
cache[key] = CLEAN
_advance(job, job_id, index, skipped=False)
@@ -113,15 +137,79 @@ def _advance(job, job_id: str, checked: int, *, skipped: bool) -> None:
state["skipped"] = state.get("skipped", 0) + 1
+def _reference_candidates(contract, asset_id: int, raw: str) -> list[str]:
+ """能当参照的:同一来源、上一级目录之下、探得出时长的 MP4。"""
+ parent = PureWindowsPath(raw).parent
+ scope = parent.parent if parent.parent != parent else parent
+ prefix = str(scope).rstrip("\\") + "\\"
+ with contract.read_connection() as connection:
+ rows = connection.execute(
+ "SELECT path FROM asset WHERE location=(SELECT location FROM asset WHERE id=?) "
+ f"AND duration>0 AND COALESCE(disposal,'')!='trash' AND {_MP4.format('')} "
+ "AND substr(path,1,?)=? COLLATE NOCASE",
+ (asset_id, len(prefix), prefix)).fetchall()
+ return [row["path"] for row in rows]
+
+
+def _record_replacement(contract, asset_id: int, source: Path, ffprobe: Path) -> None:
+ """文件换了,账本跟着换:重新探时长与画面,大小和时间照扫描的口径刷新。
+
+ 115 的 SHA1 是按旧内容算的,留着会让查重把它和别的文件认成同一份,所以清掉等下次同步。
+ """
+ stat = source.stat()
+ measured = media_probe.measure(str(ffprobe), asset_id, str(source))
+ with contract.write_transaction() as connection:
+ connection.execute(media_probe.UPDATE, measured)
+ connection.execute(
+ "UPDATE asset SET size=?,mtime=?,hash=NULL,hash_kind=NULL WHERE id=?",
+ (stat.st_size, time.strftime("%Y-%m-%d", time.localtime(stat.st_mtime)), asset_id))
+ contract.cache_bust()
+
+
+def _recover(contract, asset_id: int, raw: str, tools: tuple[Path, Path, Path]) -> bool:
+ untrunc, ffmpeg, ffprobe = tools
+ source = translate_ledger_path(raw)
+ references = [translate_ledger_path(path) for path in
+ mp4recover.pick_references(raw, _reference_candidates(contract, asset_id, raw))]
+ work = Path(contract.transcode_root) / "recover" / str(asset_id)
+ try:
+ recovery = mp4recover.recover(source, references, untrunc=untrunc, ffmpeg=ffmpeg,
+ ffprobe=ffprobe, work=work)
+ mp4recover.replace_original(source, recovery.path)
+ except (RepairUnavailable, OSError, subprocess.SubprocessError):
+ return False
+ finally:
+ shutil.rmtree(work, ignore_errors=True)
+ _record_replacement(contract, asset_id, source, ffprobe)
+ return True
+
+
+def _recovery_tools(contract) -> tuple[Path, Path, Path] | None:
+ untrunc = mp4recover.untrunc_path(contract.tools_root)
+ resolver = contract.header_repairs.resolver
+ ffmpeg, ffprobe = resolver.ffmpeg(), resolver.ffprobe()
+ if untrunc is None or ffmpeg is None or ffprobe is None:
+ return None
+ return untrunc, ffmpeg.path, ffprobe.path
+
+
def _repair(contract, job, job_id: str, found, cache: dict[str, str]) -> None:
- """逐个修。一部片要整片解码一遍,所以这里刻意不并发。"""
+ """逐个修。一部片要整片读一遍,所以这里刻意不并发。"""
store = contract.header_repairs
+ tools = _recovery_tools(contract) if any(kind == INDEX for *_, kind in found) else None
job.update(job_id, stage="修复", checked=0, total=len(found), repaired=0, failed=0)
- for index, (asset_id, source) in enumerate(found, start=1):
+ for index, (asset_id, raw, kind) in enumerate(found, start=1):
if job.snapshot() is None:
return
- made = store.repair_now(asset_id, source)
- if not made:
+ source = translate_ledger_path(raw)
+ if kind == HEADER:
+ made = store.repair_now(asset_id, source)
+ elif tools is not None:
+ made = _recover(contract, asset_id, raw, tools)
+ else:
+ # 缺的是工具不是片子:装上 untrunc 之后这部还该再试,所以不记结论。
+ made = None
+ if made is False:
try:
cache[_key(asset_id, source)] = UNAVAILABLE
except OSError:
@@ -132,15 +220,16 @@ def _repair(contract, job, job_id: str, found, cache: dict[str, str]) -> None:
state["checked"] = index
state["repaired"] = state.get("repaired", 0) + (1 if made else 0)
state["failed"] = state.get("failed", 0) + (0 if made else 1)
+ state["missing_tool"] = state.get("missing_tool", 0) + (1 if made is None else 0)
state["message"] = source.name[:80]
_save_cache(contract, cache)
-def run_media_repair(contract, job_id: str, allow_metered: bool = False) -> None:
+def run_media_repair(contract, job_id: str, scope: tuple[str, list]) -> None:
"""一轮完整的批量修复。异常由 `BackgroundJob` 变成可轮询的失败状态。"""
job = contract.media_repair_job
cache = _load_cache(contract)
- rows = _candidates(contract, allow_metered)
+ rows = _candidates(contract, scope)
job.update(job_id, stage="扫描", total=len(rows), checked=0)
found = _survey(contract, job, job_id, rows, cache)
_save_cache(contract, cache)
@@ -154,18 +243,20 @@ def run_media_repair(contract, job_id: str, allow_metered: bool = False) -> None
def _public(state: dict | None) -> dict:
if state is None:
- return {"ok": True, "status": "idle", "job_id": "", "stage": "",
- "checked": 0, "total": 0, "found": 0, "repaired": 0, "failed": 0}
+ return {"ok": True, "status": "idle", "job_id": "", "library": "", "stage": "",
+ "checked": 0, "total": 0, "found": 0, "repaired": 0, "failed": 0, "missing_tool": 0}
return {
"ok": state["status"] != "failed",
"status": state["status"],
"job_id": state["job_id"],
+ "library": state.get("library", ""),
"stage": state.get("stage", ""),
"checked": int(state.get("checked", 0)),
"total": int(state.get("total", 0)),
"found": int(state.get("found", 0)),
"repaired": int(state.get("repaired", 0)),
"failed": int(state.get("failed", 0)),
+ "missing_tool": int(state.get("missing_tool", 0)),
"skipped": int(state.get("skipped", 0)),
"message": state.get("message", ""),
**({"error": state["error"]} if state["status"] == "failed" else {}),
@@ -187,10 +278,13 @@ def w_media_repair(contract, body=None):
return _public(job.snapshot())
if contract.header_repairs is None or contract.transcode_service is None:
raise ValueError("这个服务实例没有接上转码与修复组件")
- allow_metered = body.get("allow_metered") is True
+ library = str(body.get("library") or "")
+ if not library:
+ raise ValueError("先选一个媒体库")
+ scope = _library_filter(library)
return _public(job.start(
- lambda job_id: run_media_repair(contract, job_id, allow_metered),
- initial={"stage": "扫描", "total": 0, "checked": 0, "found": 0,
- "repaired": 0, "failed": 0, "skipped": 0, "message": ""},
+ lambda job_id: run_media_repair(contract, job_id, scope),
+ initial={"library": library, "stage": "扫描", "total": 0, "checked": 0, "found": 0,
+ "repaired": 0, "failed": 0, "missing_tool": 0, "skipped": 0, "message": ""},
restart=body.get("restart") is True,
))
diff --git a/tests/test_mp4recover.py b/tests/test_mp4recover.py
new file mode 100644
index 000000000..aa1978208
--- /dev/null
+++ b/tests/test_mp4recover.py
@@ -0,0 +1,163 @@
+"""缺 `moov` 的 MP4:认得出、挑得对参照、验得住结果、换得回原路径。
+
+untrunc 与 ffmpeg 本身不在这里跑:要验的是围着它们的判据和文件操作。
+"""
+import os
+import struct
+import tempfile
+import unittest
+from pathlib import Path
+from unittest import mock
+
+from peach import mp4recover
+from peach.mp4repair import RepairUnavailable
+
+
+def box(kind: bytes, body: bytes) -> bytes:
+ return struct.pack(">I", len(body) + 8) + kind + body
+
+
+class MissingIndexTests(unittest.TestCase):
+ def setUp(self):
+ self.tmp = tempfile.TemporaryDirectory()
+ self.addCleanup(self.tmp.cleanup)
+ self.root = Path(self.tmp.name)
+
+ def write(self, name: str, payload: bytes) -> Path:
+ path = self.root / name
+ path.write_bytes(payload)
+ return path
+
+ def test_a_download_that_stopped_before_the_index_is_recognised(self):
+ """实测的坏片:`ftyp`、`free`,然后一个写到文件末尾的 `mdat`。"""
+ path = self.write("cut.mp4", box(b"ftyp", b"isom" * 4) + box(b"free", b"")
+ + struct.pack(">I", 0) + b"mdat" + b"\x21" * 64)
+
+ self.assertTrue(mp4recover.missing_index(path))
+
+ def test_a_complete_file_is_left_alone(self):
+ path = self.write("whole.mp4", box(b"ftyp", b"isom" * 4) + box(b"moov", b"\0" * 16)
+ + box(b"mdat", b"\x21" * 64))
+
+ self.assertFalse(mp4recover.missing_index(path))
+
+ def test_something_that_is_not_an_mp4_at_all_is_not_claimed(self):
+ """改了扩展名的压缩包没有 `mdat`,不归这里修。"""
+ path = self.write("fake.mp4", b"PK\x03\x04" + b"\0" * 64)
+
+ self.assertFalse(mp4recover.missing_index(path))
+
+
+class ReferenceOrderTests(unittest.TestCase):
+ def test_neighbours_in_the_same_folder_are_tried_first(self):
+ """同一批下载的文件名挨在一起:隔壁那部的编码参数最可能一样。"""
+ broken = "B:\\作者\\甲\\2021-01-03_b.mp4"
+ candidates = [
+ "B:\\作者\\乙\\2021-01-03_a.mp4",
+ "B:\\作者\\甲\\2020-11-30_a.mp4",
+ "B:\\作者\\甲\\2021-01-03_c.mp4",
+ "B:\\作者\\甲\\2021-02-07_d.mp4",
+ ]
+
+ picked = mp4recover.pick_references(broken, candidates)
+
+ self.assertEqual(set(picked[:2]), {"B:\\作者\\甲\\2020-11-30_a.mp4", "B:\\作者\\甲\\2021-01-03_c.mp4"})
+ self.assertEqual(picked[-1], "B:\\作者\\乙\\2021-01-03_a.mp4")
+
+ def test_the_broken_file_never_serves_as_its_own_reference(self):
+ broken = "B:\\x\\a.mp4"
+
+ self.assertEqual(mp4recover.pick_references(broken, [broken, "B:\\x\\b.mp4"]), ["B:\\x\\b.mp4"])
+
+ def test_only_a_handful_are_tried(self):
+ """每试一个都要把坏片整个读一遍。"""
+ candidates = [f"B:\\x\\{index:03}.mp4" for index in range(20)]
+
+ self.assertEqual(len(mp4recover.pick_references("B:\\x\\010.mp4", candidates)),
+ mp4recover.REFERENCE_LIMIT)
+
+
+class AcceptanceTests(unittest.TestCase):
+ def test_a_clean_decode_with_matching_tracks_is_kept(self):
+ self.assertTrue(mp4recover.acceptable({"video": 282.48, "audio": 282.52}, 1))
+
+ def test_decode_errors_throughout_mean_the_reference_was_wrong(self):
+ """参照分辨率不对时每一帧都报宏块错误,实测 1855 行。"""
+ self.assertFalse(mp4recover.acceptable({"video": 75.28, "audio": 75.29}, 1855))
+
+ def test_tracks_that_disagree_on_length_mean_the_timeline_is_wrong(self):
+ """参照的采样率对不上时,音频只切出 11 秒、视频却有 80 秒。"""
+ self.assertFalse(mp4recover.acceptable({"video": 80.08, "audio": 11.69}, 0))
+
+ def test_nothing_playable_is_not_a_repair(self):
+ self.assertFalse(mp4recover.acceptable({"audio": 12.0}, 0))
+
+
+class ReplaceOriginalTests(unittest.TestCase):
+ def setUp(self):
+ self.tmp = tempfile.TemporaryDirectory()
+ self.addCleanup(self.tmp.cleanup)
+ self.root = Path(self.tmp.name)
+ self.source = self.root / "library" / "片子.mp4"
+ self.source.parent.mkdir()
+ self.source.write_bytes(b"broken")
+ self.repaired = self.root / "work" / "recovered.mp4"
+ self.repaired.parent.mkdir()
+ self.repaired.write_bytes(b"repaired!")
+
+ def test_the_repaired_file_takes_the_original_path_and_the_original_is_kept_beside_it(self):
+ kept = mp4recover.replace_original(self.source, self.repaired)
+
+ self.assertEqual(self.source.read_bytes(), b"repaired!")
+ self.assertEqual(kept, self.source.with_name(".片子.mp4.peach-original"))
+ self.assertEqual(kept.read_bytes(), b"broken")
+ self.assertFalse(self.repaired.exists())
+ self.assertEqual(sorted(path.name for path in self.source.parent.iterdir()),
+ [".片子.mp4.peach-original", "片子.mp4"])
+
+ def test_an_earlier_kept_original_is_never_overwritten(self):
+ earlier = self.source.with_name(".片子.mp4.peach-original")
+ earlier.write_bytes(b"first")
+
+ with self.assertRaises(RepairUnavailable):
+ mp4recover.replace_original(self.source, self.repaired)
+
+ self.assertEqual((self.source.read_bytes(), earlier.read_bytes()), (b"broken", b"first"))
+
+ def test_a_failed_swap_puts_the_original_back(self):
+ real = os.replace
+ calls = []
+
+ def flaky(source, target):
+ calls.append(Path(target).name)
+ if len(calls) == 2:
+ raise OSError("网盘断开")
+ return real(source, target)
+
+ with mock.patch.object(mp4recover.os, "replace", flaky), self.assertRaises(OSError):
+ mp4recover.replace_original(self.source, self.repaired)
+
+ self.assertEqual(self.source.read_bytes(), b"broken")
+ self.assertEqual([path.name for path in self.source.parent.iterdir()], ["片子.mp4"])
+
+
+class ToolLookupTests(unittest.TestCase):
+ def test_the_managed_copy_under_tools_is_found(self):
+ with tempfile.TemporaryDirectory() as directory:
+ tools = Path(directory)
+ binary = tools / "untrunc" / f"untrunc{'.exe' if os.name == 'nt' else ''}"
+ binary.parent.mkdir()
+ binary.write_bytes(b"")
+ with mock.patch.dict(os.environ, {mp4recover.UNTRUNC_ENV: ""}), \
+ mock.patch.object(mp4recover.shutil, "which", return_value=None):
+ self.assertEqual(mp4recover.untrunc_path(tools), binary.resolve())
+
+ def test_nothing_installed_reads_as_none(self):
+ with tempfile.TemporaryDirectory() as directory, \
+ mock.patch.dict(os.environ, {mp4recover.UNTRUNC_ENV: ""}), \
+ mock.patch.object(mp4recover.shutil, "which", return_value=None):
+ self.assertIsNone(mp4recover.untrunc_path(Path(directory)))
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/tests/test_web_media_repair.py b/tests/test_web_media_repair.py
index 30eebc471..c355477a2 100644
--- a/tests/test_web_media_repair.py
+++ b/tests/test_web_media_repair.py
@@ -1,19 +1,27 @@
-"""批量修 MP4 头这一轮任务。
+"""按媒体库批量修 MP4 这一轮任务。
-判定和修复都用替身:这里要验的是选谁、按什么顺序、哪些不必再问一遍,
-真正重建头的算术在 `test_mp4repair` 里。
+判定、重建头和重建索引都用替身:这里要验的是选谁、按什么顺序、哪些不必再问一遍、
+修好之后文件和账本落成什么样。重建头的算术在 `test_mp4repair` 里,重建索引的判据在
+`test_mp4recover` 里。
"""
import sqlite3
import tempfile
import unittest
from pathlib import Path, PureWindowsPath
+from types import SimpleNamespace
from unittest import mock
from peach import web_contract as rm_web
from peach import web_media_repair as rm_repair
+from peach.mp4recover import Recovery
+from peach.mp4repair import RepairUnavailable
from support.ledger import fresh_ledger
+SEP = chr(92)
+#: 顶层只有 `ftyp` 和写到文件末尾的 `mdat`:下载没写完、缺整个索引的那一类。
+CUT_SHORT = b"\x00\x00\x00\x10ftypisom\x00\x00\x02\x00" + b"\x00\x00\x00\x00mdat" + b"\x21" * 32
+
class _Store:
"""`HeaderRepairStore` 的替身:记下被要求修的是谁。"""
@@ -22,6 +30,8 @@ class _Store:
self.existing = set(existing)
self.failing = set(failing)
self.repaired: list[int] = []
+ self.resolver = SimpleNamespace(ffmpeg=lambda: SimpleNamespace(path=Path("ffmpeg")),
+ ffprobe=lambda: SimpleNamespace(path=Path("ffprobe")))
def lookup(self, asset_id, source):
return "头" if asset_id in self.existing else None
@@ -54,47 +64,76 @@ class MediaRepairRunTests(unittest.TestCase):
self.media = self.root / "media"
self.media.mkdir()
self.db_path = str(fresh_ledger(self.root))
- sep = chr(92)
rows = [
- (1, "115", "B:" + sep + "seldom.mp4", "seldom.mp4", 0),
- (2, "115", "B:" + sep + "favourite.mp4", "favourite.mp4", 9),
- (3, "115", "B:" + sep + "fine.mp4", "fine.mp4", 1),
- (4, "pikpak", "A:" + sep + "metered.mp4", "metered.mp4", 5),
- (5, "115", "B:" + sep + "photo.jpg", "photo.jpg", 3),
+ (1, "115", "B:" + SEP + "seldom.mp4", "seldom.mp4", 0, 60),
+ (2, "115", "B:" + SEP + "favourite.mp4", "favourite.mp4", 9, 60),
+ (3, "115", "B:" + SEP + "fine.mp4", "fine.mp4", 1, 60),
+ (4, "pikpak", "A:" + SEP + "metered.mp4", "metered.mp4", 5, None),
+ (5, "115", "B:" + SEP + "photo.jpg", "photo.jpg", 3, None),
+ (6, "115", "B:" + SEP + "cut.mp4", "cut.mp4", 2, -1),
]
connection = sqlite3.connect(self.db_path)
connection.executemany(
- "INSERT INTO asset(id,location,path,name,medium,size,play_count) "
- "VALUES(?,?,?,?,'video',10,?)", rows)
+ "INSERT INTO asset(id,location,path,name,medium,size,play_count,duration,hash_kind,hash) "
+ "VALUES(?,?,?,?,'video',10,?,?,'sha1','old')", rows)
connection.commit()
connection.close()
- for _, _, _, name, _ in rows:
- (self.media / name).write_bytes(b"x" * 16)
- self.contract = rm_web.WebContract(Path(self.db_path), transcode_root=self.root / "cache")
+ for *_, name, _, _ in rows:
+ (self.media / name).write_bytes(CUT_SHORT if name == "cut.mp4" else b"x" * 16)
+ self.contract = rm_web.WebContract(Path(self.db_path), transcode_root=self.root / "cache",
+ tools_root=self.root / "tools")
self.store = _Store()
self.transcodes = _Transcodes({"favourite.mp4", "seldom.mp4"})
self.contract.header_repairs = self.store
self.contract.transcode_service = self.transcodes
- patch = mock.patch.object(
- rm_repair, "translate_ledger_path",
- lambda raw: self.media / PureWindowsPath(str(raw)).name)
- patch.start()
- self.addCleanup(patch.stop)
-
- def run_once(self, **body) -> dict:
+ config = SimpleNamespace(locations={"115": ("B:" + SEP,), "pikpak": ("A:" + SEP,)},
+ library_names={"B:" + SEP: "网盘", "A:" + SEP: "PikPak"})
+ for patch in (
+ mock.patch.object(rm_repair, "translate_ledger_path",
+ lambda raw: self.media / PureWindowsPath(str(raw)).name),
+ mock.patch.object(rm_repair.settings_file, "active", lambda: config),
+ mock.patch.object(rm_repair.mp4recover, "untrunc_path", lambda root: Path("untrunc")),
+ mock.patch.object(rm_repair.media_probe, "measure",
+ lambda ffprobe, asset_id, path: (95.0, 720, 406, "h264", 29.97, None,
+ "短", "横屏", "低画质", asset_id)),
+ ):
+ patch.start()
+ self.addCleanup(patch.stop)
+ self.recovered: list[tuple[str, list[str]]] = []
+
+ def recover(self, source, references, *, work, **tools):
+ """untrunc 的替身:记下拿哪些参照修了谁,产出一份「修好的」文件。"""
+ self.recovered.append((Path(source).name, [Path(path).name for path in references]))
+ work.mkdir(parents=True, exist_ok=True)
+ output = work / "recovered-0.mp4"
+ output.write_bytes(b"repaired")
+ return Recovery(output, references[0], 95.0, 1.0)
+
+ def run_once(self, library="网盘", **body) -> dict:
"""跑完一轮再返回状态:后台任务在测试里没有别的事要抢。"""
- started = rm_repair.w_media_repair(self.contract, {"restart": True, **body})
- thread = self.contract.media_repair_job.thread
- if thread is not None:
- thread.join(timeout=30)
+ with mock.patch.object(rm_repair.mp4recover, "recover", self.recover):
+ started = rm_repair.w_media_repair(self.contract, {"restart": True, "library": library, **body})
+ thread = self.contract.media_repair_job.thread
+ if thread is not None:
+ thread.join(timeout=30)
return rm_repair.q_media_repair(self.contract) or started
+ def ledger_row(self, asset_id: int):
+ connection = sqlite3.connect(self.db_path)
+ try:
+ return connection.execute(
+ "SELECT size,duration,width,hash,hash_kind FROM asset WHERE id=?", (asset_id,)).fetchone()
+ finally:
+ connection.close()
+
def test_only_the_files_that_are_actually_broken_get_repaired(self):
state = self.run_once()
self.assertEqual(self.store.repaired, [2, 1])
+ self.assertEqual([name for name, _ in self.recovered], ["cut.mp4"])
self.assertEqual(state["status"], "complete")
- self.assertEqual((state["found"], state["repaired"], state["failed"]), (2, 2, 0))
+ self.assertEqual(state["library"], "网盘")
+ self.assertEqual((state["found"], state["repaired"], state["failed"]), (3, 3, 0))
def test_the_most_played_ones_are_repaired_first(self):
"""一轮要跑几个钟头,中途停下也该已经换来体感:常看的先修好。"""
@@ -102,17 +141,62 @@ class MediaRepairRunTests(unittest.TestCase):
self.assertEqual(self.store.repaired[0], 2, "放得最多的那部没排在最前面")
- def test_a_metered_source_is_left_alone_unless_it_is_asked_for(self):
- """PikPak 上一部片要整个拉下来才修得了,不能顺手就动。"""
+ def test_a_library_has_to_be_named(self):
+ with self.assertRaisesRegex(ValueError, "先选一个媒体库"):
+ rm_repair.w_media_repair(self.contract, {})
+ with self.assertRaisesRegex(ValueError, "没有这个媒体库"):
+ rm_repair.w_media_repair(self.contract, {"library": "不存在"})
+
+ def test_other_libraries_are_left_alone(self):
+ """PikPak 上一部片要整个拉下来才修得了,不点名那个库就不能碰。"""
self.run_once()
self.assertNotIn("metered.mp4", self.transcodes.asked)
- def test_asking_for_the_metered_source_reaches_it(self):
+ def test_naming_the_metered_library_reaches_it_and_nothing_else(self):
self.transcodes.affected.add("metered.mp4")
- self.run_once(allow_metered=True)
+ self.transcodes.asked.clear()
+ self.run_once("PikPak")
+
+ self.assertEqual(self.transcodes.asked, ["metered.mp4"])
+ self.assertEqual(self.store.repaired, [4])
- self.assertIn("metered.mp4", self.transcodes.asked)
+ def test_a_file_missing_its_index_is_rebuilt_from_its_neighbours_and_swapped_in(self):
+ self.run_once()
+
+ name, references = self.recovered[0]
+ self.assertEqual(set(references), {"seldom.mp4", "favourite.mp4", "fine.mp4"})
+ self.assertEqual((self.media / "cut.mp4").read_bytes(), b"repaired")
+ self.assertEqual((self.media / ".cut.mp4.peach-original").read_bytes(), CUT_SHORT)
+
+ def test_the_ledger_follows_the_swapped_file(self):
+ """时长和画面重新探,大小照扫描的口径刷新;115 的 SHA1 算的是旧内容,清掉。"""
+ self.run_once()
+
+ self.assertEqual(self.ledger_row(6), (len(b"repaired"), 95.0, 720, None, None))
+ self.assertEqual(self.ledger_row(3)[3], "old")
+
+ def test_without_untrunc_the_file_waits_for_it_instead_of_being_written_off(self):
+ with mock.patch.object(rm_repair.mp4recover, "untrunc_path", lambda root: None):
+ first = self.run_once()
+ second = self.run_once()
+
+ self.assertEqual((first["failed"], first["missing_tool"]), (1, 1))
+ self.assertEqual((self.media / "cut.mp4").read_bytes(), b"repaired")
+ self.assertEqual(second["repaired"], 1)
+
+ def test_a_file_no_reference_can_rebuild_is_not_tried_again(self):
+ def hopeless(source, references, **kwargs):
+ self.recovered.append((Path(source).name, []))
+ raise RepairUnavailable("没有一个参照切得出能解码的片子")
+
+ self.recover = hopeless
+ first = self.run_once()
+ self.run_once()
+
+ self.assertEqual((first["failed"], first["missing_tool"]), (1, 0))
+ self.assertEqual(len(self.recovered), 1)
+ self.assertEqual((self.media / "cut.mp4").read_bytes(), CUT_SHORT)
def test_a_file_that_already_has_a_header_is_not_probed_again(self):
self.store.existing.add(2)
@@ -135,7 +219,7 @@ class MediaRepairRunTests(unittest.TestCase):
first = self.run_once()
self.run_once()
- self.assertEqual((first["repaired"], first["failed"]), (1, 1))
+ self.assertEqual((first["repaired"], first["failed"]), (2, 1))
self.assertEqual(self.store.repaired.count(2), 1)
def test_a_changed_file_is_judged_again(self):
@@ -156,7 +240,7 @@ class MediaRepairRunTests(unittest.TestCase):
self.contract.header_repairs = None
with self.assertRaises(ValueError):
- rm_repair.w_media_repair(self.contract, {})
+ rm_repair.w_media_repair(self.contract, {"library": "网盘"})
def test_an_idle_instance_reports_idle_instead_of_nothing(self):
state = rm_repair.q_media_repair(self.contract)
diff --git a/web/dist/peach-react.js b/web/dist/peach-react.js
index d26a32cc7..be766e02e 100644
--- a/web/dist/peach-react.js
+++ b/web/dist/peach-react.js
@@ -32285,12 +32285,14 @@ function AD({ startup: e, receipt: t }) {
//#region src/react/settings/media-repair.tsx
var jD = {
status: "idle",
+ library: "",
stage: "",
checked: 0,
total: 0,
found: 0,
repaired: 0,
failed: 0,
+ missing_tool: 0,
skipped: 0,
message: ""
}, MD = (e) => Number(e).toLocaleString();
@@ -32301,59 +32303,92 @@ function ND(e) {
}
return e.status === "complete" && (e.repaired || e.failed) ? e.failed ? `修好 ${MD(e.repaired)} 部,${MD(e.failed)} 部修不了` : `修好 ${MD(e.repaired)} 部` : "";
}
-function PD({ initial: e }) {
- let [t, n] = (0, C.useState)(e || jD), [r, i] = (0, C.useState)(!1), a = gb(), o = t.status === "running";
+function PD({ initial: e, initialLibraries: t }) {
+ let [n, r] = (0, C.useState)(e || jD), [i, a] = (0, C.useState)(t || []), [o, s] = (0, C.useState)(""), l = gb(), u = n.status === "running";
(0, C.useEffect)(() => {
- let e = new AbortController(), t, r = async () => {
+ if (t) return;
+ let e = new AbortController();
+ return Qm("/api/libraries", e.signal).then((t) => {
+ e.signal.aborted || a(t.libraries || []);
+ }).catch(() => void 0), () => e.abort();
+ }, [t]), (0, C.useEffect)(() => {
+ let e = new AbortController(), t, n = async () => {
try {
let i = await Qm("/api/media-repair", e.signal);
if (e.signal.aborted) return;
- n(i), i.status === "running" && (t = setTimeout(r, 2e3));
+ r(i), i.status === "running" && (t = setTimeout(n, 2e3));
} catch {}
};
- return t = setTimeout(r, o ? 2e3 : 0), () => {
+ return t = setTimeout(n, u ? 2e3 : 0), () => {
e.abort(), clearTimeout(t);
};
- }, [o]);
- let s = () => void a.run("start", (e) => q("/api/media-repair", {
- allow_metered: r,
- restart: !0
- }, "POST", e), n), c = () => void a.run("stop", (e) => q("/api/media-repair", { stop: !0 }, "POST", e), n), l = t.total ? Math.round(t.checked / t.total * 100) : 0;
+ }, [u]);
+ let d = i.find((e) => e.id === (u ? n.library : o)) ?? i.find((e) => e.id === n.library) ?? i[0], f = () => {
+ d && c({
+ title: `修复媒体库「${d.name}」`,
+ body: "缺时间戳表的片子另存一份修好的头,原文件不动;缺索引的片子重建后替换原文件,坏原件改名成同目录的隐藏文件(.文件名.peach-original)留着。" + (d.metered ? "这个库在计费来源上,每修一部都要把片子完整拉一遍。" : ""),
+ confirmLabel: "修复媒体库",
+ onConfirm: async () => r(await q("/api/media-repair", {
+ library: d.id,
+ restart: !0
+ }))
+ });
+ }, p = () => void l.run("stop", (e) => q("/api/media-repair", { stop: !0 }, "POST", e), r), m = n.total ? Math.round(n.checked / n.total * 100) : 0, h = n.status === "complete", g = [
+ u ? /* @__PURE__ */ (0, w.jsx)(dh, {
+ label: "修复进度",
+ value: m
+ }, "progress") : null,
+ h && !n.repaired && !n.failed ? /* @__PURE__ */ (0, w.jsx)(J, {
+ tone: "info",
+ title: "没有要修的",
+ children: "这个库里的片子都能直接播。"
+ }, "clean") : null,
+ h && n.missing_tool ? /* @__PURE__ */ (0, w.jsx)(J, {
+ tone: "warning",
+ title: "缺少 untrunc",
+ children: `${MD(n.missing_tool)} 部缺索引的片子要装上 untrunc 才修得了,下载入口在「运行信息」里。`
+ }, "tool") : null,
+ l.error || n.error ? /* @__PURE__ */ (0, w.jsx)(zS, { children: l.error || n.error }, "error") : null
+ ].filter(Boolean);
return /* @__PURE__ */ (0, w.jsxs)(PS, {
- title: "播放兼容修复",
- children: [/* @__PURE__ */ (0, w.jsxs)(IS, { children: [
- /* @__PURE__ */ (0, w.jsx)(RS, { children: "有些 MP4 少了一张时间戳表,浏览器按容器给的时刻排帧,会把其中一部分丢掉,看着就是卡顿。 修好之后这类片子起播直接用原片,不再实时转码。原始文件不改动,修好的头另存在缓存里。" }),
- /* @__PURE__ */ (0, w.jsx)(yS, {
- isSelected: r,
- isDisabled: o,
- onChange: i,
- children: "连 PikPak 上的一起修(要把片子完整拉一遍,走流量)"
- }),
- o ? /* @__PURE__ */ (0, w.jsx)(dh, {
- label: "修复进度",
- value: l
- }) : null,
- t.status === "complete" && !t.repaired && !t.failed ? /* @__PURE__ */ (0, w.jsx)(J, {
- tone: "info",
- title: "没有要修的",
- children: "库里的片子都能直接播,没找到缺时间戳表的。"
- }) : null,
- a.error || t.error ? /* @__PURE__ */ (0, w.jsx)(zS, { children: a.error || t.error }) : null
- ] }), /* @__PURE__ */ (0, w.jsx)(LS, {
- status: ND(t) ? /* @__PURE__ */ (0, w.jsx)("p", {
- role: "status",
- children: ND(t)
+ title: "媒体修复",
+ children: [
+ /* @__PURE__ */ (0, w.jsx)(FS, { children: /* @__PURE__ */ (0, w.jsx)(jS, {
+ label: "媒体库",
+ description: "修缺时间戳表(播放卡顿)和缺索引(打不开)的 MP4。常看的片子先修。",
+ children: /* @__PURE__ */ (0, w.jsx)(eT, {
+ "aria-label": "媒体库",
+ selectedKey: d?.id ?? null,
+ isDisabled: u || !i.length,
+ onSelectionChange: (e) => {
+ e !== null && s(String(e));
+ },
+ children: i.map((e) => /* @__PURE__ */ (0, w.jsx)(tT, {
+ id: e.id,
+ children: e.name
+ }, e.id))
+ })
+ }) }),
+ g.length ? /* @__PURE__ */ (0, w.jsx)(IS, {
+ divided: !0,
+ children: g
}) : null,
- children: o ? /* @__PURE__ */ (0, w.jsx)(X, {
- onClick: c,
- ...Z(a.busy === "stop"),
- children: "停止"
- }) : /* @__PURE__ */ (0, w.jsx)(X, {
- onClick: s,
- ...Z(a.busy === "start"),
- children: "开始修复"
+ /* @__PURE__ */ (0, w.jsx)(LS, {
+ status: ND(n) ? /* @__PURE__ */ (0, w.jsx)("p", {
+ role: "status",
+ children: ND(n)
+ }) : null,
+ children: u ? /* @__PURE__ */ (0, w.jsx)(X, {
+ onClick: p,
+ ...Z(l.busy === "stop"),
+ children: "停止"
+ }) : /* @__PURE__ */ (0, w.jsx)(X, {
+ onClick: f,
+ disabled: !d,
+ children: "开始修复"
+ })
})
- })]
+ ]
});
}
//#endregion