FFmpeg 编码脚本改进

FFmpeg 编码脚本改进

我正在使用 ffpmeg 脚本将视频编码为多个 mp4 质量,这只是一个基本脚本,需要有关如何提高速度和性能的建议。

# encoding: utf-8
# coder:    Ishaq Khan
# version:  1.0

import os
import subprocess
import sys
import time
import re
import datetime

os.chdir(os.path.dirname(os.path.abspath(sys.argv[0])))

print()
print('*' * 34)
print('** Real-time Video Encoder v1.0 **')
print('*' * 34)
print()

paths = {
    "src_dir" : "/www/wwwroot/videos/mp4/source",
    "out_dir" : "/www/wwwroot/videos/mp4/pinoy"
}

src_dir = paths['src_dir']
out_dir = paths['out_dir']

if not os.path.exists(src_dir):
    print('Source directory specified in "paths" dictionary is not valid.')
    exit()

elif not os.path.exists(out_dir):
    print('Output directory specified in "paths" dictionary is not valid.')
    exit()

# --------------------------------------------------------------------

last_act = 'encoding'

while True:
    if last_act == 'encoding':
        print('Watching source folder for incoming video files...')

    last_act = 'waiting'

    cur_date = datetime.datetime.now().date()
    cur_yr = str(cur_date.year)
    cur_mon = str(cur_date.month).zfill(2)
    cur_day = str(cur_date.day).zfill(2)

    src_files = os.listdir(src_dir)
    src_files = [eve for eve in src_files if eve.lower().endswith('.mp4')]
    src_files.sort(key=lambda x: os.path.getctime(src_dir + '/' + x))

    if src_files:
        src_file = src_files[0]
        print('Processing "{}"'.format(src_file))

        dest_dir = '{}/{}/{}/{}/{}'.format(out_dir, cur_yr, cur_mon, cur_day, src_file.rsplit('.', 1)[0])
        os.makedirs(dest_dir, exist_ok=True)

        ffmpeg_com = 'ffmpeg -y -loglevel error -i "{}/{}" -i watermark_360p.png -filter_complex "scale=640:360,overlay=0:0" -codec:a copy "{}/360.mp4"'.format(src_dir, src_file, dest_dir)
        subprocess.call(ffmpeg_com, shell=True)
        ffmpeg_wm_com = 'ffmpeg -y -loglevel error -ss 0:0:10 -i "{}/360.mp4" -vframes 1 -q:v 2 "{}/poster.jpg"'.format(dest_dir, dest_dir)
        subprocess.call(ffmpeg_wm_com, shell=True)

        ffprobe_com = 'ffprobe -loglevel error -i "{}/{}" -show_streams'.format(src_dir, src_file)
        ffprobe_com_out = subprocess.check_output(ffprobe_com, shell=True).decode('utf-8')
        height = re.search('(?<=\nheight=)\d+', ffprobe_com_out)
        height = int(ffprobe_com_out[height.start():height.end()])

        if height >= 720:
            ffmpeg_com = 'ffmpeg -y -loglevel error -i "{}/{}" -i watermark_720p.png -filter_complex "scale=1280:720,overlay=0:0" -codec:a copy "{}/720.mp4"'.format(
                src_dir, src_file, dest_dir)
            subprocess.call(ffmpeg_com, shell=True)
            ffmpeg_wm_com = 'ffmpeg -y -loglevel error -ss 0:0:10 -i "{}/720.mp4" -vframes 1 -q:v 2 "{}/poster.jpg"'.format(
                dest_dir, dest_dir)
            subprocess.call(ffmpeg_wm_com, shell=True)

        os.remove(src_dir + '/' + src_file)

        last_act = 'encoding'

    time.sleep(5)

相关内容