Describe the bug
Sharing this information just in case it's useful.
Below are my notes concerning how I was able to get it to function as intended. I'm not sure if everyone is having this issue or if for some reason it was specific to me.
Streamrip currently fails to convert downloads into Opus files on Windows environments. The application returns a generic "Error downloading track" message and leaves the unconverted source file (e.g., FLAC) in the directory. An analysis of the converter.py source code reveals three distinct bugs responsible for this failure.
Identified Issues
- Subprocess Execution Failure (
asyncio on Windows): Streamrip utilizes asyncio.create_subprocess_exec to invoke FFmpeg. The default Windows asyncio event loop does not support subprocess operations. This results in a silent NotImplementedError that terminates the Python process before FFmpeg can initialize.
- Incompatible Video Stream Parameter: The base
Converter class passes the -c:v copy argument to FFmpeg to retain embedded album art. The Opus container strictly forbids video streams, causing FFmpeg to instantly abort the conversion. (Note: Streamrip handles Opus album art correctly post-conversion via its tagging module, so this FFmpeg argument is unnecessary for Opus).
- Ignored Bitrate Configuration: The
OPUS class hardcodes a default bitrate of 128k. The get_quality_arg method is programmed to ignore user-defined lossy_bitrate settings from the config file, forcing the default.
The Solution
To resolve these issues, the Converter and OPUS classes within site-packages/streamrip/converter.py must be modified. These changes replace the incompatible asyncio method with Python's native subprocess module, strip the -c:v copy flag specifically for Opus files, and properly format the bitrate argument.
1. Replace the base Converter class:
class Converter:
"""Base class for audio codecs."""
codec_name: str
codec_lib: str
container: str
lossless: bool = False
default_ffmpeg_arg: str = ""
def __init__(
self,
filename: str,
ffmpeg_arg: Optional[str] = None,
sampling_rate: Optional[int] = None,
bit_depth: Optional[int] = None,
copy_art: bool = True,
remove_source: bool = False,
show_progress: bool = False,
):
if shutil.which("ffmpeg") is None:
raise Exception(
"Could not find FFMPEG executable. Install it to convert audio files.",
)
self.filename = filename
self.final_fn = f"{os.path.splitext(filename)[0]}.{self.container}"
self.tempfile = os.path.join(gettempdir(), os.path.basename(self.final_fn))
self.remove_source = remove_source
self.sampling_rate = sampling_rate
self.bit_depth = bit_depth
self.copy_art = copy_art
self.show_progress = show_progress
if ffmpeg_arg is None:
logger.debug("No arguments provided. Codec defaults will be used")
self.ffmpeg_arg = self.default_ffmpeg_arg
else:
self.ffmpeg_arg = ffmpeg_arg
self._is_command_valid()
logger.debug("FFmpeg codec extra argument: %s", self.ffmpeg_arg)
async def convert(self, custom_fn: Optional[str] = None):
"""Convert the file."""
import os
import subprocess
import shutil
if custom_fn:
self.final_fn = custom_fn
self.command = self._gen_command()
self.command[0] = shutil.which("ffmpeg") or "ffmpeg"
try:
process = subprocess.run(
self.command,
capture_output=True
)
if process.returncode == 0 and os.path.isfile(self.tempfile):
if self.remove_source:
os.remove(self.filename)
shutil.move(self.tempfile, self.final_fn)
else:
raise ConversionError(f"FFmpeg failed:\n{process.stderr.decode('utf-8', errors='ignore') if process.stderr else 'No output'}")
except Exception as e:
raise ConversionError(f"Python subprocess crashed:\n{repr(e)}")
def _gen_command(self):
command = [
"ffmpeg",
"-nostdin",
"-i",
self.filename,
]
if logger.getEffectiveLevel() != logging.DEBUG:
command.extend(("-loglevel", "panic"))
command.extend(("-c:a", self.codec_lib))
if self.show_progress:
command.append("-stats")
if self.copy_art and self.container != "opus":
command.extend(["-c:v", "copy"])
else:
command.append("-vn")
if self.ffmpeg_arg:
command.extend(self.ffmpeg_arg.split())
if self.lossless:
aformat = []
if isinstance(self.sampling_rate, int):
sample_rates = "|".join(
str(rate) for rate in SAMPLING_RATES if rate <= self.sampling_rate
)
aformat.append(f"sample_rates={sample_rates}")
elif self.sampling_rate is not None:
raise TypeError(
f"Sampling rate must be int, not {type(self.sampling_rate)}"
)
if isinstance(self.bit_depth, int):
bit_depths = ["s16p", "s16"]
if self.bit_depth in (24, 32):
bit_depths.extend(["s32p", "s32"])
elif self.bit_depth != 16:
raise ValueError("Bit depth must be 16, 24, or 32")
sample_fmts = "|".join(bit_depths)
aformat.append(f"sample_fmts={sample_fmts}")
elif self.bit_depth is not None:
raise TypeError(f"Bit depth must be int, not {type(self.bit_depth)}")
if aformat:
aformat_params = ":".join(aformat)
command.extend(["-af", f"aformat={aformat_params}"])
command.extend(["-y", self.tempfile])
logger.debug(command)
return command
def _is_command_valid(self):
if self.ffmpeg_arg is not None and self.lossless:
logger.debug(
"Lossless codecs don't support extra arguments; "
"the extra argument will be ignored",
)
self.ffmpeg_arg = self.default_ffmpeg_arg
return
2. Replace the OPUS class:
class OPUS(Converter):
"""Class for libopus."""
codec_name = "opus"
codec_lib = "libopus"
container = "opus"
default_ffmpeg_arg = "-b:a 192k"
def get_quality_arg(self, rate: int) -> str:
return f"-b:a {rate}k"
Note: The AAC class in the same file suffers from the same hardcoded bitrate bug and can be fixed by applying the identical get_quality_arg modification.
Command Used
Any rip (while config is set to OPUS)
Debug Traceback
Would show "error downloading track" generic error when time to convert
Config File
[downloads]
# Folder where tracks are downloaded to
folder = "F:\\#TO TRANSFER\\Audio"
# Put Qobuz albums in a 'Qobuz' folder, Tidal albums in 'Tidal' etc.
source_subdirectories = false
# Put tracks in an album with 2 or more discs into a subfolder named `Disc N`
disc_subdirectories = true
# Download (and convert) tracks all at once, instead of sequentially.
# If you are converting the tracks, or have fast internet, this will
# substantially improve processing speed.
concurrency = true
# The maximum number of tracks to download at once
# If you have very fast internet, you will benefit from a higher value,
# A value that is too high for your bandwidth may cause slowdowns
# Set to -1 for no limit
max_connections = -1
# Max number of API requests per source to handle per minute
# Set to -1 for no limit
requests_per_minute = 60
# Verify SSL certificates for API connections
# Set to false if you encounter SSL certificate verification errors (not recommended)
verify_ssl = true
[qobuz]
# 1: 320kbps MP3, 2: 16/44.1, 3: 24/<=96, 4: 24/>=96
quality = 3
# This will download booklet pdfs that are included with some albums
download_booklets = true
# Authenticate to Qobuz using auth token? Value can be true/false only
use_auth_token = false
# Enter your userid if the above use_auth_token is set to true, else enter your email
email_or_userid = ""
# Enter your auth token if the above use_auth_token is set to true, else enter the md5 hash of your plaintext password
password_or_token = ""
# Do not change
app_id = ""
# Do not change
secrets = []
[tidal]
# 0: 256kbps AAC, 1: 320kbps AAC, 2: 16/44.1 "HiFi" FLAC, 3: 24/44.1 "MQA" FLAC
quality = 3
# This will download videos included in Video Albums.
download_videos = true
# Do not change any of the fields below
user_id = ""
country_code = ""
access_token = ""
refresh_token = ""
# Tokens last 1 week after refresh. This is the Unix timestamp of the expiration
# time. If you haven't used streamrip in more than a week, you may have to log
# in again using `rip config --tidal`
token_expiry = ""
[deezer]
# 0, 1, or 2
# This only applies to paid Deezer subscriptions. Those using deezloader
# are automatically limited to quality = 1
quality = 2
# An authentication cookie that allows streamrip to use your Deezer account
# See https://github.com/nathom/streamrip/wiki/Finding-Your-Deezer-ARL-Cookie
# for instructions on how to find this
arl = "[REDACTED ARL]"
# This allows for free 320kbps MP3 downloads from Deezer
# If an arl is provided, deezloader is never used
use_deezloader = true
# This warns you when the paid deezer account is not logged in and rip falls
# back to deezloader, which is unreliable
deezloader_warnings = true
[soundcloud]
# Only 0 is available for now
quality = 0
# This changes periodically, so it needs to be updated
client_id = ""
app_version = ""
[youtube]
# Only 0 is available for now
quality = 0
# Download the video along with the audio
download_videos = false
# The path to download the videos to
video_downloads_folder = "C:\\Users\\Steven\\StreamripDownloads\\YouTubeVideos"
[database]
# Create a database that contains all the track IDs downloaded so far
# Any time a track logged in the database is requested, it is skipped
# This can be disabled temporarily with the --no-db flag
downloads_enabled = true
# Path to the downloads database
downloads_path = "C:\\Users\\Steven\\AppData\\Roaming\\streamrip\\downloads.db"
# If a download fails, the item ID is stored here. Then, `rip repair` can be
# called to retry the downloads
failed_downloads_enabled = true
failed_downloads_path = "C:\\Users\\Steven\\AppData\\Roaming\\streamrip\\failed_downloads.db"
# Convert tracks to a codec after downloading them.
[conversion]
enabled = true
# FLAC, ALAC, OPUS, MP3, VORBIS, or AAC
codec = "OPUS"
# In Hz. Tracks are downsampled if their sampling rate is greater than this.
# Value of 48000 is recommended to maximize quality and minimize space
sampling_rate = 48000
# Only 16 and 24 are available. It is only applied when the bit depth is higher
# than this value.
bit_depth = 24
# Only applicable for lossy codecs
lossy_bitrate = 192
# Filter a Qobuz artist's discography. Set to 'true' to turn on a filter.
# This will also be applied to other sources, but is not guaranteed to work correctly
[qobuz_filters]
# Remove Collectors Editions, live recordings, etc.
extras = false
# Picks the highest quality out of albums with identical titles.
repeats = false
# Remove EPs and Singles
non_albums = false
# Remove albums whose artist is not the one requested
features = false
# Skip non studio albums
non_studio_albums = false
# Only download remastered albums
non_remaster = false
[artwork]
# Write the image to the audio file
embed = true
# The size of the artwork to embed. Options: thumbnail, small, large, original.
# "original" images can be up to 30MB, and may fail embedding.
# Using "large" is recommended.
embed_size = "large"
# If this is set to a value > 0, max(width, height) of the embedded art will be set to this value in pixels
# Proportions of the image will remain the same
embed_max_width = -1
# Save the cover image at the highest quality as a seperate jpg file
save_artwork = true
# If this is set to a value > 0, max(width, height) of the saved art will be set to this value in pixels
# Proportions of the image will remain the same
saved_max_width = -1
[metadata]
# Sets the value of the 'ALBUM' field in the metadata to the playlist's name.
# This is useful if your music library software organizes tracks based on album name.
set_playlist_to_album = true
# If part of a playlist, sets the `tracknumber` field in the metadata to the track's
# position in the playlist instead of its position in its album
renumber_playlist_tracks = true
# The following metadata tags won't be applied
# See https://github.com/nathom/streamrip/wiki/Metadata-Tag-Names for more info
exclude = []
# Changes the folder and file names generated by streamrip.
[filepaths]
# Create folders for single tracks within the downloads directory using the folder_format
# template
add_singles_to_folder = false
# Available keys: "albumartist", "title", "year", "bit_depth", "sampling_rate",
# "id", and "albumcomposer"
folder_format = "{albumartist} - {title} ({year}) [{container}] [{bit_depth}B-{sampling_rate}kHz]"
# Available keys: "tracknumber", "artist", "albumartist", "composer", "title",
# and "albumcomposer", "explicit"
track_format = "{tracknumber:02}. {artist} - {title}{explicit}"
# Only allow printable ASCII characters in filenames.
restrict_characters = false
# Truncate the filename if it is greater than this number of characters
# Setting this to false may cause downloads to fail on some systems
truncate_to = 120
# Last.fm playlists are downloaded by searching for the titles of the tracks
[lastfm]
# The source on which to search for the tracks.
source = "qobuz"
# If no results were found with the primary source, the item is searched for
# on this one.
fallback_source = ""
[cli]
# Print "Downloading {Album name}" etc. to screen
text_output = true
# Show resolve, download progress bars
progress_bars = true
# The maximum number of search results to show in the interactive menu
max_search_results = 100
[misc]
# Metadata to identify this config file. Do not change.
version = "2.0.6"
# Print a message if a new version of streamrip is available
check_for_updates = true
Operating System
Windows 11
streamrip version
2.1.0
Screenshots and recordings
No response
Additional context
No response
Describe the bug
Sharing this information just in case it's useful.
Below are my notes concerning how I was able to get it to function as intended. I'm not sure if everyone is having this issue or if for some reason it was specific to me.
Streamrip currently fails to convert downloads into Opus files on Windows environments. The application returns a generic "Error downloading track" message and leaves the unconverted source file (e.g., FLAC) in the directory. An analysis of the
converter.pysource code reveals three distinct bugs responsible for this failure.Identified Issues
asyncioon Windows): Streamrip utilizesasyncio.create_subprocess_execto invoke FFmpeg. The default Windowsasyncioevent loop does not support subprocess operations. This results in a silentNotImplementedErrorthat terminates the Python process before FFmpeg can initialize.Converterclass passes the-c:v copyargument to FFmpeg to retain embedded album art. The Opus container strictly forbids video streams, causing FFmpeg to instantly abort the conversion. (Note: Streamrip handles Opus album art correctly post-conversion via its tagging module, so this FFmpeg argument is unnecessary for Opus).OPUSclass hardcodes a default bitrate of 128k. Theget_quality_argmethod is programmed to ignore user-definedlossy_bitratesettings from the config file, forcing the default.The Solution
To resolve these issues, the
ConverterandOPUSclasses withinsite-packages/streamrip/converter.pymust be modified. These changes replace the incompatibleasynciomethod with Python's nativesubprocessmodule, strip the-c:v copyflag specifically for Opus files, and properly format the bitrate argument.1. Replace the base
Converterclass:2. Replace the
OPUSclass:Command Used
Any rip (while config is set to OPUS)Debug Traceback
Config File
Operating System
Windows 11
streamrip version
2.1.0
Screenshots and recordings
No response
Additional context
No response