Create utils/ffmpeg.py
Browse files- utils/ffmpeg.py +47 -0
utils/ffmpeg.py
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import subprocess
|
| 2 |
+
import io
|
| 3 |
+
|
| 4 |
+
def ffmpeg(input_stream: io.BufferedReader, ffmpeg_args: list) -> io.BytesIO:
|
| 5 |
+
command = ["ffmpeg", "-i", "pipe:0"] + ffmpeg_args + ["pipe:1"]
|
| 6 |
+
process = subprocess.Popen(
|
| 7 |
+
command,
|
| 8 |
+
stdin=subprocess.PIPE,
|
| 9 |
+
stdout=subprocess.PIPE,
|
| 10 |
+
stderr=subprocess.PIPE,
|
| 11 |
+
bufsize=10**6
|
| 12 |
+
)
|
| 13 |
+
output_stream = io.BytesIO()
|
| 14 |
+
|
| 15 |
+
try:
|
| 16 |
+
while chunk := input_stream.read(1024 * 1024):
|
| 17 |
+
process.stdin.write(chunk)
|
| 18 |
+
|
| 19 |
+
process.stdin.close()
|
| 20 |
+
|
| 21 |
+
while chunk := process.stdout.read(1024 * 1024):
|
| 22 |
+
output_stream.write(chunk)
|
| 23 |
+
|
| 24 |
+
process.stdout.close()
|
| 25 |
+
process.wait()
|
| 26 |
+
|
| 27 |
+
if process.returncode != 0:
|
| 28 |
+
error_message = process.stderr.read().decode()
|
| 29 |
+
raise RuntimeError(f"FFmpeg error: {error_message}")
|
| 30 |
+
|
| 31 |
+
output_stream.seek(0)
|
| 32 |
+
return output_stream
|
| 33 |
+
|
| 34 |
+
except Exception as e:
|
| 35 |
+
process.terminate()
|
| 36 |
+
raise RuntimeError(f"Video processing failed: {e}")
|
| 37 |
+
|
| 38 |
+
finally:
|
| 39 |
+
process.stdout.close()
|
| 40 |
+
process.stderr.close()
|
| 41 |
+
process.stdin.close()
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def mp3_to_opus(byteIO: io.BytesIO) -> io.BytesIO:
|
| 45 |
+
return ffmpeg(io.BufferedReader(byteIO), [
|
| 46 |
+
"-c:a libopus"
|
| 47 |
+
])
|