video_dedup.py 31 KB

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