| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712 |
- #!/usr/bin/env python3
- # -*- coding: utf-8 -*-
- """
- 视频去重批处理工具
- 对输入视频做随机组合的二次处理(镜像/裁剪缩放/边框/调色/变速/帧率微调),
- 并重编码、清除原元数据,使输出在文件哈希、视觉指纹、音频指纹层面均与原片不同。
- 收尾工序(SEI 删除/SPS 裁切/元数据伪造)与音频指纹链对齐
- 「幸福BBA助手8.18」合成引擎逆向结论,见 逆向分析/8.18/分析报告_合成模式8.18增量.md。
- --ab 为 v7 无感判重引擎(掐头+几何重排+变速),物理依据与实测数据见
- 逆向分析/8.18/研究/B3_无鬼影策略.md:同内容双流混合对 pHash 全部无效且必有鬼影/闪烁,
- 单流几何重排 pHash 距离 0.41、行差优于源、零叠加伪影。
- 用法示例:
- python video_dedup.py # 处理当前目录 → ./去重输出
- python video_dedup.py -i 素材 -o 成品 -p strong
- python video_dedup.py -i a.mp4 --hw # 单文件,NVENC 硬件编码
- python video_dedup.py -i a.mp4 --ab -p strong # AB v7 无感判重(推荐)
- python video_dedup.py -i a.mp4 --interlace bff # 隔行档(场序指纹扰动,实验性)
- """
- import argparse
- import csv
- import json
- import random
- import subprocess
- import sys
- from datetime import datetime, timedelta
- from pathlib import Path
- VIDEO_EXTS = {'.mp4', '.mov', '.mkv', '.avi', '.flv', '.wmv', '.ts', '.m4v', '.webm', '.mpg', '.mpeg'}
- # 各档位:各变换的启用概率与参数范围
- PRESETS = {
- 'light': dict(
- p_hflip=0.5, p_crop=0.6, crop=(0.015, 0.03), p_eq=0.7,
- bright=0.015, contr=(0.98, 1.02), sat=(0.96, 1.04), gam=(0.98, 1.02),
- p_speed=0.6, speed=(0.96, 1.04), p_pad=0.0, p_fps=0.0,
- p_vibrato=0.3, vib_d=(0.10, 0.25), p_pinknoise=0.4, noise=(0.0008, 0.002),
- ),
- 'medium': dict(
- p_hflip=0.7, p_crop=0.8, crop=(0.03, 0.05), p_eq=0.9,
- bright=0.03, contr=(0.95, 1.05), sat=(0.92, 1.08), gam=(0.96, 1.04),
- p_speed=0.8, speed=(0.93, 1.07), p_pad=0.3, p_fps=0.0,
- p_vibrato=0.6, vib_d=(0.20, 0.40), p_pinknoise=0.6, noise=(0.001, 0.003),
- ),
- 'strong': dict(
- p_hflip=0.9, p_crop=1.0, crop=(0.05, 0.09), p_eq=1.0,
- bright=0.05, contr=(0.92, 1.08), sat=(0.88, 1.12), gam=(0.94, 1.06),
- p_speed=1.0, speed=(0.90, 1.10), p_pad=0.5, p_fps=0.8,
- p_vibrato=1.0, vib_d=(0.30, 0.60), p_pinknoise=1.0, noise=(0.002, 0.004),
- ),
- # deep(结构级深度处理,对抗特征指纹):大裁切重构图/旋转/色温/HSL/颗粒/音调/压缩
- 'deep': dict(
- p_hflip=0.0, p_crop=1.0, crop=(0.10, 0.18), p_eq=1.0,
- bright=0.06, contr=(0.90, 1.10), sat=(0.85, 1.15), gam=(0.92, 1.08),
- p_speed=1.0, speed=(0.90, 1.10), p_pad=0.6, p_fps=0.8,
- p_rotate=0.9, rotate=(0.4, 1.1), # 轻微旋转+裁边:特征点整体位移
- p_tone=1.0, tone=(0.03, 0.06), # 色温偏移(红/蓝通道)
- p_hsl=1.0, hsl_h=(-6, 6), hsl_s=(0.92, 1.08), # HSL 偏移
- p_dynhue=1.0, # 逐帧动态色相(有界正弦摆动,8.18 引擎同源思路)
- p_grain=1.0, grain=(4, 9), # 胶片颗粒:哈希注入噪声
- p_pitch=1.0, pitch=(1.02, 1.05), # 音频音调偏移(时长不变)
- p_comp=0.9, # 音频压缩器
- p_vibrato=1.0, vib_d=(0.40, 0.70), p_pinknoise=1.0, noise=(0.002, 0.005),
- ),
- }
- # AB v7 无感判重引擎档位(逆向分析/8.18/研究/B3_无鬼影策略.md 实测定稿):
- # 单流几何重排 = 裁切 + 非整数网格重采样 + 旋转 + 补裁 + 渐晕 + 色相 + 变速(可选掐头)。
- # 物理依据:同内容双流混合(逐行blend/隔行自混/90fps interleave)对 pHash 全部不变
- # (实测≤0.03),却必然引入鬼影/闪烁(快手六连败根因;B4 取证:KS 对 bff 标记去隔行,
- # 把行混内容平均成多重糊影);几何重排把像素挪位,DCT 低频相位全变(pHash 0.41)
- # 而画面零叠加(行差 2.75,优于源 3.5),且不带隔行标记,KS 不会去隔行。
- # 实测锚点: crop15%+rot1.2°+渐晕PI/8 → pHash 0.406 / SSIM 0.351 / 行差 2.69;
- # crop12%+rot0.8° → 0.19;渐晕单独仅 +0.03;hue 对亮度pHash无效(骗色彩指纹)。
- # 对齐 8.18 管线考证(B2):原版 ss0.8 仅封面取帧跳黑场、成品不掐头(掐头为 --trim-head
- # 可选);原版无变速,变速 1.03-1.05 是本工具追加的时间轴/音频指纹余量。
- AB_V7 = {
- '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),
- '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),
- '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),
- '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),
- }
- def run(cmd, **kw):
- return subprocess.run(cmd, capture_output=True, text=True,
- encoding='utf-8', errors='replace', **kw)
- def probe(path: Path) -> dict:
- r = run(['ffprobe', '-v', 'error', '-print_format', 'json',
- '-show_streams', '-show_format', str(path)])
- if r.returncode != 0:
- raise RuntimeError(f'ffprobe 失败: {r.stderr.strip()[:200]}')
- info = json.loads(r.stdout)
- v = next((s for s in info['streams'] if s.get('codec_type') == 'video'), None)
- if v is None:
- raise RuntimeError('找不到视频流')
- a = next((s for s in info['streams'] if s.get('codec_type') == 'audio'), None)
- has_audio = a is not None
- a_layout = (a or {}).get('channel_layout') # 粉噪须对齐源声道布局,否则 amix 会压成单声道
- a_rate = int((a or {}).get('sample_rate') or 44100) # 音调偏移按源率计算,补偿才精确
- w, h = int(v['width']), int(v['height'])
- for sd in v.get('side_data_list') or []:
- if 'rotation' in sd: # 手机竖拍视频常见旋转元数据,实际显示尺寸要互换
- if abs(int(sd['rotation'])) in (90, 270):
- w, h = h, w
- break
- fps = None
- num, _, den = (v.get('avg_frame_rate') or '0').partition('/')
- try:
- if int(den) > 0:
- fps = int(num) / int(den)
- except ValueError:
- pass
- dur = float(info['format'].get('duration', 0) or 0)
- # 实测帧率:按包计数换算。部分源(双pts/VFR/标称错误)的 avg_frame_rate 会骗人,
- # 若与实测偏差大,对它做 fps 重采样会重则抹掉动作(实测案例:标称30.3/实测60.05的源)。
- real_fps = None
- r = run(['ffprobe', '-v', 'error', '-count_packets', '-select_streams', 'v:0',
- '-show_entries', 'stream=nb_read_packets', '-of', 'csv=p=0', str(path)])
- if r.returncode == 0 and r.stdout.strip().isdigit() and dur > 0:
- real_fps = int(r.stdout.strip()) / dur
- return dict(w=w, h=h, has_audio=has_audio, a_layout=a_layout, a_rate=a_rate,
- fps=fps, dur=dur, real_fps=real_fps)
- def build_transform(rng: random.Random, cfg: dict, w: int, h: int, has_audio: bool, fps):
- """按档位概率随机组合滤镜。
- 返回 (vf滤镜列表, af滤镜段列表或None, 粉噪幅度或None, 变换记录dict)。
- 粉噪需要 lavfi 第二输入,由调用方拼 filter_complex,故单列。
- """
- t = {}
- vf = []
- if rng.random() < cfg['p_hflip']:
- vf.append('hflip')
- t['镜像'] = '是'
- if rng.random() < cfg['p_crop']:
- f = rng.uniform(*cfg['crop'])
- cw, ch = int(w * (1 - f)), int(h * (1 - f))
- x, y = rng.randint(0, w - cw), rng.randint(0, h - ch)
- vf.append(f'crop={cw}:{ch}:{x}:{y}')
- t['裁剪'] = f'{f * 100:.1f}%'
- if rng.random() < cfg.get('p_tone', 0): # 色温偏移:红蓝通道反向(deep)
- rs = rng.uniform(*cfg['tone']) * rng.choice((-1, 1))
- bs = -rs * rng.uniform(0.8, 1.2)
- vf.append(f'colorbalance=rs={rs:.3f}:bs={bs:.3f}')
- t['色温'] = f'R{rs:+.3f} B{bs:+.3f}'
- if rng.random() < cfg.get('p_hsl', 0): # HSL 偏移(deep)
- hh = rng.uniform(*cfg['hsl_h'])
- ss = rng.uniform(*cfg['hsl_s'])
- vf.append(f'hue=h={hh:.1f}:s={ss:.3f}')
- t['HSL'] = f'H{hh:+.0f}° S{ss:.2f}'
- if rng.random() < cfg.get('p_dynhue', 0): # 逐帧动态色相:正弦有界摆动(deep)
- amp = rng.uniform(2.0, 6.0)
- per = rng.randint(600, 1400)
- vf.append(f"hue=h='{amp:.1f}*sin(n/{per})'")
- t['动态色相'] = f'±{amp:.1f}° 周期{per}帧'
- if rng.random() < cfg.get('p_grain', 0): # 胶片颗粒:哈希噪声(deep)
- g = rng.randint(*cfg['grain'])
- vf.append(f'noise=alls={g}:allf=t')
- t['颗粒'] = str(g)
- if rng.random() < cfg['p_pad']: # 内容缩小后加黑边,再放回原尺寸
- p = rng.uniform(0.01, 0.025)
- vf.append(f'scale={int(w * (1 - 2 * p))}:{int(h * (1 - 2 * p))}')
- vf.append(f'pad={w}:{h}:(ow-iw)/2:(oh-ih)/2:black')
- t['边框'] = f'{p * 100:.1f}%'
- vf.append(f'scale={w}:{h}') # 无论前面怎么变,统一回到原始尺寸
- vf.append('setsar=1')
- if rng.random() < cfg.get('p_rotate', 0): # 轻微旋转→居中裁回原尺寸(deep,须在scale后)
- ang = rng.uniform(*cfg['rotate']) * rng.choice((-1, 1))
- vf.append(f"rotate={ang:.3f}*PI/180:ow=iw:oh=ih:c=black")
- vf.append(f'crop={w}:{h}:(ow-{w})/2:(oh-{h})/2')
- t['旋转'] = f'{ang:.1f}°'
- if rng.random() < cfg['p_eq']:
- b = rng.uniform(-cfg['bright'], cfg['bright'])
- c = rng.uniform(*cfg['contr'])
- s = rng.uniform(*cfg['sat'])
- g = rng.uniform(*cfg['gam'])
- vf.append(f'eq=brightness={b:.3f}:contrast={c:.3f}:saturation={s:.3f}:gamma={g:.3f}')
- t['调色'] = f'亮度{b:+.3f} 对比{c:.2f} 饱和{s:.2f} γ{g:.2f}'
- af_parts = []
- if rng.random() < cfg['p_speed']:
- sp = rng.uniform(*cfg['speed'])
- vf.append(f'setpts=PTS/{sp:.4f}')
- af_parts.append(f'atempo={sp:.4f}')
- t['变速'] = f'{sp:.3f}x'
- t['_speed'] = sp
- if rng.random() < cfg.get('p_pitch', 0): # 音调偏移:asetrate 升采样+atempo 补偿(时长不变)
- pr = rng.uniform(*cfg['pitch'])
- af_parts.append(f'asetrate=44100*{pr:.3f}')
- af_parts.append(f'atempo={1 / pr:.4f}')
- t['音调'] = f'{pr:.2f}x'
- if rng.random() < cfg.get('p_comp', 0): # 压缩器:动态范围重塑(频谱扰动)
- af_parts.append('acompressor=threshold=-18dB:ratio=3:attack=5:release=100')
- t['音频压缩'] = '是'
- if has_audio and rng.random() < cfg.get('p_vibrato', 0): # 颤音:音频波形指纹扰动(8.18 同源)
- fv = rng.uniform(4.0, 8.0)
- dv = rng.uniform(*cfg['vib_d'])
- af_parts.append(f'vibrato=f={fv:.1f}:d={dv:.2f}')
- t['颤音'] = f'{fv:.1f}Hz/{dv:.2f}'
- # 粉噪混入:幅度近听感阈值(-50dB 上下),改变整段音频波形与频谱哈希(8.18 同源)
- noise_amp = None
- if has_audio and rng.random() < cfg.get('p_pinknoise', 0):
- noise_amp = rng.uniform(*cfg['noise'])
- t['粉噪'] = f'{noise_amp * 1000:.2f}e-3'
- if fps and rng.random() < cfg['p_fps']:
- nf = fps + rng.choice((-1, 1)) * rng.uniform(0.4, 1.2)
- vf.append(f'fps={nf:.2f}')
- t['帧率'] = f'{fps:.2f}→{nf:.2f}'
- misc = {'speed': float(t.get('_speed', 1.0))} # 供 AB 模式同步辅助流时间轴
- t.pop('_speed', None)
- return vf, af_parts, noise_amp, t, misc
- def build_ab_v7(rng: random.Random, cfg: dict, w: int, h: int, has_audio: bool, a_rate: int):
- """AB v7 无感判重引擎:单流几何重排链(无第二路画面,零叠加零鬼影)。
- 裁切回缩 → 非整数网格重采样(半像素相位偏移) → 旋转(几何相位打乱 DCT 低频)
- → 补裁黑角 → 渐晕(低频幅度调制) → 色相 → 变速(时间轴重排+音频断开)。
- 参数与实测锚点见 AB_V7 注释;掐头为可选项(原版不掐,B2 考证)。
- 返回 (vf滤镜列表, af滤镜列表, 变速系数, 变换记录)。
- """
- t = {}
- vf = []
- f1 = rng.uniform(*cfg['crop'])
- cw, ch = int(w * (1 - f1)) // 2 * 2, int(h * (1 - f1)) // 2 * 2
- def jitter(m): # 裁切窗位置在小范围内抖动,批间差异
- return m + rng.randint(-int(m * 0.3), int(m * 0.3)) if m > 3 else m
- vf.append(f'crop={cw}:{ch}:{jitter((w - cw) // 2)}:{jitter((h - ch) // 2)}')
- vf.append(f'scale={w - 1}:{h - 2}:flags=lanczos') # 非整数网格:两次重采样相位移位
- vf.append(f'scale={w}:{h}:flags=bicubic')
- ang = rng.uniform(*cfg['rot']) * rng.choice((-1, 1))
- vf.append(f'rotate={ang:.2f}*PI/180:ow=iw:oh=ih:c=black')
- f2 = min(f1 + rng.uniform(0.005, 0.015), 0.30) # 补裁须盖过旋转黑角
- cw2, ch2 = int(w * (1 - f2)) // 2 * 2, int(h * (1 - f2)) // 2 * 2
- vf.append(f'crop={cw2}:{ch2}:{(w - cw2) // 2}:{(h - ch2) // 2}')
- vf.append(f'scale={w}:{h}:flags=lanczos')
- vf.append(f'vignette={cfg["vig"] + rng.uniform(0, 0.02):.3f}')
- hh = rng.uniform(cfg['hue'] * 0.7, cfg['hue']) * rng.choice((-1, 1))
- vf.append(f'hue=h={hh:.1f}')
- vf.append('setsar=1')
- sp = rng.uniform(*cfg['speed'])
- vf.append(f'setpts=PTS/{sp:.4f}')
- t['几何重排'] = (f'裁{f1 * 100:.0f}%+补裁{f2 * 100:.0f}%+网格重采样+转{ang:.1f}°'
- f'+渐晕+色相{hh:+.0f}°')
- t['变速'] = f'{sp:.3f}x'
- af, t_aud = _ab_audio(rng, cfg['p_pitch'], has_audio, a_rate, sp)
- t.update(t_aud)
- return vf, af, sp, t
- def _ab_audio(rng: random.Random, p_pitch: float, has_audio: bool, a_rate: int, sp: float):
- """v7/幻影共用音频链:变速不变调 atempo(时间轴重排),强档叠加微音调(可选)。"""
- t = {}
- af = [f'atempo={sp:.4f}'] # 变速不变调,音频波形时间轴重排(r_win 0.16,过)
- if has_audio and rng.random() < p_pitch:
- pr = rng.uniform(1.02, 1.04)
- factor = pr if rng.random() < 0.5 else 1 / pr
- af = [f'asetrate={a_rate * factor:.0f}', f'atempo={1 / factor:.4f}',
- 'aresample=44100', *af] # 按源率变速率+补偿,时长不变仅变调
- t['音调'] = f'{factor:.3f}x'
- return af, t
- def build_phantom(rng: random.Random, w: int, h: int, base_fps: int, sp: float):
- """8.18 幻影注入(实测定案:KS 转码前数据层取指纹→过判重;但 KS 端会直放 VFR 流,
- 幻影帧被渲染→压暗变体产生亮度闪烁)。v3 修正:变体纯色差(亮度差=0),
- 幻影帧即使被渲染亮度也恒定=无闪烁,数据层帧数加倍/零时长/pts 结构照旧;
- interleave 后 setpts 使奇数槽幻影与下一素材帧同 pts。
- 随机化变体参数;返回 (filter_complex 文本, 变换记录)。"""
- bb = 0.0 # 亮度差必须为 0(闪烁主因);判重靠数据层结构,不靠压暗
- bs = rng.uniform(0.78, 0.92)
- bh = rng.choice((-1, 1)) * rng.uniform(8, 14)
- graph = (
- f'[0:v]fps={base_fps},scale={w}:{h}:flags=lanczos,setsar=1,'
- f'format=yuv420p,split=2[A][B0];'
- f'[B0]eq=brightness={bb:.3f}:saturation={bs:.3f},hue=h={bh:+.1f},'
- f'setsar=1,format=yuv420p[B];'
- f'[A][B]interleave,'
- f"setpts='(trunc(N/2)+mod(N\\,2))/({base_fps}*{sp:.4f}*TB)'[v]"
- )
- t = {'AB交错': f'幻影注入v3纯色差(饱和{bs:.2f}/色相{bh:+.0f}°)'}
- return graph, t
- def encode_args(hw: bool, interlace: str, crf: int, enc_preset: str):
- """视频编码参数。隔行档仅 libx264 支持,--hw 下忽略(打印过提示)。"""
- if hw:
- return ['-c:v', 'h264_nvenc', '-preset', 'p5', '-rc', 'vbr',
- '-cq', str(crf + 2), '-spatial-aq', '1', '-b:v', '0']
- a = ['-c:v', 'libx264', '-preset', enc_preset, '-crf', str(crf)]
- if interlace == 'bff': # 8.18 模板:真隔行 BFF 编码,场序指纹扰动
- a += ['-x264-params',
- 'interlaced=bff:bff=1:bframes=0:keyint=30:min-keyint=15:scenecut=0:'
- 'rc-lookahead=0:ref=3:subme=7',
- '-flags', '+ilme+ildct', '-top', '0', '-g', '30', '-bf', '0']
- elif interlace == 'tff': # 8.18 模板:隔行 TFF(不强制 -r 30,避免改变时长节奏)
- a += ['-flags', '+ilme+ildct', '-x264opts', 'tff=1:bframes=0',
- '-field_order', 'tt', '-top', '1']
- return a
- HANDLER_NAMES = [ # 伪造流 handler_name,伪装采集/剪辑设备来源(实测 MP4 可落盘)
- 'GoPro.srndvr', 'Ambarella AVC encoder', 'ISO Media file produced by Google',
- 'DJI com.dji.oa2', 'Intel(R) Media SDK', 'Adobe Premiere Pro',
- ]
- def finish_args(stage: Path, dst: Path, has_audio: bool, rng: random.Random, meta_time: str):
- """收尾"洗容器"工序(8.18 同源,-c copy 不再重编码):
- 删 SEI(编码器指纹)→ SPS 裁掉底部 4 行 → 抹元数据 + 伪造
- encoder/handler_name/creation_time → bitexact 消 ffmpeg 写入痕迹。
- 注:8.18 模板里的 DURATION/音频encoder 伪造经实测会被 MP4 复用器丢弃,故不写。"""
- fake_enc_v = f'Lavc{rng.randint(10 ** 7, 10 ** 8 - 1)}libx264' # 不可能存在的版本号
- hdlr = rng.choice(HANDLER_NAMES)
- cmd = ['ffmpeg', '-y', '-hide_banner', '-loglevel', 'error', '-i', str(stage),
- '-map', '0', '-c', 'copy',
- '-bsf:v', 'filter_units=remove_types=6,h264_metadata=crop_bottom=4',
- '-map_metadata', '-1', '-fflags', '+bitexact',
- '-metadata', f'creation_time={meta_time}',
- '-metadata:s:v:0', f'encoder={fake_enc_v}',
- '-metadata:s:v:0', f'handler_name={hdlr}']
- if has_audio:
- cmd += ['-metadata:s:a:0', f'handler_name={hdlr}.a']
- return cmd + ['-movflags', '+faststart', str(dst)]
- def main():
- ap = argparse.ArgumentParser(
- description='视频去重批处理工具:随机组合二次处理,改变文件哈希与视听指纹',
- formatter_class=argparse.RawDescriptionHelpFormatter,
- epilog='示例:\n'
- ' python video_dedup.py -i 素材 -o 成品 -p strong\n'
- ' python video_dedup.py -i a.mp4 --ab-image 图.jpg # AB原味一条龙(自动制实拍)\n'
- ' python video_dedup.py -i a.mp4 --ab-image 图.jpg --mirror --audio b.mp3\n'
- ' python video_dedup.py -i a.mp4 --hw --same-name')
- ap.add_argument('-i', '--input', default='.', help='输入文件或目录(默认当前目录)')
- ap.add_argument('-o', '--output', help='输出目录(默认 输入目录/去重输出)')
- ap.add_argument('-p', '--preset', choices=list(PRESETS), default='medium',
- help='处理强度: light/medium/strong/deep(默认 medium)')
- ap.add_argument('--seed', type=int, help='随机种子(指定后可复现同一批参数)')
- ap.add_argument('--crf', type=int, default=19, help='CPU 编码质量,默认 19(越小越清晰、文件越大)')
- ap.add_argument('--enc-preset', default='veryfast', help='x264 速度档,默认 veryfast')
- ap.add_argument('--hw', action='store_true', help='用 NVIDIA NVENC 硬件编码(快很多,需 N 卡)')
- ap.add_argument('--interlace', choices=['off', 'bff', 'tff'], default='off',
- help='隔行编码档:场序指纹扰动(8.18 逆向同源)。仅 CPU 编码;平台转码后'
- '可能出现场纹,建议先小样实测再批量')
- ap.add_argument('--no-finish', action='store_true',
- help='关闭收尾工序(默认开启:删SEI/SPS裁底部4行/伪造encoder与handler_name/'
- 'creation_time 元数据;720p 等分辨率下显示高度会少 4 行)')
- ap.add_argument('--overlay', help='叠加一张半透明图片覆盖全画面(可配合 --overlay-alpha)')
- ap.add_argument('--overlay-alpha', type=float, default=0.05,
- help='叠加图层不透明度 0~1,默认 0.05(即 5%% 混合,肉眼近无感)')
- ap.add_argument('--ab', action='store_true',
- help='AB v7 无感判重引擎(推荐):单流几何重排(裁切回缩+非整数网格'
- '重采样+旋转+渐晕+色相)+变速+音调,叠加收尾洗容器。观感≈原视频'
- '(零第二路画面,无闪无鬼影),实测 pHash 距离 0.41、行差优于源。'
- '强度随 -p 档位(light/medium/strong/deep)递增')
- ap.add_argument('--ab-phantom', action='store_true',
- help='8.18 v1 幻影注入字面复现:素材=可见画面(100%%原味),自变体以'
- '零时长幻影帧嵌入数据层搅乱解码帧序。观感最优但判重依赖平台在'
- '转码前取指纹;求稳用 --ab(几何重排,任何时点取指纹均断)')
- ap.add_argument('--trim-head', type=float, default=0.0, metavar='SEC',
- help='掐头秒数,默认 0 不掐(对齐 8.18:B2 考证 ss0.8 仅是封面取帧跳黑场,'
- '成品不掐头);设 0.8 可额外错位帧序列指纹,观感少开头该秒数')
- ap.add_argument('--pair-video', metavar='PATH',
- help='AB原味模式(8.18真身,R2/R3字节级复刻):素材×实拍视频逐行混合'
- '(blend if(eq(mod(Y,2),0),A,B)+setfield=tff,A=偶行=顶场,50/50写死)。'
- '实拍需已规范化(fps30/同分辨率/定长);A流零处理,音频取素材,'
- 'aac码率随机——与原版一致。观感机理见 终稿§十二(tff场重建)')
- ap.add_argument('--ab-image', metavar='PATH',
- help='一条龙AB原味:给一张图(建议AI生成"无人物,空场景"),自动制KenBurns'
- '实拍(zoompan慢推+规范化,R3的_ZZSP+_FBL链)再逐行混合——原版AB的'
- 'B流制备全自动,等价 --pair-video 但免手动制实拍')
- ap.add_argument('--ab-dark', type=float, default=-0.25, metavar='V',
- help='AB原味模式B流压暗量,默认 -0.25(R5实测:B亮度是决定变量,近黑B在'
- '所有隔行处理路径下都不可见且无闪烁;0=字节级原味——原版无压暗滤镜,'
- '靠AI词库"无人物,空场景"出低亮度图)')
- ap.add_argument('--pair-ratio', type=float, default=0.33,
- help='(已废弃)8.18混合比例50/50由行奇偶写死,无强度配置(R2:无第8槽)')
- ap.add_argument('--audio', metavar='PATH',
- help='外部音频整体替换原声(BGM/配音,循环补足时长):搬运判重的音频指纹'
- '证据链直接归零,与画面变换叠加使用;设置后忽略颤音/粉噪/音调链')
- ap.add_argument('--mirror', action='store_true',
- help='启用镜像翻转(默认关闭:画面文字/标识不反向;开启可额外改变视觉指纹)')
- ap.add_argument('--vibrato', action='store_true',
- help='启用音频颤音调制(默认关闭:强档深度下有可闻抖动感;开启可额外扰动音频指纹)')
- ap.add_argument('--same-name', action='store_true', help='输出保持原文件名(默认追加随机后缀)')
- args = ap.parse_args()
- sys.stdout.reconfigure(encoding='utf-8', errors='replace')
- inp = Path(args.input)
- if inp.is_file():
- files = [inp]
- in_dir = inp.parent
- else:
- in_dir = inp
- files = sorted(p for p in in_dir.iterdir()
- if p.is_file() and p.suffix.lower() in VIDEO_EXTS)
- out_dir = Path(args.output) if args.output else in_dir / '去重输出'
- out_dir_resolved = out_dir.resolve()
- files = [f for f in files if out_dir_resolved not in f.resolve().parents]
- if not files:
- print(f'输入中没有找到视频文件: {in_dir.resolve()}')
- sys.exit(1)
- out_dir.mkdir(parents=True, exist_ok=True)
- rng = random.Random(args.seed)
- cfg = dict(PRESETS[args.preset])
- if not args.mirror: # 镜像默认关:画面文字/标识不反向(与白盒 dedup.mirror=false 决策对齐)
- cfg['p_hflip'] = 0.0
- if not args.vibrato: # 颤音默认关:强档深度下有可闻抖动感,听感优先
- cfg['p_vibrato'] = 0.0
- if args.interlace != 'off' and args.hw:
- print('注意: 隔行档仅 CPU 编码生效,--hw 下自动忽略隔行参数\n')
- pv = Path(args.pair_video) if args.pair_video else None
- ab_img = Path(args.ab_image) if args.ab_image else None
- if pv is not None and not pv.is_file():
- sys.exit(f'辅助视频不存在: {pv}')
- if ab_img is not None and not ab_img.is_file():
- sys.exit(f'实拍图片不存在: {ab_img}')
- if ab_img is not None and pv is not None:
- sys.exit('--ab-image 与 --pair-video 互斥(都是AB的B流来源)')
- if args.ab and (pv is not None or ab_img is not None):
- sys.exit('--ab(几何重排)与 AB原味(--pair-video/--ab-image)互斥')
- if args.ab_phantom and pv is not None:
- sys.exit('--ab-phantom 与 --pair-video 互斥')
- au = Path(args.audio) if args.audio else None
- if au is not None and not au.is_file():
- sys.exit(f'替换音频不存在: {au}')
- report_path = out_dir / '处理报告.csv'
- fields = ['文件名', '输出名', '状态', '原分辨率', '原时长(s)', '新时长(s)',
- '镜像', '几何重排', '裁剪', '旋转', '色温', 'HSL', '动态色相', '颗粒', '边框', '调色',
- '变速', '音调', '音频替换', '音频压缩', '颤音', '粉噪', '帧率', 'AB交错', '叠加图层',
- '隔行', '收尾']
- rows, ok, fail = [], 0, 0
- print(f'共 {len(files)} 个视频,档位 {args.preset},输出 → {out_dir.resolve()}\n')
- for f in files:
- row = dict.fromkeys(fields, '')
- row['文件名'] = f.name
- b_stage = None
- try:
- info = probe(f)
- w, h = info['w'] - info['w'] % 2, info['h'] - info['h'] % 2
- # 帧率微调前置检查:标称帧率与实测包率偏差>10% 视为时间戳异常源,跳过 fps 重采样
- fps_bad = (info['fps'] and info['real_fps'] and
- abs(info['real_fps'] - info['fps']) / info['fps'] > 0.10)
- if ab_img is not None: # 一条龙:图片自动制实拍(R3/R8 _ZZSP:素材头30帧+KenBurns concat)
- b_stage = out_dir / f'{f.stem}_zzsp.mp4'
- frames = int(info['dur'] * 30) + 1
- zr = run(['ffmpeg', '-y', '-v', 'error',
- '-i', str(f), '-loop', '1', '-i', str(ab_img),
- '-filter_complex',
- "[0:v]fps=30,scale=%d:%d:force_original_aspect_ratio=decrease,"
- "pad=%d:%d:(ow-iw)/2:(oh-ih)/2,setsar=1,format=yuv420p,"
- "trim=end_frame=30[h];"
- "[1:v]zoompan=z='min(zoom+0.003,3)':d=%d:"
- "x='iw/2-(iw/zoom/2)':y='ih/2-(ih/2/zoom/2)':s=%dx%d:fps=30,"
- "scale=%d:%d:force_original_aspect_ratio=decrease,"
- "pad=%d:%d:(ow-iw)/2:(oh-ih)/2,setsar=1,format=yuv420p[k];"
- "[h][k]concat=n=2:v=1:a=0[v]"
- % (w, h, w, h, frames, w, h, w, h, w, h),
- '-map', '[v]', '-t', f'{info["dur"]:.3f}',
- '-c:v', 'libx264', '-preset', 'faster', '-crf', '26',
- '-an', str(b_stage)])
- if zr.returncode != 0 or not b_stage.exists():
- raise RuntimeError(f'实拍制备失败: {zr.stderr.strip()[:120]}')
- pair_src = b_stage if b_stage is not None else pv
- pair_info = probe(pair_src) if pair_src is not None else None
- use_ab = args.ab and pair_info is None
- use_ph = args.ab_phantom and pair_info is None
- if pair_info:
- cfg_file = dict(cfg, p_fps=0.0) # AB 双流统一帧率,跳过帧率微调
- else:
- cfg_file = cfg
- ab_cfg = AB_V7[args.preset]
- if use_ab: # v7 单流引擎:不走 build_transform 的随机组合,链路自含
- vf, af_parts, sp, t = build_ab_v7(
- rng, ab_cfg, w, h, info['has_audio'], info['a_rate'])
- if args.mirror:
- vf.insert(0, 'hflip')
- t['镜像'] = '是'
- noise_amp, misc = None, {'speed': sp}
- elif use_ph: # 幻影注入:视频走 filter_complex,音频链与 v7 共用
- vf = [] # 视频链在 ph_graph 内,占位满足 assemble 引用
- base_fps = 30 if not info['fps'] or abs(info['fps'] - 30) <= 6 \
- else round(info['fps'])
- sp = rng.uniform(*ab_cfg['speed'])
- # 实测定案(2026-08-20 快手):幻影档过判重(数据层取指纹),几何档被判
- # (嵌入级几何不变)→ 幻影是判重主力,音频只留变速;音调偏移(4%≈68音分,
- # 可闻)撤除,听感回归原片。快手实测通过后以最小改动保听感。
- af_parts, t_aud = _ab_audio(rng, 0.0,
- info['has_audio'], info['a_rate'], sp)
- ph_graph, t = build_phantom(rng, w, h, base_fps, sp)
- t['变速'] = f'{sp:.3f}x'
- t.update(t_aud)
- noise_amp, misc = None, {'speed': sp}
- else:
- vf, af_parts, noise_amp, t, misc = build_transform(
- rng, cfg_file, w, h, info['has_audio'], info['fps'])
- if pair_info is not None: # 原味AB(R2复刻):素材流零处理/音频原样/无变速
- vf, af_parts, noise_amp = [], [], None
- t = {}
- misc = {'speed': 1.0}
- if args.mirror:
- t['镜像'] = '是(A流)'
- if fps_bad and not use_ph:
- t['帧率'] = (f"跳过(标称{info['fps']:.2f}/实测{info['real_fps']:.2f}fps,"
- "时间戳异常,重采样会损动作)")
- elif use_ph:
- t['帧率'] = f'→{base_fps}fps基准+幻影注入'
- elif pair_info:
- t['帧率'] = '跳过(AB双流统一帧率)'
- if au is not None: # 外部音频替换:原声证据链归零,音频处理链全部跳过
- af_parts = []
- noise_amp = None
- t['音频替换'] = au.name
- row['原分辨率'] = f"{info['w']}x{info['h']}"
- row['原时长(s)'] = f"{info['dur']:.1f}"
- row.update(t)
- token = '' if args.same_name else '_' + ''.join(
- rng.choices('abcdefghijkmnpqrstuvwxyz23456789', k=6))
- dst = out_dir / (f.stem + token + '.mp4')
- n = 1
- while dst.exists():
- n += 1
- dst = out_dir / (f.stem + token + f'_{n}.mp4')
- row['输出名'] = dst.name
- meta_time = (datetime(2021, 1, 1) + timedelta(
- seconds=rng.randint(0, 5 * 365 * 86400))).strftime('%Y-%m-%dT%H:%M:%S')
- stage = out_dir / (dst.stem + '.stage.mp4')
- ov = Path(args.overlay) if args.overlay else None
- if ov is not None and not ov.is_file():
- raise RuntimeError(f'叠加图层不存在: {ov}')
- use_noise = noise_amp is not None
- use_pair = pair_info is not None
- noise_idx = (1 if use_pair else 0) + (2 if ov is not None else 1)
- audio_idx = (1 if use_pair else 0) + (1 if ov is not None else 0) + \
- (1 if use_noise else 0) + 1
- a_br = f'{rng.randint(128, 192)}k' if use_pair else '160k' # 原味AB随机aac码率
- sp = misc['speed']
- # 输出时长基准:主视频变速后时长;掐头可选(--trim-head,B2考证:原版不掐头);
- # 实拍循环流无限,用 -t 锁长
- trim = args.trim_head if use_ab else 0.0
- out_dur = (info['dur'] - trim) / sp
- def assemble(hw: bool):
- cmd = ['ffmpeg', '-y', '-hide_banner', '-loglevel', 'error']
- cmd += (['-ss', f'{trim:g}'] if trim > 0 else []) + ['-i', str(f)]
- if use_pair:
- cmd += ['-stream_loop', '-1', '-i', str(pair_src)] # 素材循环(8.18模板原味)
- if ov is not None:
- cmd += ['-i', str(ov)]
- if use_noise:
- cmd += ['-f', 'lavfi', '-i',
- f'anoisesrc=color=pink:amplitude={noise_amp:.5f}:sample_rate=44100']
- if au is not None:
- cmd += ['-stream_loop', '-1', '-i', str(au)] # 替换音频循环补足
- fc = None
- if use_ph or use_pair or ov is not None or use_noise:
- parts = []
- vchain = ','.join(vf)
- if use_ph:
- parts.append(ph_graph)
- elif use_pair:
- # 8.18 原味AB(R2 逐字节复核定稿):A/B 流进模板仅 scale+format,
- # 阈值0=偶行取A(=tff顶场),50/50写死,素材音频硬映射。
- # B流压暗为本工具追加(R5实测安全垫,--ab-dark 0 可回退字节原味)。
- pre = 'hflip,' if args.mirror else ''
- beq = f'eq=brightness={args.ab_dark:.3f},' if args.ab_dark else ''
- parts.append(f'[0:v]{pre}scale={w}:{h},format=yuv420p[filt_a];')
- parts.append(f'[1:v]scale={w}:{h},{beq}format=yuv420p[filt_b];')
- t['AB交错'] = f'素材×实拍50/50(tff,码率{a_br}' + \
- (f',B压暗{args.ab_dark:g})' if args.ab_dark else ')')
- parts.append(f'[filt_a][filt_b]blend=all_expr='
- f"'if(eq(mod(Y\\,2)\\,0)\\,A\\,B)',"
- f'setfield=tff,format=yuv420p[v_mix];')
- if ov is not None:
- ov_src = 2
- parts.append(f'[{ov_src}:v]scale={w}:{h},format=rgba,'
- f'colorchannelmixer=aa={args.overlay_alpha}[ovx];')
- parts.append('[v_mix][ovx]overlay=0:0[v];') # 静态图铺满全程
- t['叠加图层'] = f'{args.overlay_alpha * 100:.0f}%'
- else:
- parts.append('[v_mix]null[v];')
- elif ov is not None:
- parts.append(f'[0:v]{vchain}[base];')
- parts.append(f'[1:v]scale={w}:{h},format=rgba,'
- f'colorchannelmixer=aa={args.overlay_alpha}[ov];')
- parts.append('[base][ov]overlay=0:0[v];') # 静态图,overlay 默认重复末帧铺满全程
- t['叠加图层'] = f'{args.overlay_alpha * 100:.0f}%'
- else:
- parts.append(f'[0:v]{vchain}[v];')
- if use_noise: # 音频指纹链:原声(重采样44100) ⊕ 粉噪 → amix → 限幅(8.18 同源)
- ach = ','.join(af_parts + ['aresample=44100']) if af_parts else 'aresample=44100'
- parts.append(f'[0:a]{ach}[am];')
- if info.get('a_layout'): # 粉噪对齐源声道布局,防止 amix 把立体声压成单声道
- parts.append(f'[{noise_idx}:a]aformat=channel_layouts={info["a_layout"]}[bn];')
- n_src = '[bn]'
- else:
- n_src = f'[{noise_idx}:a]'
- parts.append(f'[am]{n_src}amix=inputs=2:duration=first:'
- f'normalize=0,alimiter=limit=0.94[outa];')
- fc = ''.join(parts).rstrip(';')
- if fc is not None:
- cmd += ['-filter_complex', fc, '-map', '[v]']
- else:
- cmd += ['-vf', ','.join(vf), '-map', '0:v:0']
- if au is not None:
- cmd += ['-map', f'{audio_idx}:a:0']
- elif use_noise:
- cmd += ['-map', '[outa]']
- elif info['has_audio']:
- cmd += ['-map', '0:a:0']
- cmd += ['-map_metadata', '-1',
- '-metadata', f'creation_time={meta_time}']
- cmd += encode_args(hw, 'tff' if use_pair else args.interlace,
- args.crf, args.enc_preset)
- # R4 实测:setfield 须配 -flags +ilme+ildct 才能把 tff 写进 h264 流;
- # tff+偶行素材经 KS 单场去隔行=纯素材零损耗,bff=糊影(v6 失败根因)
- if au is not None:
- cmd += ['-c:a', 'aac', '-b:a', '160k']
- elif use_noise:
- cmd += ['-c:a', 'aac', '-b:a', '160k']
- elif info['has_audio']:
- cmd += ['-c:a', 'aac', '-b:a', a_br]
- if af_parts:
- cmd += ['-af', ','.join(af_parts)]
- else:
- cmd += ['-an']
- out_tail = (['-t', f'{out_dur:.3f}'] if use_pair else []) + \
- (['-shortest'] if au is not None else []) + \
- ['-pix_fmt', 'yuv420p', '-movflags', '+faststart', str(stage)]
- return cmd + out_tail
- cmd = assemble(args.hw and not use_pair) # AB原味 tff 隔行编码仅 CPU 支持
- r = run(cmd)
- if r.returncode != 0 and args.hw: # NVENC 不可用时整体重建为 CPU 命令再跑
- print(f' [硬件编码失败,改用 CPU] {r.stderr.strip()[:120]}')
- r = run(assemble(False))
- if r.returncode != 0:
- raise RuntimeError(r.stderr.strip()[-300:])
- if args.interlace != 'off' and not args.hw:
- t['隔行'] = args.interlace
- if args.no_finish:
- stage.replace(dst)
- t['收尾'] = '关闭'
- else:
- r2 = run(finish_args(stage, dst, info['has_audio'] or au is not None,
- rng, meta_time))
- if r2.returncode != 0: # 收尾失败时保底用第一阶段产物
- print(f' [收尾工序失败,保留未洗容器版本] {r2.stderr.strip()[:120]}')
- stage.replace(dst)
- t['收尾'] = '跳过'
- else:
- stage.unlink()
- t['收尾'] = 'SEI删+SPS裁+元数据伪造'
- row.update({k: t.get(k, '') for k in ('叠加图层', '隔行', '收尾')})
- if b_stage is not None:
- b_stage.unlink(missing_ok=True)
- new_info = probe(dst)
- row['新时长(s)'] = f"{new_info['dur']:.1f}"
- row['状态'] = '成功'
- ok += 1
- desc = ' '.join(f'{k}:{v}' for k, v in t.items()) or '仅重编码+元数据'
- print(f' ✔ {f.name} → {dst.name} [{desc}]')
- except Exception as e:
- stage = out_dir / (row.get('输出名', '').replace('.mp4', '.stage.mp4'))
- if row.get('输出名'):
- stage.unlink(missing_ok=True)
- if b_stage is not None:
- b_stage.unlink(missing_ok=True)
- row['状态'] = f'失败:{e}'
- fail += 1
- print(f' ✘ {f.name} 失败: {e}')
- rows.append(row)
- with open(report_path, 'w', newline='', encoding='utf-8-sig') as fp:
- writer = csv.DictWriter(fp, fieldnames=fields)
- writer.writeheader()
- writer.writerows(rows)
- print(f'\n完成: 成功 {ok} / 失败 {fail},处理报告 → {report_path.resolve()}')
- if __name__ == '__main__':
- main()
|