video_dedup.py 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. """
  4. 视频去重批处理工具
  5. 对输入视频做随机组合的二次处理(镜像/裁剪缩放/边框/调色/变速/帧率微调),
  6. 并重编码、清除原元数据,使输出在文件哈希、视觉指纹、音频指纹层面均与原片不同。
  7. 收尾工序(SEI 删除/SPS 裁切/元数据伪造)与音频指纹链对齐
  8. 「幸福BBA助手8.18」合成引擎逆向结论,见 逆向分析/8.18/分析报告_合成模式8.18增量.md。
  9. --ab 为 v7 无感判重引擎(掐头+几何重排+变速),物理依据与实测数据见
  10. 逆向分析/8.18/研究/B3_无鬼影策略.md:同内容双流混合对 pHash 全部无效且必有鬼影/闪烁,
  11. 单流几何重排 pHash 距离 0.41、行差优于源、零叠加伪影。
  12. 用法示例:
  13. python video_dedup.py # 处理当前目录 → ./去重输出
  14. python video_dedup.py -i 素材 -o 成品 -p strong
  15. python video_dedup.py -i a.mp4 --hw # 单文件,NVENC 硬件编码
  16. python video_dedup.py -i a.mp4 --ab -p strong # AB v7 无感判重(推荐)
  17. python video_dedup.py -i a.mp4 --interlace bff # 隔行档(场序指纹扰动,实验性)
  18. """
  19. import argparse
  20. import csv
  21. import json
  22. import random
  23. import subprocess
  24. import sys
  25. from datetime import datetime, timedelta
  26. from pathlib import Path
  27. VIDEO_EXTS = {'.mp4', '.mov', '.mkv', '.avi', '.flv', '.wmv', '.ts', '.m4v', '.webm', '.mpg', '.mpeg'}
  28. # 各档位:各变换的启用概率与参数范围
  29. PRESETS = {
  30. 'light': dict(
  31. p_hflip=0.5, p_crop=0.6, crop=(0.015, 0.03), p_eq=0.7,
  32. bright=0.015, contr=(0.98, 1.02), sat=(0.96, 1.04), gam=(0.98, 1.02),
  33. p_speed=0.6, speed=(0.96, 1.04), p_pad=0.0, p_fps=0.0,
  34. p_vibrato=0.3, vib_d=(0.10, 0.25), p_pinknoise=0.4, noise=(0.0008, 0.002),
  35. ),
  36. 'medium': dict(
  37. p_hflip=0.7, p_crop=0.8, crop=(0.03, 0.05), p_eq=0.9,
  38. bright=0.03, contr=(0.95, 1.05), sat=(0.92, 1.08), gam=(0.96, 1.04),
  39. p_speed=0.8, speed=(0.93, 1.07), p_pad=0.3, p_fps=0.0,
  40. p_vibrato=0.6, vib_d=(0.20, 0.40), p_pinknoise=0.6, noise=(0.001, 0.003),
  41. ),
  42. 'strong': dict(
  43. p_hflip=0.9, p_crop=1.0, crop=(0.05, 0.09), p_eq=1.0,
  44. bright=0.05, contr=(0.92, 1.08), sat=(0.88, 1.12), gam=(0.94, 1.06),
  45. p_speed=1.0, speed=(0.90, 1.10), p_pad=0.5, p_fps=0.8,
  46. p_vibrato=1.0, vib_d=(0.30, 0.60), p_pinknoise=1.0, noise=(0.002, 0.004),
  47. ),
  48. # deep(结构级深度处理,对抗特征指纹):大裁切重构图/旋转/色温/HSL/颗粒/音调/压缩
  49. 'deep': dict(
  50. p_hflip=0.0, p_crop=1.0, crop=(0.10, 0.18), p_eq=1.0,
  51. bright=0.06, contr=(0.90, 1.10), sat=(0.85, 1.15), gam=(0.92, 1.08),
  52. p_speed=1.0, speed=(0.90, 1.10), p_pad=0.6, p_fps=0.8,
  53. p_rotate=0.9, rotate=(0.4, 1.1), # 轻微旋转+裁边:特征点整体位移
  54. p_tone=1.0, tone=(0.03, 0.06), # 色温偏移(红/蓝通道)
  55. p_hsl=1.0, hsl_h=(-6, 6), hsl_s=(0.92, 1.08), # HSL 偏移
  56. p_dynhue=1.0, # 逐帧动态色相(有界正弦摆动,8.18 引擎同源思路)
  57. p_grain=1.0, grain=(4, 9), # 胶片颗粒:哈希注入噪声
  58. p_pitch=1.0, pitch=(1.02, 1.05), # 音频音调偏移(时长不变)
  59. p_comp=0.9, # 音频压缩器
  60. p_vibrato=1.0, vib_d=(0.40, 0.70), p_pinknoise=1.0, noise=(0.002, 0.005),
  61. ),
  62. }
  63. # AB v7 无感判重引擎档位(逆向分析/8.18/研究/B3_无鬼影策略.md 实测定稿):
  64. # 单流几何重排 = 裁切 + 非整数网格重采样 + 旋转 + 补裁 + 渐晕 + 色相 + 变速(可选掐头)。
  65. # 物理依据:同内容双流混合(逐行blend/隔行自混/90fps interleave)对 pHash 全部不变
  66. # (实测≤0.03),却必然引入鬼影/闪烁(快手六连败根因;B4 取证:KS 对 bff 标记去隔行,
  67. # 把行混内容平均成多重糊影);几何重排把像素挪位,DCT 低频相位全变(pHash 0.41)
  68. # 而画面零叠加(行差 2.75,优于源 3.5),且不带隔行标记,KS 不会去隔行。
  69. # 实测锚点: crop15%+rot1.2°+渐晕PI/8 → pHash 0.406 / SSIM 0.351 / 行差 2.69;
  70. # crop12%+rot0.8° → 0.19;渐晕单独仅 +0.03;hue 对亮度pHash无效(骗色彩指纹)。
  71. # 对齐 8.18 管线考证(B2):原版 ss0.8 仅封面取帧跳黑场、成品不掐头(掐头为 --trim-head
  72. # 可选);原版无变速,变速 1.03-1.05 是本工具追加的时间轴/音频指纹余量。
  73. AB_V7 = {
  74. 'light': dict(crop=(0.12, 0.14), rot=(0.8, 1.0), vig=0.35, hue=6, speed=(1.03, 1.04), p_pitch=0.0),
  75. 'medium': dict(crop=(0.13, 0.16), rot=(1.0, 1.3), vig=0.37, hue=7, speed=(1.03, 1.05), p_pitch=0.0),
  76. 'strong': dict(crop=(0.15, 0.18), rot=(1.2, 1.5), vig=0.39, hue=8, speed=(1.04, 1.05), p_pitch=0.6),
  77. 'deep': dict(crop=(0.17, 0.20), rot=(1.4, 1.6), vig=0.39, hue=9, speed=(1.04, 1.05), p_pitch=1.0),
  78. }
  79. def run(cmd, **kw):
  80. return subprocess.run(cmd, capture_output=True, text=True,
  81. encoding='utf-8', errors='replace', **kw)
  82. def probe(path: Path) -> dict:
  83. r = run(['ffprobe', '-v', 'error', '-print_format', 'json',
  84. '-show_streams', '-show_format', str(path)])
  85. if r.returncode != 0:
  86. raise RuntimeError(f'ffprobe 失败: {r.stderr.strip()[:200]}')
  87. info = json.loads(r.stdout)
  88. v = next((s for s in info['streams'] if s.get('codec_type') == 'video'), None)
  89. if v is None:
  90. raise RuntimeError('找不到视频流')
  91. a = next((s for s in info['streams'] if s.get('codec_type') == 'audio'), None)
  92. has_audio = a is not None
  93. a_layout = (a or {}).get('channel_layout') # 粉噪须对齐源声道布局,否则 amix 会压成单声道
  94. a_rate = int((a or {}).get('sample_rate') or 44100) # 音调偏移按源率计算,补偿才精确
  95. w, h = int(v['width']), int(v['height'])
  96. for sd in v.get('side_data_list') or []:
  97. if 'rotation' in sd: # 手机竖拍视频常见旋转元数据,实际显示尺寸要互换
  98. if abs(int(sd['rotation'])) in (90, 270):
  99. w, h = h, w
  100. break
  101. fps = None
  102. num, _, den = (v.get('avg_frame_rate') or '0').partition('/')
  103. try:
  104. if int(den) > 0:
  105. fps = int(num) / int(den)
  106. except ValueError:
  107. pass
  108. dur = float(info['format'].get('duration', 0) or 0)
  109. # 实测帧率:按包计数换算。部分源(双pts/VFR/标称错误)的 avg_frame_rate 会骗人,
  110. # 若与实测偏差大,对它做 fps 重采样会重则抹掉动作(实测案例:标称30.3/实测60.05的源)。
  111. real_fps = None
  112. r = run(['ffprobe', '-v', 'error', '-count_packets', '-select_streams', 'v:0',
  113. '-show_entries', 'stream=nb_read_packets', '-of', 'csv=p=0', str(path)])
  114. if r.returncode == 0 and r.stdout.strip().isdigit() and dur > 0:
  115. real_fps = int(r.stdout.strip()) / dur
  116. return dict(w=w, h=h, has_audio=has_audio, a_layout=a_layout, a_rate=a_rate,
  117. fps=fps, dur=dur, real_fps=real_fps)
  118. def build_transform(rng: random.Random, cfg: dict, w: int, h: int, has_audio: bool, fps):
  119. """按档位概率随机组合滤镜。
  120. 返回 (vf滤镜列表, af滤镜段列表或None, 粉噪幅度或None, 变换记录dict)。
  121. 粉噪需要 lavfi 第二输入,由调用方拼 filter_complex,故单列。
  122. """
  123. t = {}
  124. vf = []
  125. if rng.random() < cfg['p_hflip']:
  126. vf.append('hflip')
  127. t['镜像'] = '是'
  128. if rng.random() < cfg['p_crop']:
  129. f = rng.uniform(*cfg['crop'])
  130. cw, ch = int(w * (1 - f)), int(h * (1 - f))
  131. x, y = rng.randint(0, w - cw), rng.randint(0, h - ch)
  132. vf.append(f'crop={cw}:{ch}:{x}:{y}')
  133. t['裁剪'] = f'{f * 100:.1f}%'
  134. if rng.random() < cfg.get('p_tone', 0): # 色温偏移:红蓝通道反向(deep)
  135. rs = rng.uniform(*cfg['tone']) * rng.choice((-1, 1))
  136. bs = -rs * rng.uniform(0.8, 1.2)
  137. vf.append(f'colorbalance=rs={rs:.3f}:bs={bs:.3f}')
  138. t['色温'] = f'R{rs:+.3f} B{bs:+.3f}'
  139. if rng.random() < cfg.get('p_hsl', 0): # HSL 偏移(deep)
  140. hh = rng.uniform(*cfg['hsl_h'])
  141. ss = rng.uniform(*cfg['hsl_s'])
  142. vf.append(f'hue=h={hh:.1f}:s={ss:.3f}')
  143. t['HSL'] = f'H{hh:+.0f}° S{ss:.2f}'
  144. if rng.random() < cfg.get('p_dynhue', 0): # 逐帧动态色相:正弦有界摆动(deep)
  145. amp = rng.uniform(2.0, 6.0)
  146. per = rng.randint(600, 1400)
  147. vf.append(f"hue=h='{amp:.1f}*sin(n/{per})'")
  148. t['动态色相'] = f'±{amp:.1f}° 周期{per}帧'
  149. if rng.random() < cfg.get('p_grain', 0): # 胶片颗粒:哈希噪声(deep)
  150. g = rng.randint(*cfg['grain'])
  151. vf.append(f'noise=alls={g}:allf=t')
  152. t['颗粒'] = str(g)
  153. if rng.random() < cfg['p_pad']: # 内容缩小后加黑边,再放回原尺寸
  154. p = rng.uniform(0.01, 0.025)
  155. vf.append(f'scale={int(w * (1 - 2 * p))}:{int(h * (1 - 2 * p))}')
  156. vf.append(f'pad={w}:{h}:(ow-iw)/2:(oh-ih)/2:black')
  157. t['边框'] = f'{p * 100:.1f}%'
  158. vf.append(f'scale={w}:{h}') # 无论前面怎么变,统一回到原始尺寸
  159. vf.append('setsar=1')
  160. if rng.random() < cfg.get('p_rotate', 0): # 轻微旋转→居中裁回原尺寸(deep,须在scale后)
  161. ang = rng.uniform(*cfg['rotate']) * rng.choice((-1, 1))
  162. vf.append(f"rotate={ang:.3f}*PI/180:ow=iw:oh=ih:c=black")
  163. vf.append(f'crop={w}:{h}:(ow-{w})/2:(oh-{h})/2')
  164. t['旋转'] = f'{ang:.1f}°'
  165. if rng.random() < cfg['p_eq']:
  166. b = rng.uniform(-cfg['bright'], cfg['bright'])
  167. c = rng.uniform(*cfg['contr'])
  168. s = rng.uniform(*cfg['sat'])
  169. g = rng.uniform(*cfg['gam'])
  170. vf.append(f'eq=brightness={b:.3f}:contrast={c:.3f}:saturation={s:.3f}:gamma={g:.3f}')
  171. t['调色'] = f'亮度{b:+.3f} 对比{c:.2f} 饱和{s:.2f} γ{g:.2f}'
  172. af_parts = []
  173. if rng.random() < cfg['p_speed']:
  174. sp = rng.uniform(*cfg['speed'])
  175. vf.append(f'setpts=PTS/{sp:.4f}')
  176. af_parts.append(f'atempo={sp:.4f}')
  177. t['变速'] = f'{sp:.3f}x'
  178. t['_speed'] = sp
  179. if rng.random() < cfg.get('p_pitch', 0): # 音调偏移:asetrate 升采样+atempo 补偿(时长不变)
  180. pr = rng.uniform(*cfg['pitch'])
  181. af_parts.append(f'asetrate=44100*{pr:.3f}')
  182. af_parts.append(f'atempo={1 / pr:.4f}')
  183. t['音调'] = f'{pr:.2f}x'
  184. if rng.random() < cfg.get('p_comp', 0): # 压缩器:动态范围重塑(频谱扰动)
  185. af_parts.append('acompressor=threshold=-18dB:ratio=3:attack=5:release=100')
  186. t['音频压缩'] = '是'
  187. if has_audio and rng.random() < cfg.get('p_vibrato', 0): # 颤音:音频波形指纹扰动(8.18 同源)
  188. fv = rng.uniform(4.0, 8.0)
  189. dv = rng.uniform(*cfg['vib_d'])
  190. af_parts.append(f'vibrato=f={fv:.1f}:d={dv:.2f}')
  191. t['颤音'] = f'{fv:.1f}Hz/{dv:.2f}'
  192. # 粉噪混入:幅度近听感阈值(-50dB 上下),改变整段音频波形与频谱哈希(8.18 同源)
  193. noise_amp = None
  194. if has_audio and rng.random() < cfg.get('p_pinknoise', 0):
  195. noise_amp = rng.uniform(*cfg['noise'])
  196. t['粉噪'] = f'{noise_amp * 1000:.2f}e-3'
  197. if fps and rng.random() < cfg['p_fps']:
  198. nf = fps + rng.choice((-1, 1)) * rng.uniform(0.4, 1.2)
  199. vf.append(f'fps={nf:.2f}')
  200. t['帧率'] = f'{fps:.2f}→{nf:.2f}'
  201. misc = {'speed': float(t.get('_speed', 1.0))} # 供 AB 模式同步辅助流时间轴
  202. t.pop('_speed', None)
  203. return vf, af_parts, noise_amp, t, misc
  204. def build_ab_v7(rng: random.Random, cfg: dict, w: int, h: int, has_audio: bool, a_rate: int):
  205. """AB v7 无感判重引擎:单流几何重排链(无第二路画面,零叠加零鬼影)。
  206. 裁切回缩 → 非整数网格重采样(半像素相位偏移) → 旋转(几何相位打乱 DCT 低频)
  207. → 补裁黑角 → 渐晕(低频幅度调制) → 色相 → 变速(时间轴重排+音频断开)。
  208. 参数与实测锚点见 AB_V7 注释;掐头为可选项(原版不掐,B2 考证)。
  209. 返回 (vf滤镜列表, af滤镜列表, 变速系数, 变换记录)。
  210. """
  211. t = {}
  212. vf = []
  213. f1 = rng.uniform(*cfg['crop'])
  214. cw, ch = int(w * (1 - f1)) // 2 * 2, int(h * (1 - f1)) // 2 * 2
  215. def jitter(m): # 裁切窗位置在小范围内抖动,批间差异
  216. return m + rng.randint(-int(m * 0.3), int(m * 0.3)) if m > 3 else m
  217. vf.append(f'crop={cw}:{ch}:{jitter((w - cw) // 2)}:{jitter((h - ch) // 2)}')
  218. vf.append(f'scale={w - 1}:{h - 2}:flags=lanczos') # 非整数网格:两次重采样相位移位
  219. vf.append(f'scale={w}:{h}:flags=bicubic')
  220. ang = rng.uniform(*cfg['rot']) * rng.choice((-1, 1))
  221. vf.append(f'rotate={ang:.2f}*PI/180:ow=iw:oh=ih:c=black')
  222. f2 = min(f1 + rng.uniform(0.005, 0.015), 0.30) # 补裁须盖过旋转黑角
  223. cw2, ch2 = int(w * (1 - f2)) // 2 * 2, int(h * (1 - f2)) // 2 * 2
  224. vf.append(f'crop={cw2}:{ch2}:{(w - cw2) // 2}:{(h - ch2) // 2}')
  225. vf.append(f'scale={w}:{h}:flags=lanczos')
  226. vf.append(f'vignette={cfg["vig"] + rng.uniform(0, 0.02):.3f}')
  227. hh = rng.uniform(cfg['hue'] * 0.7, cfg['hue']) * rng.choice((-1, 1))
  228. vf.append(f'hue=h={hh:.1f}')
  229. vf.append('setsar=1')
  230. sp = rng.uniform(*cfg['speed'])
  231. vf.append(f'setpts=PTS/{sp:.4f}')
  232. t['几何重排'] = (f'裁{f1 * 100:.0f}%+补裁{f2 * 100:.0f}%+网格重采样+转{ang:.1f}°'
  233. f'+渐晕+色相{hh:+.0f}°')
  234. t['变速'] = f'{sp:.3f}x'
  235. af, t_aud = _ab_audio(rng, cfg['p_pitch'], has_audio, a_rate, sp)
  236. t.update(t_aud)
  237. return vf, af, sp, t
  238. def _ab_audio(rng: random.Random, p_pitch: float, has_audio: bool, a_rate: int, sp: float):
  239. """v7/幻影共用音频链:变速不变调 atempo(时间轴重排),强档叠加微音调(可选)。"""
  240. t = {}
  241. af = [f'atempo={sp:.4f}'] # 变速不变调,音频波形时间轴重排(r_win 0.16,过)
  242. if has_audio and rng.random() < p_pitch:
  243. pr = rng.uniform(1.02, 1.04)
  244. factor = pr if rng.random() < 0.5 else 1 / pr
  245. af = [f'asetrate={a_rate * factor:.0f}', f'atempo={1 / factor:.4f}',
  246. 'aresample=44100', *af] # 按源率变速率+补偿,时长不变仅变调
  247. t['音调'] = f'{factor:.3f}x'
  248. return af, t
  249. def build_phantom(rng: random.Random, w: int, h: int, base_fps: int, sp: float):
  250. """8.18 v1 路线字面复现(C3 老版实证 + C2 情报互证定案):
  251. 素材本体 = 可见时间轴;自变体(暗化微调)以零时长"幻影帧"嵌入数据层——
  252. interleave 后 setpts='(trunc(N/2)+(N%2))*...' 使奇数槽幻影与下一素材帧同 pts,
  253. CFR 播放/转码坍缩后观众只见素材原画面(无感不闪),全解码帧序则被搅乱。
  254. 随机化变体参数;返回 (filter_complex 文本, 变换记录)。"""
  255. bb = rng.uniform(-0.08, -0.04)
  256. bs = rng.uniform(0.85, 0.95)
  257. bh = rng.choice((-1, 1)) * rng.uniform(4, 8)
  258. graph = (
  259. f'[0:v]fps={base_fps},scale={w}:{h}:flags=lanczos,setsar=1,'
  260. f'format=yuv420p,split=2[A][B0];'
  261. f'[B0]eq=brightness={bb:.3f}:saturation={bs:.3f},hue=h={bh:+.1f},'
  262. f'setsar=1,format=yuv420p[B];'
  263. f'[A][B]interleave,'
  264. f"setpts='(trunc(N/2)+mod(N\\,2))/({base_fps}*{sp:.4f}*TB)'[v]"
  265. )
  266. t = {'AB交错': f'幻影注入(变体:亮度{bb:+.2f}/饱和{bs:.2f}/色相{bh:+.0f}°)'}
  267. return graph, t
  268. def encode_args(hw: bool, interlace: str, crf: int, enc_preset: str):
  269. """视频编码参数。隔行档仅 libx264 支持,--hw 下忽略(打印过提示)。"""
  270. if hw:
  271. return ['-c:v', 'h264_nvenc', '-preset', 'p5', '-rc', 'vbr',
  272. '-cq', str(crf + 2), '-spatial-aq', '1', '-b:v', '0']
  273. a = ['-c:v', 'libx264', '-preset', enc_preset, '-crf', str(crf)]
  274. if interlace == 'bff': # 8.18 模板:真隔行 BFF 编码,场序指纹扰动
  275. a += ['-x264-params',
  276. 'interlaced=bff:bff=1:bframes=0:keyint=30:min-keyint=15:scenecut=0:'
  277. 'rc-lookahead=0:ref=3:subme=7',
  278. '-flags', '+ilme+ildct', '-top', '0', '-g', '30', '-bf', '0']
  279. elif interlace == 'tff': # 8.18 模板:隔行 TFF(不强制 -r 30,避免改变时长节奏)
  280. a += ['-flags', '+ilme+ildct', '-x264opts', 'tff=1:bframes=0',
  281. '-field_order', 'tt', '-top', '1']
  282. return a
  283. HANDLER_NAMES = [ # 伪造流 handler_name,伪装采集/剪辑设备来源(实测 MP4 可落盘)
  284. 'GoPro.srndvr', 'Ambarella AVC encoder', 'ISO Media file produced by Google',
  285. 'DJI com.dji.oa2', 'Intel(R) Media SDK', 'Adobe Premiere Pro',
  286. ]
  287. def finish_args(stage: Path, dst: Path, has_audio: bool, rng: random.Random, meta_time: str):
  288. """收尾"洗容器"工序(8.18 同源,-c copy 不再重编码):
  289. 删 SEI(编码器指纹)→ SPS 裁掉底部 4 行 → 抹元数据 + 伪造
  290. encoder/handler_name/creation_time → bitexact 消 ffmpeg 写入痕迹。
  291. 注:8.18 模板里的 DURATION/音频encoder 伪造经实测会被 MP4 复用器丢弃,故不写。"""
  292. fake_enc_v = f'Lavc{rng.randint(10 ** 7, 10 ** 8 - 1)}libx264' # 不可能存在的版本号
  293. hdlr = rng.choice(HANDLER_NAMES)
  294. cmd = ['ffmpeg', '-y', '-hide_banner', '-loglevel', 'error', '-i', str(stage),
  295. '-map', '0', '-c', 'copy',
  296. '-bsf:v', 'filter_units=remove_types=6,h264_metadata=crop_bottom=4',
  297. '-map_metadata', '-1', '-fflags', '+bitexact',
  298. '-metadata', f'creation_time={meta_time}',
  299. '-metadata:s:v:0', f'encoder={fake_enc_v}',
  300. '-metadata:s:v:0', f'handler_name={hdlr}']
  301. if has_audio:
  302. cmd += ['-metadata:s:a:0', f'handler_name={hdlr}.a']
  303. return cmd + ['-movflags', '+faststart', str(dst)]
  304. def main():
  305. ap = argparse.ArgumentParser(
  306. description='视频去重批处理工具:随机组合二次处理,改变文件哈希与视听指纹',
  307. formatter_class=argparse.RawDescriptionHelpFormatter,
  308. epilog='示例:\n'
  309. ' python video_dedup.py -i 素材 -o 成品 -p strong\n'
  310. ' python video_dedup.py -i a.mp4 --hw --same-name\n'
  311. ' python video_dedup.py -i a.mp4 --interlace bff')
  312. ap.add_argument('-i', '--input', default='.', help='输入文件或目录(默认当前目录)')
  313. ap.add_argument('-o', '--output', help='输出目录(默认 输入目录/去重输出)')
  314. ap.add_argument('-p', '--preset', choices=list(PRESETS), default='medium',
  315. help='处理强度: light/medium/strong/deep(默认 medium)')
  316. ap.add_argument('--seed', type=int, help='随机种子(指定后可复现同一批参数)')
  317. ap.add_argument('--crf', type=int, default=19, help='CPU 编码质量,默认 19(越小越清晰、文件越大)')
  318. ap.add_argument('--enc-preset', default='veryfast', help='x264 速度档,默认 veryfast')
  319. ap.add_argument('--hw', action='store_true', help='用 NVIDIA NVENC 硬件编码(快很多,需 N 卡)')
  320. ap.add_argument('--interlace', choices=['off', 'bff', 'tff'], default='off',
  321. help='隔行编码档:场序指纹扰动(8.18 逆向同源)。仅 CPU 编码;平台转码后'
  322. '可能出现场纹,建议先小样实测再批量')
  323. ap.add_argument('--no-finish', action='store_true',
  324. help='关闭收尾工序(默认开启:删SEI/SPS裁底部4行/伪造encoder与handler_name/'
  325. 'creation_time 元数据;720p 等分辨率下显示高度会少 4 行)')
  326. ap.add_argument('--overlay', help='叠加一张半透明图片覆盖全画面(可配合 --overlay-alpha)')
  327. ap.add_argument('--overlay-alpha', type=float, default=0.05,
  328. help='叠加图层不透明度 0~1,默认 0.05(即 5%% 混合,肉眼近无感)')
  329. ap.add_argument('--ab', action='store_true',
  330. help='AB v7 无感判重引擎(推荐):单流几何重排(裁切回缩+非整数网格'
  331. '重采样+旋转+渐晕+色相)+变速+音调,叠加收尾洗容器。观感≈原视频'
  332. '(零第二路画面,无闪无鬼影),实测 pHash 距离 0.41、行差优于源。'
  333. '强度随 -p 档位(light/medium/strong/deep)递增')
  334. ap.add_argument('--ab-phantom', action='store_true',
  335. help='8.18 v1 幻影注入字面复现:素材=可见画面(100%%原味),自变体以'
  336. '零时长幻影帧嵌入数据层搅乱解码帧序。观感最优但判重依赖平台在'
  337. '转码前取指纹;求稳用 --ab(几何重排,任何时点取指纹均断)')
  338. ap.add_argument('--trim-head', type=float, default=0.0, metavar='SEC',
  339. help='掐头秒数,默认 0 不掐(对齐 8.18:B2 考证 ss0.8 仅是封面取帧跳黑场,'
  340. '成品不掐头);设 0.8 可额外错位帧序列指纹,观感少开头该秒数')
  341. ap.add_argument('--pair-video', metavar='PATH',
  342. help='8.18 逐行混合模板字面复现:素材与实拍按像素行奇偶逐行混合'
  343. '(blend=setfield=bff)。⚠ 物理实证与快手实测均判死:B4 取证确认'
  344. '快手对 bff 标记执行去隔行,行混内容会被平均成多重糊影;'
  345. '生产用途请改用 --ab,本参数仅供模板比对')
  346. ap.add_argument('--pair-ratio', type=float, default=0.33,
  347. help='(已废弃,仅 --pair-video 模板复现使用)辅助视频占空比 1/3 或 2/3')
  348. ap.add_argument('--mirror', action='store_true',
  349. help='启用镜像翻转(默认关闭:画面文字/标识不反向;开启可额外改变视觉指纹)')
  350. ap.add_argument('--vibrato', action='store_true',
  351. help='启用音频颤音调制(默认关闭:强档深度下有可闻抖动感;开启可额外扰动音频指纹)')
  352. ap.add_argument('--same-name', action='store_true', help='输出保持原文件名(默认追加随机后缀)')
  353. args = ap.parse_args()
  354. sys.stdout.reconfigure(encoding='utf-8', errors='replace')
  355. inp = Path(args.input)
  356. if inp.is_file():
  357. files = [inp]
  358. in_dir = inp.parent
  359. else:
  360. in_dir = inp
  361. files = sorted(p for p in in_dir.iterdir()
  362. if p.is_file() and p.suffix.lower() in VIDEO_EXTS)
  363. out_dir = Path(args.output) if args.output else in_dir / '去重输出'
  364. out_dir_resolved = out_dir.resolve()
  365. files = [f for f in files if out_dir_resolved not in f.resolve().parents]
  366. if not files:
  367. print(f'输入中没有找到视频文件: {in_dir.resolve()}')
  368. sys.exit(1)
  369. out_dir.mkdir(parents=True, exist_ok=True)
  370. rng = random.Random(args.seed)
  371. cfg = dict(PRESETS[args.preset])
  372. if not args.mirror: # 镜像默认关:画面文字/标识不反向(与白盒 dedup.mirror=false 决策对齐)
  373. cfg['p_hflip'] = 0.0
  374. if not args.vibrato: # 颤音默认关:强档深度下有可闻抖动感,听感优先
  375. cfg['p_vibrato'] = 0.0
  376. if args.interlace != 'off' and args.hw:
  377. print('注意: 隔行档仅 CPU 编码生效,--hw 下自动忽略隔行参数\n')
  378. pv = Path(args.pair_video) if args.pair_video else None
  379. if pv is not None:
  380. if not pv.is_file():
  381. sys.exit(f'辅助视频不存在: {pv}')
  382. if not (0.05 <= args.pair_ratio <= 0.95):
  383. sys.exit('--pair-ratio 取值范围 0.05~0.95(≤0.4=1/3占空,>0.4=2/3占空)')
  384. if args.ab and pv is not None:
  385. sys.exit('--ab(无感自AB)与 --pair-video(外部辅助视频)互斥')
  386. if args.ab and args.ab_phantom:
  387. sys.exit('--ab(几何重排)与 --ab-phantom(幻影注入)互斥,二选一')
  388. if args.ab_phantom and pv is not None:
  389. sys.exit('--ab-phantom 与 --pair-video 互斥')
  390. report_path = out_dir / '处理报告.csv'
  391. fields = ['文件名', '输出名', '状态', '原分辨率', '原时长(s)', '新时长(s)',
  392. '镜像', '几何重排', '裁剪', '旋转', '色温', 'HSL', '动态色相', '颗粒', '边框', '调色',
  393. '变速', '音调', '音频压缩', '颤音', '粉噪', '帧率', 'AB交错', '叠加图层', '隔行', '收尾']
  394. rows, ok, fail = [], 0, 0
  395. print(f'共 {len(files)} 个视频,档位 {args.preset},输出 → {out_dir.resolve()}\n')
  396. for f in files:
  397. row = dict.fromkeys(fields, '')
  398. row['文件名'] = f.name
  399. try:
  400. info = probe(f)
  401. w, h = info['w'] - info['w'] % 2, info['h'] - info['h'] % 2
  402. # 帧率微调前置检查:标称帧率与实测包率偏差>10% 视为时间戳异常源,跳过 fps 重采样
  403. fps_bad = (info['fps'] and info['real_fps'] and
  404. abs(info['real_fps'] - info['fps']) / info['fps'] > 0.10)
  405. pair_info = probe(pv) if pv is not None else None
  406. use_ab = args.ab and pair_info is None
  407. use_ph = args.ab_phantom and pair_info is None
  408. if pair_info:
  409. cfg_file = dict(cfg, p_fps=0.0) # AB 双流统一帧率,跳过帧率微调
  410. else:
  411. cfg_file = cfg
  412. ab_cfg = AB_V7[args.preset]
  413. if use_ab: # v7 单流引擎:不走 build_transform 的随机组合,链路自含
  414. vf, af_parts, sp, t = build_ab_v7(
  415. rng, ab_cfg, w, h, info['has_audio'], info['a_rate'])
  416. if args.mirror:
  417. vf.insert(0, 'hflip')
  418. t['镜像'] = '是'
  419. noise_amp, misc = None, {'speed': sp}
  420. elif use_ph: # 幻影注入:视频走 filter_complex,音频链与 v7 共用
  421. vf = [] # 视频链在 ph_graph 内,占位满足 assemble 引用
  422. base_fps = 30 if not info['fps'] or abs(info['fps'] - 30) <= 6 \
  423. else round(info['fps'])
  424. sp = rng.uniform(*ab_cfg['speed'])
  425. af_parts, t_aud = _ab_audio(rng, ab_cfg['p_pitch'],
  426. info['has_audio'], info['a_rate'], sp)
  427. ph_graph, t = build_phantom(rng, w, h, base_fps, sp)
  428. t['变速'] = f'{sp:.3f}x'
  429. t.update(t_aud)
  430. noise_amp, misc = None, {'speed': sp}
  431. else:
  432. vf, af_parts, noise_amp, t, misc = build_transform(
  433. rng, cfg_file, w, h, info['has_audio'], info['fps'])
  434. if fps_bad and not use_ph:
  435. t['帧率'] = (f"跳过(标称{info['fps']:.2f}/实测{info['real_fps']:.2f}fps,"
  436. "时间戳异常,重采样会损动作)")
  437. elif use_ph:
  438. t['帧率'] = f'→{base_fps}fps基准+幻影注入'
  439. elif pair_info:
  440. t['帧率'] = '跳过(AB双流统一帧率)'
  441. row['原分辨率'] = f"{info['w']}x{info['h']}"
  442. row['原时长(s)'] = f"{info['dur']:.1f}"
  443. row.update(t)
  444. token = '' if args.same_name else '_' + ''.join(
  445. rng.choices('abcdefghijkmnpqrstuvwxyz23456789', k=6))
  446. dst = out_dir / (f.stem + token + '.mp4')
  447. n = 1
  448. while dst.exists():
  449. n += 1
  450. dst = out_dir / (f.stem + token + f'_{n}.mp4')
  451. row['输出名'] = dst.name
  452. meta_time = (datetime(2021, 1, 1) + timedelta(
  453. seconds=rng.randint(0, 5 * 365 * 86400))).strftime('%Y-%m-%dT%H:%M:%S')
  454. stage = out_dir / (dst.stem + '.stage.mp4')
  455. ov = Path(args.overlay) if args.overlay else None
  456. if ov is not None and not ov.is_file():
  457. raise RuntimeError(f'叠加图层不存在: {ov}')
  458. use_noise = noise_amp is not None
  459. use_pair = pair_info is not None
  460. noise_idx = (1 if use_pair else 0) + (2 if ov is not None else 1)
  461. sp = misc['speed']
  462. # 输出时长基准:主视频变速后时长;掐头可选(--trim-head,B2考证:原版不掐头);
  463. # 实拍循环流无限,用 -t 锁长
  464. trim = args.trim_head if use_ab else 0.0
  465. out_dur = (info['dur'] - trim) / sp
  466. def assemble(hw: bool):
  467. cmd = ['ffmpeg', '-y', '-hide_banner', '-loglevel', 'error']
  468. cmd += (['-ss', f'{trim:g}'] if trim > 0 else []) + ['-i', str(f)]
  469. if use_pair:
  470. cmd += ['-stream_loop', '-1', '-i', str(pv)] # 实拍循环播放(8.18 模板原味)
  471. if ov is not None:
  472. cmd += ['-i', str(ov)]
  473. if use_noise:
  474. cmd += ['-f', 'lavfi', '-i',
  475. f'anoisesrc=color=pink:amplitude={noise_amp:.5f}:sample_rate=44100']
  476. fc = None
  477. if use_ph or use_pair or ov is not None or use_noise:
  478. parts = []
  479. vchain = ','.join(vf)
  480. if use_ph:
  481. parts.append(ph_graph)
  482. elif use_pair:
  483. # 8.18 blend0 模板铁证复现(B1_簇29解构:0x5353d4 阈值=编译期字面量0,
  484. # 无运行时替换;setfield=tff;偶行素材/奇行实拍;R→aac码率随机):
  485. # [a][b]blend=all_expr='if(eq(mod(Y,2),0),A,B)',setfield=tff
  486. # ⚠ 物理实证(B3/B4):混合族 pHash 不变且 KS 去隔行会把行混平均成糊影
  487. # (原版观感成立依赖 B 流为暗化 AI 图,平均后≈素材压暗版);
  488. # 生产用途请用 --ab v7,本参数仅供模板比对。
  489. parts.append(f'[0:v]{vchain},scale={w}:{h}:flags=lanczos,setsar=1,'
  490. f'format=yuv420p,unsharp=5:5:1:5:5:2[filt_a];')
  491. parts.append(f'[1:v]scale={w}:{h}:flags=lanczos,setsar=1,'
  492. f'format=yuv420p[filt_b];')
  493. t['AB交错'] = '素材×实拍逐行混合(tff,阈值0,B1铁证)'
  494. parts.append(f'[filt_a][filt_b]blend=all_expr='
  495. f"'if(eq(mod(Y\\,2)\\,0)\\,A\\,B)',"
  496. f'setfield=tff,format=yuv420p[v_mix];')
  497. if ov is not None:
  498. ov_src = 2
  499. parts.append(f'[{ov_src}:v]scale={w}:{h},format=rgba,'
  500. f'colorchannelmixer=aa={args.overlay_alpha}[ovx];')
  501. parts.append('[v_mix][ovx]overlay=0:0[v];') # 静态图铺满全程
  502. t['叠加图层'] = f'{args.overlay_alpha * 100:.0f}%'
  503. else:
  504. parts.append('[v_mix]null[v];')
  505. elif ov is not None:
  506. parts.append(f'[0:v]{vchain}[base];')
  507. parts.append(f'[1:v]scale={w}:{h},format=rgba,'
  508. f'colorchannelmixer=aa={args.overlay_alpha}[ov];')
  509. parts.append('[base][ov]overlay=0:0[v];') # 静态图,overlay 默认重复末帧铺满全程
  510. t['叠加图层'] = f'{args.overlay_alpha * 100:.0f}%'
  511. else:
  512. parts.append(f'[0:v]{vchain}[v];')
  513. if use_noise: # 音频指纹链:原声(重采样44100) ⊕ 粉噪 → amix → 限幅(8.18 同源)
  514. ach = ','.join(af_parts + ['aresample=44100']) if af_parts else 'aresample=44100'
  515. parts.append(f'[0:a]{ach}[am];')
  516. if info.get('a_layout'): # 粉噪对齐源声道布局,防止 amix 把立体声压成单声道
  517. parts.append(f'[{noise_idx}:a]aformat=channel_layouts={info["a_layout"]}[bn];')
  518. n_src = '[bn]'
  519. else:
  520. n_src = f'[{noise_idx}:a]'
  521. parts.append(f'[am]{n_src}amix=inputs=2:duration=first:'
  522. f'normalize=0,alimiter=limit=0.94[outa];')
  523. fc = ''.join(parts).rstrip(';')
  524. if fc is not None:
  525. cmd += ['-filter_complex', fc, '-map', '[v]']
  526. else:
  527. cmd += ['-vf', ','.join(vf), '-map', '0:v:0']
  528. if use_noise:
  529. cmd += ['-map', '[outa]']
  530. elif info['has_audio']:
  531. cmd += ['-map', '0:a:0']
  532. cmd += ['-map_metadata', '-1',
  533. '-metadata', f'creation_time={meta_time}']
  534. cmd += encode_args(hw, args.interlace, args.crf, args.enc_preset)
  535. if use_noise:
  536. cmd += ['-c:a', 'aac', '-b:a', '160k']
  537. elif info['has_audio']:
  538. cmd += ['-c:a', 'aac', '-b:a', '160k']
  539. if af_parts:
  540. cmd += ['-af', ','.join(af_parts)]
  541. else:
  542. cmd += ['-an']
  543. out_tail = (['-t', f'{out_dur:.3f}'] if use_pair else []) + \
  544. ['-pix_fmt', 'yuv420p', '-movflags', '+faststart', str(stage)]
  545. return cmd + out_tail
  546. cmd = assemble(args.hw)
  547. r = run(cmd)
  548. if r.returncode != 0 and args.hw: # NVENC 不可用时整体重建为 CPU 命令再跑
  549. print(f' [硬件编码失败,改用 CPU] {r.stderr.strip()[:120]}')
  550. r = run(assemble(False))
  551. if r.returncode != 0:
  552. raise RuntimeError(r.stderr.strip()[-300:])
  553. if args.interlace != 'off' and not args.hw:
  554. t['隔行'] = args.interlace
  555. if args.no_finish:
  556. stage.replace(dst)
  557. t['收尾'] = '关闭'
  558. else:
  559. r2 = run(finish_args(stage, dst, info['has_audio'], rng, meta_time))
  560. if r2.returncode != 0: # 收尾失败时保底用第一阶段产物
  561. print(f' [收尾工序失败,保留未洗容器版本] {r2.stderr.strip()[:120]}')
  562. stage.replace(dst)
  563. t['收尾'] = '跳过'
  564. else:
  565. stage.unlink()
  566. t['收尾'] = 'SEI删+SPS裁+元数据伪造'
  567. row.update({k: t.get(k, '') for k in ('叠加图层', '隔行', '收尾')})
  568. new_info = probe(dst)
  569. row['新时长(s)'] = f"{new_info['dur']:.1f}"
  570. row['状态'] = '成功'
  571. ok += 1
  572. desc = ' '.join(f'{k}:{v}' for k, v in t.items()) or '仅重编码+元数据'
  573. print(f' ✔ {f.name} → {dst.name} [{desc}]')
  574. except Exception as e:
  575. stage = out_dir / (row.get('输出名', '').replace('.mp4', '.stage.mp4'))
  576. if row.get('输出名'):
  577. stage.unlink(missing_ok=True)
  578. row['状态'] = f'失败:{e}'
  579. fail += 1
  580. print(f' ✘ {f.name} 失败: {e}')
  581. rows.append(row)
  582. with open(report_path, 'w', newline='', encoding='utf-8-sig') as fp:
  583. writer = csv.DictWriter(fp, fieldnames=fields)
  584. writer.writeheader()
  585. writer.writerows(rows)
  586. print(f'\n完成: 成功 {ok} / 失败 {fail},处理报告 → {report_path.resolve()}')
  587. if __name__ == '__main__':
  588. main()