Skip to content

Speakr is a personal, self-hosted web application designed for transcribing audio recordings

Python

fix: decode ffmpeg/ffprobe output defensively so non-UTF-8 metadata bytes cannot crash processing (supersedes #350)

Murtaza Nasir77e3332c2bde
diff --git a/src/audio_chunking.py b/src/audio_chunking.py
index 97f70371..a4d02afd 100644
--- a/src/audio_chunking.py
+++ b/src/audio_chunking.py
@@ -18,7 +18,7 @@ from typing import List, Dict, Any, Optional, Tuple, TYPE_CHECKING
from datetime import datetime
import mimetypes
-from src.utils.ffmpeg_utils import convert_to_mp3, FFmpegError, FFmpegNotFoundError
+from src.utils.ffmpeg_utils import convert_to_mp3, decode_ffmpeg_output, FFmpegError, FFmpegNotFoundError
if TYPE_CHECKING:
from src.services.transcription.base import ConnectorSpecifications
@@ -348,9 +348,9 @@ class AudioChunkingService:
result = subprocess.run([
'ffprobe', '-v', 'error', '-show_entries', 'format=duration',
'-of', 'default=noprint_wrappers=1:nokey=1', file_path
- ], capture_output=True, text=True, check=True, timeout=_SUBPROCESS_TIMEOUT_SECONDS)
+ ], capture_output=True, check=True, timeout=_SUBPROCESS_TIMEOUT_SECONDS)
- duration = float(result.stdout.strip())
+ duration = float(decode_ffmpeg_output(result.stdout).strip())
return duration
except (subprocess.CalledProcessError, subprocess.TimeoutExpired, ValueError, FileNotFoundError) as e:
logger.error(f"Error getting audio duration for {file_path}: {e}")
@@ -617,12 +617,12 @@ class AudioChunkingService:
]
try:
- result = subprocess.run(cmd, capture_output=True, text=True, timeout=_SUBPROCESS_TIMEOUT_SECONDS)
+ result = subprocess.run(cmd, capture_output=True, timeout=_SUBPROCESS_TIMEOUT_SECONDS)
except subprocess.TimeoutExpired:
logger.error(f"ffmpeg timed out extracting chunk {chunk_index} after {_SUBPROCESS_TIMEOUT_SECONDS}s")
continue
if result.returncode != 0:
- logger.error(f"ffmpeg failed for chunk {chunk_index}: {result.stderr}")
+ logger.error(f"ffmpeg failed for chunk {chunk_index}: {decode_ffmpeg_output(result.stderr)}")
continue
# Verify chunk was created and get its size
@@ -822,8 +822,8 @@ class AudioChunkingService:
'-show_format', '-show_streams', chunk_path
]
- result = subprocess.run(cmd, capture_output=True, text=True, check=True, timeout=_SUBPROCESS_TIMEOUT_SECONDS)
- probe_data = json.loads(result.stdout)
+ result = subprocess.run(cmd, capture_output=True, check=True, timeout=_SUBPROCESS_TIMEOUT_SECONDS)
+ probe_data = json.loads(decode_ffmpeg_output(result.stdout))
audio_stream = None
for stream in probe_data.get('streams', []):
@@ -996,8 +996,8 @@ def get_audio_duration_ffprobe(file_path: str) -> Optional[float]:
result = subprocess.run([
'ffprobe', '-v', 'error', '-show_entries', 'format=duration',
'-of', 'default=noprint_wrappers=1:nokey=1', file_path
- ], capture_output=True, text=True, check=True, timeout=_SUBPROCESS_TIMEOUT_SECONDS)
- return float(result.stdout.strip())
+ ], capture_output=True, check=True, timeout=_SUBPROCESS_TIMEOUT_SECONDS)
+ return float(decode_ffmpeg_output(result.stdout).strip())
except Exception:
return None
@@ -1142,12 +1142,12 @@ def extract_speaker_samples(
]
try:
- result = subprocess.run(cmd, capture_output=True, text=True, timeout=_SUBPROCESS_TIMEOUT_SECONDS)
+ result = subprocess.run(cmd, capture_output=True, timeout=_SUBPROCESS_TIMEOUT_SECONDS)
except subprocess.TimeoutExpired:
logger.error(f"ffmpeg timed out extracting sample for speaker {speaker} after {_SUBPROCESS_TIMEOUT_SECONDS}s")
continue
if result.returncode != 0:
- logger.error(f"Failed to extract sample for speaker {speaker}: {result.stderr}")
+ logger.error(f"Failed to extract sample for speaker {speaker}: {decode_ffmpeg_output(result.stderr)}")
continue
if os.path.exists(sample_path) and os.path.getsize(sample_path) > 0:
diff --git a/src/services/recording_stitch.py b/src/services/recording_stitch.py
index 7a69a5af..f0306f9a 100644
--- a/src/services/recording_stitch.py
+++ b/src/services/recording_stitch.py
@@ -51,6 +51,7 @@ from typing import Tuple
from src.database import db
from src.models import RecordingSession, Recording
+from src.utils.ffmpeg_utils import decode_ffmpeg_output
logger = logging.getLogger(__name__)
@@ -155,7 +156,7 @@ def _remux_copy(src_path: str, output_path: str) -> None:
except subprocess.TimeoutExpired:
raise StitchError('ffmpeg remux timed out after 10 minutes')
if result.returncode != 0:
- stderr = (result.stderr.decode('utf-8', errors='replace') or '').strip()
+ stderr = decode_ffmpeg_output(result.stderr).strip()
logger.warning(
f"Remux failed (exit {result.returncode}): {stderr[:300]}; "
"falling back to raw byte-joined stream"
@@ -184,7 +185,7 @@ def _concat_demux(segment_files: list, output_path: str, work_dir: str) -> None:
except subprocess.TimeoutExpired:
raise StitchError('ffmpeg segment concat timed out after 10 minutes')
if result.returncode != 0:
- stderr = (result.stderr.decode('utf-8', errors='replace') or '').strip()
+ stderr = decode_ffmpeg_output(result.stderr).strip()
raise StitchError(f'ffmpeg segment concat failed (exit {result.returncode}): {stderr[:500]}')
diff --git a/src/utils/ffmpeg_utils.py b/src/utils/ffmpeg_utils.py
index c904df33..c90677e3 100644
--- a/src/utils/ffmpeg_utils.py
+++ b/src/utils/ffmpeg_utils.py
@@ -1,5 +1,6 @@
"""Centralized FFmpeg utilities for consistent audio/video processing."""
+import locale
import os
import subprocess
import tempfile
@@ -476,25 +477,55 @@ def temp_audio_conversion(input_path: str, target_format: str = 'mp3'):
current_app.logger.warning(f"Failed to cleanup temp file {temp_path}: {e}")
+def decode_ffmpeg_output(data) -> str:
+ """
+ Decode ffmpeg/ffprobe byte output defensively.
+
+ ffmpeg echoes container metadata (e.g. ID3 tags) into its output as raw
+ bytes without transcoding, so the stream is not guaranteed to be valid
+ UTF-8 — a GBK-tagged MP3 crashes a strict decode even inside the Linux
+ container. Try UTF-8, then the system's preferred encoding (covers
+ Windows code pages such as GBK/cp1252 for local runs), and finally
+ replace undecodable bytes. Never raises.
+ """
+ if data is None:
+ return ''
+ if isinstance(data, str):
+ return data
+ try:
+ return data.decode('utf-8')
+ except UnicodeDecodeError:
+ pass
+ preferred = locale.getpreferredencoding(False)
+ if preferred and preferred.lower().replace('-', '') != 'utf8':
+ try:
+ return data.decode(preferred)
+ except (UnicodeDecodeError, LookupError):
+ pass
+ return data.decode('utf-8', errors='replace')
+
+
def _run_ffmpeg_command(cmd: list, operation_description: str) -> None:
"""
Execute FFmpeg command with consistent error handling.
-
+
Args:
cmd: FFmpeg command as list of strings
operation_description: Human-readable description for error messages
-
+
Raises:
FFmpegNotFoundError: If FFmpeg is not installed
FFmpegError: If FFmpeg command fails
"""
try:
current_app.logger.debug(f"Running FFmpeg command: {' '.join(cmd)}")
+ # No text=True: that would strict-decode ffmpeg's output inside
+ # communicate() and raise UnicodeDecodeError on non-UTF-8 metadata
+ # bytes before any error handling below could run.
result = subprocess.run(
cmd,
check=True,
capture_output=True,
- text=True,
timeout=FFMPEG_TIMEOUT_SECONDS,
)
current_app.logger.debug(f"FFmpeg {operation_description} completed successfully")
@@ -513,6 +544,6 @@ def _run_ffmpeg_command(cmd: list, operation_description: str) -> None:
raise FFmpegError(error_msg)
except subprocess.CalledProcessError as e:
- error_msg = f"{operation_description} failed: {e.stderr}"
+ error_msg = f"{operation_description} failed: {decode_ffmpeg_output(e.stderr)}"
current_app.logger.error(f"FFmpeg error: {error_msg}")
raise FFmpegError(error_msg)
\ No newline at end of file
diff --git a/src/utils/ffprobe.py b/src/utils/ffprobe.py
index 33dbbf96..a37e37d3 100644
--- a/src/utils/ffprobe.py
+++ b/src/utils/ffprobe.py
@@ -13,6 +13,8 @@ import subprocess
from datetime import datetime
from typing import Optional, Dict, Any, Tuple
+from src.utils.ffmpeg_utils import decode_ffmpeg_output
+
logger = logging.getLogger(__name__)
# Every valid WebM/Matroska file begins with this 4-byte EBML magic. A browser
@@ -57,10 +59,12 @@ def probe(filename: str, cmd: str = 'ffprobe', timeout: Optional[int] = None) ->
out, err = p.communicate(timeout=timeout)
if p.returncode != 0:
- error_msg = err.decode('utf-8', errors='ignore')
+ error_msg = decode_ffmpeg_output(err)
raise FFProbeError(f'ffprobe failed: {error_msg}')
-
- return json.loads(out.decode('utf-8'))
+
+ # ffprobe copies metadata tag values into its JSON as raw bytes, so
+ # the output is not guaranteed to be valid UTF-8 (e.g. GBK ID3 tags).
+ return json.loads(decode_ffmpeg_output(out))
except subprocess.TimeoutExpired:
if p:
p.kill()
@@ -101,12 +105,11 @@ def mp3_duration_is_estimated(filename: str, timeout: Optional[int] = None) -> b
result = subprocess.run(
args,
capture_output=True,
- text=True,
timeout=timeout,
)
if result.returncode != 0:
return False
- return 'Estimating duration from bitrate' in (result.stderr or '')
+ return 'Estimating duration from bitrate' in decode_ffmpeg_output(result.stderr)
except (subprocess.TimeoutExpired, FileNotFoundError, OSError) as e:
logger.warning(f"Could not check MP3 duration header for {filename}: {e}")
return False
@@ -469,7 +472,7 @@ def _get_duration_from_packets(filename: str, timeout: Optional[int] = None) ->
return None
# Parse the output to find the last timestamp
- lines = out.decode('utf-8').strip().split('\n')
+ lines = decode_ffmpeg_output(out).strip().split('\n')
last_valid_time = None
for line in reversed(lines):
line = line.strip()
diff --git a/tests/test_ffmpeg_output_decoding.py b/tests/test_ffmpeg_output_decoding.py
new file mode 100644
index 00000000..cc483164
--- /dev/null
+++ b/tests/test_ffmpeg_output_decoding.py
@@ -0,0 +1,128 @@
+"""
+Regression tests for defensive decoding of ffmpeg/ffprobe output.
+
+ffmpeg copies container metadata (ID3/INFO tags, etc.) into its stderr — and
+some writers into stdout — as raw bytes without transcoding. A GBK-tagged
+file therefore produces non-UTF-8 output, and the old `text=True` /
+`.decode('utf-8')` call sites raised UnicodeDecodeError inside
+subprocess.run before any error handling could run. Reproduced on Linux
+inside the Docker container, not only on Windows locales.
+
+Unit tests cover decode_ffmpeg_output directly; the integration test builds
+a real GBK-tagged WAV and drives it through _run_ffmpeg_command.
+"""
+
+import locale
+import struct
+import subprocess
+import sys
+import os
+from pathlib import Path
+from unittest import mock
+
+import pytest
+
+sys.path.insert(0, str(Path(__file__).parent.parent))
+
+from src.utils.ffmpeg_utils import decode_ffmpeg_output, _run_ffmpeg_command, FFmpegError
+
+GBK_BYTES = '中文标题测试'.encode('gbk')
+
+
+# ===========================================================================
+# decode_ffmpeg_output unit tests (no ffmpeg required)
+# ===========================================================================
+
+def test_decode_none_returns_empty():
+ assert decode_ffmpeg_output(None) == ''
+
+
+def test_decode_str_passthrough():
+ assert decode_ffmpeg_output('already text') == 'already text'
+
+
+def test_decode_valid_utf8():
+ assert decode_ffmpeg_output('héllo'.encode('utf-8')) == 'héllo'
+
+
+def test_decode_gbk_via_preferred_encoding():
+ # On a system whose preferred encoding is GBK (Windows zh locales),
+ # the bytes decode to the original text.
+ with mock.patch.object(locale, 'getpreferredencoding', return_value='gbk'):
+ assert decode_ffmpeg_output(GBK_BYTES) == '中文标题测试'
+
+
+def test_decode_gbk_on_utf8_system_never_raises():
+ # On a UTF-8 system (Linux/Docker) the GBK bytes cannot be decoded
+ # correctly, but the result must be a string, never an exception.
+ with mock.patch.object(locale, 'getpreferredencoding', return_value='UTF-8'):
+ out = decode_ffmpeg_output(GBK_BYTES)
+ assert isinstance(out, str)
+
+
+def test_decode_garbage_bytes_never_raises():
+ out = decode_ffmpeg_output(bytes(range(256)))
+ assert isinstance(out, str)
+
+
+def test_decode_unknown_preferred_encoding_falls_back():
+ with mock.patch.object(locale, 'getpreferredencoding', return_value='not-a-codec'):
+ out = decode_ffmpeg_output(b'\xd6\xd0')
+ assert isinstance(out, str)
+
+
+# ===========================================================================
+# Integration: real ffmpeg over a GBK-tagged WAV (skips without ffmpeg)
+# ===========================================================================
+
+def _ffmpeg_available():
+ try:
+ subprocess.run(['ffmpeg', '-version'], capture_output=True, check=True)
+ return True
+ except (FileNotFoundError, subprocess.CalledProcessError):
+ return False
+
+
+def _write_gbk_tagged_wav(path):
+ """Minimal WAV with a LIST/INFO INAM tag holding raw GBK bytes."""
+ def chunk(cid, data):
+ if len(data) % 2:
+ data += b'\x00'
+ return cid + struct.pack('<I', len(data)) + data
+
+ fmt = chunk(b'fmt ', struct.pack('<HHIIHH', 1, 1, 8000, 16000, 2, 16))
+ data = chunk(b'data', b'\x00\x00' * 8000)
+ info = chunk(b'LIST', b'INFO' + chunk(b'INAM', GBK_BYTES + b'\x00'))
+ body = b'WAVE' + fmt + data + info
+ with open(path, 'wb') as f:
+ f.write(b'RIFF' + struct.pack('<I', len(body)) + body)
+
+
[email protected](not _ffmpeg_available(), reason="ffmpeg not found")
+def test_run_ffmpeg_command_gbk_metadata_fails_cleanly(tmp_path):
+ # ffmpeg dumps the GBK tag bytes raw into stderr. A failing command must
+ # surface as FFmpegError (with a decoded message), not UnicodeDecodeError
+ # from inside subprocess.run.
+ from src.app import app
+
+ wav = tmp_path / 'gbk_tagged.wav'
+ _write_gbk_tagged_wav(str(wav))
+ out = tmp_path / 'out.mp3'
+
+ with app.app_context():
+ with pytest.raises(FFmpegError):
+ _run_ffmpeg_command(
+ ['ffmpeg', '-i', str(wav), '-codec:a', 'nonexistent_codec', str(out), '-y'],
+ 'gbk metadata regression',
+ )
+
+
[email protected](not _ffmpeg_available(), reason="ffmpeg not found")
+def test_probe_gbk_tagged_wav(tmp_path):
+ # probe() must parse the file cleanly regardless of raw tag bytes.
+ from src.utils.ffprobe import probe
+
+ wav = tmp_path / 'gbk_tagged.wav'
+ _write_gbk_tagged_wav(str(wav))
+ data = probe(str(wav))
+ assert 'format' in data