import subprocess import os def transcode_file(socketio, file_path, codec, resolution, crf, preset, cpu_used): width = resolution output_file = file_path.replace('.mkv', '_transcoded.mkv') if os.path.exists(output_file): # Проверяем существование файла os.remove(output_file) # Удаляем файл print(f"File already exists. {output_file} was deleted.") command = [ "ffmpeg", "-i", file_path, "-c:v", codec, "-vf", f"scale={width}:-1", "-c:a", "copy", "-crf", crf ] if codec == "libaom-av1": command.append("-cpu-used") command.append(cpu_used) elif codec == "libvpx-vp9": command.append("-cpu-used") command.append(cpu_used) else: command.append("-preset") command.append(preset) command.append(output_file); print("\n"); print(" ".join(command)) process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True) for line in process.stdout: # Parse progress from ffmpeg output and send via WebSocket if "frame=" in line: socketio.emit('progress', {"message": line.strip()}) process.wait() # Step 3: Replace the original file with the transcoded file if process.returncode == 0: os.replace(output_file, file_path) socketio.emit('completed', {"message": f"File {file_path} transcoded successfully"}) # Optionally delete original else: socketio.emit('error', {"message": f"Transcoding failed for {file_path}"})