修改批处理脚本后ffprobe读取视频码率失败的问题排查
批处理脚本ffprobe读取码率失效排查与修复
问题背景
这是一款Windows批处理脚本,核心功能为:通过ffprobe读取视频码率,再以相同码率、x265_10bit编码转码去除视频黑边(解决Icaros缩略图显示黑边问题);支持资源管理器右键菜单触发、任务队列机制,仅首个脚本实例执行转码,后续实例自动退出。
此前脚本运行正常,修改其他逻辑后,ffprobe读取码率功能频繁失效,返回N/A而非预期的数值(如2534533,需处理为2534k/s用于转码)。已确认ffprobe命令本身未改动,怀疑是脚本引号或语法问题导致。
排查步骤
单独验证ffprobe命令:在CMD中直接执行目标视频的ffprobe命令,格式如下:
ffprobe "你的视频完整路径" -v 0 -select_streams v:0 -show_entries stream=bit_rate -print_format compact=p=0:nokey=1如果返回
N/A,说明视频本身无可用码率信息;如果返回正常数值,问题出在脚本变量传递或语法逻辑。检查变量传递正确性:在
:transcode标签开头添加调试语句,确认文件路径是否正常:echo 当前处理文件:%in%运行脚本查看输出,验证路径是否完整、是否被正确包裹在引号中,有无因空格或特殊字符导致的截断。
检查临时文件内容:在ffprobe命令后添加语句,查看临时文件写入的内容:
type "%temporary%"确认临时文件是否确实写入了
N/A,还是混入了其他错误输出。
修复方案
1. 解决变量延迟扩展问题
批处理for循环中使用set和call时,默认变量扩展会提前完成,导致%in%等变量值错误。需开启延迟扩展并修改变量引用方式:
- 在脚本开头
@echo off后添加:setlocal enabledelayedexpansion - 将
:transcode标签内的%in%、%out%替换为!in!、!out!
2. 修正路径特殊字符处理
确保ffprobe命令中的文件路径被正确包裹,支持含特殊字符(如&、^等)的路径:
修改ffprobe命令为:
ffprobe "!in!" -v 0 -select_streams v:0 -show_entries stream=bit_rate -print_format compact=p=0:nokey=1 >"%temporary%"
3. 优化临时文件可靠性
改用脚本所在目录存储临时文件,避免系统临时目录的权限或冲突问题:
set "temporary=%~dp0%~n0.tmp"
修复后的完整脚本
@echo off setlocal enabledelayedexpansion cd /d "%~dp0" set "manifest=%~dpn0.txt" set "temporary=%~dp0%~n0.tmp" :: input must exist and be no duplicate if exist "%~1" findstr /c:"%~1" "%manifest%" >nul || echo "%~1">>"%manifest%" :: exit all but first instance tasklist /fi "imagename eq handbrakecli.exe" | find /i "handbrakecli" && exit :manifest for /f "delims=" %%f in (%manifest%) do ( set "in=%%~ff" set "out=%%~dpnf-2.mkv" call :transcode ) for %%a in ("%manifest%") do if not %%~za lss 4 goto :manifest exit /b :transcode if not exist "!in!" goto :cleanup if exist "!out!" goto :cleanup ffprobe "!in!" -v 0 -select_streams v:0 -show_entries stream=bit_rate -print_format compact=p=0:nokey=1 >"%temporary%" set /p bitrate=<%temporary% if not defined bitrate echo failed to fetch bitrate & goto :cleanup :: reduce to full kilobytes set "bitrate=%bitrate:~0,-3%" if %bitrate% gtr 7000 set bitrate=7000 HandBrakeCLI -i "!in!" -o "!out!" --encoder x265_10bit --vb %bitrate% --two-pass --turbo --audio 1-9 --aencoder copy --audio-copy-mask aac,ac3,mp2,mp3,opus --audio-fallback opus --ab 160 --drc 2.0 :cleanup findstr /v /c:"!in!" "%manifest%">"%temporary%" move /y "%temporary%" "%manifest%">nul endlocal
内容的提问来源于stack exchange,提问作者Bricktop
相关产品推荐
相关产品推荐

