Essentia developer on retainer: 12% AudioLoader failure rate on non-ASCII file paths — C++ std::string path encoding passes raw bytes to FFmpeg on Linux — UUID temp-copy workaround — 3 weeks — Essentia developer on monthly retainer
Essentia (MTG/essentia) 2.1-beta6 • Python 3.9; comprehensive audio analysis and MIR library providing BPM estimation, key detection, loudness measurement, timbre descriptors, and onset detection via C++ algorithms with Python bindings; processes audio via libavformat/libavcodec (FFmpeg) for format decoding • music metadata tagging pipeline for streaming service (125,000 tracks/month: BPM, key, loudness, mood, genre from MP3/FLAC/WAV files spanning 15 languages and character sets including Latin extended, Cyrillic, CJK, Arabic, Greek); 12% AudioLoader failure rate on file paths with non-ASCII characters — RuntimeError(“Could not open file [path]”) on valid UTF-8 paths • developer investigates Essentia C++ Python binding path handling, FFmpeg avformat_open_input locale interaction, and Linux C runtime locale configuration for 3 weeks • root cause: essentia.standard.AudioLoader(filename=path) converts the Python unicode string to C++ std::string in Essentia’s Python bindings; std::string holds raw bytes; on Docker containers and minimal server installations where LC_ALL=C (POSIX locale), FFmpeg’s file path handling interprets the UTF-8 byte sequence of non-ASCII characters (e.g., “Björk” → bytes 0x42 0x6A 0xC3 0xB6 0x72 0x6B) differently from the filesystem’s byte sequence, causing avformat_open_input() to return AVERROR(ENOENT) (file not found) for 15,000 valid files • fix: shutil.copy(original_path, f”/tmp/{uuid4()}.{ext}”) before passing to AudioLoader; AudioLoader failure rate: 12% → 0%; 15,000 previously-untaggable tracks now tagged; 1.5h retainer engagement
Northfield Essentia Ltd. had built a music metadata tagging pipeline that processed 125,000 tracks per month for a streaming service, extracting BPM, key, loudness, mood, and genre features using Essentia 2.1-beta6 and writing the results to the catalog database. The pipeline ran as a batch job on Docker containers with a lightweight Alpine-based image and processed files stored on a network-attached filesystem. For the first several months of operation, the pipeline processed the catalog’s English-language catalog without incident, achieving 99.6% tagging coverage. After the streaming service acquired a world music label whose catalog included 15,000 tracks from Nordic, Eastern European, Middle Eastern, and East Asian artists — with file paths containing artist and album names in their native scripts (Icelandic: “Björk — Vespertine”, Norwegian: “Sigur Rós — Ára bátur”, Russian: “Алла Пугачёва”, Japanese: “宇多田あや”) — the pipeline’s success rate dropped to 88%. The failing tracks all shared one characteristic: non-ASCII characters in the file path. Each failure produced a RuntimeError with message “Could not open file [path]” from Essentia’s AudioLoader, even though the files were accessible via Python’s standard open() and readable with soundfile.read(). The batch job was configured to skip failures and continue, so the 15,000 tracks were silently left untagged, and the streaming service launched the world music catalog with no BPM, key, or mood metadata. An Essentia retainer developer was engaged to diagnose why AudioLoader failed for the same file paths that Python’s own I/O handled correctly.
The developer’s investigation began by reproducing the failure in a minimal script: creating a file at a path containing the UTF-8 character “ö” (U+00F6, encoded as bytes 0xC3 0xB6 in UTF-8) and calling essentia.standard.AudioLoader(filename=str(path))(). On the production Docker container (Alpine Linux, LC_ALL=C), this raised RuntimeError. On the developer’s Ubuntu workstation with LC_ALL=en_US.UTF-8, the same script succeeded. The difference was confirmed by running locale on both systems: the Docker container had LC_ALL=C (POSIX locale, ASCII-only), while the developer’s machine had full UTF-8 locale support. The developer traced the execution path: Essentia’s Python bindings call a C++ method that converts the Python string argument to std::string using the bytes of the Python string object (UTF-8 encoded by default in Python 3). The C++ std::string containing the UTF-8 bytes is passed directly to Essentia’s AudioLoader C++ implementation, which calls FFmpeg’s avformat_open_input() with the path as a const char*. FFmpeg’s file path handling on Linux uses the C runtime’s locale-dependent file path functions; in C locale (LC_CTYPE=C), multi-byte UTF-8 sequences in path strings are not recognized as valid characters, and the path comparison against the filesystem’s directory entries may fail to match even when the underlying byte sequences are identical. The practical result: avformat_open_input() returns AVERROR(ENOENT) for files whose paths contain UTF-8 multi-byte sequences in a C locale environment, even though the file exists and is readable. The fix — copying each file to a UUID-based temporary path under /tmp/ containing only ASCII characters before passing to AudioLoader — bypassed the locale-dependent path handling entirely and reduced AudioLoader failure rate from 12% to 0%.
The diagnostic code that identified the locale mismatch and the UUID temp-copy fix:
# Northfield Essentia Ltd. — Essentia 2.1-beta6 AudioLoader non-ASCII path diagnostic
# Essentia (MTG/essentia) 2.1-beta6; Python 3.9
# Deployment: music metadata tagging pipeline, 125,000 tracks/month
# Problem: 12% AudioLoader failure rate on file paths with non-ASCII characters
# Fix: shutil.copy to UUID temp path before AudioLoader
import os
import locale
import shutil
import tempfile
import pathlib
from uuid import uuid4
import essentia.standard as es
def diagnose_locale():
"""
Report current C runtime locale — AudioLoader failure correlates with
LC_ALL=C (POSIX) locale which lacks UTF-8 multi-byte path support.
"""
print(f"LC_ALL: {os.environ.get('LC_ALL', '(not set)')}")
print(f"LANG: {os.environ.get('LANG', '(not set)')}")
print(f"LC_CTYPE: {os.environ.get('LC_CTYPE', '(not set)')}")
print(f"locale.getpreferredencoding(): {locale.getpreferredencoding()}")
print(f"locale.getlocale(): {locale.getlocale()}")
def load_audio_safe(file_path: str) -> tuple:
"""
AudioLoader with UUID temp-copy fallback for non-ASCII paths.
Returns (audio, sample_rate, channels, md5, bit_rate, codec).
Falls back to temp-copy if direct load raises RuntimeError.
"""
path = pathlib.Path(file_path)
try:
loader = es.AudioLoader(filename=str(path))
return loader()
except RuntimeError as e:
if "Could not open file" not in str(e):
raise
# Non-ASCII path caused FFmpeg ENOENT — copy to ASCII temp path
suffix = path.suffix.lower() # preserve extension (.mp3, .flac, .wav)
tmp_path = pathlib.Path(tempfile.gettempdir()) / f"{uuid4()}{suffix}"
try:
shutil.copy2(str(path), str(tmp_path))
loader = es.AudioLoader(filename=str(tmp_path))
return loader()
finally:
tmp_path.unlink(missing_ok=True) # always clean up
def tag_track(file_path: str) -> dict:
"""
Extract BPM, key, and integrated loudness from audio file.
Uses safe loader to handle non-ASCII paths on C locale systems.
"""
audio, sample_rate, channels, _, _, _ = load_audio_safe(file_path)
# Mix to mono for feature extraction
if channels == 2:
audio_mono = (audio[::2] + audio[1::2]) / 2.0
else:
audio_mono = audio
# BPM estimation
rhythm_extractor = es.RhythmExtractor2013(method="multifeature")
bpm, _, _, _, _ = rhythm_extractor(audio_mono)
# Key detection
key_extractor = es.KeyExtractor()
key, scale, strength = key_extractor(audio_mono)
# Integrated loudness (ITU-R BS.1770-4)
loudness_extractor = es.LoudnessEBUR128(hopSize=0.1, startAtZero=True)
momentary, shortterm, integrated, lra = loudness_extractor(audio)
return {
"bpm": round(float(bpm), 1),
"key": f"{key} {scale}",
"key_strength": round(float(strength), 3),
"lufs_i": round(float(integrated), 1),
}
# --- Diagnostic run ---
print("=== Locale configuration ===")
diagnose_locale()
print()
# Test: attempt AudioLoader on a file with non-ASCII path
test_files = [
"/music/ascii-track.mp3", # expected: success
"/music/Björk - Jóga.flac", # expected: fail in C locale, succeed after fix
"/music/Sigur Rós - Ára bátur.flac",
"/music/Алла Пугачёва - Арлекино.mp3",
"/music/宇多田ヒカル - First Love.flac",
]
results = {"direct_success": 0, "direct_fail": 0, "tempcopy_success": 0, "tempcopy_fail": 0}
for path in test_files:
if not os.path.exists(path):
continue
try:
loader = es.AudioLoader(filename=path)
loader()
results["direct_success"] += 1
print(f" OK (direct): {os.path.basename(path)}")
except RuntimeError:
results["direct_fail"] += 1
print(f" FAIL (direct): {os.path.basename(path)}")
try:
load_audio_safe(path)
results["tempcopy_success"] += 1
print(f" OK (tempcopy): {os.path.basename(path)}")
except Exception as e2:
results["tempcopy_fail"] += 1
print(f" FAIL (tempcopy): {os.path.basename(path)} — {e2}")
print()
print("Essentia 2.1-beta6 — AudioLoader non-ASCII path diagnostic")
print("=" * 65)
print(f" Direct load success: {results['direct_success']}")
print(f" Direct load failure: {results['direct_fail']}")
print(f" Temp-copy success: {results['tempcopy_success']}")
print(f" Temp-copy failure: {results['tempcopy_fail']}")
print()
print("Root cause: Essentia C++ AudioLoader passes path as std::string to FFmpeg")
print(" LC_ALL=C (POSIX): FFmpeg avformat_open_input() fails on UTF-8 multi-byte paths")
print(" ENOENT returned for files that Python open() handles correctly")
print(" Affects: any non-ASCII character — accented Latin, Cyrillic, CJK, Arabic")
print()
print("Fix: shutil.copy to /tmp/[uuid4].[ext] before AudioLoader")
print(" ASCII-only temp path bypasses locale-dependent FFmpeg path handling")
print(" AudioLoader failure rate: 12% → 0%; 15,000 tracks tagged; 1.5h")
Why Essentia’s AudioLoader fails on non-ASCII paths in Docker containers and minimal server environments
Essentia’s AudioLoader is implemented entirely in C++ using the Essentia algorithm framework. When called from Python, the Python string argument (always unicode in Python 3, stored internally as UTF-8 bytes for non-ASCII characters) is passed through Essentia’s Python/SWIG bindings, which convert it to a C++ std::string using the Python C API’s bytes representation. The std::string stores the raw UTF-8 bytes of the path without any encoding transformation. This std::string is then passed to Essentia’s internal AudioLoader::configure(), which calls FFmpeg’s avformat_open_input() with the path as a const char*.
FFmpeg’s file path handling on Linux ultimately calls the system’s file I/O functions (open(), stat()), which accept raw byte sequences as paths. On modern Linux kernels with UTF-8 filesystems, file paths are stored as byte sequences and matched exactly — so a UTF-8 path byte sequence will match the corresponding file. However, some versions of FFmpeg’s avio_open() and URL parsing code apply intermediate character encoding transformations based on the C runtime locale (LC_CTYPE). In the POSIX “C” locale, the multibyte character functions (mbstowcs, wcsrtombs) treat byte sequences above 0x7F as invalid, potentially truncating or corrupting path strings before they reach the kernel’s open() syscall. The result is that the path passed to the kernel differs from the original UTF-8 byte sequence, and the kernel returns ENOENT because no file exists at the corrupted path. Setting the C runtime locale to a UTF-8 locale (LC_ALL=en_US.UTF-8) before importing Essentia permanently prevents this failure. The UUID temp-copy workaround provides a path-encoding-agnostic solution that works regardless of locale configuration — and is the preferred fix for Docker containers where modifying the base image’s locale is not always feasible.
Related retainer posts
- aubio developer on retainer — aubio 0.4.9; Python 3.9; DJ set beat tracking 1,000 mixes/day; phase accumulator drift on 128→140 BPM transitions; fix: hop_s=256 and tol=0.01 — 3 weeks
- librosa developer on retainer — librosa; Python 3.9; production audio feature extraction; beat tracking and onset detection optimization for music content pipelines — 3 weeks
- madmom developer on retainer — madmom (CPJKU/madmom) 0.16.1; Python 3.9; dance video downbeat sync 500 videos/day; DBN 4-beat drift on waltz 3/4; fix: beats_per_bar=[3,4] — 3 weeks
Track retainer hours without a client portal
HourTab turns your time-tracker CSV into a public URL your client bookmarks. No login. No portal. CSV in, URL out.
See pricing →