Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions sample.env
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,11 @@ LIBRARY_NAME=
# MIN_BIT_DEPTH=8
# Minimal Bitrate (default: 256)
# MIN_BITRATE=256
# Highest bitrate in kbps to accept, so a single track cannot arrive as a 138 MB
# WAV. Worked out from file size when a peer reports no bitrate, so it applies
# to files that describe themselves and files that do not. 0 disables the
# ceiling. (default: 0)
# MAX_BITRATE=0
# Comma-separated (without spaces) keywords to avoid, when filtering slskd results (default: live,remix,instrumental,extended,clean,acapella)
# FILTER_LIST=live,remix,instrumental,extended,clean,acapella

Expand Down
4 changes: 4 additions & 0 deletions src/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,10 @@ type Filters struct {
Extensions []string `env:"EXTENSIONS" env-default:"flac,mp3"` // slskd
MinBitDepth int `env:"MIN_BIT_DEPTH" env-default:"8"`
MinBitRate int `env:"MIN_BITRATE" env-default:"256"`
// Ceiling in kbps. Zero disables it, so nothing changes on upgrade until
// someone sets one. Compared against a bitrate derived from file size when
// the peer reports none.
MaxBitRate int `env:"MAX_BITRATE" env-default:"0"`
FilterList []string `env:"FILTER_LIST" env-default:"live,remix,instrumental,extended,clean,acapella"`
}

Expand Down
75 changes: 75 additions & 0 deletions src/downloader/quality.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
package downloader

import "strings"

// losslessExtensions are the formats that carry no lossy compression. The
// split matters because it is the line people actually think in when they talk
// about a "small" or a "big" file, far more than any particular bitrate.
var losslessExtensions = map[string]struct{}{
"flac": {},
"wav": {},
"aiff": {},
"aif": {},
"alac": {},
"ape": {},
"wv": {},
}

// isLossless reports whether a file's format is lossless.
func isLossless(file File) bool {
_, ok := losslessExtensions[strings.ToLower(strings.TrimPrefix(file.Extension, "."))]
return ok
}

// effectiveBitRate reports a file's bitrate in kbps.
//
// Soulseek peers often report no bitrate at all, which is why the existing
// quality floors are written to skip a file rather than judge it when BitRate
// is 0. A ceiling cannot be written that way round: skipping the files nobody
// described would let through exactly the ones a ceiling exists to exclude. So
// when the peer says nothing, derive the bitrate from how big the file is and
// how long it plays.
//
// The reported value is preferred where there is one, so files that already
// describe themselves are judged exactly as they were before.
//
// Returns 0 when neither is available, which callers must read as "unknown"
// rather than "zero": an unknown file is never rejected by the ceiling.
func effectiveBitRate(file File) int {
if file.BitRate > 0 {
return file.BitRate
}

if file.Size > 0 && file.Length > 0 {
return file.Size * 8 / file.Length / 1000
}

return 0
}

// withinQualityRange reports whether a file sits inside the configured floor
// and ceiling. A file of unknown bitrate passes: it may well be fine, and
// dropping everything undescribed would throw away most of what Soulseek
// offers.
func (c Slskd) withinQualityRange(file File) bool {
if file.BitDepth > 0 && file.BitDepth < c.Cfg.Filters.MinBitDepth {
return false
}

bitRate := effectiveBitRate(file)
if bitRate == 0 {
return true
}

if c.Cfg.Filters.MinBitRate > 0 && bitRate < c.Cfg.Filters.MinBitRate {
return false
}

// Zero disables the ceiling, so an upgrade changes nothing until someone
// sets one.
if c.Cfg.Filters.MaxBitRate > 0 && bitRate > c.Cfg.Filters.MaxBitRate {
return false
}

return true
}
228 changes: 228 additions & 0 deletions src/downloader/quality_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,228 @@
package downloader

import (
"testing"

cfg "explo/src/config"
"explo/src/models"
)

func TestEffectiveBitRate(t *testing.T) {
tests := []struct {
name string
file File
want int
}{
{
// A file that describes itself is judged exactly as it was before.
name: "reported bitrate wins",
file: File{BitRate: 320, Size: 99_999_999, Length: 200},
want: 320,
},
{
// 210 s of 320 kbps is about 8.4 MB.
name: "derived from size and length when unreported",
file: File{Size: 8_400_000, Length: 210},
want: 320,
},
{
name: "derived for a CD flac",
file: File{Size: 26_000_000, Length: 210},
want: 990,
},
{
name: "unknown without a length",
file: File{Size: 8_400_000},
want: 0,
},
{
name: "unknown without a size",
file: File{Length: 210},
want: 0,
},
}

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got := effectiveBitRate(tt.file)
// Derivation is integer division, so allow a kbps either way.
if got < tt.want-2 || got > tt.want+2 {
t.Errorf("effectiveBitRate(%+v) = %d, want about %d", tt.file, got, tt.want)
}
})
}
}

func TestIsLossless(t *testing.T) {
for _, ext := range []string{"flac", "FLAC", ".flac", "wav", "aiff", "alac"} {
if !isLossless(File{Extension: ext}) {
t.Errorf("isLossless(%q) = false, want true", ext)
}
}
for _, ext := range []string{"mp3", "m4a", "aac", "ogg", ""} {
if isLossless(File{Extension: ext}) {
t.Errorf("isLossless(%q) = true, want false", ext)
}
}
}

func rangeClient(minRate, maxRate int) Slskd {
return Slskd{Cfg: cfg.Slskd{
DownloadAttempts: 10,
Filters: cfg.Filters{
Extensions: []string{"flac", "mp3"},
MinBitRate: minRate,
MaxBitRate: maxRate,
MinBitDepth: 8,
},
}}
}

func TestWithinQualityRange(t *testing.T) {
tests := []struct {
name string
client Slskd
file File
wantIn bool
}{
{"inside the range", rangeClient(192, 320), File{BitRate: 256}, true},
{"below the floor", rangeClient(192, 320), File{BitRate: 128}, false},
{"above the ceiling", rangeClient(192, 320), File{BitRate: 1000}, false},
{"at the ceiling", rangeClient(192, 320), File{BitRate: 320}, true},
{"at the floor", rangeClient(192, 320), File{BitRate: 192}, true},
{
// The default: no ceiling configured, so nothing changes for
// anyone who has not set one.
name: "a zero ceiling rejects nothing",
client: rangeClient(192, 0),
file: File{BitRate: 4608},
wantIn: true,
},
{
// Most of Soulseek reports nothing. Dropping all of it would leave
// almost no candidates.
name: "unknown bitrate passes the ceiling",
client: rangeClient(192, 320),
file: File{},
wantIn: true,
},
{
// Derived from size, so the ceiling reaches files the old
// reported-only checks skipped entirely.
name: "a big unreported file is caught by derivation",
client: rangeClient(192, 320),
file: File{Size: 26_000_000, Length: 210},
wantIn: false,
},
{"bit depth below the floor", rangeClient(0, 0), File{BitDepth: 4, BitRate: 256}, false},
}

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := tt.client.withinQualityRange(tt.file); got != tt.wantIn {
t.Errorf("withinQualityRange(%+v) = %v, want %v", tt.file, got, tt.wantIn)
}
})
}
}

// filterFiles is the single-track path.
func TestFilterFiles_AppliesTheCeiling(t *testing.T) {
client := rangeClient(192, 320)

files := []File{
{Name: "big.flac", Extension: "flac", BitRate: 1000},
{Name: "ok.mp3", Extension: "mp3", BitRate: 320},
}

got, err := client.filterFiles(files)
if err != nil {
t.Fatalf("filterFiles() = %v, want nil", err)
}
if len(got) != 1 || string(got[0].Name) != "ok.mp3" {
t.Errorf("kept %v, want only ok.mp3", got)
}
}

func TestFilterFiles_NoCeilingKeepsEverything(t *testing.T) {
client := rangeClient(192, 0)

files := []File{
{Name: "big.flac", Extension: "flac", BitRate: 4608},
{Name: "ok.mp3", Extension: "mp3", BitRate: 320},
}

got, err := client.filterFiles(files)
if err != nil {
t.Fatalf("filterFiles() = %v, want nil", err)
}
if len(got) != 2 {
t.Errorf("kept %d files, want both", len(got))
}
}

// The album path exempts the recommended track from the quality floors, on the
// grounds that a mediocre entry beats none. The ceiling is a different
// question -- it is about transfer volume -- so the primary must not be exempt
// from it.
func TestQualityFiltered_CeilingAppliesToThePrimaryToo(t *testing.T) {
client := rangeClient(192, 320)

primary := File{Name: "01 primary.flac", Extension: "flac", BitRate: 1000}
dir := peerDir{
files: []File{primary, {Name: "02 sibling.mp3", Extension: "mp3", BitRate: 320}},
primary: &primary,
}

kept := client.qualityFiltered(dir)
for _, f := range kept {
if string(f.Name) == "01 primary.flac" {
t.Error("the primary was kept despite being over the ceiling")
}
}
}

// The floor exemption for the primary has to survive, or album mode loses the
// playlist entry it exists to produce.
func TestQualityFiltered_PrimaryStillExemptFromTheFloor(t *testing.T) {
client := rangeClient(320, 0)

primary := File{Name: "01 primary.mp3", Extension: "mp3", BitRate: 128}
dir := peerDir{
files: []File{primary, {Name: "02 sibling.mp3", Extension: "mp3", BitRate: 128}},
primary: &primary,
}

kept := client.qualityFiltered(dir)
if len(kept) != 1 || string(kept[0].Name) != "01 primary.mp3" {
t.Errorf("kept %v, want just the primary -- it is exempt from the floor, siblings are not", kept)
}
}

// Guard against the album flow silently ignoring the new setting.
func TestCollectAlbumFiles_RespectsTheCeiling(t *testing.T) {
client := rangeClient(0, 320)
client.Cfg.AlbumMode = true

results := albumResults(peer{"peer1", `@@x\Billie Eilish\When We All Fall Asleep`,
[]string{"01 Bury A Friend.flac", "02 Bad Guy.flac"}})
// albumResults leaves BitRate unset, so give the files a size that derives
// well above the ceiling.
for i := range results {
for j := range results[i].Files {
results[i].Files[j].Size = 26_000_000
results[i].Files[j].Length = 210
}
}

track := models.Track{
CleanTitle: "Bad Guy",
Artist: "Billie Eilish",
MainArtist: "Billie Eilish",
Album: "When We All Fall Asleep",
}

if _, err := client.CollectAlbumFiles(track, results); err == nil {
t.Error("CollectAlbumFiles() = nil error, want a failure when every file is over the ceiling")
}
}
6 changes: 1 addition & 5 deletions src/downloader/slskd.go
Original file line number Diff line number Diff line change
Expand Up @@ -337,11 +337,7 @@ func (c Slskd) filterFiles(files []File) ([]File, error) {
continue
}

if file.BitRate > 0 && file.BitRate < c.Cfg.Filters.MinBitRate {
continue
}

if file.BitDepth > 0 && file.BitDepth < c.Cfg.Filters.MinBitDepth {
if !c.withinQualityRange(file) {
continue
}

Expand Down
17 changes: 11 additions & 6 deletions src/downloader/slskd_album.go
Original file line number Diff line number Diff line change
Expand Up @@ -134,15 +134,20 @@ func (c Slskd) qualityFiltered(dir peerDir) []File {
kept := make([]File, 0, len(dir.files))

for _, file := range dir.files {
isPrimary := dir.primary != nil && file.Name == dir.primary.Name
if !isPrimary {
if file.BitRate > 0 && file.BitRate < c.Cfg.Filters.MinBitRate {
continue
}
if file.BitDepth > 0 && file.BitDepth < c.Cfg.Filters.MinBitDepth {
// The ceiling applies to every file including the primary: it is about
// how much gets transferred, not how good the track is, and a single
// oversized primary is exactly what it exists to stop.
if c.Cfg.Filters.MaxBitRate > 0 {
if rate := effectiveBitRate(file); rate > 0 && rate > c.Cfg.Filters.MaxBitRate {
continue
}
}

isPrimary := dir.primary != nil && file.Name == dir.primary.Name
if !isPrimary && !c.withinQualityRange(file) {
continue
}

kept = append(kept, file)
}
return kept
Expand Down
1 change: 1 addition & 0 deletions src/web/backend/defs/defs.go
Original file line number Diff line number Diff line change
Expand Up @@ -180,6 +180,7 @@ var AllConfigKeys = []string{
"SYSTEM_USERNAME", "SYSTEM_PASSWORD", "PLAYLIST_DIR", "SLEEP", "PUBLIC_PLAYLIST",
"DOWNLOAD_DIR", "USE_SUBDIRECTORY", "PATH_TEMPLATE", "ENRICH_TRACK_METADATA",
"DOWNLOAD_SERVICES", "YOUTUBE_API_KEY", "TRACK_EXTENSION", "FILTER_LIST",
"MIN_BITRATE", "MAX_BITRATE",
"SLSKD_URL", "SLSKD_API_KEY", "SLSKD_ALBUM_MODE",
"WIZARD_COMPLETE", "MIGRATE_DOWNLOADS", "EXTENSIONS", "LISTENBRAINZ_USER_TOKEN",
}
Loading
Loading