市面轉檔工具琳瑯滿目,但論功能之全面,FFmpeg 幾乎無敵,只是它沒有圖形介面。沒關係,在 FreeBSD/Linux 下直接走命令列就好。
整體思路是:指定一個資料夾存放原始影片,讓 Python 走訪資料夾內所有檔案,先呼叫 FFmpeg 分析每支影片的解析度,再依需求調整編碼、尺寸與幀率,最後轉檔輸出。
這次的需求很實際:家裡的液晶電視只吃長寬皆小於 720、編碼為 divx/xvid 的 AVI,且 fps 得低於 25——這些限制說明書根本沒寫,全是反覆試出來的。
下面的程式會把 /root/root2/video/origin 底下所有檔案轉成電視能播的 AVI:
# coding=gb2312
import string, os, time, re, sys
if len(sys.argv) < 2:
print 'please input q'
sys.exit()
for root, dirs, files in os.walk('/root/root2/video/origin'):
for name in files:
name = name.replace('[', '\\[') # 對檔名中的 [ 轉義
newname = name[0: name.rindex('.')]
# 先跑一次 ffmpeg 取得解析度
(si, so, se) = os.popen3('cd /root/root2/video; mkdir -p ffm; rm -f ffm/ffm.txt; csh -c "(ffmpeg -i origin/' + name + ' >& ffm/ffm.txt)"; grep Stream ffm/ffm.txt')
t = so.readlines()
width = 0
height = 0
if len(sys.argv) > 3:
width = string.atof(sys.argv[2])
height = string.atof(sys.argv[3])
reg = "^\s*Stream.*,\s*(\d+)x(\d+),"
for line in t:
result = re.compile(reg).findall(line)
for c in result:
# 電視解析度不得超過 720
if len(sys.argv) <= 3:
width = string.atof(c[0])
height = string.atof(c[1])
if width > 720:
height = height * 720 / width
width = 720
if height > 720:
width = width * 720 / height
height = 720
print 'new:', width, 'x', height
break
# 產生命令:mp3 + xvid 的 avi
cmd = 'csh -c "' + "cd /root/root2/video; touch ffm/output.log; (ffmpeg -y -i origin/" + name + " -acodec libmp3lame -ar 44100 -ab 64K -vcodec libxvid -qmin " + sys.argv[1] + " -qmax " + sys.argv[1] + " -r 25 -s " + str(width) + "x" + str(height) + " -aspect " + str(width) + ":" + str(height) + " -threads 0 -f avi ./ok/xvid/" + newname + ".avi" + ' >& ffm/output.log)"'
(si, so, se) = os.popen3(cmd)
程式會先解析每支影片的長寬,若超過 720 便按比例縮放,再以固定的 qmin/qmax 控制畫質、25 fps 與 mp3 音軌輸出,達成電視可辨識的格式。