animebot / bot /encoder.py
luci18's picture
Re-upload fresh bot files
7cb306b verified
Raw History Blame Contribute Delete
11.1 kB
"""Video encoding module using FFmpeg."""
import logging
import subprocess
import re
import json
from pathlib import Path
from typing import Optional, Dict, Callable
from uuid import uuid4
from config import Config
from bot.database import db
logger = logging.getLogger(__name__)
class VideoEncoder:
"""Handler for video encoding using FFmpeg."""
def __init__(self):
self.encode_dir = Config.ENCODE_DIR
self.temp_dir = Config.TEMP_DIR
self.ffmpeg_path = Config.FFMPEG_PATH
self.ffprobe_path = Config.FFPROBE_PATH
self.active_encodes: Dict[str, subprocess.Popen] = {}
def get_video_info(self, file_path: Path) -> Optional[Dict]:
"""Get video file information using ffprobe."""
try:
cmd = [
self.ffprobe_path,
"-v", "error",
"-show_format",
"-show_streams",
"-of", "json",
str(file_path)
]
result = subprocess.run(cmd, capture_output=True, text=True)
if result.returncode == 0:
return json.loads(result.stdout)
return None
except Exception as e:
logger.error(f"ffprobe error: {e}")
return None
def get_duration(self, file_path: Path) -> float:
"""Get video duration in seconds."""
try:
cmd = [
self.ffprobe_path,
"-v", "error",
"-show_entries", "format=duration",
"-of", "default=noprint_wrappers=1:nokey=1",
str(file_path)
]
result = subprocess.run(cmd, capture_output=True, text=True)
return float(result.stdout.strip()) if result.returncode == 0 else 0.0
except Exception:
return 0.0
def get_audio_info(self, file_path: Path) -> Optional[Dict]:
"""Get audio stream information using ffprobe."""
try:
cmd = [
self.ffprobe_path,
"-v", "error",
"-select_streams", "a:0",
"-show_entries", "stream=codec_name,bit_rate",
"-of", "json",
str(file_path)
]
result = subprocess.run(cmd, capture_output=True, text=True)
if result.returncode == 0:
data = json.loads(result.stdout)
if 'streams' and len(data.get('streams', [])) > 0:
stream = data['streams'][0]
return {
'codec': stream.get('codec_name', 'Unknown'),
'bitrate': stream.get('bit_rate', 'Unknown')
}
return None
except Exception as e:
logger.error(f"ffprobe audio error: {e}")
return None
def encode_video(self, input_path: Path, user_id: int,
settings: Optional[Dict] = None,
progress_callback: Optional[Callable[[int, str], None]] = None) -> Optional[Path]:
"""Encode video with specified settings.
Args:
input_path: Path to input video
user_id: Telegram user ID
settings: Encoding settings (uses user defaults if not provided)
progress_callback: Callback function(progress_percent, status_message)
Returns:
Path to encoded file or None if failed
"""
task_id = str(uuid4())
# Get user settings or use defaults
if settings is None:
settings = db.get_user_settings(user_id)
# Build output path
output_name = f"{input_path.stem}_encoded.mkv"
output_path = self.encode_dir / str(user_id) / output_name
output_path.parent.mkdir(parents=True, exist_ok=True)
# Add to database
db.add_encode_task(task_id, user_id, str(input_path), str(output_path), settings)
try:
db.update_encode_status(task_id, "encoding")
# Build FFmpeg command
cmd = self._build_ffmpeg_command(input_path, output_path, settings)
logger.info(f"Starting encode: {' '.join(cmd)}")
# Get video duration for progress calculation
duration = self.get_duration(input_path)
# Start encode process
process = subprocess.Popen(
cmd,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True,
bufsize=1,
universal_newlines=True
)
self.active_encodes[task_id] = process
# Monitor progress
last_progress = 0
for line in process.stderr:
line = line.strip()
if "time=" in line and duration > 0:
progress = self._parse_progress(line, duration)
if progress and progress_callback and abs(progress - last_progress) >= 5:
progress_callback(progress, f"Encoding... {progress}%")
db.update_encode_status(task_id, "encoding", progress)
last_progress = progress
process.wait()
if process.returncode == 0:
db.update_encode_status(task_id, "completed", 100)
if progress_callback:
progress_callback(100, "Encoding completed!")
logger.info(f"Encoding completed: {output_path}")
return output_path
else:
stderr = process.stderr.read() if process.stderr else "Unknown error"
error_msg = f"Encoding failed: {stderr}"
db.update_encode_status(task_id, "failed", error=error_msg)
logger.error(error_msg)
return None
except Exception as e:
error_msg = f"Encoding error: {e}"
db.update_encode_status(task_id, "failed", error=error_msg)
logger.error(error_msg)
return None
finally:
if task_id in self.active_encodes:
del self.active_encodes[task_id]
def _build_ffmpeg_command(self, input_path: Path, output_path: Path, settings: Dict) -> list:
"""Build FFmpeg command based on settings."""
cmd = [
self.ffmpeg_path,
"-i", str(input_path),
"-y", # Overwrite output
]
# Video codec settings
codec = settings.get("codec", Config.DEFAULT_CODEC)
crf = settings.get("crf", Config.DEFAULT_CRF)
preset = settings.get("preset", Config.DEFAULT_PRESET)
resolution = settings.get("resolution", "original")
# Video filter
vf_parts = []
if resolution != "original":
height = resolution.replace("p", "")
vf_parts.append(f"scale=-2:{height}")
# Apply video filter if any
if vf_parts:
cmd.extend(["-vf", ",".join(vf_parts)])
# Video codec configuration
cmd.extend([
"-c:v", codec,
"-preset", preset,
"-crf", str(crf),
"-pix_fmt", "yuv420p",
])
# 10-bit support for HEVC/H265
if "265" in codec or "hevc" in codec.lower():
cmd.extend(["-pix_fmt", "yuv420p10le"])
# Audio codec settings
audio_codec = settings.get("audio_codec", Config.DEFAULT_AUDIO_CODEC)
audio_bitrate = settings.get("audio_bitrate", Config.DEFAULT_AUDIO_BITRATE)
cmd.extend([
"-c:a", audio_codec,
"-b:a", audio_bitrate,
])
# Audio channels
if "channels" in settings:
cmd.extend(["-ac", str(settings["channels"])])
# Hardsub subtitles
if settings.get("hardsub", False):
cmd.extend([
"-vf", "subtitles='" + str(input_path) + "'",
])
# Copy subtitle streams if not hardsubbing
if not settings.get("hardsub", False):
cmd.extend(["-c:s", "copy"])
# Faststart for web playback
cmd.extend(["-movflags", "+faststart"])
# Output file
cmd.append(str(output_path))
return cmd
def _parse_progress(self, line: str, duration: float) -> Optional[int]:
"""Parse encoding progress from FFmpeg output."""
match = re.search(r'time=(\d+):(\d+):(\d+\.?\d*)', line)
if match and duration > 0:
hours, minutes, seconds = match.groups()
current_time = float(hours) * 3600 + float(minutes) * 60 + float(seconds)
progress = int((current_time / duration) * 100)
return min(progress, 100)
return None
def cancel_encode(self, task_id: str) -> bool:
"""Cancel an active encoding."""
if task_id in self.active_encodes:
process = self.active_encodes[task_id]
process.terminate()
try:
process.wait(timeout=5)
except subprocess.TimeoutExpired:
process.kill()
db.update_encode_status(task_id, "cancelled")
del self.active_encodes[task_id]
return True
return False
def reencode_audio(self, input_path: Path, output_path: Path,
audio_codec: str = "aac", bitrate: str = "128k",
channels: int = 2) -> bool:
"""Re-encode only audio stream."""
try:
cmd = [
self.ffmpeg_path,
"-i", str(input_path),
"-c:v", "copy",
"-c:a", audio_codec,
"-b:a", bitrate,
"-ac", str(channels),
"-y",
str(output_path)
]
result = subprocess.run(cmd, capture_output=True)
return result.returncode == 0
except Exception as e:
logger.error(f"Audio re-encode error: {e}")
return False
def extract_audio(self, input_path: Path, output_path: Path,
audio_codec: str = "mp3") -> bool:
"""Extract audio from video."""
try:
cmd = [
self.ffmpeg_path,
"-i", str(input_path),
"-vn", # No video
"-c:a", audio_codec,
"-y",
str(output_path)
]
result = subprocess.run(cmd, capture_output=True)
return result.returncode == 0
except Exception as e:
logger.error(f"Audio extract error: {e}")
return False
# Global encoder instance
encoder = VideoEncoder()