Commit f2a1dce8 authored by Aryan Noshirvnai's avatar Aryan Noshirvnai

Fix the real "can't sync to MPEG frame" cause: mutagen, not ffmpeg

The previous fix (permissive ffmpeg retry on CouldntDecodeError) never
actually applied to this case - confirmed via the full traceback this time
(added logger.exception in the prior commit, which paid off immediately):
the failing file had a .mp3 extension, so it took the "already mp3, just
copy" fast path entirely, skipping ffmpeg. The actual failure was
mutagen.mp3.HeaderNotFoundError inside MP3(mp3_file_path, ID3=ID3) - a
.mp3 extension doesn't guarantee mutagen's strict frame-sync scanner can
parse the content.

Now: if that direct-copy fast path produces something mutagen can't read,
re-encode through the same permissive ffmpeg fallback (which sniffs actual
content, not the extension) and retry once. If even that fails, raises the
same AudioDecodeError as before for a clean user-facing message instead of
a raw mutagen exception.

Added tests/test_audio_processing.py with two real (not mocked) cases:
real WAV audio misnamed as .mp3 (exercises the actual recovery path with
real audio content) and pure random bytes (confirms genuinely unrecoverable
input still fails cleanly via AudioDecodeError, not a raw exception).
Co-Authored-By: 's avatarClaude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019i3NAUkLkHNbsPg5vKfzF9
parent 2cb2e5a1
Pipeline #1041 passed with stage
in 9 minutes and 10 seconds
...@@ -4,7 +4,7 @@ import shutil ...@@ -4,7 +4,7 @@ import shutil
import aiohttp import aiohttp
from pydub import AudioSegment from pydub import AudioSegment
from pydub.exceptions import CouldntDecodeError from pydub.exceptions import CouldntDecodeError
from mutagen.mp3 import MP3 from mutagen.mp3 import MP3, HeaderNotFoundError
from mutagen.id3 import ID3, APIC, USLT, TIT2, TPE1, TALB, TDRC, TCON, TRCK, error from mutagen.id3 import ID3, APIC, USLT, TIT2, TPE1, TALB, TDRC, TCON, TRCK, error
from src.core.config import logger from src.core.config import logger
...@@ -57,8 +57,23 @@ async def tag_and_convert_audio(raw_file_path: str, candidate: dict) -> str: ...@@ -57,8 +57,23 @@ async def tag_and_convert_audio(raw_file_path: str, candidate: dict) -> str:
logger.error(f"Standard decode failed, retrying with permissive ffmpeg flags: {e}") logger.error(f"Standard decode failed, retrying with permissive ffmpeg flags: {e}")
await _convert_with_permissive_ffmpeg(raw_file_path, mp3_file_path) await _convert_with_permissive_ffmpeg(raw_file_path, mp3_file_path)
# 2. Add ID3 Tags # 2. Add ID3 tags. A ".mp3" extension doesn't guarantee mutagen can actually parse the
# file - the fast-path copy above trusts the extension blindly, but garbage-prefixed/
# malformed real-world files (or a differently-encoded file just renamed to .mp3) can
# still fail here with "can't sync to MPEG frame" even though step 1 skipped ffmpeg
# entirely for them. Re-encode through the same permissive ffmpeg fallback and retry
# once before giving up - this is the actual case a real upload hit (confirmed via the
# traceback: HeaderNotFoundError here, not a CouldntDecodeError from step 1 at all).
try:
mp3 = MP3(mp3_file_path, ID3=ID3) mp3 = MP3(mp3_file_path, ID3=ID3)
except HeaderNotFoundError as e:
logger.error(f"Copied file isn't valid MP3 despite its extension, re-encoding: {e}")
await _convert_with_permissive_ffmpeg(raw_file_path, mp3_file_path)
try:
mp3 = MP3(mp3_file_path, ID3=ID3)
except HeaderNotFoundError as e2:
raise AudioDecodeError(str(e2)) from e2
try: mp3.add_tags() try: mp3.add_tags()
except error: pass except error: pass
......
import asyncio
import os
import shutil
import tempfile
import pytest
from src.services.audio_processing import AudioDecodeError, tag_and_convert_audio
FIXTURES_DIR = os.path.join(os.path.dirname(__file__), "fixtures")
CANDIDATE = {"title": "Test Title", "artist": "Test Artist"}
def test_recovers_real_audio_misnamed_as_mp3():
"""The actual bug this regresses: a file whose content isn't a valid MP3 despite its
.mp3 extension (a real production case - confirmed via a live traceback showing
mutagen.mp3.HeaderNotFoundError, not a pydub decode failure) should still get tagged
successfully by falling back to ffmpeg re-encoding, not 500 the whole request."""
with tempfile.TemporaryDirectory() as tmpdir:
# Real WAV audio content, but named .mp3 - mutagen's strict MP3 frame scanner can't
# find an MPEG sync in WAV data, so this exercises the real fallback path rather than
# a fake/mocked failure.
misnamed_path = os.path.join(tmpdir, "upload.mp3")
shutil.copyfile(os.path.join(FIXTURES_DIR, "tone.wav"), misnamed_path)
final_path = asyncio.run(tag_and_convert_audio(misnamed_path, CANDIDATE))
assert os.path.exists(final_path)
assert os.path.getsize(final_path) > 0
def test_raises_clean_error_for_genuinely_unrecoverable_file():
"""Pure random bytes have no real audio signal for even the permissive ffmpeg fallback to
recover - should fail with AudioDecodeError (caught upstream for a clean user-facing
message), not propagate a raw mutagen/ffmpeg exception."""
with tempfile.TemporaryDirectory() as tmpdir:
garbage_path = os.path.join(tmpdir, "upload.mp3")
with open(garbage_path, "wb") as f:
f.write(os.urandom(4096))
with pytest.raises(AudioDecodeError):
asyncio.run(tag_and_convert_audio(garbage_path, CANDIDATE))
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment