Skip to content

Openverse is a search engine for openly-licensed media. This monorepo includes all application code.

Handle silent audio and missing durations in waveform generation (#5852)

Anand Rajaramc2fd0d01f9d3
diff --git a/api/api/utils/waveform.py b/api/api/utils/waveform.py
index 57329841c..292196e7e 100644
--- a/api/api/utils/waveform.py
+++ b/api/api/utils/waveform.py
@@ -100,6 +100,15 @@ def generate_waveform(file_name: str, duration: int):
logger.debug("waveform_generation_started")
+ if duration is None or duration <= 0:
+ # ``duration`` is nullable on the model and is used as a divisor below.
+ logger.error(
+ "waveform_generation_invalid_duration",
+ file_name=file_name,
+ duration=duration,
+ )
+ raise WaveformGenerationFailure("Audio duration is missing or invalid.")
+
# Determine the width of the waveform based on the duration of the audio.
# The width varies to improve the appearance and "resolution" of the waveform.
# It also prevents requesting to many points from short audio files.
@@ -163,7 +172,9 @@ def process_waveform_output(json_out):
transformed_data.append(val)
if val > max_val:
max_val = val
- transformed_data = [round(val / max_val, 5) for val in transformed_data]
+ if max_val > 0:
+ transformed_data = [round(val / max_val, 5) for val in transformed_data]
+ # Otherwise the audio is silent and every peak is already 0.
logger.debug(
f"finished transformation len(transformed_data)={len(transformed_data)}"
)
diff --git a/api/test/unit/utils/test_waveform.py b/api/test/unit/utils/test_waveform.py
index 1bb538829..a0cb72139 100644
--- a/api/test/unit/utils/test_waveform.py
+++ b/api/test/unit/utils/test_waveform.py
@@ -4,7 +4,13 @@ from pathlib import Path
import pook
import pytest
-from api.utils.waveform import UA_STRING, download_audio, generate_waveform
+from api.utils.waveform import (
+ UA_STRING,
+ WaveformGenerationFailure,
+ download_audio,
+ generate_waveform,
+ process_waveform_output,
+)
_MOCK_AUDIO_PATH = Path(__file__).parent / ".." / ".." / "factory"
@@ -44,3 +50,23 @@ def test_generate_waveform(audio, duration):
json_out = generate_waveform(file_name, duration)
assert len(json_out) > 0
+
+
[email protected]("duration", [0, -1, None])
+def test_generate_waveform_rejects_invalid_duration(duration):
+ file_name = str(_MOCK_AUDIO_PATH.joinpath("sample-audio.mp3"))
+
+ with pytest.raises(WaveformGenerationFailure):
+ generate_waveform(file_name, duration)
+
+
+def test_process_waveform_output_normalizes_peaks():
+ json_out = {"data": [-2, 2, -4, 4, -1, -1]}
+
+ assert process_waveform_output(json_out) == [0.5, 1.0, 0]
+
+
+def test_process_waveform_output_handles_silent_audio():
+ json_out = {"data": [0, 0, 0, 0, 0, 0]}
+
+ assert process_waveform_output(json_out) == [0, 0, 0]