import subprocess import os def transcode_file(transcoding_tasks, 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, "-map", "0", "-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(" ".join(command)) process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True) task = { "id": "id_" + str(len(transcoding_tasks) + 1), "file": file_path, "output": output_file, "command": command, "process": process } transcoding_tasks[task["id"]] = task; for line in process.stdout: # Parse progress from ffmpeg output and send via WebSocket if "frame=" in line: socketio.emit('progress', { "task": { "id": task["id"], "file": task["file"], "command": task["command"] }, "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', { "task": { "id": task["id"], "file": task["file"], "command": task["command"] }, "message": f"File {file_path} transcoded successfully" }) os.rename(output_file, file_path) del transcoding_tasks[task["id"]] else: if(task["id"] in transcoding_tasks): socketio.emit('error', { "task": { "id": task["id"], "file": task["file"], "command": task["command"] }, "message": f"Transcoding failed for {file_path}" }) del transcoding_tasks[task["id"]] else: # canceled socketio.emit('canceled', { "task": { "id": task["id"], "file": task["file"], "command": task["command"] }, "message": f"Transcoding canceled for {file_path}" }) if os.path.exists(output_file): os.remove(output_file)