Skip to content

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

Python

Repair MP3s missing a Xing/VBR header with a lossless in-place remux on upload passthrough so Chromium playback stops stuttering (fixes #325)

Murtaza Nasirf831b0fbdc40
diff --git a/src/utils/audio_conversion.py b/src/utils/audio_conversion.py
index b13a9d9d..7211e408 100644
--- a/src/utils/audio_conversion.py
+++ b/src/utils/audio_conversion.py
@@ -377,14 +377,37 @@ def convert_if_needed(
logger.warning(f"Failed to compress lossless audio: {e}. Continuing with original.")
# Fall through to return original file
- # No processing needed - return original file
+ # No processing needed - the file is stored as-is. Before returning,
+ # repair MP3s that lack a Xing/Info (VBR) header: ffmpeg has to estimate
+ # their duration from bitrate and Chromium-based browsers stutter during
+ # playback/seeking (issue #325). A lossless in-place remux writes a
+ # proper header without re-encoding. Best-effort: any failure keeps the
+ # original file.
+ final_size = original_size
+ if audio_codec == 'mp3':
+ try:
+ from src.utils.ffprobe import mp3_duration_is_estimated
+ from src.utils.ffmpeg_utils import remux_mp3_in_place
+ if mp3_duration_is_estimated(filepath):
+ logger.info(
+ f"MP3 {original_filename} is missing a Xing/VBR header "
+ f"(duration estimated from bitrate) — remuxing losslessly"
+ )
+ remux_mp3_in_place(filepath)
+ final_size = os.path.getsize(filepath)
+ except Exception as e:
+ logger.warning(
+ f"Xing header repair failed for {original_filename}: {e}. "
+ f"Continuing with original file."
+ )
+
return ConversionResult(
output_path=filepath,
mime_type=_guess_mime_type(filepath),
was_converted=False,
was_compressed=False,
original_size=original_size,
- final_size=original_size,
+ final_size=final_size,
original_codec=original_codec,
final_codec=audio_codec
)
diff --git a/src/utils/ffmpeg_utils.py b/src/utils/ffmpeg_utils.py
index 797b7d36..01f70c8e 100644
--- a/src/utils/ffmpeg_utils.py
+++ b/src/utils/ffmpeg_utils.py
@@ -385,6 +385,53 @@ def extract_audio_segment(
_run_ffmpeg_command(cmd, f"Segment extraction from {os.path.basename(input_path)}")
+def remux_mp3_in_place(filepath: str) -> None:
+ """
+ Losslessly remux an MP3 file in place so ffmpeg writes a fresh
+ Xing/Info header (issue #325). No re-encoding: the audio stream is
+ stream-copied, so this is fast and bit-identical, and ID3 metadata
+ carries over. The original file is only replaced after the remux
+ succeeds and produced non-empty output.
+
+ Args:
+ filepath: Path to the MP3 file to repair
+
+ Raises:
+ FFmpegNotFoundError: If FFmpeg is not installed
+ FFmpegError: If the remux fails or produces empty output
+ """
+ # Temp file in the same directory so os.replace() stays atomic
+ # (same filesystem) and inherits the directory's permissions.
+ fd, temp_path = tempfile.mkstemp(
+ suffix='.mp3', dir=os.path.dirname(filepath) or None
+ )
+ os.close(fd)
+ try:
+ cmd = [
+ 'ffmpeg',
+ '-y',
+ '-i', filepath,
+ '-map', '0:a:0',
+ '-c:a', 'copy',
+ '-map_metadata', '0',
+ '-f', 'mp3',
+ temp_path,
+ ]
+ _run_ffmpeg_command(cmd, f"Xing header remux of {os.path.basename(filepath)}")
+
+ if os.path.getsize(temp_path) == 0:
+ raise FFmpegError("MP3 remux produced empty output")
+
+ os.replace(temp_path, filepath)
+ finally:
+ # Only present if the remux failed before os.replace() consumed it
+ if os.path.exists(temp_path):
+ try:
+ os.unlink(temp_path)
+ except OSError:
+ pass
+
+
@contextmanager
def temp_audio_conversion(input_path: str, target_format: str = 'mp3'):
"""
diff --git a/src/utils/ffprobe.py b/src/utils/ffprobe.py
index 0bdcbce0..4cd33105 100644
--- a/src/utils/ffprobe.py
+++ b/src/utils/ffprobe.py
@@ -65,6 +65,47 @@ def probe(filename: str, cmd: str = 'ffprobe', timeout: Optional[int] = None) ->
raise FFProbeError(f'Failed to parse ffprobe output: {e}')
+def mp3_duration_is_estimated(filename: str, timeout: Optional[int] = None) -> bool:
+ """
+ Detect MP3 files whose duration ffmpeg has to estimate from bitrate,
+ i.e. files missing a Xing/Info/VBRI header. Chromium-based browsers
+ stutter when seeking/playing such files (issue #325).
+
+ Runs ffprobe at warning loglevel and checks stderr for the demuxer's
+ "Estimating duration from bitrate" warning — the same signal ffmpeg
+ itself uses, so it stays authoritative across container quirks.
+
+ Args:
+ filename: Path to the MP3 file to check
+ timeout: Optional timeout in seconds
+
+ Returns:
+ True if the duration is estimated (header missing), False otherwise.
+ Returns False on any probe failure — callers treat this as a
+ best-effort repair hint, never a hard gate.
+ """
+ if timeout is None:
+ try:
+ timeout = max(10, int(os.getenv('FFPROBE_TIMEOUT_SECONDS', '60')))
+ except (TypeError, ValueError):
+ timeout = 60
+
+ args = ['ffprobe', '-v', 'warning', '-show_format', '-of', 'json', filename]
+ try:
+ 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 '')
+ except (subprocess.TimeoutExpired, FileNotFoundError, OSError) as e:
+ logger.warning(f"Could not check MP3 duration header for {filename}: {e}")
+ return False
+
+
def get_codec_info(filename: str, timeout: Optional[int] = None) -> Dict[str, Any]:
"""
Get codec information for a media file.
diff --git a/tests/test_mp3_xing_repair.py b/tests/test_mp3_xing_repair.py
new file mode 100644
index 00000000..75a7907b
--- /dev/null
+++ b/tests/test_mp3_xing_repair.py
@@ -0,0 +1,106 @@
+#!/usr/bin/env python3
+"""
+Tests for the MP3 Xing/VBR header repair (issue #325).
+
+MP3s missing a Xing/Info header force ffmpeg (and Chromium's player) to
+estimate duration from bitrate, which causes stuttering playback in
+Chromium-based browsers. Speakr repairs such files with a lossless remux
+when they would otherwise be stored untouched.
+
+These tests exercise real ffmpeg/ffprobe binaries (available in the dev
+container and CI), generating a header-less MP3 via -write_xing 0.
+"""
+
+import os
+import shutil
+import subprocess
+import sys
+import tempfile
+import unittest
+
+sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
+
+from src.app import app
+from src.utils.ffprobe import mp3_duration_is_estimated, get_codec_info
+from src.utils.ffmpeg_utils import remux_mp3_in_place
+from src.utils.audio_conversion import convert_if_needed
+
+
+FFMPEG_AVAILABLE = shutil.which('ffmpeg') is not None and shutil.which('ffprobe') is not None
+
+
+def _generate_mp3(path, write_xing=True, duration=2):
+ """Generate a small sine-wave MP3, optionally without a Xing header."""
+ cmd = [
+ 'ffmpeg', '-v', 'error',
+ '-f', 'lavfi', '-i', f'sine=frequency=440:duration={duration}',
+ '-c:a', 'libmp3lame', '-b:a', '64k',
+ ]
+ if not write_xing:
+ cmd += ['-write_xing', '0']
+ cmd += ['-y', path]
+ subprocess.run(cmd, check=True, capture_output=True, timeout=60)
+
+
[email protected](FFMPEG_AVAILABLE, "ffmpeg/ffprobe not installed")
+class TestMp3XingRepair(unittest.TestCase):
+ def setUp(self):
+ self.ctx = app.app_context()
+ self.ctx.push()
+ self.tmpdir = tempfile.mkdtemp(prefix='xing_test_')
+ self.broken = os.path.join(self.tmpdir, 'broken.mp3')
+ self.good = os.path.join(self.tmpdir, 'good.mp3')
+ _generate_mp3(self.broken, write_xing=False)
+ _generate_mp3(self.good, write_xing=True)
+
+ def tearDown(self):
+ shutil.rmtree(self.tmpdir, ignore_errors=True)
+ self.ctx.pop()
+
+ def test_detects_missing_xing_header(self):
+ self.assertTrue(mp3_duration_is_estimated(self.broken))
+
+ def test_healthy_mp3_not_flagged(self):
+ self.assertFalse(mp3_duration_is_estimated(self.good))
+
+ def test_missing_file_returns_false(self):
+ self.assertFalse(mp3_duration_is_estimated(os.path.join(self.tmpdir, 'nope.mp3')))
+
+ def test_remux_repairs_header_and_preserves_duration(self):
+ before = get_codec_info(self.broken)
+ remux_mp3_in_place(self.broken)
+ self.assertFalse(mp3_duration_is_estimated(self.broken))
+ after = get_codec_info(self.broken)
+ # Still an mp3, duration within a frame or two of the original
+ self.assertEqual(after.get('audio_codec'), 'mp3')
+ self.assertAlmostEqual(
+ float(after.get('duration') or 0),
+ float(before.get('duration') or 0),
+ delta=0.5,
+ )
+ self.assertGreater(os.path.getsize(self.broken), 0)
+
+ def test_remux_leaves_no_temp_files(self):
+ remux_mp3_in_place(self.broken)
+ leftovers = [f for f in os.listdir(self.tmpdir) if f not in ('broken.mp3', 'good.mp3')]
+ self.assertEqual(leftovers, [])
+
+ def test_convert_if_needed_repairs_passthrough_mp3(self):
+ # An mp3 with a supported codec is stored as-is; the passthrough
+ # branch must repair the missing header on the way out.
+ result = convert_if_needed(self.broken, needs_chunking=False, is_asr_endpoint=False)
+ self.assertEqual(result.output_path, self.broken)
+ self.assertFalse(result.was_converted)
+ self.assertFalse(mp3_duration_is_estimated(self.broken))
+
+ def test_convert_if_needed_leaves_healthy_mp3_untouched(self):
+ size_before = os.path.getsize(self.good)
+ mtime_before = os.path.getmtime(self.good)
+ result = convert_if_needed(self.good, needs_chunking=False, is_asr_endpoint=False)
+ self.assertEqual(result.output_path, self.good)
+ self.assertEqual(os.path.getsize(self.good), size_before)
+ self.assertEqual(os.path.getmtime(self.good), mtime_before)
+
+
+if __name__ == "__main__":
+ unittest.main(verbosity=2)