diff --git a/README.md b/README.md index dcda9d15..72471612 100644 --- a/README.md +++ b/README.md @@ -91,6 +91,7 @@ The MiniMax Code Agent communicates through the host MCP client. Business reques | [Quota Bottle](plugins/7723qqq/quota-bottle/) | An octopus-shaped glass bottle that floats on your desktop and shows the remaining Token Plan quota from a login you configure yourself, with the liquid level and opacity following the remaining share, and a device-code login plus an opt-in local token-usage estimate as fallbacks | [7723qqq](https://github.com/7723qqq) | | [Site QA](plugins/lonelyguy-se1/site-qa/) | Check local HTML/robots/sitemap for SEO and accessibility gaps, then ask the agent to fix them (Mini App + skill/CLI). Requires MiniMax Code 3.1.6 or later | [LonelyGuySE1](https://github.com/LonelyGuy-SE1) | | [H3-Image-Executor](plugins/liddalidd/h3-image-executor/) | Turn one sentence into verified 4K images: it plans the shot list, searches for reference images, generates, reviews each image by looking at it, corrects colour cast, runs a bounded fix loop and delivers the result with an acceptance report; multi-image runs generate a character sheet first so the same subject stays the same subject. Needs an H3-Image endpoint and key you configure yourself. Requires MiniMax Code 3.1.6 or later | [liddalidd](https://github.com/liddalidd) | +| [Express Media](plugins/andre-1998/express-media/) | Compress a video to the size each platform accepts and report whether it fits; the bundled limits table shows where every number comes from | [Andre-1998](https://github.com/Andre-1998) |
Preview: Cutline diff --git a/README.zh-CN.md b/README.zh-CN.md index 223aae0b..911e8dcd 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -91,6 +91,7 @@ MiniMax Code Agent 通过宿主 MCP 客户端与 MiniApp 协作。业务请求 | [额度瓶](plugins/7723qqq/quota-bottle/README.zh-CN.md) | 一只悬浮在桌面上的章鱼形玻璃瓶,用你自己配置的登录读取 Token Plan 剩余额度;液面与透明度按剩余占比走,拿不到实时额度时回退到设备码登录或手填总额与可选的本机本月用量 | [7723qqq](https://github.com/7723qqq) | | [Site QA](plugins/lonelyguy-se1/site-qa/) | 检查本地 HTML/robots/sitemap 的 SEO / 无障碍问题,再让 Agent 修复(Mini App + skill/CLI)。需要 MiniMax Code 3.1.6 或更高版本(说明文档为英文) | [LonelyGuySE1](https://github.com/LonelyGuy-SE1) | | [H3-Image-Executor](plugins/liddalidd/h3-image-executor/README.zh-CN.md) | 把一句话需求跑成经过校验的 4K 图片:规划分镜、检索参考图、生成、看图评审、色偏校正、有限次修正,最后交付图片和验收报告;多图任务会先生成角色设定图锁定主体外观。需要自备 H3-Image 接口地址和 Key。需要 MiniMax Code 3.1.6 或更高版本 | [liddalidd](https://github.com/liddalidd) | +| [急件 · 视频投递](plugins/andre-1998/express-media/README.zh-CN.md) | 把视频压到各平台能收的体积,并如实告诉你发不发得出去;内置上限表标明每个数字的来源 | [Andre-1998](https://github.com/Andre-1998) |
预览:Cutline diff --git a/plugins/andre-1998/express-media/.minimax-plugin/plugin.json b/plugins/andre-1998/express-media/.minimax-plugin/plugin.json new file mode 100644 index 00000000..c3829a4f --- /dev/null +++ b/plugins/andre-1998/express-media/.minimax-plugin/plugin.json @@ -0,0 +1,21 @@ +{ + "schemaVersion": 1, + "name": "express-media", + "displayName": "急件 · 视频投递", + "version": "1.1.0", + "description": "在本地把视频压到各平台能收的体积,并能如实告诉你发不发得出去。用于「视频太大发不出去」「微信/Telegram/Discord/邮件限制多少」「压到 25MB」「转 GIF 表情包」「视频太长要裁一段」这类场景。全部在本机处理,文件不上传。", + "author": "Andre-1998", + "icon": "icon.png", + "darkIcon": "icon-dark.png", + "category": "Productivity", + "exampleQueries": [ + "这个视频 90MB,微信发不出去,帮我压到能发的大小", + "帮我查一下这个视频发到微信、Telegram、Discord 各是什么限制", + "把这段视频转成 GIF 表情包,控制在 1MB 以内" + ], + "apps": [], + "mcpServers": [], + "skills": [ + "skills/express-media/SKILL.md" + ] +} diff --git a/plugins/andre-1998/express-media/LICENSE b/plugins/andre-1998/express-media/LICENSE new file mode 100644 index 00000000..69cd2220 --- /dev/null +++ b/plugins/andre-1998/express-media/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 Andre-1998 + +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. \ No newline at end of file diff --git a/plugins/andre-1998/express-media/README.md b/plugins/andre-1998/express-media/README.md new file mode 100644 index 00000000..3d8e50ee --- /dev/null +++ b/plugins/andre-1998/express-media/README.md @@ -0,0 +1,99 @@ +# Express Media (`express-media`) + +English | [简体中文](README.zh-CN.md) + +A video that is too big to send is a problem you cannot solve by wishing harder. Express Media +measures your clip against the size each platform actually accepts, compresses it locally until +it fits, and tells you the truth when it cannot fit. + +**Everything runs on your machine. No file is uploaded anywhere.** + +## What you get + +- **A Mini App that looks up the limits.** One page listing every supported platform: the size + cap, the duration cap, how trustworthy that number is, and the source it came from. +- **A bundled skill.** Ask for it in plain language: "this video is 90MB and WeChat refuses it, + shrink it to something that fits" or "what is the WeChat / Telegram / Discord video limit". +- **A local CLI.** The same work without the chat: inspect, fit, split, trim, GIF, and a delivery + card for the result. + +## The Mini App + +Open it from the Mini App entry in the right panel, or ask the Agent to open +"急件 · 平台限制速查". The page reads the bundled `data/platforms.json` — the same table the skill +and the CLI use — and never touches the network. + +![The platform limit lookup page](docs/screenshot-limits.png) + +## The skill + +```text +这个视频发不到微信 / 发不出去 / 太大了 +帮我压到 25MB / 20MB 以内 +微信、Telegram、Discord 的视频限制是多少 +视频太长,裁一段 / 切成几段 +``` + +The skill drives the CLI under the plugin root. Every compression pass is measured with +`ffprobe` afterwards, so "it fits" means the file on disk really is that small. When the target +cannot be reached, the tool says so and offers the next step instead of handing you a file that +still fails. + +## The CLI + +```bash +node bin/express.mjs doctor # check ffmpeg and report broken candidates +node bin/express.mjs inspect clip.mp4 # size, duration, and what each platform accepts +node bin/express.mjs fit clip.mp4 --to wechat-chat +node bin/express.mjs split clip.mp4 --to wechat-chat +node bin/express.mjs trim clip.mp4 --start 0:10 --end 1:20 +node bin/express.mjs gif clip.mp4 --width 320 --square +node bin/express.mjs card clip.mp4 --from clip.mp4 +``` + +Exit codes: `0` fits, `1` compressed but still over the limit, `2` bad arguments or environment. + +## Install + +Copy this directory, including the hidden `.minimax-plugin/`, into the MiniMax Code plugins +directory as `express-media/` (`~/.minimax/plugins/express-media/` by default; see the root +README's Install section). Restart MiniMax Code, then open "急件 · 平台限制速查" from the +Mini App entry in the right panel. + +From MiniMax Code 3.1.11 you can import it instead of copying it: on the Plugins page, choose +**Create**, then **Import from a Git repository** under Mini App, and paste the URL of this +directory: + +```text +https://github.com/MiniMax-AI/MiniMax-Code-MiniApps/tree/main/plugins/andre-1998/express-media +``` + +Compressing needs Node.js 20.11 or later and an ffmpeg build with `libx264`, `aac`, `gif` and +the `sidedata` filter. The limits page needs neither. + +## Tested environment + +- Windows 11, Node.js 24, ffmpeg 9.0.2 (`libx264`, `aac`, `gif`, `sidedata` all reported usable + by `express doctor`). +- The CLI and the skill were exercised on real video: 96 unit tests and 63 end-to-end tests pass, + every compressed output was measured with `ffprobe`, and the split path was checked by summing + the real duration of every segment. +- The Mini App was published and opened inside the MiniMax Code Host (MiniMax Code 3.1.14 Insider, + Windows 11): the page rendered the full table of 10 platforms, typing 微信 in the search box + narrowed it to the 3 WeChat entries, and the page console reported no errors and no warnings. + The Node entry was also exercised against a stub Host context, where `/limits` and + `/api/platforms` returned the platform table and an unknown route returned 404. + +## Data & access + +- **Reads** the bundled `data/platforms.json`, and the video file you name. Nothing else. +- **Writes** the compressed file next to the source (or wherever `--out` points) and, unless + `--no-ledger` is given, one ledger line per run in `~/.express/ledger.jsonl`. +- **Network**: none. The plugin never uploads a file, and the limits page loads nothing remote. +- **Permissions**: the Mini App declares no agent, tool, device or host access. It reads no + microphone, camera or notification. +- **Accounts**: none. Nothing is signed in, and no usage data leaves the machine. + +## License + +MIT \ No newline at end of file diff --git a/plugins/andre-1998/express-media/README.zh-CN.md b/plugins/andre-1998/express-media/README.zh-CN.md new file mode 100644 index 00000000..a93118ca --- /dev/null +++ b/plugins/andre-1998/express-media/README.zh-CN.md @@ -0,0 +1,87 @@ +# 急件 · 视频投递 (`express-media`) + +[English](README.md) | 简体中文 + +视频太大发不出去,不是靠想想就能解决的。急件先量一遍你的片子在各平台到底能收多大,再在本机压到 +刚好能发的大小;实在压不进去,它会直说,并给出下一步该怎么处理。 + +**全部在本机处理,文件不上传任何服务器。** + +## 里面有什么 + +- **一个查上限的 Mini App**:一页列出所有支持平台的体积上限、时长上限、这个数字有多可信,以及它来自哪里。 +- **一个内置 skill**:用大白话说就行 —— 「这个视频 90MB,微信发不出去,帮我压到能发的大小」、 + 「微信、Telegram、Discord 的视频限制分别是多少」。 +- **一个本地命令行工具**:同样的活儿,不用聊天也能做 —— 体检、压、分段、裁剪、转 GIF、出投递卡。 + +## Mini App + +在右侧面板的 Mini App 入口打开,或直接让 Agent 打开「急件 · 平台限制速查」。页面读的是插件自带的 +`data/platforms.json` —— 和 skill、命令行用的是同一份表,全程不联网。 + +![平台限制速查页](docs/screenshot-limits.png) + +## skill + +```text +这个视频发不到微信 / 发不出去 / 太大了 +帮我压到 25MB / 20MB 以内 +微信、Telegram、Discord 的视频限制是多少 +视频太长,裁一段 / 切成几段 +``` + +skill 会驱动插件根目录下的命令行工具。每压一档都用 `ffprobe` 量真实体积,所以「达标」说的是磁盘上 +那个文件真的那么大。真压不进去时,工具会明说,并给出替代方案,而不是丢一个仍然发不出去的文件给你。 + +## 命令行 + +```bash +node bin/express.mjs doctor # 体检环境(先跑这个) +node bin/express.mjs inspect clip.mp4 # 多大、多长、能不能发 +node bin/express.mjs fit clip.mp4 --to wechat-chat +node bin/express.mjs split clip.mp4 --to wechat-chat +node bin/express.mjs trim clip.mp4 --start 0:10 --end 1:20 +node bin/express.mjs gif clip.mp4 --width 320 --square +node bin/express.mjs card clip.mp4 --from clip.mp4 +``` + +退出码:`0` 达标 | `1` 压了但仍超限 | `2` 参数或环境问题。 + +## 安装 + +把这个目录(含隐藏的 `.minimax-plugin/`)整个复制进 MiniMax Code 的插件目录,命名为 +`express-media/`(默认是 `~/.minimax/plugins/express-media/`;见根 README 的 Install 一节)。 +重启 MiniMax Code 后,在右侧面板的 Mini App 入口打开「急件 · 平台限制速查」。 + +MiniMax Code 3.1.11 起也可以直接导入:在插件页选 **创建** → Mini App 下的 **从 Git 仓库导入**, +粘贴本目录地址: + +```text +https://github.com/MiniMax-AI/MiniMax-Code-MiniApps/tree/main/plugins/andre-1998/express-media +``` + +压缩需要 Node.js 20.11 及以上,以及带 `libx264`、`aac`、`gif` 和 `sidedata` 滤镜的 ffmpeg; +只查上限的话两者都不需要。 + +## 实测环境 + +- Windows 11,Node.js 24,ffmpeg 9.0.2(`express doctor` 报告 `libx264`、`aac`、`gif`、`sidedata` 均可用)。 +- 命令行与 skill 用真实视频跑过:96 个单测、63 个端到端测试全过;每个产物都用 `ffprobe` 独立量过体积, + 分段结果逐段核对了真实时长。 +- Mini App 在 MiniMax Code 宿主里发布并打开过(Windows 11 上的 MiniMax Code 3.1.14 Insider): + 页面完整渲染出 10 个平台,搜索框输入「微信」能筛到 3 条, + 页面控制台没有报错也没有警告。Node 入口也用桩 Host 上下文跑过,`/limits` 与 `/api/platforms` 都正常返回 + 平台表,未知路由返回 404。 + +## 数据与权限 + +- **读取**:插件自带的 `data/platforms.json`,以及你指定的那个视频文件。没有别的。 +- **写入**:压好的文件放在源文件旁边(或 `--out` 指定的位置);除非加 `--no-ledger`, + 每次运行会在 `~/.express/ledger.jsonl` 追加一行台账。 +- **网络**:无。插件不上传任何文件,上限页也不加载任何远程资源。 +- **权限**:Mini App 没有声明 agent、tool、设备、宿主权限,不碰麦克风、摄像头和通知。 +- **账号**:无。不需要登录,也没有任何使用数据离开本机。 + +## 许可 + +MIT \ No newline at end of file diff --git a/plugins/andre-1998/express-media/bin/express.mjs b/plugins/andre-1998/express-media/bin/express.mjs new file mode 100644 index 00000000..96811b1f --- /dev/null +++ b/plugins/andre-1998/express-media/bin/express.mjs @@ -0,0 +1,7 @@ +#!/usr/bin/env node +import { main } from '../src/cli.js'; + +main().catch((err) => { + process.stderr.write(`急件崩了:${err?.stack || err}\n`); + process.exit(1); +}); diff --git a/plugins/andre-1998/express-media/data/platforms.json b/plugins/andre-1998/express-media/data/platforms.json new file mode 100644 index 00000000..35c88e33 --- /dev/null +++ b/plugins/andre-1998/express-media/data/platforms.json @@ -0,0 +1,208 @@ +{ + "schema": 1, + "updatedAt": "2026-10-01", + "disclaimer": "平台限制经常变,而且同一个平台不同入口(聊天 / 朋友圈 / 网页投稿)的限制并不一样。本表每条都带来源与置信度:confidence=official 表示官方文档或厂商客服明确写出,community 表示社区实测或第三方汇总(可能已过期或因版本而异)。判定「能不能发」以 maxBytes 为准,压缩时以 suggestedMaxBytes 为目标并留出余量。", + "confidenceLevels": { + "official": "官方文档 / 厂商客服明确写出", + "community": "社区实测 / 第三方汇总,可能随版本变化", + "mixed": "存在互相矛盾的口径,已在 variants 里全部列出,取最保守值作为 maxBytes" + }, + "targets": [ + { + "id": "wechat-chat", + "label": "微信 · 聊天窗口", + "maxBytes": 26214400, + "suggestedMaxBytes": 18874368, + "maxDurationSec": 300, + "container": "mp4", + "video": "h264", + "audio": "aac", + "confidence": "mixed", + "notes": [ + "不勾选「原画 / 原视频」时微信会自己压缩,容易被压成糊画质;勾了又常常直接超限发不出去", + "社区实测约 25MB 开始失败;厂商客服口径是聊天支持 1GB 以下视频传输", + "两侧口径不一致,这里取更保守的 25MB 作为硬上限" + ], + "variants": [ + { "maxBytes": 1073741824, "note": "厂商客服口径:微信聊天仅支持 1GB 以下的视频传输" } + ], + "sources": [ + { "url": "https://club.honor.com/cn/forum.php?mod=viewthread&tid=29334258", "note": "厂商客服回复:微信聊天仅支持 1GB 以下的视频传输" }, + { "url": "https://www.wyouhua.com/case/show/1633.html", "note": "社区汇总:聊天窗口约 25MB、朋友圈更严,建议压到 18MB 以内" } + ] + }, + { + "id": "wechat-moments", + "label": "微信 · 朋友圈", + "maxBytes": 10485760, + "suggestedMaxBytes": 8388608, + "maxDurationSec": 30, + "container": "mp4", + "video": "h264", + "audio": "aac", + "confidence": "community", + "notes": [ + "时长限制比体积更早触发:超过 30 秒需要先发视频号再转发", + "2025 年起朋友圈灰度支持 5 分钟长视频,未全量放开,这里按 30 秒保守判定" + ], + "sources": [ + { "url": "https://m.gmw.cn/2025-03/11/content_1303988124.htm", "note": "朋友圈由 30 秒放宽到 5 分钟,仍处灰度放量" }, + { "url": "https://vibbit.ai/zh-CN/blog/video-export-settings-guide", "note": "第三方汇总:朋友圈建议不超过 25MB、10MB 以内更稳" } + ] + }, + { + "id": "telegram-bot", + "label": "Telegram · Bot API", + "maxBytes": 52428800, + "suggestedMaxBytes": 50331648, + "maxDurationSec": null, + "container": "mp4", + "video": "h264", + "audio": "aac", + "confidence": "official", + "notes": [ + "官方原文:bot 目前只能发送不超过 50MB 的文件,该限制未来可能变更", + "超 200MB 的视频有些第三方集成会「原样透传」然后被 Telegram 拒收" + ], + "sources": [ + { "url": "https://core.telegram.org/bots/faq", "note": "官方 FAQ:Bots can currently send files of any type of up to 50 MB in size" } + ] + }, + { + "id": "discord-free", + "label": "Discord · 免费账号", + "maxBytes": 20971520, + "suggestedMaxBytes": 19922944, + "maxDurationSec": null, + "container": "mp4", + "video": "h264", + "audio": "aac", + "confidence": "mixed", + "notes": [ + "2026-08-17 官方把免费账号单文件上限从 10MB 提到 20MB", + "部分账号仍在 A/B 测试 25MB,别按 25MB 规划", + "图片超过约 8MB 会退化成下载链接,不内嵌显示" + ], + "variants": [{ "maxBytes": 26214400, "note": "部分账号 A/B 测试中的 25MB" }], + "sources": [ + { "url": "https://baike.baidu.com/item/Nitro/68368766", "note": "2026-08-17 Discord 将免费账号单文件上传上限从 10MB 提高至 20MB" }, + { "url": "https://discordtexttools.com/blog/discord-file-size-limit", "note": "2026 免费账号 20MB,仍在 A/B 测试,可能再次变动" } + ] + }, + { + "id": "discord-nitro", + "label": "Discord · Nitro Basic / Nitro", + "maxBytes": 52428800, + "suggestedMaxBytes": 50331648, + "maxDurationSec": null, + "container": "mp4", + "video": "h264", + "audio": "aac", + "confidence": "community", + "notes": ["Nitro Basic 50MB;完整 Nitro 最高 500MB,服务器 Boost 还能叠加"], + "variants": [{ "maxBytes": 524288000, "note": "完整 Nitro 500MB" }], + "sources": [ + { "url": "https://filesize.org/limits/discord/", "note": "Nitro Basic 50MB / Nitro 500MB" } + ] + }, + { + "id": "gmail", + "label": "Gmail 附件", + "maxBytes": 26214400, + "suggestedMaxBytes": 24000000, + "maxDurationSec": null, + "container": "mp4", + "video": "h264", + "audio": "aac", + "confidence": "community", + "notes": [ + "超过约 25MB 会变成 Google Drive 链接而不是附件", + "不少企业邮件网关自行压到 20MB 甚至更小,按 20MB 更稳" + ], + "sources": [ + { "url": "https://support.google.com/mail/answer/6580", "note": "Gmail 附件上限 25MB,超出自动转 Drive 链接" } + ] + }, + { + "id": "xiaohongshu", + "label": "小红书", + "maxBytes": 1073741824, + "suggestedMaxBytes": 1006632960, + "maxDurationSec": 900, + "aspect": "3:4 或 9:16", + "container": "mp4", + "video": "h264", + "audio": "aac", + "confidence": "community", + "notes": [ + "体积上限很宽松(1GB),真正的痛点是竖屏比例和首帧封面", + "3:4(1080×1440)在信息流里显示面积比 9:16 更大,推荐优先" + ], + "sources": [ + { "url": "https://vibbit.ai/zh-CN/blog/video-export-settings-guide", "note": "小红书:1080×1440 或 1080×1920、≤1GB、5 秒至 15 分钟" }, + { "url": "https://www.secaiyun.com/docs/social-media-video-size-specification-guide-2026-08-28.html", "note": "小红书 3:4 封面推荐,时长 15 分钟" } + ] + }, + { + "id": "douyin", + "label": "抖音", + "maxBytes": 75497472, + "suggestedMaxBytes": 71303168, + "maxDurationSec": 900, + "aspect": "9:16", + "container": "mp4", + "video": "h264", + "audio": "aac", + "confidence": "community", + "notes": [ + "安卓端上传上限约 72MB,iOS 端约 287MB,取小的那个", + "9:16 竖屏 1080×1920,15–60 秒表现最佳" + ], + "variants": [{ "maxBytes": 301989888, "note": "iOS 端约 287.6MB" }], + "sources": [ + { "url": "https://vibbit.ai/zh-CN/blog/video-export-settings-guide", "note": "抖音:iOS 不超过 287.6MB,安卓不超过 72MB" } + ] + }, + { + "id": "bilibili", + "label": "B 站", + "maxBytes": 8589934592, + "suggestedMaxBytes": 2147483648, + "maxDurationSec": 36000, + "aspect": "16:9", + "container": "mp4", + "video": "h264", + "audio": "aac", + "confidence": "community", + "notes": [ + "投稿上限很宽松:来源明确写的是文件不超过 8GB、最长 10 小时,这里按 8GB / 10 小时取", + "真正的成本是二压:上传码率给足比事后补救划算", + "封面推荐 1146×717(16:10),和视频 16:9 不是一回事,要单独做" + ], + "variants": [ + { "maxBytes": 10737418240, "note": "部分第三方汇总写成 10GB,与来源的 8GB 不一致,取更保守的 8GB" } + ], + "sources": [ + { "url": "https://vibbit.ai/zh-CN/blog/video-export-settings-guide", "note": "B 站:文件不超过 8GB,最长 10 小时" }, + { "url": "https://www.secaiyun.com/docs/social-media-video-size-specification-guide-2026-08-28.html", "note": "B 站封面 1146×717,建议码率 20-30Mbps" } + ] + }, + { + "id": "shipinhao", + "label": "微信视频号", + "maxBytes": 1073741824, + "suggestedMaxBytes": 1006632960, + "maxDurationSec": 1800, + "aspect": "9:16 或 1:1", + "container": "mp4", + "video": "h264", + "audio": "aac", + "confidence": "community", + "notes": ["视频号转码较狠,码率建议给到 6–10Mbps 再上传"], + "sources": [ + { "url": "https://www.secaiyun.com/docs/social-media-video-size-specification-guide-2026-08-28.html", "note": "视频号 1080×1920、30 分钟、16-20Mbps" }, + { "url": "https://cutfa.st/blog/how-to-resize-mp4-online-free-2026-cutfast-guide", "note": "视频号 1:1 或 9:16 均可,时长上限 60 分钟" } + ] + } + ] +} diff --git a/plugins/andre-1998/express-media/docs/screenshot-limits.png b/plugins/andre-1998/express-media/docs/screenshot-limits.png new file mode 100644 index 00000000..74e05438 Binary files /dev/null and b/plugins/andre-1998/express-media/docs/screenshot-limits.png differ diff --git a/plugins/andre-1998/express-media/icon-dark.png b/plugins/andre-1998/express-media/icon-dark.png new file mode 100644 index 00000000..42027da0 Binary files /dev/null and b/plugins/andre-1998/express-media/icon-dark.png differ diff --git a/plugins/andre-1998/express-media/icon.png b/plugins/andre-1998/express-media/icon.png new file mode 100644 index 00000000..5fb1e9d1 Binary files /dev/null and b/plugins/andre-1998/express-media/icon.png differ diff --git a/plugins/andre-1998/express-media/miniapp/client/index.html b/plugins/andre-1998/express-media/miniapp/client/index.html new file mode 100644 index 00000000..4bd77953 --- /dev/null +++ b/plugins/andre-1998/express-media/miniapp/client/index.html @@ -0,0 +1,155 @@ + + + + + + 急件 · 平台限制速查 + + + +
+

急件 · 平台限制速查

+

各平台视频体积与时长上限,以及这个数字是谁说的。

+
+ + +
+ + + + + +
平台体积上限时长上限口径说明与来源
+ +
+ 表由插件内置的 data/platforms.json 提供,与命令行、skill 用的是同一份数据。
+ 压视频请直接在对话里说:比如「这个视频 90MB,微信发不出去,帮我压」。 +
+
+ + + \ No newline at end of file diff --git a/plugins/andre-1998/express-media/miniapp/miniapp.json b/plugins/andre-1998/express-media/miniapp/miniapp.json new file mode 100644 index 00000000..0112a5f2 --- /dev/null +++ b/plugins/andre-1998/express-media/miniapp/miniapp.json @@ -0,0 +1,20 @@ +{ + "schemaVersion": 1, + "artifacts": { + "client": [ + "./miniapp/client" + ], + "node": [ + "./miniapp/node" + ] + }, + "runtime": { + "kind": "process", + "entry": "./miniapp/node/server.mjs", + "lifecycle": "on-demand" + }, + "surface": { + "path": "/limits" + }, + "mcpEndpoints": [] +} diff --git a/plugins/andre-1998/express-media/miniapp/node/server.mjs b/plugins/andre-1998/express-media/miniapp/node/server.mjs new file mode 100644 index 00000000..7c33dc25 --- /dev/null +++ b/plugins/andre-1998/express-media/miniapp/node/server.mjs @@ -0,0 +1,103 @@ +// @ts-check +// +// 急件 · 平台限制速查 —— Mini App 的 Node 入口。 +// +// 只做一件事:把插件自带的平台限制表读出来交给页面渲染。 +// 数据来自插件根目录的 data/platforms.json —— 与 skill、CLI 用的是同一份表, +// 全程本机读取,不发任何网络请求,也不需要任何设备权限。 +import { readFile } from 'node:fs/promises'; +import { createServer } from 'node:http'; +import { join } from 'node:path'; + +/** @typedef {import('./miniapp-api.js').MiniAppContext} MiniAppContext */ +/** @typedef {import('./miniapp-api.js').MiniAppLifecycle} MiniAppLifecycle */ + +const SURFACE_PATH = '/limits'; +const API_PATH = '/api/platforms'; + +/** + * 启动 Mini App 的本地服务。 + * @param {MiniAppContext} context + * @returns {Promise} + */ +export async function start(context) { + const clientHtml = await readFile(join(context.pluginRoot, 'miniapp/client/index.html')); + const table = await loadTable(context); + const payload = JSON.stringify(table); + + const server = createServer((request, response) => { + const url = new URL(request.url ?? '/', 'http://miniapp.local'); + if (request.method === 'GET' && url.pathname === SURFACE_PATH) { + response.writeHead(200, { 'content-type': 'text/html; charset=utf-8' }); + response.end(clientHtml); + return; + } + if (request.method === 'GET' && url.pathname === API_PATH) { + response.writeHead(200, { 'content-type': 'application/json; charset=utf-8' }); + response.end(payload); + return; + } + response.writeHead(404, { 'content-type': 'application/json; charset=utf-8' }); + response.end(JSON.stringify({ error: 'not_found' })); + }); + + await listen(server, context.listen.host, context.listen.port); + context.logger.info('express-media.miniapp.listening', { platforms: table.targets.length }); + + let disposed = false; + const dispose = async () => { + if (disposed) return; + disposed = true; + context.signal.removeEventListener('abort', onAbort); + await close(server); + }; + const onAbort = () => { + void dispose(); + }; + context.signal.addEventListener('abort', onAbort, { once: true }); + if (context.signal.aborted) await dispose(); + + return { dispose }; +} + +/** + * 读插件自带的平台限制表。读不到就返回空表,让页面说明原因,而不是让 Mini App 起不来。 + * @param {MiniAppContext} context + */ +async function loadTable(context) { + const file = join(context.pluginRoot, 'data', 'platforms.json'); + try { + const raw = await readFile(file, 'utf8'); + const parsed = JSON.parse(raw); + if (parsed && Array.isArray(parsed.targets)) return parsed; + context.logger.error('express-media.miniapp.table_shape', { path: 'data/platforms.json' }); + } catch (error) { + context.logger.error('express-media.miniapp.table_missing', { path: 'data/platforms.json' }); + } + return { schema: 1, updatedAt: null, targets: [] }; +} + +/** + * @param {import('node:http').Server} server + * @param {string} host + * @param {number} port + */ +function listen(server, host, port) { + return new Promise((resolve, reject) => { + const onError = (error) => reject(error); + server.once('error', onError); + server.listen(port, host, () => { + server.off('error', onError); + resolve(); + }); + }); +} + +/** + * @param {import('node:http').Server} server + */ +function close(server) { + return new Promise((resolve, reject) => { + server.close((error) => (error ? reject(error) : resolve())); + }); +} \ No newline at end of file diff --git a/plugins/andre-1998/express-media/package.json b/plugins/andre-1998/express-media/package.json new file mode 100644 index 00000000..a4158a56 --- /dev/null +++ b/plugins/andre-1998/express-media/package.json @@ -0,0 +1,10 @@ +{ + "name": "express-media", + "version": "1.1.0", + "description": "急件 — 视频太大发不出去?按平台限制实测收敛地压好、封好、发出去。本地处理,不上传。", + "type": "module", + "mcode": { + "schemaVersion": 2, + "miniApp": "./miniapp/miniapp.json" + } +} diff --git a/plugins/andre-1998/express-media/skills/express-media/SKILL.md b/plugins/andre-1998/express-media/skills/express-media/SKILL.md new file mode 100644 index 00000000..87257fbb --- /dev/null +++ b/plugins/andre-1998/express-media/skills/express-media/SKILL.md @@ -0,0 +1,149 @@ +--- +name: express-media +description: 在本地把视频压到各平台能收的体积,并如实报告发不发得出去。当用户说视频太大发不出去、要压到某个大小、问微信/Telegram/Discord/邮件/小红书/抖音/B站的视频体积限制、要转 GIF 表情包、要裁剪视频、或压不进去要分段时使用。不处理字幕烧录、封面设计,也不递归批量处理整个目录。 +--- + +# 急件 · 视频投递 + +本机视频处理工具。核心原则:**压完会真的去量,量完才告诉用户成没成。** + +## 工具位置 + +可执行入口是插件根目录下的 `bin/express.mjs`: + +```text +<插件根>/bin/express.mjs +<插件根>/src/*.js +<插件根>/data/platforms.json # 平台限制表(带来源与置信度) +``` + +`<插件根>` 就是本 SKILL.md 所在目录的上两级。例如 SKILL.md 在 +`.../plugins/express-media/skills/express-media/SKILL.md`,则插件根是 +`.../plugins/express-media`。 + +把它拼成绝对路径再调用,不要假设当前工作目录: + +```powershell +node <插件根绝对路径>\bin\express.mjs inspect "<视频文件路径>" +``` + +macOS / Linux 把 `\` 换成 `/` 即可,命令名与参数完全一致。 + +## 什么时候用 + +- 「这个视频发不到微信 / 发不出去 / 太大了」 +- 「帮我压到 25MB / 20MB 以内」 +- 「微信、Telegram、Discord 的视频限制是多少」 +- 「转成 GIF / 做表情包」(表情包上限 1MB) +- 「视频太长,裁一段 / 切成几段」 + +## 什么时候不用(别硬套) + +- 要**烧录字幕**、加片头片尾、改 BGM —— 这个工具只做「压缩 / 裁剪 / 转格式」 +- 要**批量递归处理整个文件夹** —— 一次只处理一个文件,用户要批量就逐个调用 +- 源文件不是视频(图片、音频、文档) +- 用户要的是「重新导出」而不是「压到能发」 + +## 标准流程 + +### 第 0 步:环境体检(只在第一次或用户报环境异常时跑) + +```bash +node <插件根>/bin/express.mjs doctor +``` + +退出码 `0` 才说明 ffmpeg 可用。这个命令会同时报出**坏的候选**(例如 Windows 上 +`WinGet\Links` 里的悬空符号链接:`where ffmpeg` 查得到、一执行就报找不到文件), +并自动绕开它去找能用的那个。看到 warn 行要如实转达给用户。 + +### 第 1 步:体检并判定(用户问「能不能发」时) + +```bash +node <插件根>/bin/express.mjs inspect "<文件>" # 人类可读表格 +node <插件根>/bin/express.mjs inspect "<文件>" --json # 结构化 +``` + +会输出时长、体积、分辨率、码率、旋转、HDR,以及**每个平台的上限、超出多少、这个数字是谁说的** +(`官方` / `社区实测` / `口径不一`)。平台表在 `data/platforms.json`,每条都带来源 URL。 + +### 第 2 步:压(主力动作) + +```bash +node <插件根>/bin/express.mjs fit "<文件>" --to <目标> +``` + +`<目标>` 可以是平台 id,也可以是自定义大小: + +| 平台 id | 上限 | 置信度 | +| --- | --- | --- | +| `wechat-chat` | 25 MB + 限 5 分钟 | 口径不一(1 GB / 25 MB,取保守值) | +| `wechat-moments` | 10 MB + 限 30 秒 | 社区实测 | +| `telegram-bot` | 50 MB | **官方** | +| `discord-free` | 20 MB | 口径不一(25 MB / 20 MB,取保守值) | +| `discord-nitro` | 50 MB | 社区实测 | +| `gmail` | 25 MB | 社区实测 | +| `xiaohongshu` | 1 GB + 限 15 分钟 | 社区实测 | +| `douyin` | 72 MB + 限 15 分钟 | 社区实测 | +| `bilibili` | 8 GB + 限 10 小时 | 社区实测 | +| `shipinhao` | 1 GB + 限 30 分钟 | 社区实测 | + +上表由 `data/platforms.json` 逐条生成,两处数字必须一致;改表时以 JSON 为准,同步更新本表。 + +自定义大小写 `25MB` / `500k` / `1.5g`,也可以直接给字节数。下限 16KB。 + +常用参数: + +| 参数 | 用途 | +| --- | --- | +| `--preset keep` | 保画质,不降分辨率 | +| `--preset small` | 再小一档(分辨率再降一级) | +| `--out <路径>` | 指定输出(不带扩展名会自动补上) | +| `--dry-run` | 只看压缩计划,**不产生任何文件** | +| `--normalize` | 体积已达标也重编码一遍,把方向烤进像素 | +| `--card` | 压完顺便生成一张投递卡 HTML | +| `--max-passes ` | 最多试几档,默认 4 | +| `--speed veryfast` | 机器慢时提速,画质略降 | +| `--no-ledger` | 不写台账(`~/.express/ledger.jsonl`) | + +退出码:`0` 达标 | `1` 压了但仍超限 | `2` 参数或环境问题。**脚本里可以靠退出码判断成败。** + +### 第 3 步:压不进去时(工具会自己给出替代方案) + +工具不会闷声交一个超限文件说「好了」。它会明确报「压不进去」,并给出裁剪秒数、 +分段数、发链接等建议。**这时候要把这些建议如实转达,不要自己另想办法悄悄降质量。** + +真要分段: + +```bash +node <插件根>/bin/express.mjs split "<文件>" --to wechat-chat +``` + +## 其他命令 + +```bash +node <插件根>/bin/express.mjs trim "<文件>" --start 0:10 --end 1:20 # 裁一段 +node <插件根>/bin/express.mjs gif "<文件>" --width 320 --square # 转 GIF/表情包 +node <插件根>/bin/express.mjs card "<文件>" --to wechat-chat # 只生成投递卡 +node <插件根>/bin/express.mjs ledger # 压缩台账与节省报告 +node <插件根>/bin/express.mjs platforms # 看完整限制表和来源 +node <插件根>/bin/express.mjs help # 全部命令 +``` + +## 向用户汇报时 + +**要给的数字**:原始体积 → 产出体积、压缩比、省下多少、目标上限、实际耗时。 + +**必须转达的三件事**: + +1. **压不进去就说压不进去**,并把替代方案(裁多少秒 / 分几段 / 发链接)一起给出。 +2. **平台限制是带来源的**。如果用户问「凭什么微信是 25MB」,要说明这是社区实测值, + 厂商客服口径是 1GB,工具取了更保守的那个;`platforms` 命令能看全部来源。 +3. **体积达标但文件带旋转元数据**时,工具会提示「个别客户端会横着显示,加 `--normalize` 可烤进像素」。 + 这条要转达,因为它是「文件没问题但对方看着是横的」这类问题的唯一线索。 + +**质量预期要诚实**:压到 25MB 的一分钟 1080p 录屏,画质一定有损失。 +工具的策略是「优先降分辨率和帧率,尽量保住编码质量」,但如果用户对画质有硬要求, +建议先 `--preset keep` 试一次看体积够不够。 + +**不要**替用户承诺「画质无损」或「肯定能发上去」——平台规则会变, +本工具的判定基于 `data/platforms.json` 里的静态表(带 `updatedAt`)。 diff --git a/plugins/andre-1998/express-media/src/card.js b/plugins/andre-1998/express-media/src/card.js new file mode 100644 index 00000000..33bbb2db --- /dev/null +++ b/plugins/andre-1998/express-media/src/card.js @@ -0,0 +1,145 @@ +// 投递卡:把「压好了」变成一个能直接发出去的成品。 +// 产出是 HTML + 封面图,引用同目录下的视频文件——不是把视频转成 base64 塞进去。 +import { existsSync, mkdirSync, statSync } from 'node:fs'; +import path from 'node:path'; +import { run } from './ffmpeg.js'; +import { formatBytes, formatBitrate, formatDuration } from './format.js'; + +export function posterArgs({ input, output, at = 1, width = 640 }) { + return [ + '-nostdin', '-v', 'error', '-y', '-ss', String(at), '-i', input, + '-frames:v', '1', '-vf', `scale=${width}:-2:flags=lanczos`, '-q:v', '3', output, + ]; +} + +/** 抽封面。失败不算致命——投递卡没有封面也能用。 */ +export async function extractPoster(input, { ffmpeg, at = 1, width = 640, out }) { + if (!ffmpeg?.path) return { path: null, error: '没有 ffmpeg' }; + const outPath = out || path.join(path.dirname(input), `${path.basename(input, path.extname(input))}.cover.jpg`); + // ffmpeg -y 自带覆盖,所以不需要先删旧封面 + const { code, stderr } = await run(ffmpeg.path, posterArgs({ input, output: outPath, at, width })); + if (code !== 0 || !existsSync(outPath)) { + return { path: null, error: (stderr || '').trim().slice(0, 200) || `退出码 ${code}` }; + } + return { path: outPath, bytes: statSync(outPath).size }; +} + +const CSS = ` +:root{--bg:#0e1014;--panel:#161920;--line:#242936;--fg:#e8ebf1;--dim:#8d95a7;--ok:#4ade80;--bad:#f87171;--accent:#7c9cff} +*{box-sizing:border-box} +body{margin:0;padding:28px;background:var(--bg);color:var(--fg);font:15px/1.65 -apple-system,"Segoe UI","Microsoft YaHei",system-ui,sans-serif} +.wrap{max-width:960px;margin:0 auto} +h1{font-size:21px;margin:0 0 2px;font-weight:650} +.sub{color:var(--dim);font-size:13px;margin-bottom:22px} +.panel{background:var(--panel);border:1px solid var(--line);border-radius:12px;overflow:hidden;margin-bottom:18px} +video{width:100%;display:block;background:#000} +.bar{display:block;padding:11px 14px;border-top:1px solid var(--line);font-size:13px;display:flex;gap:10px;align-items:center;flex-wrap:wrap} +a.dl{color:var(--accent);text-decoration:none;border:1px solid var(--line);border-radius:7px;padding:5px 11px;font-size:13px} +a.dl:hover{border-color:var(--accent)} +table{width:100%;border-collapse:collapse;font-size:13px} +th,td{padding:8px 12px;border-bottom:1px solid var(--line);text-align:left} +th{color:var(--dim);font-weight:500;width:130px;font-size:12px} +tr:last-child td{border-bottom:none} +td.num{font-variant-numeric:tabular-nums} +.pill{display:inline-block;padding:2px 9px;border-radius:999px;font-size:11px;border:1px solid} +.pill.ok{color:var(--ok);border-color:#1d5c37;background:#0f2418} +.pill.bad{color:var(--bad);border-color:#6b2626;background:#251414} +.pill.warn{color:#fbbf24;border-color:#6b5320;background:#241f10} +h2{font-size:14px;margin:22px 0 8px;color:var(--dim);font-weight:600} +.metric{font-size:30px;font-weight:650;font-variant-numeric:tabular-nums} +.metric.ok{color:var(--ok)} +.foot{color:var(--dim);font-size:12px;margin-top:24px;text-align:center} +ul.alt{margin:6px 0 0;padding-left:20px;color:var(--fg)} ul.alt li{margin:3px 0} +code{background:#1e222c;padding:1px 5px;border-radius:4px;font-size:12px} +`; + +/** + * 生成投递卡。 + * @param videoPath 要展示的视频(相对路径引用) + * @param meta 附加信息 { beforeBytes, afterBytes, target, verdict, platformChecks, alternatives, content, passes } + */ +export function cardHtml({ videoPath, meta = {}, title, posterName: poster = '' }) { + const m = meta; + const v = m.verdict || {}; + const head = title || path.basename(videoPath || '视频'); + const saving = Number.isFinite(m.beforeBytes) && Number.isFinite(m.afterBytes) ? Math.max(0, m.beforeBytes - m.afterBytes) : null; + const ratio = Number.isFinite(m.afterBytes) && m.afterBytes > 0 && Number.isFinite(m.beforeBytes) + ? (m.beforeBytes / m.afterBytes) : null; + const posterName = poster || ''; + + const verdictPill = v.fitsHardLimit === true + ? '可以发' + : v.fitsHardLimit === false ? '仍然超限' : ''; + const durPill = v.durationOk === false ? '时长超限' : ''; + + const rows = [ + ['原始体积', m.beforeBytes ? formatBytes(m.beforeBytes) : '—'], + ['产出体积', m.afterBytes ? `${formatBytes(m.afterBytes)} ${verdictPill}` : '—'], + ['省下', saving !== null ? `${formatBytes(saving)}${ratio ? `(${ratio.toFixed(1)}×)` : ''}` : '—'], + ['目标', m.target || '—'], + ['时长', m.durationSec ? formatDuration(m.durationSec) : '—'], + ['画面', m.resolution || '—'], + ['内容判定', m.contentLabel || '—'], + ['码率', m.bitrate || '—'], + ]; + if (Number.isFinite(m.encodeSeconds)) rows.push(['编码耗时', formatDuration(m.encodeSeconds)]); + + // 判定必须区分「体积超」和「时长超」:有些平台体积很宽松但卡时长(朋友圈 30 秒), + // 那种情况下体积差值是 0 甚至负数,只按体积算就会显示成「超 0 B」,等于没说。 + const checks = (m.platformChecks || []).map((c) => { + const sizeOver = typeof c.sizeOk === 'boolean' && !c.sizeOk; + const durOver = typeof c.durationOk === 'boolean' && !c.durationOk; + const overBytes = Math.max(0, (c.bytes || 0) - (c.maxBytes || 0)); + let cls = 'ok'; + let label = '可发'; + let note = ''; + if (sizeOver && durOver) { + cls = 'bad'; + label = '体积和时长都超'; + note = `超出 ${formatBytes(overBytes)};时长 ${formatDuration(c.durationSec)} 超过 ${formatDuration(c.maxDurationSec)}`; + } else if (sizeOver) { + cls = 'bad'; + label = `超 ${formatBytes(overBytes)}`; + } else if (durOver) { + cls = 'bad'; + label = '时长超限'; + note = `${formatDuration(c.durationSec)} 超过 ${formatDuration(c.maxDurationSec)}`; + } + return `${esc(c.label)}${c.maxBytes ? formatBytes(c.maxBytes) : '—'}${label}${esc(note || c.note || '')}`; + }).join(''); + + const alts = (m.alternatives || []).length + ? `

这个体积还是发不出去的话

    ${m.alternatives.map((a) => `
  • ${esc(a.text)}
  • `).join('')}
` + : ''; + + return ` + + +${esc(head)} +
+

${esc(head)}

+
急件 · 投递卡${m.target ? ' · 目标 ' + esc(m.target) : ''}
+ +
+ +
+ 下载原文件 + ${m.afterBytes ? formatBytes(m.afterBytes) : ''} + ${saving !== null ? `省下 ${formatBytes(saving)}` : ''} + ${durPill} +
+
+ +${saving !== null ? `
${formatBytes(saving)}
相对原始体积节省${ratio ? ` ${(100 - 100 / ratio).toFixed(0)}%` : ''}
` : ''} + +
${rows.map(([k, val]) => ``).join('')}
${esc(k)}${val}
+ +${checks ? `

各平台能不能收

${checks}
平台上限判定说明
` : ''} +${alts} +
本文件在本机生成,视频没有被上传到任何服务器。
+
`; +} + +function esc(s) { + return String(s ?? '').replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c])); +} diff --git a/plugins/andre-1998/express-media/src/classify.js b/plugins/andre-1998/express-media/src/classify.js new file mode 100644 index 00000000..a4a3f4cf --- /dev/null +++ b/plugins/andre-1998/express-media/src/classify.js @@ -0,0 +1,218 @@ +// 内容类型探测:真的解码几帧灰度图,算运动量、细节密度、黑边。 +// +// 为什么不用文件名/分辨率猜?因为「屏保录屏」和「游戏实录」可以用一样的分辨率和帧率, +// 但需要的码率差 3 倍。压缩参数猜错,产物就是「压小了但全糊」或「压不动」。 +// +// 采样为什么用原始分辨率而不是缩小? +// 一开始我把整帧缩到 64×36(10 倍下采样)来省事,结果文字边缘被均值抹平, +// 屏幕录制反而被判成 detail 最低的「静止画面」。均值化是细节的敌人。 +// 现在按原始像素采样(上限 2560 宽),用步长控制计算量,不再下采样。 +import { run } from './ffmpeg.js'; + +export const MAX_SAMPLE_W = 2560; +export const SAMPLE_STRIDE = 4; // 运动量:每 4 个像素取 1 个 +export const DETAIL_STRIDE = 2; // 细节量:步长小一点,否则 4×4 色块会被完全跳过 + +/** + * 只有三类。原先把「静止」和「屏幕录制」分开是假精度——两者的压缩参数只差 CRF 34 vs 33, + * 分了等于没分。真正影响成品的是「动得厉害吗、细节多吗」,那才是要分开的地方。 + */ +export const KINDS = { + screen: { label: '静止 / 文字画面(录屏、PPT、聊天记录)', minBpp: 0.012, crfStart: 28, crfStep: 2, maxCrf: 36 }, + camera: { label: '一般画面(实拍、人物讲话、日常)', minBpp: 0.05, crfStart: 25, crfStep: 2, maxCrf: 30 }, + motion: { label: '高运动(游戏、体育、快速摇摄)', minBpp: 0.1, crfStart: 23, crfStep: 2, maxCrf: 28 }, +}; + +/** 采样帧尺寸:不超过上限,保持原始宽高比,且是偶数(gray 不挑,但保持偶数省心)。 */ +export function sampleDims(displayW, displayH) { + const w0 = Math.max(16, displayW || 1280); + const h0 = Math.max(16, displayH || 720); + const w = Math.min(MAX_SAMPLE_W, w0); + const h = Math.max(2, Math.round((h0 * w) / w0 / 2) * 2); + return { w: Math.round(w / 2) * 2, h }; +} + +/** + * 在头/中/尾三个位置各取几帧原始分辨率灰度图。 + * 分三次取样是因为一段视频开头可能是静止标题卡,只看开头会判错。 + */ +export async function sampleGrayFrames(file, { ff, durationSec, dims, batches = 3, perBatch = 4, fps = 2 }) { + const { w, h } = dims; + const frameBytes = w * h; + const dur = Number.isFinite(durationSec) && durationSec > 0 ? durationSec : 3; + const positions = batches <= 1 + ? [0] + : [0.08, 0.5, 0.92].slice(0, batches).map((f) => Math.max(0, Math.min(dur - 0.1, dur * f))); + + const frames = []; + for (const pos of positions) { + const args = [ + '-v', 'error', '-nostdin', + ...(pos > 0.05 ? ['-ss', String(pos.toFixed(3))] : []), + '-i', file, + '-an', '-sn', '-dn', + '-vf', `fps=${fps},scale=${w}:${h}:flags=area,format=gray`, + '-frames:v', String(perBatch), + '-f', 'rawvideo', '-pix_fmt', 'gray', 'pipe:1', + ]; + const { code, stdoutBuffer } = await run(ff, args); + if (code !== 0) continue; // 采样失败不该让整条命令挂掉 + for (let off = 0; off + frameBytes <= stdoutBuffer.length; off += frameBytes) { + frames.push(stdoutBuffer.subarray(off, off + frameBytes)); + } + } + return frames; +} + +/** 逐帧对比:变化像素占比(|Δ|≥8 记为变化)。比「平均差值」更能拉开差距。 */ +export function motionRatio(frames, width, threshold = 8) { + if (frames.length < 2 || !width) return null; + const height = frames[0].length / width; + const st = SAMPLE_STRIDE; + let changed = 0; + let total = 0; + for (let i = 1; i < frames.length; i += 1) { + const a = frames[i - 1]; + const b = frames[i]; + for (let y = 0; y < height; y += st) { + const row = y * width; + for (let x = 0; x < width; x += st) { + if (Math.abs(a[row + x] - b[row + x]) >= threshold) changed += 1; + total += 1; + } + } + } + return total ? changed / total : null; +} + +/** 细节密度:水平方向相邻像素的落差(原始分辨率下,文字笔画会直接体现成大落差)。 */ +export function detailScore(frames, width, threshold = 32) { + if (!frames.length || !width) return null; + const st = DETAIL_STRIDE; + const height = frames[0].length / width; + let grad = 0; + let gradN = 0; + let sharp = 0; + for (const f of frames) { + for (let y = 0; y < height; y += st) { + const row = y * width; + for (let x = 0; x + 1 < width; x += st) { + const d = Math.abs(f[row + x] - f[row + x + 1]); + grad += d; + gradN += 1; + if (d >= threshold) sharp += 1; + } + } + } + return { + detail: gradN ? grad / gradN / 255 : null, + sharp: gradN ? sharp / gradN : null, + }; +} + +function meanOf(f) { + let s = 0; + for (let i = 0; i < f.length; i += 1) s += f[i]; + return s / f.length; +} + +function meanRows(f, width) { + const height = f.length / width; + const rows = []; + for (let y = 0; y < height; y += 1) { + let s = 0; + for (let x = 0; x < width; x += 1) s += f[y * width + x]; + rows.push(s / width); + } + return rows; +} + +function meanCols(f, width) { + const height = f.length / width; + const cols = []; + for (let x = 0; x < width; x += 1) { + let s = 0; + for (let y = 0; y < height; y += 1) s += f[y * width + x]; + cols.push(s / height); + } + return cols; +} + +/** 从抽样帧里量黑边:头尾若明显比中间暗,且整帧并不暗,那就是真黑边。 */ +export function detectBars(f, width) { + if (!f || !width) return null; + const height = f.length / width; + const DARK = 16; + const overall = meanOf(f); + if (overall <= 40) return null; // 整帧本来就黑,说不清是黑边还是黑屏 + const rows = meanRows(f, width); + const cols = meanCols(f, width); + const edgeMax = Math.max(...rows, ...cols); + if (edgeMax <= 45) return null; // 没有亮的东西,多半是暗场而不是黑边 + + let top = 0; + while (top < height / 2 && rows[top] < DARK) top += 1; + let bottom = 0; + while (bottom < height / 2 && rows[height - 1 - bottom] < DARK) bottom += 1; + let left = 0; + while (left < width / 2 && cols[left] < DARK) left += 1; + let right = 0; + while (right < width / 2 && cols[width - 1 - right] < DARK) right += 1; + + const has = (n) => n >= 2; + if (!has(top) && !has(bottom) && !has(left) && !has(right)) return null; + const by = []; + if (has(top)) by.push('top'); + if (has(bottom)) by.push('bottom'); + if (has(left)) by.push('left'); + if (has(right)) by.push('right'); + return { top: top / height, bottom: bottom / height, left: left / width, right: right / width, by }; +} + +// 阈值是对着 10 段合成素材量出来的,不是拍脑袋。 +// 实测分布(motion = 变化像素占比): +// 0.0002 录屏 | 0.034~0.117 一段实拍/测试图 | 0.19~0.31 快速摇摄与高频画面 +// 两个阈值都落在明显的空档里。 +export const THRESHOLDS = { + screenMotion: 0.02, // 低于此:画面基本不动,文字/PPT/录屏 + motionMotion: 0.16, // 高于此:动得厉害,游戏/体育/快速摇摄 +}; + +/** 纯函数:给运动量,判定内容类型。拆出来是为了能对着合成素材标定阈值。 */ +export function classifyByMetrics({ motion }) { + if (motion === null || motion === undefined) return 'camera'; // 判不出来就走保守的一档 + if (motion < THRESHOLDS.screenMotion) return 'screen'; + if (motion >= THRESHOLDS.motionMotion) return 'motion'; + return 'camera'; +} + +export async function analyzeContent(file, { ff, durationSec, width, height } = {}) { + const dims = sampleDims(width, height); + const frames = await sampleGrayFrames(file, { ff, durationSec, dims }); + if (frames.length < 2) { + return { + kind: 'camera', metrics: { motion: null, detail: null, sharp: null, brightness: null, frames: frames.length, sample: `${dims.w}×${dims.h}` }, + bars: null, sampled: false, label: KINDS.camera.label, sampleDims: dims, + note: '抽不到足够帧,按一般画面处理(参数偏保守,代价是文件略大)', + }; + } + const motion = motionRatio(frames, dims.w, 8); + const det = detailScore(frames, dims.w, 32); + const brightness = frames.reduce((acc, f) => acc + meanOf(f), 0) / frames.length; + const kind = classifyByMetrics({ motion }); + return { + kind, + label: KINDS[kind].label, + metrics: { + motion: r4(motion), detail: r4(det.detail), sharp: r4(det.sharp), + brightness: r2(brightness), frames: frames.length, sample: `${dims.w}×${dims.h}`, + }, + bars: detectBars(frames[Math.floor(frames.length / 2)], dims.w), + sampled: true, + sampleDims: dims, + note: null, + }; +} + +function r4(n) { return n === null ? null : Math.round(n * 10000) / 10000; } +function r2(n) { return n === null ? null : Math.round(n * 100) / 100; } diff --git a/plugins/andre-1998/express-media/src/cli.js b/plugins/andre-1998/express-media/src/cli.js new file mode 100644 index 00000000..63b827b4 --- /dev/null +++ b/plugins/andre-1998/express-media/src/cli.js @@ -0,0 +1,525 @@ +// 命令行入口。中文界面,零第三方依赖。 +import { parseArgs } from 'node:util'; +import { existsSync, mkdirSync, statSync, writeFileSync } from 'node:fs'; +import path from 'node:path'; +import { resolveBinaries } from './ffmpeg.js'; +import { probe } from './probe.js'; +import { loadPlatforms, resolveTarget, formatBytes, formatDuration, formatBitrate, displayWidth, padDisplay, containerLabel } from './format.js'; +import { fit, estimateRange } from './fit.js'; +import { toGif } from './gif.js'; +import { trim } from './trim.js'; +import { split } from './split.js'; +import { cardHtml, extractPoster } from './card.js'; +import { doctor, formatDoctor } from './doctor.js'; +import { analyzeContent } from './classify.js'; +import { appendEntry, readEntries, summarize, writeReport, toEntry, ledgerPath } from './ledger.js'; + +const C = (() => { + const on = process.stdout.isTTY && !process.env.NO_COLOR; + const w = (code) => (s) => (on ? `\u001b[${code}m${s}\u001b[0m` : String(s)); + return { dim: w('2'), bold: w('1'), green: w('32'), red: w('31'), yellow: w('33'), blue: w('36') }; +})(); + +const HELP = `${C.bold('急件 express')} — 视频太大发不出去?按平台限制压好、封好、发出去。 +${C.dim('全部在本机跑,文件不上传任何服务器。')} + +${C.bold('用法')} + express doctor 体检 ffmpeg 环境(先跑这个) + express platforms 列出各平台的限制、来源与置信度 + express inspect <文件...> [--json] 体检:多大、多长、各平台能不能收 + express fit <文件> --to <目标> 压到能发(实测收敛,压完一定量) + express trim <文件> --start 0:10 --end 1:20 裁一段 + express split <文件> --to <目标> 一个文件太大,切成几段都发得出去 + express gif <文件> [--width 320] 转 GIF / 表情包 + express card <文件> [--from 原始文件] 生成投递卡 HTML + express ledger [--out 报告.html] 压缩台账与节省报告 + +${C.bold('fit 的常用参数')} + --to <目标> 平台 id(wechat-chat / telegram-bot / discord-free …)或自定义大小(25MB / 500k) + --preset <档位> keep 保画质 | balanced 默认 | small 再小一档 (默认 balanced) + --out <路径> 输出文件(默认在原文件旁边加后缀) + --speed <档位> ultrafast…veryslow,默认 medium + --max-passes 最多试几档,默认 4 + --dry-run 只出计划不真压 + --normalize 体积已达标也重编码一遍(把方向烤进像素、统一容器) + --card 压完顺手生成投递卡 + --no-ledger 不记台账 + +${C.bold('例子')} + express inspect 录屏.mp4 + express fit 录屏.mp4 --to wechat-chat + express fit 发布会.mp4 --to 50MB --preset small --card + express gif 精彩瞬间.mp4 --start 12 --duration 3 --width 320 --square +`; + +function out(s = '') { process.stdout.write(s + '\n'); } + +async function binariesOrDie() { + const b = await resolveBinaries(); + if (!b.ffmpeg || !b.ffprobe) { + out(C.red('✘ 找不到能用的 ffmpeg/ffprobe。')); + const broken = (b.rejected || []).filter((x) => x.reason === 'enoent'); + if (broken.length) { + out(C.yellow(` 有 ${broken.length} 个候选路径能解析但执行失败(常见于 winget 升级后 WinGet\\Links 里的悬空链接):`)); + for (const x of broken.slice(0, 3)) out(C.dim(` ${x.path} ← ${x.from}`)); + } + out(C.dim(' 跑 express doctor 看详细诊断,或装一个:winget install ffmpeg')); + process.exit(2); + } + return b; +} + +function progressReporter(label) { + if (!process.stdout.isTTY) return () => {}; + let last = -1; + return ({ ratio }) => { + if (ratio === null) return; + const pct = Math.round(ratio * 100); + if (pct === last) return; + last = pct; + process.stdout.write(`\r ${label} ${String(pct).padStart(3)}%`); + }; +} + +// —— inspect —— + +function platformChecks(info) { + const db = loadPlatforms(); + return db.targets.map((t) => { + const sizeOk = info.sizeBytes <= t.maxBytes; + const durOk = t.maxDurationSec === null || t.maxDurationSec === undefined + ? null : (info.durationSec || 0) <= t.maxDurationSec; + let fits; + if (durOk === false) fits = false; + else fits = sizeOk; + const notes = []; + if (!sizeOk) notes.push(`超出 ${formatBytes(info.sizeBytes - t.maxBytes)}`); + if (durOk === false) notes.push(`时长超过 ${formatDuration(t.maxDurationSec)}`); + return { + id: t.id, label: t.label, maxBytes: t.maxBytes, + maxDurationSec: t.maxDurationSec ?? null, + confidence: t.confidence, bytes: info.sizeBytes, + sizeOk, durationOk: durOk, fits, note: notes.join(','), + }; + }); +} + +function printInspect(info, checks) { + const v = info.video; + out(); + out(`${C.bold(path.basename(info.file))}`); + out(` 体积 ${C.bold(formatBytes(info.sizeBytes))} 时长 ${formatDuration(info.durationSec)} 容器 ${containerLabel(info.format.name)}`); + if (v.present) { + out(` 画面 ${v.displayWidth}×${v.displayHeight} ${v.fps ? v.fps.toFixed(2) + ' fps' : ''} ${v.codec}${v.rotation ? ` ${C.yellow('旋转 ' + v.rotation + '°')}` : ''}${v.hdr ? C.yellow(' HDR') : ''}`); + out(` 码率 ${formatBitrate(info.video.bitrateBps ?? info.bitrateBps)}`); + } + if (info.audio.present) { + out(` 音频 ${info.audio.codec} ${info.audio.channels}ch ${info.audio.sampleRate}Hz ${formatBitrate(info.audio.bitrateBps)}`); + } else { + out(` 音频 ${C.dim('无')}`); + } + out(); + out(C.bold('各平台能不能收')); + const labelW = Math.max(...checks.map((c) => displayWidth(c.label))); + for (const c of checks) { + const mark = c.fits === true ? C.green('✔ 可发') : c.fits === false ? C.red('✘ 发不出去') : C.yellow('? 未知'); + const conf = c.confidence === 'official' ? C.dim('官方') : c.confidence === 'community' ? C.dim('社区实测') : C.yellow('口径不一'); + out(` ${mark} ${padDisplay(c.label, labelW)} ${padDisplay('上限 ' + formatBytes(c.maxBytes), 18)} ${conf} ${C.dim(c.note)}`); + } + out(); +} + +// —— fit —— + +function printFit(r, encodeSeconds) { + out(); + out(`${C.bold(r.action === 'copy' ? '不用压,直接发' : '压好了')}`); + out(` ${path.basename(r.input)} ${formatBytes(r.before)} ${C.dim('→')} ${C.bold(formatBytes(r.after))}`); + if (r.action === 'encode') { + out(` 压缩比 ${r.ratio}×${r.savedBytes > 0 ? C.green(`(省下 ${formatBytes(r.savedBytes)})`) : ''}`); + out(` 内容判定 ${r.content.label} ${C.dim(`运动 ${r.content.metrics.motion ?? '—'} / 细节 ${r.content.metrics.detail ?? '—'}`)}`); + out(` 耗时 ${formatDuration(encodeSeconds)},试了 ${r.passes.length} 档`); + for (const p of r.passes) { + const hit = p.measuredBytes !== null && p.measuredBytes <= r.target.aimBytes; + out(C.dim(` ${p.width}×${p.height} ${p.fps}fps CRF${p.crf ?? '—'}${p.bitrateBps ? ' ' + formatBitrate(p.bitrateBps) : ''} → ${formatBytes(p.measuredBytes)} ${hit ? C.green('✔') : ''}`)); + } + } + const v = r.verdict; + for (const w of r.warnings || []) out(C.yellow(` ! ${w}`)); + if ((r.warnings || []).length) out(); + out(); + if (v.fitsHardLimit) out(C.green(` ✔ ${formatBytes(r.after)} ≤ 上限 ${formatBytes(r.target.hardBytes)},可以发`)); + else out(C.red(` ✘ 还是超了 ${formatBytes(r.after - r.target.hardBytes)}`)); + if (v.durationOk === false) out(C.yellow(` ! 时长 ${formatDuration(r.inputInfo.durationSec)} 超过 ${r.target.label} 的 ${formatDuration(r.target.maxDurationSec)}`)); + if (r.alternatives?.length) { + out(); + out(C.bold(' 换个思路:')); + for (const a of r.alternatives) out(C.dim(` · ${a.text}`)); + } + out(); + out(` ${C.dim('产出:')}${r.output}`); +} + +async function cardFor(file, result, { ffmpeg, out: cardOut } = {}) { + const cardPath = cardOut || path.join(path.dirname(result.output), `${path.basename(result.output, '.mp4')}.card.html`); + const poster = await extractPoster(result.output, { ffmpeg }); + const posterName = poster?.path ? path.basename(poster.path) : ''; + const checks = platformChecks(result.afterInfo || result.inputInfo); + const html = cardHtml({ + videoPath: path.basename(result.output), + posterName, + meta: { + beforeBytes: result.before, + afterBytes: result.after, + target: result.target.label, + durationSec: result.inputInfo.durationSec, + resolution: `${result.afterInfo?.video.displayWidth ?? result.inputInfo.video.displayWidth}×${result.afterInfo?.video.displayHeight ?? result.inputInfo.video.displayHeight}`, + contentLabel: result.content.label, + bitrate: formatBitrate(result.afterInfo?.bitrateBps), + encodeSeconds: result.encodeSeconds, + verdict: result.verdict, + platformChecks: checks, + alternatives: result.alternatives, + }, + }); + writeFileSync(cardPath, html, 'utf8'); + return cardPath; +} + +// —— 命令实现 —— + +const commands = { + async help() { out(HELP); }, + + async platforms(args) { + const db = loadPlatforms(); + if (args.json) { + out(JSON.stringify(db.targets, null, 2)); + return; + } + out(); + out(`${C.bold('平台限制速查')} ${C.dim(`更新于 ${db.updatedAt}`)}`); + out(C.dim(db.disclaimer)); + out(); + for (const t of db.targets) { + const conf = t.confidence === 'official' ? C.green('官方') : t.confidence === 'community' ? C.dim('社区') : C.yellow('口径不一'); + out(`${C.bold(t.id)} ${t.label} ${conf}`); + out(` 体积上限 ${formatBytes(t.maxBytes)}${t.suggestedMaxBytes ? C.dim(`(建议压到 ${formatBytes(t.suggestedMaxBytes)})`) : ''}${t.maxDurationSec ? ` 时长上限 ${formatDuration(t.maxDurationSec)}` : ''}`); + for (const n of t.notes || []) out(C.dim(` · ${n}`)); + for (const s of t.sources || []) out(C.dim(` 来源 ${s.url} — ${s.note}`)); + out(); + } + }, + + async doctor() { + const r = await doctor(); + out(formatDoctor(r)); + if (!r.ok) process.exitCode = 2; + }, + + async inspect(args) { + const bins = await binariesOrDie(); + const files = args._; + if (!files.length) throw new Error('至少给一个文件:express inspect 视频.mp4'); + const results = []; + for (const f of files) { + const info = await probe(f, { ffprobe: bins.ffprobe }); + const checks = platformChecks(info); + results.push({ file: f, info, checks }); + if (!args.json) printInspect(info, checks); + } + if (args.json) out(JSON.stringify(results, null, 2)); + }, + + async fit(args) { + const bins = await binariesOrDie(); + const input = args._[0]; + if (!input) throw new Error('用法:express fit 视频.mp4 --to wechat-chat'); + if (!args.to) throw new Error('必须给目标:--to wechat-chat 或 --to 25MB(用 express platforms 看有哪些目标)'); + + const t0 = Date.now(); + const result = await fit(input, { + to: args.to, + preset: args.preset || 'balanced', + out: args.out, + speed: args.speed || 'medium', + maxPasses: Number(args['max-passes'] || 4), + dryRun: Boolean(args['dry-run']), + normalize: Boolean(args.normalize), + ffmpeg: bins.ffmpeg, + ffprobe: bins.ffprobe, + onProgress: progressReporter('压缩中'), + onPass: () => {}, + }); + if (process.stdout.isTTY) process.stdout.write('\r' + ' '.repeat(24) + '\r'); + const encodeSeconds = Math.round(((Date.now() - t0) / 1000) * 10) / 10; + result.encodeSeconds = encodeSeconds; + + if (args.json) { + out(JSON.stringify(result, null, 2)); + } else if (args['dry-run']) { + out(); + out(`${C.bold('压缩计划')} ${C.dim('(--dry-run,没有真压)')}`); + out(` 目标 ${result.target.label} ${formatBytes(result.target.hardBytes)}`); + out(` 内容 ${result.content.label}`); + for (const p of result.passes) { + const r = estimateRange({ + width: p.width, height: p.height, fps: p.fps, crf: p.crf ?? 30, + kind: result.content.kind, durationSec: result.inputInfo.durationSec, + audioBytes: p.hasAudio ? 0 : 0, + }); + out(C.dim(` ${p.width}×${p.height} ${p.fps}fps CRF${p.crf ?? '—'} 预估 ${formatBytes(r.low)} ~ ${formatBytes(r.high)}`)); + } + out(); + out(C.dim(' 预估是粗略区间:不同内容的压缩难度能差几倍,所以给区间而不是一个看着精确的数字。')); + out(C.dim(' 实际以压完量到的为准——超了会自动试下一档,直到达标或明确说压不进去。')); + out(); + } else { + printFit(result, encodeSeconds); + } + + if (!args['dry-run']) { + if (args.ledger !== false) { + try { appendEntry(toEntry(result, { encodeSeconds })); } catch { /* 台账写不进去不该影响主流程 */ } + } + if (args.card) { + const cardPath = await cardFor(input, result, { ffmpeg: bins.ffmpeg }); + out(C.dim(` 投递卡 ${cardPath}`)); + } + if (result.verdict.fitsHardLimit === false) process.exitCode = 1; + } + }, + + async trim(args) { + const bins = await binariesOrDie(); + const input = args._[0]; + if (!input) throw new Error('用法:express trim 视频.mp4 --start 0:10 --end 1:20'); + const r = await trim(input, { + start: args.start || 0, + end: args.end ?? null, + duration: args.duration ?? null, + out: args.out, + reencode: args.fast !== true, + ffmpeg: bins.ffmpeg, + ffprobe: bins.ffprobe, + onProgress: progressReporter('裁剪中'), + }); + out(); + out(`${C.bold('裁好了')} ${formatBytes(r.before)} ${C.dim('→')} ${formatBytes(r.after)}`); + out(` 片段 ${formatDuration(r.startSec)} 起 ${r.durationSec ? formatDuration(r.durationSec) : '到结尾'}`); + out(` ${C.dim('产出:')}${r.output}`); + out(); + }, + + async gif(args) { + const bins = await binariesOrDie(); + const input = args._[0]; + if (!input) throw new Error('用法:express gif 视频.mp4 --width 320 --square'); + const r = await toGif(input, { + out: args.out, + width: Number(args.width || 320), + fps: Number(args.fps || 12), + start: Number(args.start || 0), + duration: args.duration ? Number(args.duration) : null, + cropSquare: Boolean(args.square), + ffmpeg: bins.ffmpeg, + onProgress: progressReporter('转 GIF'), + }); + if (process.stdout.isTTY) process.stdout.write('\r' + ' '.repeat(24) + '\r'); + out(); + out(`${C.bold('GIF 好了')} ${formatBytes(r.bytes)} ${r.width}px ${r.fps}fps`); + for (const w of r.warnings) out(C.yellow(` ! ${w}`)); + if (!r.warnings.length) out(C.green(` ✔ 在微信表情 1MB 上限之内`)); + out(` ${C.dim('产出:')}${r.output}`); + out(); + }, + + async split(args) { + const bins = await binariesOrDie(); + const input = args._[0]; + if (!input) throw new Error('用法:express split 视频.mp4 --to wechat-chat'); + if (!args.to) throw new Error('必须给目标:--to wechat-chat 或 --to 25MB'); + const r = await split(input, { + to: args.to, + parts: args.parts ? Number(args.parts) : null, + outDir: args.out || null, + preset: args.preset || 'balanced', + speed: args.speed || 'medium', + ffmpeg: bins.ffmpeg, + ffprobe: bins.ffprobe, + maxPasses: Number(args['max-passes'] || 3), + onProgress: progressReporter('分段压缩'), + onPart: (p) => out(C.dim(` 第 ${p.index}/${p.of} 段 → ${formatBytes(p.bytes)} ${p.fits ? C.green('✔') : C.red('✘')}`)), + }); + if (process.stdout.isTTY) process.stdout.write('\r' + ' '.repeat(24) + '\r'); + + if (r.action === 'noop') { + out(); + out(C.green(`✔ ${r.reason}`)); + out(); + return; + } + out(); + out(`${C.bold(`切成了 ${r.segments.length} 段`)} ${C.dim(`每段都压到 ${r.target.label} 以内`)}`); + for (const s of r.segments) { + out(` ${String(s.index).padStart(2)} ${s.startText} → ${s.endText} ${formatBytes(s.bytes).padStart(9)} ${s.fits ? C.green('✔') : C.red('✘ 超限')}`); + } + out(); + if (r.allFit) { + out(C.green(` ✔ 每段都在 ${formatBytes(r.target.hardBytes)} 以内`)); + out(C.dim(` 目录 ${r.dir}`)); + } else { + out(C.red(` ✘ 第 ${r.overSegments.join('、')} 段仍然超限`)); + out(C.dim(' 试试 --parts 给更多段数,或者把 --to 调小')); + } + if (args.ledger !== false) { + for (const s of r.segments) { + try { + appendEntry({ + action: 'split', input, output: s.path, + targetId: r.target.kind === 'platform' ? r.target.platform.id : 'custom', + targetLabel: r.target.label, + beforeBytes: s.bytes, afterBytes: s.bytes, + durationSec: s.end - s.start, contentKind: s.content?.kind ?? null, + passCount: 0, fitsHardLimit: s.fits, encodeSeconds: null, + }); + } catch { /* 台账写不进去不影响主流程 */ } + } + } + out(); + }, + + async card(args) { + const bins = await binariesOrDie(); + const input = args._[0]; + if (!input) throw new Error('用法:express card 视频.mp4'); + const info = await probe(input, { ffprobe: bins.ffprobe }); + // 顺序很重要:先定卡片落在哪,封面再抽到**卡片同目录**。 + // 之前封面默认抽到「视频所在目录」,于是 `--out` 指到别处时, + // 卡片里的 poster="xxx.cover.jpg" 这个相对路径会指错地方 —— 在别处打开是张没有封面的卡。 + const cardPath = args.out + ? path.resolve(args.out) + : path.join(path.dirname(input), `${path.basename(input, path.extname(input))}.card.html`); + const cardDir = path.dirname(cardPath); + mkdirSync(cardDir, { recursive: true }); + const poster = await extractPoster(input, { + ffmpeg: bins.ffmpeg, + out: path.join(cardDir, `${path.basename(input, path.extname(input))}.cover.jpg`), + }); + const beforeBytes = args.from && existsSync(args.from) ? statSync(args.from).size : null; + const target = args.to ? resolveTarget(args.to) : null; + const checks = platformChecks(info).filter((c) => (target ? c.id === target.platform?.id : true)); + // 独立生成卡片时也要量一次内容判定,否则卡片上「内容判定」那一栏是空的, + // 而这恰恰是投递方最想看的信息之一(决定对方会看到多糊的画面) + const content = await analyzeContent(input, { + ff: bins.ffmpeg.path, + durationSec: info.durationSec, + width: info.video.displayWidth, + height: info.video.displayHeight, + }); + const html = cardHtml({ + videoPath: path.basename(input), + posterName: poster.path ? path.basename(poster.path) : '', + meta: { + beforeBytes, + afterBytes: info.sizeBytes, + target: target?.label ?? null, + durationSec: info.durationSec, + resolution: `${info.video.displayWidth}×${info.video.displayHeight}`, + contentLabel: content.label, + bitrate: formatBitrate(info.bitrateBps), + verdict: { fitsHardLimit: target ? info.sizeBytes <= target.hardBytes : null, durationOk: target?.maxDurationSec ? info.durationSec <= target.maxDurationSec : null }, + platformChecks: checks, + }, + }); + writeFileSync(cardPath, html, 'utf8'); + out(`${C.green('✔')} 投递卡 ${cardPath}`); + if (poster.path) out(C.dim(` 封面 ${poster.path}`)); + // 视频不在卡片旁边时要提示:卡片里引用的是文件名,连同视频一起发给别人就会缺文件。 + // 判断得看「视频在不在**卡片**目录」——之前写成查视频在不在它自己的目录,那永远成立, + // 于是提示语从来没打印过,测出来「静默」正好是它的表现。 + if (!existsSync(path.join(cardDir, path.basename(input)))) { + out(C.dim(' 注意:视频不在卡片同一目录,卡片在这里能看,但连同视频一起发给别人会缺文件。')); + out(C.dim(` 要一起发的话,把视频也拷到 ${cardDir}`)); + } + }, + + async ledger(args) { + const entries = readEntries(); + const s = summarize(entries); + if (args.json) { out(JSON.stringify({ summary: s, entries }, null, 2)); return; } + out(); + out(`${C.bold('压缩台账')} ${C.dim(ledgerPath())}`); + if (!entries.length) { out(C.dim(' 还是空的——先压一个视频。')); out(); return; } + out(` 共 ${s.count} 次,省下 ${C.green(formatBytes(s.savedBytes))},平均 ${s.savedRatio?.toFixed(1)}×`); + for (const t of s.byTarget) { + out(C.dim(` ${t.target}:${t.count} 次,${formatBytes(t.before)} → ${formatBytes(t.after)}`)); + } + const htmlPath = args.out || path.join(process.cwd(), 'express-台账.html'); + writeReport(htmlPath, s, entries); + out(); + out(` ${C.green('✔')} 报告 ${htmlPath}`); + out(); + }, +}; + +export async function main(argv = process.argv.slice(2)) { + const known = new Set(Object.keys(commands)); + const cmd = argv[0] && !argv[0].startsWith('-') ? argv[0] : 'help'; + const rest = argv[0] && !argv[0].startsWith('-') ? argv.slice(1) : argv; + + let parsed; + try { + parsed = parseArgs({ + args: rest, + options: { + to: { type: 'string' }, + out: { type: 'string' }, + preset: { type: 'string' }, + speed: { type: 'string' }, + 'max-passes': { type: 'string' }, + start: { type: 'string' }, + end: { type: 'string' }, + duration: { type: 'string' }, + width: { type: 'string' }, + fps: { type: 'string' }, + from: { type: 'string' }, + parts: { type: 'string' }, + json: { type: 'boolean' }, + card: { type: 'boolean' }, + 'dry-run': { type: 'boolean' }, + square: { type: 'boolean' }, + normalize: { type: 'boolean' }, + fast: { type: 'boolean' }, + help: { type: 'boolean', short: 'h' }, + version: { type: 'boolean' }, + ledger: { type: 'boolean' }, + }, + allowPositionals: true, + strict: false, + }); + } catch (err) { + out(C.red(`参数有误:${err.message}`)); + out(C.dim('跑 express help 看用法')); + process.exitCode = 2; + return; + } + + const args = { ...parsed.values, _: parsed.positionals }; + if (args['no-ledger']) args.ledger = false; + if (args.version) { out(JSON.parse((await import('node:fs')).readFileSync(new URL('../package.json', import.meta.url), 'utf8')).version); return; } + if (args.help || cmd === 'help' || !known.has(cmd)) { + if (cmd && !known.has(cmd) && cmd !== 'help') out(C.red(`没有这个命令:${cmd}`)); + await commands.help(args); + if (cmd && !known.has(cmd) && cmd !== 'help') process.exitCode = 2; + return; + } + + try { + await commands[cmd](args); + } catch (err) { + out(C.red(`✘ ${err.message}`)); + if (process.env.EXPRESS_DEBUG) out(C.dim(String(err.stack))); + process.exitCode = 1; + } +} diff --git a/plugins/andre-1998/express-media/src/doctor.js b/plugins/andre-1998/express-media/src/doctor.js new file mode 100644 index 00000000..a5f40ed5 --- /dev/null +++ b/plugins/andre-1998/express-media/src/doctor.js @@ -0,0 +1,86 @@ +// doctor:把「能不能跑」和「为什么跑不了」都讲清楚。 +// 起因是 winget 升级后 WinGet\Links 里的 ffmpeg.exe 变成悬空符号链接: +// 路径能解析,一执行就报「系统找不到指定的文件」。这种情况必须说人话。 +import { resolveBinaries, IS_WINDOWS } from './ffmpeg.js'; + +const NEEDED_ENCODERS = ['libx264', 'aac', 'gif']; + +export async function doctor({ env = process.env } = {}) { + const found = await resolveBinaries({ env }); + const checks = []; + + for (const name of ['ffmpeg', 'ffprobe']) { + const bin = found[name]; + if (bin) { + checks.push({ level: 'ok', name, text: `可用:${bin.path}`, detail: `${bin.version}(来源:${bin.source})` }); + } else { + checks.push({ level: 'bad', name, text: `没找到可用的 ${name}` }); + } + } + + // 悬空链接这类「解析得到但跑不起来」的候选,单列出来——这比「没找到」有用得多 + const broken = found.rejected || []; + for (const b of broken) { + let why; + if (b.reason === 'enoent') why = '路径能解析,但执行时找不到目标文件——典型的悬空符号链接'; + else if (b.reason === 'timeout') why = '执行超过 8 秒没有返回,疑似卡死'; + else why = `执行失败:${b.error || b.reason}`; + checks.push({ + level: 'warn', name: b.name, + text: `这个 ${b.name} 用不了:${b.path}`, + detail: `${why}(来源:${b.from})`, + }); + } + + if (found.ffmpeg) { + // 一次执行就够了:既要退出码,也要拿到编码器列表 + const { run } = await import('./ffmpeg.js'); + const enc = await run(found.ffmpeg.path, ['-hide_banner', '-encoders'], { maxBuffer: 4 * 1024 * 1024 }); + const text = (enc.stdout || '') + (enc.stderr || ''); + for (const e of NEEDED_ENCODERS) { + const has = new RegExp(`(^|\\s)${e}(\\s|$)`, 'm').test(text); + checks.push({ + level: has ? 'ok' : 'warn', name: e, + text: has ? `编码器 ${e} 可用` : `没找到编码器 ${e}`, + detail: has ? '' : 'H.264 是各平台兼容性最好的选择,缺它就得换 ffmpeg 构建(推荐 gyan.dev 的 essentials build)', + }); + } + + // 处理旋转元数据要用 sidedata 滤镜(ffmpeg 6.0 才有)。缺了它, + // 竖屏视频会被烤正一次之后又被播放器再转一次 —— 发出去是躺着的。 + const filters = await run(found.ffmpeg.path, ['-hide_banner', '-filters'], { maxBuffer: 4 * 1024 * 1024 }); + const ftext = (filters.stdout || '') + (filters.stderr || ''); + const hasSidedata = /(^|\s)sidedata(\s|$)/m.test(ftext); + checks.push({ + level: hasSidedata ? 'ok' : 'warn', name: 'sidedata 滤镜', + text: hasSidedata ? 'sidedata 滤镜可用(竖屏方向能处理干净)' : '没有 sidedata 滤镜,竖屏视频可能被重复旋转', + detail: hasSidedata ? '' : '需要 ffmpeg ≥ 6.0。老版本遇到带旋转元数据的竖屏素材,请先用别的方式把方向烤进像素。', + }); + } + + if (found.missing && broken.length) { + checks.push({ + level: 'bad', name: '提示', + text: '所有候选都跑不通', + detail: '装一个:winget install ffmpeg,或者从 https://www.gyan.dev/ffmpeg/builds/ 下载后把 bin 目录加进 PATH', + }); + } + + return { ok: Boolean(found.ffmpeg && found.ffprobe), checks, binaries: { ffmpeg: found.ffmpeg, ffprobe: found.ffprobe }, broken }; +} + +export function formatDoctor(result) { + const icon = { ok: '✔', warn: '!', bad: '✘' }; + const lines = ['急件 · 环境体检', '']; + for (const c of result.checks) { + lines.push(`${icon[c.level]} ${c.text}`); + if (c.detail) lines.push(` ${c.detail}`); + } + lines.push(''); + lines.push(result.ok + ? '环境就绪。试试:express inspect 你的视频.mp4' + : '环境没就绪,先按上面的提示修 ffmpeg;修完再跑一次 express doctor。'); + return lines.join('\n'); +} + +export const isWindows = IS_WINDOWS; diff --git a/plugins/andre-1998/express-media/src/ffmpeg.js b/plugins/andre-1998/express-media/src/ffmpeg.js new file mode 100644 index 00000000..9cf880ca --- /dev/null +++ b/plugins/andre-1998/express-media/src/ffmpeg.js @@ -0,0 +1,257 @@ +// ffmpeg / ffprobe 的发现与执行层。 +// +// 这里刻意解决一个真实踩过的坑:Windows 上 winget 升级后,%LOCALAPPDATA%\Microsoft\WinGet\Links +// 里的 ffmpeg.exe 会变成悬空符号链接——`where ffmpeg` 能查到、`Get-Command ffmpeg` 能解析出路径, +// 但一执行就报「系统找不到指定的文件」。只看「路径能不能解析」是不够的,**必须真的执行一次**。 +import { spawn } from 'node:child_process'; +import { existsSync, readdirSync } from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; + +const IS_WIN = process.platform === 'win32'; + +/** 已知安装位置。顺序即优先级:先专用安装,再系统目录,最后才信 PATH。 */ +function knownDirs(env = process.env) { + const home = env.USERPROFILE || os.homedir(); + const dirs = []; + if (env.EXPRESS_FFMPEG_DIR) dirs.push(env.EXPRESS_FFMPEG_DIR); + if (IS_WIN) { + // 常见的手动安装位置(winget 链接坏掉时的救命稻草) + dirs.push(path.join(home, '.minimax', 'tools', 'ffmpeg')); + dirs.push(path.join(home, 'scoop', 'apps', 'ffmpeg', 'current', 'bin')); + dirs.push('C:\\ffmpeg\\bin', 'C:\\Program Files\\ffmpeg\\bin'); + if (env.LOCALAPPDATA) { + dirs.push(path.join(env.LOCALAPPDATA, 'Microsoft', 'WinGet', 'Links')); + } + } else if (process.platform === 'darwin') { + dirs.push('/opt/homebrew/bin', '/usr/local/bin'); + if (env.HOMEBREW_PREFIX) dirs.push(path.join(env.HOMEBREW_PREFIX, 'bin')); + } else { + dirs.push('/usr/bin', '/usr/local/bin', '/snap/bin'); + } + return dirs.filter(Boolean); +} + +/** 展开目录:既接受直接指向 bin 的目录,也接受里面还有一层版本目录的目录。 */ +function expandDir(dir) { + const found = []; + const direct = path.join(dir, IS_WIN ? 'ffmpeg.exe' : 'ffmpeg'); + if (existsSync(direct)) found.push(dir); + else { + // 形如 ~/.minimax/tools/ffmpeg/ffmpeg-9.0.2-essentials_build/bin + let entries = []; + try { + entries = readdirSync(dir, { withFileTypes: true }); + } catch { + entries = []; + } + for (const e of entries) { + if (!e.isDirectory()) continue; + const sub = path.join(dir, e.name, 'bin'); + if (existsSync(path.join(sub, IS_WIN ? 'ffmpeg.exe' : 'ffmpeg'))) found.push(sub); + } + } + return found; +} + +function whichAll(cmd) { + // 用 shell 拿 PATH 上所有同名可执行文件(Windows 上 where.exe,类 Unix 用 command -v) + return new Promise((resolve) => { + const shellCmd = IS_WIN ? `where ${cmd}` : `command -v ${cmd}`; + const p = spawn(shellCmd, { shell: true, windowsHide: true }); + let out = ''; + p.stdout.on('data', (d) => (out += d)); + p.on('close', (code) => { + resolve( + code === 0 + ? out + .split(/\r?\n/) + .map((s) => s.trim()) + .filter(Boolean) + : [], + ); + }); + p.on('error', () => resolve([])); + }); +} + +/** 真的把二进制跑起来。返回 null 表示「路径在但跑不通」——这正是悬空链接的情形。 */ +export function tryRun(bin, args = ['-version'], { timeoutMs = 8000 } = {}) { + return new Promise((resolve) => { + let p; + try { + p = spawn(bin, args, { windowsHide: true }); + } catch (err) { + resolve({ ok: false, reason: err.code || 'spawn-failed', error: err.message }); + return; + } + let out = ''; + let settled = false; + const timer = setTimeout(() => { + if (settled) return; + settled = true; + try { p.kill(); } catch { /* 已经退了 */ } + resolve({ ok: false, reason: 'timeout' }); + }, timeoutMs); + p.stdout.on('data', (d) => (out += d)); + p.stderr.on('data', (d) => (out += d)); + p.on('error', (err) => { + if (settled) return; + settled = true; + clearTimeout(timer); + resolve({ ok: false, reason: err.code === 'ENOENT' ? 'enoent' : err.code || 'error', error: err.message }); + }); + p.on('close', (code) => { + if (settled) return; + settled = true; + clearTimeout(timer); + if (code === 0) resolve({ ok: true, version: parseVersion(out) }); + else resolve({ ok: false, reason: 'exit-' + code, output: out.slice(0, 400) }); + }); + }); +} + +function firstLine(s) { + const line = String(s).split(/\r?\n/).find((l) => l.trim()); + return line ? line.trim() : ''; +} + +/** + * 从 ffmpeg 的版本横幅里只取版本号。 + * 整行横幅是 "ffmpeg version 9.0.2-... Copyright (C) 2020-2026 the FFmpeg developers", + * 直接回显给用户既吵又掺进一堆英文(界面承诺是中文),所以这里剥掉。 + */ +export function parseVersion(banner) { + const line = firstLine(banner); + const m = /version\s+(\S+)/i.exec(line); + return m ? m[1] : line; +} + +function basename(p) { + return path.basename(p); +} + +/** + * 找一个真正能跑的 ffmpeg(以及同目录的 ffprobe)。 + * 返回 { ffmpeg, ffprobe, rejected[] }——rejected 记录「解析得到但跑不通」的候选, + * 这样 doctor 能把真实原因讲出来,而不是笼统地报「找不到 ffmpeg」。 + */ +export async function resolveBinaries({ env = process.env, required = ['ffmpeg', 'ffprobe'] } = {}) { + const rejected = []; + const candidates = new Map(); // 绝对路径 → 来源说明 + + const addFromEnv = (name) => { + const v = env[`EXPRESS_${name.toUpperCase()}`]; + if (v) candidates.set(path.resolve(v), `环境变量 EXPRESS_${name.toUpperCase()}`); + }; + required.forEach(addFromEnv); + + for (const dir of knownDirs(env)) { + for (const d of expandDir(dir)) { + for (const name of required) { + const bin = path.join(d, IS_WIN ? `${name}.exe` : name); + if (existsSync(bin) && !candidates.has(bin)) candidates.set(bin, `已知安装位置 ${d}`); + } + } + } + + for (const name of required) { + for (const p of await whichAll(name)) { + const abs = path.resolve(p); + if (!candidates.has(abs)) candidates.set(abs, 'PATH'); + } + } + + const found = {}; + for (const name of required) { + // 全都探一遍,而不是找到一个就收工:把「别的候选其实是坏的」这件事也报出来, + // 否则用户只会看到「一切正常」,然后在别的工具里踩同一个坑。 + // 注意悬空符号链接对 existsSync 是不可见的(existsSync 跟随链接、目标没了就返回 false), + // 所以这类坏路径只能靠「where 列出来 + 真的执行一次」发现。 + let hit = null; + const probedDirs = new Set(); + for (const [bin, from] of candidates) { + if (basename(bin).replace(/\.exe$/i, '') !== name) continue; + const dir = path.dirname(bin); + if (probedDirs.has(dir)) continue; // 同一个目录只探一次 + probedDirs.add(dir); + const r = await tryRun(bin, ['-version']); + if (r.ok) { + if (!hit) hit = { path: bin, version: r.version, source: from }; + } else { + rejected.push({ name, path: bin, from, reason: r.reason, error: r.error }); + } + } + if (!hit) { + return { ffmpeg: found.ffmpeg || null, ffprobe: found.ffprobe || null, rejected, missing: name }; + } + found[name] = hit; + } + return { ffmpeg: found.ffmpeg, ffprobe: found.ffprobe, rejected }; +} + +const TIME_RE = /time=\s*(-?)(\d+):(\d+):(\d+(?:\.\d+)?)/; + +/** 解析 ffmpeg 进度行里的 time=HH:MM:SS.ss */ +export function parseFfmpegTime(line) { + const m = TIME_RE.exec(line); + if (!m) return null; + const sign = m[1] === '-' ? -1 : 1; + return sign * (Number(m[2]) * 3600 + Number(m[3]) * 60 + Number(m[4])); +} + +/** + * 跑一个 ffmpeg / ffprobe 进程。stderr 收日志(ffmpeg 把它当日志通道),stdout 按需收集。 + */ +export function run(bin, args, { onProgress, durationSec, maxBuffer = 32 * 1024 * 1024, signal } = {}) { + return new Promise((resolve, reject) => { + let p; + try { + p = spawn(bin, args, { windowsHide: true, maxBuffer }); + } catch (err) { + reject(Object.assign(new Error(`无法启动 ${basename(bin)}:${err.message}`), { code: err.code })); + return; + } + let stdout = ''; + const chunks = []; + let bytes = 0; + let stderrTail = ''; + let progress = { seconds: 0, ratio: null }; + let onAbort; + if (signal) { + if (signal.aborted) { try { p.kill(); } catch { /* noop */ } } + onAbort = () => { try { p.kill(); } catch { /* noop */ } }; + signal.addEventListener('abort', onAbort, { once: true }); + } + p.stdout.on('data', (d) => { + chunks.push(d); + bytes += d.length; + if (bytes > maxBuffer) { try { p.kill(); } catch { /* noop */ } return; } + stdout += d.toString('utf8'); + }); + p.stderr.on('data', (d) => { + const s = d.toString(); + stderrTail = (stderrTail + s).slice(-8000); + if (onProgress) { + for (const line of s.split(/\r?\n|\r/)) { + const t = parseFfmpegTime(line); + if (t !== null) { + progress = { seconds: t, ratio: durationSec ? Math.max(0, Math.min(1, t / durationSec)) : null }; + onProgress(progress); + } + } + } + }); + p.on('error', (err) => { + if (signal) signal.removeEventListener('abort', onAbort); + reject(Object.assign(new Error(`无法执行 ${basename(bin)}:${err.message}(路径:${bin})`), { code: err.code, bin })); + }); + p.on('close', (code) => { + if (signal) signal.removeEventListener('abort', onAbort); + // stdout 是给 ffprobe / 文本输出用的字符串;stdoutBuffer 是给抽帧这种二进制场景用的 + resolve({ code, stdout, stdoutBuffer: Buffer.concat(chunks), stderr: stderrTail }); + }); + }); +} + +export const IS_WINDOWS = IS_WIN; diff --git a/plugins/andre-1998/express-media/src/fit.js b/plugins/andre-1998/express-media/src/fit.js new file mode 100644 index 00000000..c70742a0 --- /dev/null +++ b/plugins/andre-1998/express-media/src/fit.js @@ -0,0 +1,435 @@ +// 核心:把一个视频压到「能发出去」的体积。 +// +// 设计上只有一条硬规矩:**不量就别说成功**。 +// 每一次编码之后都用 ffprobe 量真实体积,超了才算下一档;宁可报「压不进去」也不交一个超限文件。 +import { copyFileSync, existsSync, mkdirSync, readdirSync, statSync, unlinkSync } from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; +import { run } from './ffmpeg.js'; +import { probe } from './probe.js'; +import { analyzeContent, KINDS } from './classify.js'; +import { resolveTarget } from './format.js'; + +const PRESET_CAPS = { keep: Infinity, balanced: 1920, small: 1280 }; +const IM_VIDEO_CODECS = new Set(['h264']); +const IM_AUDIO_CODECS = new Set(['aac', 'mp3', 'none']); + +function even(n) { const v = Math.round(n); return v % 2 === 0 ? v : v + 1; } + +/** 按长边上限等比缩到偶数;不放大。 */ +export function capLongSide(w, h, cap) { + if (!w || !h) return { w: null, h: null }; + const long = Math.max(w, h); + if (long <= cap) return { w: even(w), h: even(h) }; + const k = cap / long; + return { w: even(w * k), h: even(h * k) }; +} + +/** 降一档分辨率:长边 ×0.75,够狠又不至于掉到马赛克。 */ +export function stepDown({ w, h }, factor = 0.75) { + return { w: even(w * factor), h: even(h * factor) }; +} + +export function resolutionLadder(w, h, preset = 'balanced', { minLong = 360 } = {}) { + const cap = PRESET_CAPS[preset] ?? PRESET_CAPS.balanced; + const start = capLongSide(w, h, cap); + const steps = [start]; + let cur = start; + while (steps.length < 8) { + const next = stepDown(cur); + if (Math.max(next.w, next.h) < minLong) break; + steps.push(next); + cur = next; + } + return steps; +} + +export function fpsCap(sourceFps, preset = 'balanced') { + if (!sourceFps) return null; + // 24fps 这种本来就低的保持原样——把 24 拉到 30 只会浪费体积 + if (sourceFps <= 30.5) return Math.round(sourceFps * 100) / 100; + return preset === 'keep' ? 60 : 30; +} + +/** 旋转的像素处理:宁可把方向烤进画面,也别指望每个 IM 客户端都认 display matrix。 */ +export function rotationFilter(rotation) { + switch (((Number(rotation) || 0) % 360 + 360) % 360) { + case 90: return 'transpose=1'; + case 180: return 'hflip,vflip'; + case 270: return 'transpose=2'; + default: return null; + } +} + +/** + * 裁剪用输出选项 `-ss` / `-t`,**不要用 `trim` 滤镜**。 + * + * 实测踩过的坑:ffmpeg 9.0.2 上 `-vf trim=0:12.5` 根本不裁剪,产出仍是完整的 25 秒; + * 而 `-t 12.5` 正确给出 12.5 秒。所以「为了快而改用滤镜」这个优化是倒退—— + * 它既没更快,还悄悄丢掉了裁剪语义。 + * + * 语义对齐 trim.js:`start > 0` 时把 `-ss` 放 `-i` 之前(快速定位), + * `-t` 放在输出侧表示「定位之后再取多少秒」,两者相加就是区间长度。 + */ +export function trimArgs({ start = 0, end = null, duration = null }) { + const args = { seek: null, take: null }; + if (start > 0) args.seek = start; + if (duration !== null && duration !== undefined && duration > 0) args.take = duration; + else if (end !== null && end !== undefined && end > start) args.take = end - start; + return args; +} + +export function buildFilter({ width, height, rotation }) { + const parts = []; + const tf = rotationFilter(rotation); + const hadRotation = Boolean(tf); + if (tf) parts.push(tf); + if (width && height) parts.push(`scale=${width}:${height}:flags=lanczos`, 'setsar=1'); + // 关键:像素转正之后,必须把容器里的显示矩阵删掉。 + // 只做 transpose 是不够的——实测 ffmpeg 会把输入的 display matrix 一路带到输出, + // 结果播放器再转一次,竖屏视频发出去是躺着的(而 -metadata rotate=0 只写老式 tag,管不到矩阵)。 + if (hadRotation) parts.push('sidedata=mode=delete:type=DISPLAYMATRIX'); + return parts.length ? parts.join(',') : null; +} + +function videoArgs({ width, height, fps, crf, bitrateBps, rotation, speed }) { + const args = []; + const vf = buildFilter({ width, height, rotation }); + if (vf) args.push('-vf', vf); + args.push('-c:v', 'libx264', '-preset', speed, '-pix_fmt', 'yuv420p', '-profile:v', 'high'); + if (bitrateBps) { + args.push('-b:v', String(Math.round(bitrateBps))); + args.push('-maxrate', String(Math.round(bitrateBps * 1.25))); + args.push('-bufsize', String(Math.round(bitrateBps * 2))); + } else { + args.push('-crf', String(crf)); + } + if (fps) args.push('-r', String(fps)); + return args; +} + +function audioArgs(audio) { + if (!audio.present) return ['-an']; + return ['-c:a', 'aac', '-b:a', `${audio.kbps}k`, '-ac', String(audio.channels || 2), '-ar', '48000']; +} + +/** 单遍编码的参数(抽出来是为了能在单测里逐条断言参数) */ +export function encodeArgs({ input, output, width, height, fps, crf, bitrateBps, audio, rotation, speed = 'medium', trim = null }) { + const t = trim ? trimArgs(trim) : { seek: null, take: null }; + return [ + '-nostdin', '-v', 'error', '-y', '-noautorotate', + ...(t.seek !== null ? ['-ss', String(t.seek)] : []), + '-i', input, + ...videoArgs({ width, height, fps, crf, bitrateBps, rotation, speed }), + ...(t.take !== null ? ['-t', String(t.take)] : []), + ...audioArgs(audio), + '-metadata:s:v:0', 'rotate=0', '-movflags', '+faststart', output, + ]; +} + +/** 两遍编码要跑两个进程:第二遍的码率分配依赖第一遍写出的统计文件 */ +export function twoPassArgsList({ input, output, width, height, fps, bitrateBps, audio, rotation, speed = 'medium', trim = null, logPrefix }) { + const t = trim ? trimArgs(trim) : { seek: null, take: null }; + const common = ['-nostdin', '-v', 'error', '-y', '-noautorotate', + ...(t.seek !== null ? ['-ss', String(t.seek)] : []), '-i', input, + ...videoArgs({ width, height, fps, crf: null, bitrateBps, rotation, speed })]; + const pass1 = [...common, ...(t.take !== null ? ['-t', String(t.take)] : []), '-pass', '1', '-passlogfile', logPrefix, '-an', '-f', 'mp4', os.devNull]; + const pass2 = [...common, ...(t.take !== null ? ['-t', String(t.take)] : []), '-pass', '2', '-passlogfile', logPrefix, '-metadata:s:v:0', 'rotate=0', '-movflags', '+faststart', output]; + return [pass1, pass2]; +} + +function audioPlan(info, targetBytes) { + const channels = info.audio.channels || 2; + if (!info.audio.present) return { present: false, kbps: 0, channels: 2, estimatedBytes: 0 }; + // 目标极小时直接丢音频——省下的体积比降分辨率还多 + if (targetBytes < 512 * 1024) return { present: false, kbps: 0, channels, estimatedBytes: 0, dropped: true }; + const kbps = targetBytes < 2 * 1024 * 1024 ? 64 : 96; + return { + present: true, kbps, + channels: channels > 2 ? 2 : channels, + estimatedBytes: Math.ceil((kbps * 1000 * (info.durationSec || 0)) / 8), + }; +} + +/** + * 体积估算:只用来排「这一档值不值得试」,最终判定一律以实测为准。 + * + * 对着合成素材标定的结果:camera 档的模型值 0.050 / 实测 0.0504,几乎正中; + * screen 和 motion 两档的合成素材不具代表性(一个是纯色暗背景,一个是纯色方块, + * 都比真实内容好压一个量级),所以没有拿它们去反推模型——那会让模型对真实内容更不准。 + * + * 正因为跨内容类型的偏差能到几倍,调用方应该把它当**区间**展示,而不是一个精确数字。 + */ +export function estimateBytes({ width, height, fps, crf, kind, durationSec, audioBytes = 0 }) { + const k = KINDS[kind] || KINDS.camera; + // bpp 随 CRF 下滑的经验曲线,够用来排顺序,不用来承诺结果 + const bpp = Math.max(0.004, k.minBpp * Math.pow(0.86, crf - k.crfStart)); + const videoBytes = Math.ceil((width * height * fps * bpp * (durationSec || 0)) / 8); + return videoBytes + audioBytes; +} + +/** 估算区间。宁可给一个宽区间,也不要给一个看着精确、实际偏乐观 35% 的数字。 */ +export function estimateRange(args) { + const mid = estimateBytes(args); + return { low: Math.round(mid * 0.5), high: Math.round(mid * 1.8) }; +} + +function publicPass(plan) { + return { + width: plan.width, height: plan.height, fps: plan.fps, crf: plan.crf ?? null, + bitrateBps: plan.bitrateBps ?? null, audioKbps: plan.audio.present ? plan.audio.kbps : 0, + hasAudio: plan.audio.present, + }; +} + +async function runEncode(ffmpegPath, argsList, { onProgress, durationSec, signal }) { + let last = null; + for (const args of argsList) { + last = await run(ffmpegPath, args, { onProgress, durationSec, signal }); + if (last.code !== 0) return last; + } + return last; +} + +function makeLogPrefix() { + return path.join(os.tmpdir(), `express-2pass-${process.pid}-${Math.random().toString(36).slice(2, 8)}`); +} + +function cleanupPassLogs(prefix) { + if (!prefix) return; + let entries = []; + try { entries = readdirSync(path.dirname(prefix)); } catch { return; } + const base = path.basename(prefix); + for (const f of entries) { + if (f.startsWith(base)) { try { unlinkSync(path.join(path.dirname(prefix), f)); } catch { /* 清理失败无所谓 */ } } + } +} + +/** + * 主流程。 + * @returns 每一档的参数、实测体积、最终判定,以及「压不进去」时给出的替代方案。 + */ +export async function fit(input, opts = {}) { + const { + to, preset = 'balanced', out, ffmpeg, ffprobe, + speed = 'medium', maxPasses = 4, signal, onProgress, + onPass = () => {}, dryRun = false, trim = null, + // normalize = 即使体积已经达标也重编码一遍:把方向烤进像素、统一容器。 + // 默认关掉是因为「直接复制」既无损又快,没必要为了统一而重压一次。 + normalize = false, + } = opts; + + if (!ffmpeg?.path) throw new Error('缺少 ffmpeg 路径,先跑 express doctor'); + if (!existsSync(input)) throw new Error(`文件不存在:${input}`); + + const target = resolveTarget(to); + const info = await probe(input, { ffprobe }); + if (!info.video.present) throw new Error(`这个文件里没有视频轨:${input}`); + + const content = await analyzeContent(input, { + ff: ffmpeg.path, + durationSec: info.durationSec, + // 用「观看者看到的尺寸」采样:竖屏带旋转元数据时,原始宽高和显示宽高是互换的 + width: info.video.displayWidth, + height: info.video.displayHeight, + }); + const k = KINDS[content.kind] || KINDS.camera; + const outPath = out || defaultOutPath(input, target, preset); + // 目录必须在第一次写文件之前就建好:中间档的临时文件也是往这儿写的, + // 等到 produce() 再建的话,前面每一次编码都会因为「打不开输出文件」而失败。 + mkdirSync(path.dirname(outPath), { recursive: true }); + const base = { input, inputInfo: info, target, content, preset, speed, out: outPath }; + + // —— 情况 1:本来就发得出去,而且格式是各家都认的 —— + // normalize 会跳过这条捷径:用户明确要求把方向/容器统一好 + if (info.sizeBytes <= target.hardBytes && !trim && !normalize) { + const friendly = IM_VIDEO_CODECS.has(info.video.codec) && IM_AUDIO_CODECS.has(info.audio.present ? info.audio.codec : 'none'); + if (friendly) { + // 体积达标时保持无损(直接复制)。但如果它带旋转元数据,得说清楚: + // 有些客户端不认 display matrix,收到的是躺着的大文件——那不叫「能发」。 + const warnings = []; + if (info.video.rotation !== 0) { + warnings.push( + `这个文件靠旋转元数据(${info.video.rotation}°)摆正,体积达标所以保持了原样、没有重编码。` + + '个别客户端不认这个元数据,收到会横着显示。真遇到了就加 --normalize 强制把方向烤进像素。', + ); + } + if (info.video.hdr) { + warnings.push('这是 HDR 视频,部分平台和播放器会显示成偏色。发之前最好确认一下对方看得到。'); + } + if (dryRun) { + return finish({ ...base, action: 'copy', output: outPath, before: info.sizeBytes, after: info.sizeBytes, passes: [], afterInfo: info, dryRun: true }); + } + await produce(input, outPath, ffmpeg, { copy: true }); + return finish({ ...base, action: 'copy', output: outPath, before: info.sizeBytes, after: statSync(outPath).size, passes: [], afterInfo: await probe(outPath, { ffprobe }), warnings }); + } + // 体积过关但格式不吃香(比如 HEVC/MKV),继续走重编码 + } + + const ladder = resolutionLadder(info.video.displayWidth, info.video.displayHeight, preset); + const fps = fpsCap(info.video.fps, preset); + const audio = audioPlan(info, target.aimBytes); + const passes = []; + + let crf = k.crfStart; + let resIdx = 0; + let bitrateBps = null; + let best = null; + + // dry-run 要把整条阶梯走完(观众要知道「最坏情况下会试到哪」),不受 maxPasses 限制 + while (passes.length < (dryRun ? Number.POSITIVE_INFINITY : maxPasses)) { + const { w, h } = ladder[resIdx]; + const plan = { width: w, height: h, fps, crf, bitrateBps, audio, rotation: info.video.rotation, speed, trim }; + const predicted = estimateBytes({ ...plan, kind: content.kind, durationSec: info.durationSec, audioBytes: audio.estimatedBytes }); + + if (dryRun) { + passes.push({ ...publicPass(plan), predictedBytes: predicted, measuredBytes: null, done: false }); + onPass({ type: 'plan', ...publicPass(plan), predictedBytes: predicted }); + if (bitrateBps) break; + if (crf < k.maxCrf) crf = Math.min(k.maxCrf, crf + k.crfStep); + else if (resIdx < ladder.length - 1) { resIdx += 1; crf = k.crfStart; } + else break; + continue; + } + + const tmp = `${outPath}.p${passes.length + 1}.tmp.mp4`; + const logPrefix = bitrateBps ? makeLogPrefix() : null; + const argsList = bitrateBps + ? twoPassArgsList({ input, output: tmp, width: w, height: h, fps, bitrateBps, audio, rotation: info.video.rotation, speed, trim, logPrefix }) + : [encodeArgs({ input, output: tmp, width: w, height: h, fps, crf, audio, rotation: info.video.rotation, speed, trim })]; + + const t0 = Date.now(); + const { code, stderr } = await runEncode(ffmpeg.path, argsList, { onProgress, durationSec: info.durationSec, signal }); + if (logPrefix) cleanupPassLogs(logPrefix); + + const measured = existsSync(tmp) ? statSync(tmp).size : null; + const record = { + ...publicPass(plan), predictedBytes: predicted, measuredBytes: measured, + seconds: Math.round(((Date.now() - t0) / 1000) * 10) / 10, done: true, + error: code === 0 ? null : (stderr || '').trim().slice(0, 300), + tmp, + }; + passes.push({ ...record, tmp: undefined }); + onPass({ type: 'done', ...record }); + + if (code !== 0 || measured === null) { + if (best) break; + if (resIdx < ladder.length - 1) { resIdx += 1; crf = k.crfStart; bitrateBps = null; continue; } + break; + } + + if (measured <= target.aimBytes) { best = { path: tmp, bytes: measured }; break; } + if (!best || measured < best.bytes) best = { path: tmp, bytes: measured }; + + const ratio = measured / target.aimBytes; + if (bitrateBps) { + if (resIdx < ladder.length - 1) { resIdx += 1; bitrateBps = null; crf = k.crfStart; } + else break; + continue; + } + if (crf < k.maxCrf) { + // 体积对 CRF 近似指数关系,所以按超出倍数取 log2 推下一档,通常 2–3 档就收敛 + const jump = Math.max(k.crfStep, Math.min(8, Math.ceil(6 * Math.log2(ratio)))); + crf = Math.min(k.maxCrf, crf + jump); + continue; + } + if (resIdx < ladder.length - 1) { resIdx += 1; crf = k.crfStart + k.crfStep; continue; } + // 分辨率和 CRF 都到底了:最后上一发按目标体积反算码率 + bitrateBps = Math.max(80_000, Math.floor(((target.aimBytes - audio.estimatedBytes) * 8 * 0.9) / Math.max(1, info.durationSec))); + } + + if (dryRun) { + // dry-run 只描述「打算怎么试」,没有真的压过任何东西, + // 所以绝不能拿「没产出」去判定压不进去——那是拿没跑过的实验当结论。 + return finish({ ...base, action: 'encode', output: outPath, before: info.sizeBytes, after: null, passes, afterInfo: null, dryRun: true }); + } + + if (!best) { + const floor = ladder[ladder.length - 1]; + throw new Error( + `压不进去:${input}\n` + + ` 时长 ${(info.durationSec || 0).toFixed(1)}s,目标 ${target.label},分辨率已经降到 ${floor.w}×${floor.h}、CRF 拉满 ${k.maxCrf} 仍然超限。\n` + + ` 换一条路:裁短时长(express trim)、分段发(express split),或者改成发网盘链接。`, + ); + } + + await produce(best.path, outPath, ffmpeg, { move: true }); + cleanupTmp(outPath); + const after = statSync(outPath).size; + return finish({ + ...base, action: 'encode', output: outPath, before: info.sizeBytes, after, + passes, afterInfo: await probe(outPath, { ffprobe }), + }); +} + +function cleanupTmp(outPath) { + const dir = path.dirname(outPath); + const base = path.basename(outPath); + let entries = []; + try { entries = readdirSync(dir); } catch { return; } + for (const f of entries) { + if (/^.*\.p\d+\.tmp\.mp4$/.test(f) && f.startsWith(base.replace(/\.mp4$/, ''))) { + try { unlinkSync(path.join(dir, f)); } catch { /* 清理失败不影响主流程 */ } + } + } +} + +async function produce(src, dest, ffmpeg, { copy = false, move = false } = {}) { + mkdirSync(path.dirname(dest), { recursive: true }); + if (path.resolve(src) === path.resolve(dest)) return; + if (move) { + copyFileSync(src, dest); + try { unlinkSync(src); } catch { /* 已经不在就算了 */ } + return; + } + if (copy) { copyFileSync(src, dest); return; } + const { code, stderr } = await run(ffmpeg.path, ['-nostdin', '-v', 'error', '-y', '-i', src, '-c', 'copy', dest]); + if (code !== 0) throw new Error(`封装失败:${(stderr || '').trim()}`); +} + +function defaultOutPath(input, target, preset) { + const dir = path.dirname(input); + const base = path.basename(input, path.extname(input)); + const tag = target.kind === 'platform' ? target.platform.id : `lt${Math.max(1, Math.round(target.hardBytes / 1024 / 1024))}mb`; + return path.join(dir, `${base}.${tag}.${preset}.mp4`); +} + +function finish(o) { + const hasAfter = o.after !== null && o.after !== undefined; + const fits = hasAfter ? o.after <= o.target.hardBytes : null; + const dur = o.inputInfo.durationSec || 0; + const durationOk = o.target.maxDurationSec === null || o.target.maxDurationSec === undefined + ? null : dur <= o.target.maxDurationSec; + return { + ...o, + verdict: { + fitsHardLimit: fits, + fitsAim: hasAfter ? o.after <= o.target.aimBytes : null, + durationOk, + }, + savedBytes: hasAfter ? Math.max(0, o.before - o.after) : null, + ratio: hasAfter && o.after > 0 ? Math.round((o.before / o.after) * 100) / 100 : null, + alternatives: hasAfter && !fits ? suggestAlternatives(o) : [], + }; +} + +/** 压不进去时,至少告诉用户「要换什么才可能行」。 */ +export function suggestAlternatives(o) { + const out = []; + const dur = o.inputInfo.durationSec || 0; + const k = KINDS[o.content.kind] || KINDS.camera; + const w = Math.max(360, Math.round((o.inputInfo.video.displayWidth || 1280) * 0.25)); + const h = Math.max(360, Math.round((o.inputInfo.video.displayHeight || 720) * 0.25)); + const fps = fpsCap(o.inputInfo.video.fps, 'small') || 30; + const bytesPerSec = estimateBytes({ width: w, height: h, fps, crf: k.maxCrf, kind: o.content.kind, durationSec: 1 }); + if (bytesPerSec > 0 && dur > 0) { + const maxSec = Math.floor(o.target.aimBytes / bytesPerSec); + // 只在真帮得上忙时才提:裁掉不到两成的片子等于没裁,这种建议是噪音 + if (maxSec > 0 && maxSec < dur * 0.8) { + out.push({ kind: 'trim', text: `裁到约 ${maxSec} 秒(现在 ${Math.round(dur)} 秒)大概能压进去`, seconds: maxSec }); + } + } + out.push({ kind: 'split', text: `按 ${Math.max(2, Math.ceil(o.inputInfo.sizeBytes / o.target.hardBytes))} 段分开发,每段都小于上限` }); + out.push({ kind: 'link', text: '上传到网盘 / 视频平台后发链接,这类场景大多数平台都收链接不收文件' }); + return out; +} diff --git a/plugins/andre-1998/express-media/src/format.js b/plugins/andre-1998/express-media/src/format.js new file mode 100644 index 00000000..410bbdc4 --- /dev/null +++ b/plugins/andre-1998/express-media/src/format.js @@ -0,0 +1,174 @@ +// 输出格式化 + 平台限制表加载。 +import { readFileSync } from 'node:fs'; +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; + +const here = path.dirname(fileURLToPath(import.meta.url)); +export const DATA_PATH = path.resolve(here, '..', 'data', 'platforms.json'); + +let cached = null; +export function loadPlatforms({ reload = false } = {}) { + if (cached && !reload) return cached; + const raw = JSON.parse(readFileSync(DATA_PATH, 'utf8')); + if (!Array.isArray(raw.targets) || raw.targets.length === 0) { + throw new Error(`平台表坏了:${DATA_PATH} 里没有 targets`); + } + const byId = new Map(); + for (const t of raw.targets) { + if (!t.id) throw new Error('平台表里有一条没有 id'); + if (byId.has(t.id)) throw new Error(`平台表里 id 重复:${t.id}`); + byId.set(t.id, t); + } + cached = { ...raw, byId }; + return cached; +} + +export function getTarget(id) { + const db = loadPlatforms(); + const t = db.byId.get(id); + if (!t) { + throw new Error(`没这个目标:${id}。可用:${[...db.byId.keys()].join(', ')}`); + } + return t; +} + +const SIZE_RE = /^(\d+(?:\.\d+)?)\s*(b|kb|mb|gb|k|m|g)?$/i; + +/** 把 "25MB" / "500k" / "1.5g" / 数字 统一成字节数 */ +export function parseSize(spec) { + if (typeof spec === 'number') return Math.floor(spec); + const m = SIZE_RE.exec(String(spec).trim()); + if (!m) throw new Error(`看不懂的大小:${spec}(试试 25MB / 500k / 1.5g)`); + const value = Number(m[1]); + const unit = (m[2] || 'b').toLowerCase(); + const mult = { b: 1, k: 1024, kb: 1024, m: 1024 ** 2, mb: 1024 ** 2, g: 1024 ** 3, gb: 1024 ** 3 }[unit]; + return Math.floor(value * mult); +} + +export const MIN_TARGET_BYTES = 16 * 1024; + +/** + * 解析 --to 的值:要么是平台 id,要么是自定义大小。 + * 返回 { label, hardBytes, aimBytes, confidence, platform } + */ +export function resolveTarget(spec) { + const s = String(spec).trim(); + if (/^\d/.test(s)) { + const bytes = parseSize(s); + // 荒唐的输入要在入口就拦下:给一个 0 字节的目标,工具会老老实实压三档再报超限, + // 浪费几分钟还让人以为自己哪里没设置对。这明显是打字打错了。 + if (bytes < MIN_TARGET_BYTES) { + throw new Error( + `目标体积太小:${s}(${bytes} 字节)。视频压到 ${MIN_TARGET_BYTES / 1024}KB 以下已经不算视频了。\n` + + ' 如果你想发到某个平台,用 --to 加平台 id(express platforms 看有哪些),或者确认一下是不是少打了个 0。', + ); + } + return { + kind: 'custom', + label: `自定义 ${formatBytes(bytes)}`, + hardBytes: bytes, + aimBytes: safeAim(bytes), + confidence: 'custom', + platform: null, + }; + } + const t = getTarget(s); + return { + kind: 'platform', + label: t.label, + hardBytes: t.maxBytes, + // 平台给了建议值就用建议值,否则自己留 2% 余量 + aimBytes: t.suggestedMaxBytes ? Math.min(t.suggestedMaxBytes, safeAim(t.maxBytes)) : safeAim(t.maxBytes), + confidence: t.confidence, + maxDurationSec: t.maxDurationSec ?? null, + platform: t, + }; +} + +/** + * 压到硬上限以内还要留一点余量:容器/元数据的开销、以及各家「25MB 但实际 25.0 就失败」的脾气。 + * + * 余量取「固定 512KB / 2% 里的大者」,但**再封顶在上限的 10%**。 + * 不封顶会踩坑:固定 512KB 对 400KB 的目标来说比上限还大, + * 目标体积会被吃成 1KB,于是「裁到多少秒能压进去」这类建议永远算不出来。 + */ +export function safeAim(hardBytes) { + const want = Math.max(512 * 1024, Math.round(hardBytes * 0.02)); + const headroom = Math.min(want, Math.round(hardBytes * 0.1)); + return Math.max(1, hardBytes - headroom); +} + +export function formatBytes(n) { + if (n === null || n === undefined || !Number.isFinite(n)) return '—'; + const units = ['B', 'KB', 'MB', 'GB']; + let v = Math.abs(n); + let i = 0; + while (v >= 1024 && i < units.length - 1) { v /= 1024; i += 1; } + const digits = v >= 100 || i === 0 ? 0 : v >= 10 ? 1 : 2; + return `${n < 0 ? '-' : ''}${v.toFixed(digits)} ${units[i]}`; +} + +export function formatDuration(sec) { + if (sec === null || sec === undefined || !Number.isFinite(sec)) return '—'; + if (sec < 60) return `${sec.toFixed(sec < 10 ? 1 : 0)} 秒`; + const m = Math.floor(sec / 60); + const s = Math.round(sec % 60); + if (m < 60) return s ? `${m} 分 ${s} 秒` : `${m} 分`; + const h = Math.floor(m / 60); + return `${h} 小时 ${m % 60} 分`; +} + +export function formatBitrate(bps) { + if (!bps || !Number.isFinite(bps)) return '—'; + if (bps >= 1e6) return `${(bps / 1e6).toFixed(1)} Mbps`; + return `${Math.round(bps / 1e3)} kbps`; +} + +/** + * ffprobe 的 format_name 是「所有能装下这个流的容器」的清单,例如 mp4 会报 + * "mov,mp4,m4a,3gp,3g2,mj2"。用户只关心「这是个什么文件」,所以挑一个真容器名出来。 + */ +export function containerLabel(formatName) { + const list = String(formatName || '').split(',').map((s) => s.trim()).filter(Boolean); + if (!list.length) return '—'; + const known = ['matroska', 'webm', 'mp4', 'mov', 'avi', 'mpegts', 'flv', 'gif', 'mxf', 'asf', '3gp', 'm4v']; + for (const k of known) if (list.includes(k)) return k === 'matroska' ? 'mkv' : k; + return list[0]; +} + +/** + * 按**显示宽度**补空格对齐。中文是双宽字符,用 padEnd 按字符数补会彻底错位。 + */ +const WIDE = /[\u1100-\u115F\u2E80-\u303E\u3041-\u33FF\u3400-\u4DBF\u4E00-\u9FFF\uA000-\uA4CF\uAC00-\uD7A3\uF900-\uFAFF\uFE30-\uFE6F\uFF00-\uFF60\uFFE0-\uFFE6]/; +export function displayWidth(s) { + let w = 0; + for (const ch of String(s)) w += WIDE.test(ch) ? 2 : 1; + return w; +} +export function padDisplay(s, width) { + const str = String(s); + return str + ' '.repeat(Math.max(0, width - displayWidth(str))); +} + +export function formatTimecode(sec) { + if (!Number.isFinite(sec)) return '00:00'; + const m = Math.floor(sec / 60); + const s = Math.floor(sec % 60); + return `${String(m).padStart(2, '0')}:${String(s).padStart(2, '0')}`; +} + +/** + * 补上输出文件的扩展名。 + * + * ffmpeg 靠扩展名判断输出格式,路径没有扩展名时它会报一句 + * "Unable to choose an output format for 'xxx'; use a standard extension", + * 而用户只是写了 `--out myclip` —— 这种报错不该由用户来翻译。 + * 扩展名不对时也不覆盖用户写的名字(那样太意外),而是在后面补上正确的一个。 + */ +export function ensureExtension(p, ext) { + const s = String(p); + const current = path.extname(s); + if (!current) return `${s}.${ext}`; + if (current.toLowerCase() === `.${ext.toLowerCase()}`) return s; + return `${s}.${ext}`; +} diff --git a/plugins/andre-1998/express-media/src/gif.js b/plugins/andre-1998/express-media/src/gif.js new file mode 100644 index 00000000..8626eb1a --- /dev/null +++ b/plugins/andre-1998/express-media/src/gif.js @@ -0,0 +1,83 @@ +// 转 GIF / 表情包。 +// 关键点:用 palettegen + paletteuse 两段滤镜,量化调色板由内容决定。 +// 直接 -vf fps,scale 输出 GIF 的典型症状是渐变区域出现色带,看着像坏了。 +import { existsSync, mkdirSync, statSync } from 'node:fs'; +import path from 'node:path'; +import { run } from './ffmpeg.js'; +import { ensureExtension } from './format.js'; + +export const GIF_LIMITS = { + wechatEmojiBytes: 1024 * 1024, // 微信自定义表情单个 1MB 以内 + practicalBytes: 2 * 1024 * 1024, // 超过这个体积,很多 IM 里滑动会卡 +}; + +export function buildGifFilter({ width = 480, fps = 12, cropSquare = false, maxColors = 256, dither = 'bayer' }) { + const parts = [`fps=${fps}`]; + if (cropSquare) { + parts.push(`scale=${width}:${width}:force_original_aspect_ratio=increase:flags=lanczos`); + parts.push(`crop=${width}:${width}`); + } else { + parts.push(`scale=${width}:-1:flags=lanczos`); + } + const base = parts.join(','); + // 注意:带显式输入标签的滤镜,选项前必须用 `=` 而不是 `:`。 + // 写成 `paletteuse:dither=bayer` 的话,ffmpeg 会把 `:dither` 当成链上的下一个滤镜, + // 然后报一句完全指不到真因的 "No option name near 'bayer'"。 + const ditherArg = dither === 'none' ? '' : `=dither=${dither}:bayer_scale=3`; + return `[0:v]${base},split[s0][s1];[s0]palettegen=max_colors=${maxColors}:stats_mode=diff[p];[s1][p]paletteuse${ditherArg}`; +} + +/** 体积预测只用于给建议;真实结果一律量出来。 */ +export function estimateGifBytes({ width, height, fps, durationSec }) { + return Math.ceil(width * height * fps * durationSec * 0.09); +} + +export async function toGif(input, opts = {}) { + const { + out, width = 480, fps = 12, start = 0, duration = null, + cropSquare = false, maxColors = 256, dither = 'bayer', + speed = 'medium', ffmpeg, onProgress, signal, + } = opts; + if (!ffmpeg?.path) throw new Error('缺少 ffmpeg 路径,先跑 express doctor'); + if (!existsSync(input)) throw new Error(`文件不存在:${input}`); + const outPath = ensureExtension(out || defaultGifPath(input), 'gif'); + // 目录要先建好,否则 ffmpeg 会因为「打不开输出文件」直接失败, + // 而报错信息是 exit code 1,指向不了真正的原因 + mkdirSync(path.dirname(outPath), { recursive: true }); + const filter = buildGifFilter({ width, fps, cropSquare, maxColors, dither }); + const args = ['-nostdin', '-v', 'error', '-y']; + if (start > 0) args.push('-ss', String(start)); + args.push('-i', input); + if (duration) args.push('-t', String(duration)); + args.push('-filter_complex', filter, '-loop', '0', outPath); + + const { code, stderr } = await run(ffmpeg.path, args, { onProgress, signal }); + if (code !== 0 || !existsSync(outPath)) { + throw new Error(`转 GIF 失败:${(stderr || '').trim() || `退出码 ${code}`}`); + } + const bytes = statSync(outPath).size; + return { + output: outPath, + bytes, + width, fps, cropSquare, + estimate: estimateGifBytes({ width, height: width, fps, durationSec: duration || 3 }), + warnings: gifWarnings(bytes, cropSquare ? width : width), + }; +} + +export function gifWarnings(bytes, width) { + const w = []; + if (bytes > GIF_LIMITS.wechatEmojiBytes) { + w.push(`体积 ${(bytes / 1024 / 1024).toFixed(2)}MB 超过微信表情的 1MB 上限;把 width 降到 ${Math.max(80, Math.floor(width * 0.6))} 或 fps 降到 8–10 再试`); + } else if (bytes > GIF_LIMITS.practicalBytes) { + w.push(`体积 ${(bytes / 1024 / 1024).toFixed(2)}MB 虽然在 1MB 之上但不算离谱;要更顺滑建议继续压到 1MB 以内`); + } + if (width > 480) w.push(`${width}px 偏大,聊天窗口里会缩得很小,表情包一般 240–320px 就够看清`); + return w; +} + +function defaultGifPath(input) { + const dir = path.dirname(input); + const base = path.basename(input, path.extname(input)); + return path.join(dir, `${base}.gif`); +} diff --git a/plugins/andre-1998/express-media/src/ledger.js b/plugins/andre-1998/express-media/src/ledger.js new file mode 100644 index 00000000..bbe243a8 --- /dev/null +++ b/plugins/andre-1998/express-media/src/ledger.js @@ -0,0 +1,157 @@ +// 压缩台账:每压一次记一笔,回答「我到底省了多少」「都花在哪些平台上了」。 +import { appendFileSync, existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; +import { formatBytes, formatDuration } from './format.js'; + +export function ledgerDir(env = process.env) { + return env.EXPRESS_HOME || path.join(env.USERPROFILE || os.homedir(), '.express'); +} + +export function ledgerPath(env = process.env) { + return path.join(ledgerDir(env), 'ledger.jsonl'); +} + +export function appendEntry(entry, { env = process.env } = {}) { + const dir = ledgerDir(env); + mkdirSync(dir, { recursive: true }); + const record = { ts: new Date().toISOString(), ...entry }; + appendFileSync(ledgerPath(env), JSON.stringify(record) + '\n', 'utf8'); + return record; +} + +export function readEntries({ env = process.env } = {}) { + const p = ledgerPath(env); + if (!existsSync(p)) return []; + return readFileSync(p, 'utf8') + .split(/\r?\n/) + .filter(Boolean) + .map((line) => { + try { return JSON.parse(line); } catch { return null; } + }) + .filter(Boolean); +} + +export function summarize(entries) { + const valid = entries.filter((e) => Number.isFinite(e.beforeBytes) && Number.isFinite(e.afterBytes)); + const before = valid.reduce((s, e) => s + e.beforeBytes, 0); + const after = valid.reduce((s, e) => s + e.afterBytes, 0); + const seconds = valid.reduce((s, e) => s + (e.encodeSeconds || 0), 0); + const byTarget = new Map(); + for (const e of valid) { + const key = e.targetLabel || '未知'; + const cur = byTarget.get(key) || { count: 0, before: 0, after: 0 }; + cur.count += 1; cur.before += e.beforeBytes; cur.after += e.afterBytes; + byTarget.set(key, cur); + } + return { + count: valid.length, + beforeBytes: before, + afterBytes: after, + savedBytes: Math.max(0, before - after), + savedRatio: before > 0 ? before / Math.max(1, after) : null, + encodeSeconds: seconds, + byTarget: [...byTarget.entries()] + .map(([target, v]) => ({ target, ...v, savedBytes: Math.max(0, v.before - v.after) })) + .sort((a, b) => b.savedBytes - a.savedBytes), + }; +} + +export function toEntry(result, { encodeSeconds = 0 } = {}) { + return { + action: result.action, + input: result.input, + output: result.output, + targetId: result.target.kind === 'platform' ? result.target.platform.id : 'custom', + targetLabel: result.target.label, + beforeBytes: result.before, + afterBytes: result.after, + durationSec: result.inputInfo?.durationSec ?? null, + contentKind: result.content?.kind ?? null, + passCount: result.passes?.length ?? 0, + fitsHardLimit: result.verdict?.fitsHardLimit ?? null, + encodeSeconds, + }; +} + +const CSS = ` +:root{--bg:#0f1115;--panel:#171a21;--line:#252a34;--fg:#e7eaf0;--dim:#8b93a5;--ok:#4ade80;--bad:#f87171;--warn:#fbbf24;--accent:#7c9cff} +*{box-sizing:border-box} +body{margin:0;padding:32px;background:var(--bg);color:var(--fg); + font:15px/1.6 -apple-system,"Segoe UI","Microsoft YaHei",system-ui,sans-serif} +.wrap{max-width:1080px;margin:0 auto} +h1{font-size:22px;margin:0 0 4px;font-weight:650;letter-spacing:.02em} +.sub{color:var(--dim);font-size:13px;margin-bottom:24px} +.grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(160px,1fr));gap:12px;margin-bottom:24px} +.card{background:var(--panel);border:1px solid var(--line);border-radius:10px;padding:14px 16px} +.card .k{color:var(--dim);font-size:12px;margin-bottom:4px} +.card .v{font-size:20px;font-weight:600;font-variant-numeric:tabular-nums} +.card .v.ok{color:var(--ok)} .card .v.bad{color:var(--bad)} +table{width:100%;border-collapse:collapse;font-size:13px;margin-bottom:24px} +th,td{text-align:left;padding:8px 10px;border-bottom:1px solid var(--line)} +th{color:var(--dim);font-weight:500;font-size:12px} +td.num{text-align:right;font-variant-numeric:tabular-nums} +.bar{height:8px;border-radius:4px;background:var(--accent);display:inline-block;vertical-align:middle} +.pill{display:inline-block;padding:2px 8px;border-radius:999px;font-size:11px;border:1px solid} +.pill.ok{color:var(--ok);border-color:#1d5c37} .pill.bad{color:var(--bad);border-color:#6b2626} +.pill.warn{color:var(--warn);border-color:#6b5320} +a{color:var(--accent)} +.empty{color:var(--dim);padding:40px;text-align:center;border:1px dashed var(--line);border-radius:10px} +`; + +export function reportHtml(summary, entries, { title = '急件 · 压缩台账' } = {}) { + const rows = entries + .slice() + .reverse() + .map((e) => { + const pct = e.beforeBytes > 0 ? Math.max(1, Math.round((e.afterBytes / e.beforeBytes) * 100)) : 0; + return ` + ${esc(e.ts ? e.ts.slice(0, 19).replace('T', ' ') : '—')} + ${esc(pathBasename(e.input))} + ${esc(e.targetLabel || '—')} + ${formatBytes(e.beforeBytes)} + ${formatBytes(e.afterBytes)} + ${e.beforeBytes / Math.max(1, e.afterBytes) > 1 ? (e.beforeBytes / e.afterBytes).toFixed(1) + '×' : '—'} + ${e.fitsHardLimit === true ? '达标' : e.fitsHardLimit === false ? '超限' : '—'} + `; + }) + .join('\n'); + + const targetRows = summary.byTarget + .map((t) => `${esc(t.target)}${t.count}${formatBytes(t.before)}${formatBytes(t.after)}${formatBytes(t.before - t.after)}`) + .join('\n'); + + return ` + + +${esc(title)} +
+

${esc(title)}

+
共 ${summary.count} 次处理,累计 ${formatBytes(summary.beforeBytes)} → ${formatBytes(summary.afterBytes)}
+
+
累计省下
${formatBytes(summary.savedBytes)}
+
平均压缩比
${summary.savedRatio ? summary.savedRatio.toFixed(1) + '×' : '—'}
+
处理次数
${summary.count}
+
累计编码耗时
${formatDuration(summary.encodeSeconds)}
+
+${summary.byTarget.length ? `

按目标平台

+${targetRows}
目标次数原始产出省下
` : ''} +

明细

+${entries.length ? `${rows}
时间文件目标原始产出压缩比判定
` : '
台账还是空的,先压一个文件试试。
'} +
`; +} + +function esc(s) { + return String(s ?? '').replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c])); +} +function pathBasename(p) { + if (!p) return '—'; + const parts = String(p).split(/[\\/]/); + return parts[parts.length - 1]; +} + +export function writeReport(htmlPath, summary, entries, title) { + mkdirSync(path.dirname(htmlPath), { recursive: true }); + writeFileSync(htmlPath, reportHtml(summary, entries, { title }), 'utf8'); + return htmlPath; +} diff --git a/plugins/andre-1998/express-media/src/probe.js b/plugins/andre-1998/express-media/src/probe.js new file mode 100644 index 00000000..bf1de723 --- /dev/null +++ b/plugins/andre-1998/express-media/src/probe.js @@ -0,0 +1,159 @@ +// 文件体检:把 ffprobe 的 JSON 变成一份「能拿来做判断」的 MediaInfo。 +// 重点是把那些容易漏掉的字段捞出来:旋转、HDR、真实帧率、音频声道。 +import { statSync } from 'node:fs'; +import { run } from './ffmpeg.js'; + +export function parseRational(s) { + if (!s || typeof s !== 'string') return null; + const [num, den] = s.split('/'); + const n = Number(num); + const d = den === undefined ? 1 : Number(den); + if (!Number.isFinite(n) || !Number.isFinite(d) || d === 0) return null; + return n / d; +} + +/** 新版 ffmpeg 把旋转放在 side_data_list,旧版放在 tags.rotate,两个都要认。 */ +export function extractRotation(stream) { + const list = Array.isArray(stream.side_data_list) ? stream.side_data_list : []; + for (const sd of list) { + if (typeof sd.rotation === 'number') return normalizeAngle(sd.rotation); + } + const tag = stream.tags && stream.tags.rotate; + if (tag !== undefined && tag !== null && tag !== '') { + const n = Number(tag); + if (Number.isFinite(n)) return normalizeAngle(n); + } + return 0; +} + +function normalizeAngle(deg) { + const a = Math.round(deg) % 360; + return a < 0 ? a + 360 : a; +} + +export function isHdr(stream) { + const t = String(stream.color_transfer || ''); + return t === 'smpte2084' || t === 'arib-std-b67'; +} + +/** 从 ffprobe 的 JSON 文本构造 MediaInfo(拆出来是为了能单测解析本身) */ +export function parseProbe(json, { file, sizeBytes: sizeOverride } = {}) { + let data; + try { + data = typeof json === 'string' ? JSON.parse(json) : json; + } catch (err) { + throw new Error(`无法解析 ffprobe 输出:${err.message}`); + } + const fmt = data.format || {}; + const streams = Array.isArray(data.streams) ? data.streams : []; + const vs = streams.find((s) => s.codec_type === 'video'); + const as = streams.find((s) => s.codec_type === 'audio'); + + const durationSec = num(fmt.duration) ?? (vs ? num(vs.duration) : null) ?? null; + const sizeBytes = sizeOverride ?? num(fmt.size) ?? null; + const overallBitrate = num(fmt.bit_rate) ?? (durationSec && sizeBytes ? Math.round((sizeBytes * 8) / durationSec) : null); + + const video = vs + ? { + present: true, + codec: vs.codec_name || null, + profile: vs.profile || null, + width: num(vs.width) ?? null, + height: num(vs.height) ?? null, + fps: parseRational(vs.avg_frame_rate) ?? parseRational(vs.r_frame_rate) ?? null, + nominalFps: parseRational(vs.r_frame_rate) ?? null, + bitrateBps: num(vs.bit_rate) ?? null, + pixFmt: vs.pix_fmt || null, + rotation: extractRotation(vs), + displayWidth: num(vs.coded_width) ?? num(vs.width) ?? null, + displayHeight: num(vs.coded_height) ?? num(vs.height) ?? null, + hdr: isHdr(vs), + colorTransfer: vs.color_transfer || null, + frameCount: num(vs.nb_frames) ?? null, + hasBFrames: num(vs.has_b_frames) === 1, + } + // 没有视频轨时也要把字段补齐成 null:调用方写 info.video.displayWidth 不该 + // 在「有视频」和「没视频」两种情况下拿到 undefined 和 null 两种东西 + : { + present: false, codec: null, profile: null, width: null, height: null, + fps: null, nominalFps: null, bitrateBps: null, pixFmt: null, rotation: 0, + displayWidth: null, displayHeight: null, hdr: false, colorTransfer: null, + frameCount: null, hasBFrames: false, + }; + + const audio = as + ? { + present: true, + codec: as.codec_name || null, + sampleRate: num(as.sample_rate) ?? null, + channels: num(as.channels) ?? null, + channelLayout: as.channel_layout || null, + bitrateBps: num(as.bit_rate) ?? null, + } + : { + present: false, codec: null, sampleRate: null, channels: null, + channelLayout: null, bitrateBps: null, + }; + + // 旋转 90/270 时,宽高对「观看者」来说是互换的 + const swap = video.rotation === 90 || video.rotation === 270; + const displayW = swap ? video.height : video.width; + const displayH = swap ? video.width : video.height; + + return { + file: file ?? null, + sizeBytes, + durationSec, + bitrateBps: overallBitrate, + format: { + name: fmt.format_name || null, + longName: fmt.format_long_name || null, + nbStreams: num(fmt.nb_streams) ?? streams.length, + }, + video: { + ...video, + displayWidth: displayW ?? null, + displayHeight: displayH ?? null, + megapixels: displayW && displayH ? round2((displayW * displayH) / 1e6) : null, + aspect: displayW && displayH ? round4(displayW / displayH) : null, + }, + audio, + }; +} + +function num(v) { + if (v === undefined || v === null || v === '') return null; + const n = Number(v); + return Number.isFinite(n) ? n : null; +} +function round2(n) { return Math.round(n * 100) / 100; } +function round4(n) { return Math.round(n * 10000) / 10000; } + +/** + * @param ffprobe 可以是「路径字符串」也可以是「{ path } 对象」。 + * 两种都收,是因为这两种传法在项目里都出现过,接口却只认一种—— + * 传错时的报错是 spawn 抱怨 "path argument must be of type string",完全指不到真因。 + */ +export async function probe(file, { ffprobe, stat = true } = {}) { + const ffprobeBin = typeof ffprobe === 'string' ? ffprobe : ffprobe?.path; + if (!ffprobeBin) throw new Error('缺少 ffprobe 路径,先跑 express doctor'); + if (!file) throw new Error('缺少要体检的文件路径'); + if (stat) { + const st = statSync(file); + if (!st.isFile()) throw new Error(`不是文件:${file}`); + if (st.size === 0) throw new Error(`文件是空的(0 字节):${file}`); + } + const { code, stdout, stderr } = await run(ffprobeBin, [ + '-v', 'error', + '-print_format', 'json', + '-show_format', + '-show_streams', + file, + ]); + if (code !== 0) { + throw new Error(`ffprobe 读不了这个文件(退出码 ${code}):${file}\n${(stderr || '').trim()}`); + } + let sizeBytes = null; + try { sizeBytes = statSync(file).size; } catch { /* 允许不 stat */ } + return parseProbe(stdout, { file, sizeBytes }); +} diff --git a/plugins/andre-1998/express-media/src/split.js b/plugins/andre-1998/express-media/src/split.js new file mode 100644 index 00000000..6007b7a9 --- /dev/null +++ b/plugins/andre-1998/express-media/src/split.js @@ -0,0 +1,79 @@ +// 分段:一个大文件拆成几个都小于上限的片段。 +// +// 复用 fit 的收敛逻辑——每一段都自己压、自己量、自己判定,不存在「以为压好了」的可能。 +// 分段数按「体积 / 目标」估算,视频码率大体恒定,所以等分时长 ≈ 等分体积。 +import { mkdirSync } from 'node:fs'; +import path from 'node:path'; +import { statSync } from 'node:fs'; +import { fit } from './fit.js'; +import { resolveTarget, formatBytes, formatDuration } from './format.js'; + +export function planSplit({ sizeBytes, aimBytes, durationSec, parts = null }) { + const need = Math.max(2, Math.ceil(sizeBytes / aimBytes)); + // 段数的语义要说清楚:不给(或给 0)就按体积自动算;给 1 等于没分,抬到 2; + // 给 ≥2 就尊重用户的选择,哪怕比「刚好够」多切几段 + const n = !parts || parts === 0 ? need : parts < 2 ? 2 : parts; + const seg = durationSec / n; + return { parts: n, need, segSeconds: seg }; +} + +export async function split(input, opts = {}) { + const { + to, parts = null, outDir = null, preset = 'balanced', speed = 'medium', + ffmpeg, ffprobe, onProgress, onPart = () => {}, signal, maxPasses = 3, + } = opts; + if (!ffmpeg?.path) throw new Error('缺少 ffmpeg 路径,先跑 express doctor'); + + const target = resolveTarget(to); + const dir = outDir || path.join(path.dirname(input), path.basename(input, path.extname(input)) + '.分片'); + mkdirSync(dir, { recursive: true }); + + // 先体检一次:整体已经装得下就没必要分 + const { probe } = await import('./probe.js'); + const info = await probe(input, { ffprobe }); + if (info.sizeBytes <= target.hardBytes) { + return { action: 'noop', target, inputInfo: info, segments: [], reason: `本来就装得下(${formatBytes(info.sizeBytes)} ≤ ${formatBytes(target.hardBytes)}),不用分` }; + } + + const plan = planSplit({ sizeBytes: info.sizeBytes, aimBytes: target.aimBytes, durationSec: info.durationSec, parts }); + const segments = []; + const total = plan.parts; + for (let i = 0; i < total; i += 1) { + const start = round3(i * plan.segSeconds); + let end = round3((i + 1) * plan.segSeconds); + if (i === total - 1) end = round3(info.durationSec); + if (end <= start) continue; + const out = path.join(dir, `${String(i + 1).padStart(2, '0')}.mp4`); + const r = await fit(input, { + to, out, preset, speed, ffmpeg, ffprobe, maxPasses, signal, + trim: { start, end }, + onProgress: onProgress ? (p) => onProgress({ ...p, part: i + 1, parts: total }) : undefined, + }); + const bytes = statSync(out).size; + segments.push({ + index: i + 1, of: total, path: out, start, end, bytes, + startText: formatDuration(start), endText: formatDuration(end), + fits: bytes <= target.hardBytes, + content: r.content, + }); + onPart({ index: i + 1, of: total, bytes, fits: bytes <= target.hardBytes }); + } + + const over = segments.filter((s) => !s.fits); + return { + action: 'split', + target, + inputInfo: info, + plan, + dir, + segments, + allFit: over.length === 0, + overSegments: over.map((s) => s.index), + // 分段 = 体积之和(各段压完的总和),用于跟原文件对比 + totalBytes: segments.reduce((a, s) => a + s.bytes, 0), + }; +} + +function round3(n) { + return Math.round(n * 1000) / 1000; +} diff --git a/plugins/andre-1998/express-media/src/trim.js b/plugins/andre-1998/express-media/src/trim.js new file mode 100644 index 00000000..c722f2e5 --- /dev/null +++ b/plugins/andre-1998/express-media/src/trim.js @@ -0,0 +1,91 @@ +// 裁剪 / 切片。视频太长时,先剪一刀往往比暴力压缩划算得多。 +import { existsSync, mkdirSync, statSync } from 'node:fs'; +import path from 'node:path'; +import { run } from './ffmpeg.js'; +import { parseProbe } from './probe.js'; +import { ensureExtension } from './format.js'; + +export function parseTimecode(spec) { + // 支持 12 / 1:30 / 01:02:03 / 1m30s / 90.5 + const s = String(spec).trim(); + if (/^\d+(\.\d+)?$/.test(s)) return Number(s); + const parts = s.split(':'); + if (parts.length > 3) throw new Error(`看不懂的时间:${spec}`); + const nums = parts.map((p) => { + if (!/^\d+(\.\d+)?$/.test(p)) throw new Error(`看不懂的时间:${spec}`); + return Number(p); + }); + if (nums.length === 3) return nums[0] * 3600 + nums[1] * 60 + nums[2]; + if (nums.length === 2) return nums[0] * 60 + nums[1]; + return nums[0]; +} + +export function trimArgs({ input, output, start, duration, reencode = true, speed = 'medium' }) { + const args = ['-nostdin', '-v', 'error', '-y']; + if (start > 0) args.push('-ss', String(start)); + args.push('-i', input); + if (duration !== null && duration !== undefined) args.push('-t', String(duration)); + if (reencode) { + args.push('-c:v', 'libx264', '-preset', speed, '-crf', '20', '-pix_fmt', 'yuv420p', '-c:a', 'aac', '-b:a', '160k', '-movflags', '+faststart'); + } else { + args.push('-c', 'copy'); + } + args.push(output); + return args; +} + +export async function trim(input, opts = {}) { + const { start = 0, end = null, duration = null, out, reencode = true, speed = 'medium', ffmpeg, ffprobe, signal, onProgress } = opts; + if (!ffmpeg?.path) throw new Error('缺少 ffmpeg 路径,先跑 express doctor'); + if (!existsSync(input)) throw new Error(`文件不存在:${input}`); + const startSec = start ? parseTimecode(start) : 0; + let dur = duration !== null && duration !== undefined ? parseTimecode(duration) : null; + if (dur === null && end !== null && end !== undefined) { + const endSec = parseTimecode(end); + dur = endSec - startSec; + if (dur <= 0) throw new Error(`结束时间(${end})必须晚于开始时间(${start})`); + } + if (dur !== null && dur <= 0) throw new Error('时长必须大于 0'); + const outPath = ensureExtension(out || defaultPath(input, startSec, dur), 'mp4'); + // 输出目录要先建好:ffmpeg 打不开输出文件时只会给一个 exit code 1, + // 报错完全指不到「目录不存在」这个真正的原因 + mkdirSync(path.dirname(outPath), { recursive: true }); + const { code, stderr } = await run(ffmpeg.path, trimArgs({ input, output: outPath, start: startSec, duration: dur, reencode, speed }), { onProgress, signal }); + if (code !== 0 || !existsSync(outPath)) { + throw new Error(`裁剪失败:${(stderr || '').trim() || `退出码 ${code}`}`); + } + const before = statSync(input).size; + const after = statSync(outPath).size; + const afterInfo = ffprobe ? await probeQuiet(outPath, ffprobe) : null; + return { output: outPath, startSec, durationSec: dur, before, after, afterInfo }; +} + +/** 体检产出是加分项,失败不该让整个裁剪失败 */ +async function probeQuiet(file, ffprobe) { + const bin = typeof ffprobe === 'string' ? ffprobe : ffprobe?.path; + if (!bin) return null; + try { + const res = await run(bin, ['-v', 'error', '-print_format', 'json', '-show_format', '-show_streams', file]); + if (res.code !== 0) return null; + return parseProbe(res.stdout, { file, sizeBytes: statSync(file).size }); + } catch { + return null; + } +} + +/** 切成 N 段(每段都不超过 targetBytes),用于「一个文件太大但必须整段发」的场景。 */ +export function splitArgs({ input, output, start, duration }) { + return [ + '-nostdin', '-v', 'error', '-y', '-ss', String(start), '-i', input, '-t', String(duration), + '-c:v', 'libx264', '-preset', 'veryfast', '-crf', '23', '-pix_fmt', 'yuv420p', + '-c:a', 'aac', '-b:a', '128k', '-movflags', '+faststart', output, + ]; +} + +function defaultPath(input, startSec, dur) { + const dir = path.dirname(input); + const base = path.basename(input, path.extname(input)); + const s = Math.round(startSec); + const d = dur ? `-${Math.round(dur)}s` : ''; + return path.join(dir, `${base}.trim${s ? `-${s}s` : ''}${d}.mp4`); +}