diff --git a/.github/workflows/android-card-ui.yml b/.github/workflows/android-card-ui.yml index 06c8143d..ae8d34ea 100644 --- a/.github/workflows/android-card-ui.yml +++ b/.github/workflows/android-card-ui.yml @@ -77,7 +77,7 @@ jobs: adb shell pm disable-user --user 0 com.google.android.apps.messaging sleep 10 set +e - python3 tools/run_android_emulator_tests.py --output test-output/android-card-ui --classes cloud.gitwide.ampverse.CardUiDeviceTest,cloud.gitwide.ampverse.CleanUiDeviceTest,cloud.gitwide.ampverse.RadioOfflineTest,cloud.gitwide.ampverse.IncrementalSyncDeviceTest,cloud.gitwide.ampverse.PhoneListeningDeviceTest,cloud.gitwide.ampverse.DjLoadPadsDeviceTest,cloud.gitwide.ampverse.AudioFeatureDeviceTest,cloud.gitwide.ampverse.CastBadgeLayoutDeviceTest,cloud.gitwide.ampverse.RemoteDiscoveryDeviceTest,cloud.gitwide.ampverse.DiscoveryDeviceTest,cloud.gitwide.ampverse.RemoteTaskCardsDeviceTest,cloud.gitwide.ampverse.LabNavigationDeviceTest,cloud.gitwide.ampverse.lab.EditingSessionTest,cloud.gitwide.ampverse.ModuleBadgesDeviceTest,cloud.gitwide.ampverse.LibrarySyncCardsDeviceTest,cloud.gitwide.ampverse.LibraryChooserDeviceTest,cloud.gitwide.ampverse.MusicBackupDeviceTest,cloud.gitwide.ampverse.LibraryStoreDeviceTest,cloud.gitwide.ampverse.CatalogDeviceTest + python3 tools/run_android_emulator_tests.py --output test-output/android-card-ui --classes cloud.gitwide.ampverse.SongIdentityDeviceTest,cloud.gitwide.ampverse.CardUiDeviceTest,cloud.gitwide.ampverse.CleanUiDeviceTest,cloud.gitwide.ampverse.RadioOfflineTest,cloud.gitwide.ampverse.IncrementalSyncDeviceTest,cloud.gitwide.ampverse.PhoneListeningDeviceTest,cloud.gitwide.ampverse.DjLoadPadsDeviceTest,cloud.gitwide.ampverse.AudioFeatureDeviceTest,cloud.gitwide.ampverse.CastBadgeLayoutDeviceTest,cloud.gitwide.ampverse.RemoteDiscoveryDeviceTest,cloud.gitwide.ampverse.DiscoveryDeviceTest,cloud.gitwide.ampverse.RemoteTaskCardsDeviceTest,cloud.gitwide.ampverse.LabNavigationDeviceTest,cloud.gitwide.ampverse.lab.EditingSessionTest,cloud.gitwide.ampverse.ModuleBadgesDeviceTest,cloud.gitwide.ampverse.LibrarySyncCardsDeviceTest,cloud.gitwide.ampverse.LibraryChooserDeviceTest,cloud.gitwide.ampverse.MusicBackupDeviceTest,cloud.gitwide.ampverse.LibraryStoreDeviceTest,cloud.gitwide.ampverse.CatalogDeviceTest result=$? mkdir -p test-output/android-card-ui adb logcat -d > test-output/android-card-ui/logcat.txt diff --git a/android/app/src/androidTest/java/cloud/gitwide/ampverse/DjLoadPadsDeviceTest.java b/android/app/src/androidTest/java/cloud/gitwide/ampverse/DjLoadPadsDeviceTest.java index dc2d2840..4eca9864 100644 --- a/android/app/src/androidTest/java/cloud/gitwide/ampverse/DjLoadPadsDeviceTest.java +++ b/android/app/src/androidTest/java/cloud/gitwide/ampverse/DjLoadPadsDeviceTest.java @@ -37,7 +37,7 @@ public class DjLoadPadsDeviceTest { assertTrue(e.queue(Arrays.asList(high,low,high),rules));java.lang.reflect.Field cursor=DjEngine.class.getDeclaredField("nextAuto");cursor.setAccessible(true);cursor.setInt(e,1);e.mixStyle("Hype");plan.invoke(e,0,1);assertEquals("Keep the played prefix when a song occurs again later",high,e.autoQueue.get(0));assertEquals(high,e.autoQueue.get(1));assertEquals(low,e.autoQueue.get(2)); org.json.JSONObject ramp=new org.json.JSONObject(rules.toString()).put("smart",true).put("energy",.2).put("energy_progression",new org.json.JSONObject().put("target",.9).put("transitions",4)); assertTrue(e.queue(Arrays.asList(low,high),ramp));e.mixStyle("Hype");plan.invoke(e,0,1);assertEquals("Keep the explicit ramp's planned order",low,e.autoQueue.get(0)); - assertNotNull("Unknown outgoing energy must use the shared unknown-data policy, not make every cost NaN",DjLogic.replacement(context,null,Arrays.asList(low,high),new org.json.JSONObject().put("style","Hype"),Collections.emptyList())); + assertNotNull("Unknown outgoing energy must use the shared unknown-data policy, not make every cost NaN",DjLogic.replacement(context,null,Arrays.asList(low,high),new org.json.JSONObject().put("style","Hype"),Collections.emptyList(),Collections.emptyList())); android.os.Bundle unknown=new android.os.Bundle();unknown.putString("amp-preparation",new org.json.JSONObject().put("energy",.8).put("perceptual_energy",org.json.JSONObject.NULL).toString()); MediaItem uncertain=new MediaItem.Builder().setMediaId("style-unknown-measurement").setUri("file:///unknown.wav").setMediaMetadata(new androidx.media3.common.MediaMetadata.Builder().setExtras(unknown).build()).build(); assertTrue("A missing normalized score cannot silently become legacy loudness",Double.isNaN(PhonePlaylists.knownEnergy(context,uncertain))); diff --git a/android/app/src/androidTest/java/cloud/gitwide/ampverse/LibrarySyncCardsDeviceTest.java b/android/app/src/androidTest/java/cloud/gitwide/ampverse/LibrarySyncCardsDeviceTest.java index d27ab502..4c1f74cb 100644 --- a/android/app/src/androidTest/java/cloud/gitwide/ampverse/LibrarySyncCardsDeviceTest.java +++ b/android/app/src/androidTest/java/cloud/gitwide/ampverse/LibrarySyncCardsDeviceTest.java @@ -36,6 +36,12 @@ private static final class Fixture implements AutoCloseable { accept=new Thread(()->{while(!server.isClosed())try{Socket socket=server.accept();clients.execute(()->serve(socket));}catch(Exception error){if(!server.isClosed())failure.compareAndSet(null,error);}},"library-download-fixture");accept.start(); } String base(){return "http://"+server.getInetAddress().getHostAddress()+":"+server.getLocalPort();} + final Map audioVariants=new HashMap<>(); + synchronized byte[] audio(String path){ + // Distinct fixture songs must contain distinct PCM now that repeat + // detection compares audio rather than just their different paths. + return audioVariants.computeIfAbsent(path,key->{byte[] data=wave.clone();double frequency=220+110*audioVariants.size();ByteBuffer pcm=ByteBuffer.wrap(data).order(ByteOrder.LITTLE_ENDIAN);for(int n=44;n+1=0&&audioReads.getAndIncrement()>=failAfter)return; assertEquals(identity,headers.get("x-amp-server"));assertEquals(library,headers.get("x-amp-library"));assertEquals("fixture-secret",headers.get("x-amp-password")); - boolean second="b.wav".equals(android.net.Uri.parse(base()+path).getQueryParameter("path"));if(second&&failSecond){code=503;body=new JSONObject().put("error","Fixture song unavailable");}else{audio=wave;if(second&&slowSecond){OutputStream out=socket.getOutputStream();out.write(("HTTP/1.1 200 OK\r\nContent-Type: audio/wav\r\nContent-Length: "+wave.length+"\r\nConnection: close\r\n\r\n").getBytes(StandardCharsets.US_ASCII));out.flush();blocked.countDown();release.await(12,TimeUnit.SECONDS);try{out.write(wave);out.flush();}catch(IOException cancelled){}return;}} + String song=android.net.Uri.parse(base()+path).getQueryParameter("path");boolean second="b.wav".equals(song);if(second&&failSecond){code=503;body=new JSONObject().put("error","Fixture song unavailable");}else{audio=audio(song);if(second&&slowSecond){OutputStream out=socket.getOutputStream();out.write(("HTTP/1.1 200 OK\r\nContent-Type: audio/wav\r\nContent-Length: "+audio.length+"\r\nConnection: close\r\n\r\n").getBytes(StandardCharsets.US_ASCII));out.flush();blocked.countDown();release.await(12,TimeUnit.SECONDS);try{out.write(audio);out.flush();}catch(IOException cancelled){}return;}} }else{failure.compareAndSet(null,new AssertionError("Unexpected request "+first));code=404;body=new JSONObject();} byte[] payload=audio!=null?audio:body.toString().getBytes(StandardCharsets.UTF_8);OutputStream out=socket.getOutputStream();out.write(("HTTP/1.1 "+code+" OK\r\nContent-Type: "+(audio==null?"application/json":"audio/wav")+"\r\nContent-Length: "+payload.length+"\r\nConnection: close\r\n\r\n").getBytes(StandardCharsets.US_ASCII));if(!first.startsWith("HEAD "))out.write(payload);out.flush(); }catch(Throwable error){if(!server.isClosed())failure.compareAndSet(null,error);}} @@ -165,6 +171,7 @@ private interface Check {boolean ready()throws Exception;} Context c=ApplicationProvider.getApplicationContext();SharedPreferences locals=c.getSharedPreferences("phone-playlists",0);String drafts=locals.getString("lists",null);locals.edit().putString("lists","[]").commit(); JSONObject[] lists=new JSONObject[2];File original=new File(c.getCacheDir(),"qa-original-kept.wav"); try(Fixture fixture=new Fixture(30)){ + assertFalse("Fixture songs represent distinct audio",Arrays.equals(fixture.audio("a.wav"),fixture.audio("b.wav"))); try(FileOutputStream out=new FileOutputStream(original)){out.write(fixture.wave);} PlaylistSync.enable(c,fixture.base(),"fixture-secret",fixture.identity,fixture.library);lists[0]=list(c,"Office mix");lists[1]=list(c,"edm"); try(ActivityScenario screen=ActivityScenario.launch(new Intent(c,MainActivity.class).putExtra("module","AMP DJ"))){ diff --git a/android/app/src/androidTest/java/cloud/gitwide/ampverse/SongIdentityDeviceTest.java b/android/app/src/androidTest/java/cloud/gitwide/ampverse/SongIdentityDeviceTest.java new file mode 100644 index 00000000..b389972a --- /dev/null +++ b/android/app/src/androidTest/java/cloud/gitwide/ampverse/SongIdentityDeviceTest.java @@ -0,0 +1,30 @@ +package cloud.gitwide.ampverse; + +import androidx.media3.common.MediaItem; +import androidx.media3.common.MediaMetadata; +import androidx.test.ext.junit.runners.AndroidJUnit4; +import org.junit.Test; +import org.junit.runner.RunWith; +import java.util.*; +import static org.junit.Assert.*; + +@RunWith(AndroidJUnit4.class) +public class SongIdentityDeviceTest { + private MediaItem song(String id,String title) { + return new MediaItem.Builder().setMediaId(id).setUri("file:///"+id+".mp3") + .setMediaMetadata(new MediaMetadata.Builder().setArtist("Artist").setTitle(title).build()).build(); + } + @Test public void removedPlayingAndRecentItemsKeepTheirIdentityDuringRefill() { + MediaItem current=song("removed","Song (Radio Edit)"),copy=song("copy","Song (Extended Mix)"); + MediaItem heard=song("heard","Previous (Club_Remix)"),edit=song("edit","Previous (Radio-Edit)"),next=song("next","Next"); + List candidates=Arrays.asList(copy,edit,next); + assertEquals(Collections.singletonList(next),PhoneSmartRules.repeatCandidates(candidates,Collections.singletonList(heard),current,Collections.emptyList(),5)); + assertTrue(PhoneSmartRules.repeatCandidates(Collections.singletonList(copy),Collections.emptyList(),current,Collections.emptyList(),5).isEmpty()); + } + @Test public void loadedDeckAliasesRemainExcludedWhenRecentHistoryRelaxes() { + MediaItem loaded=song("loaded","Song (Radio Edit)"),edit=song("edit","Song (Extended Mix)"); + assertTrue(PhoneSmartRules.repeatCandidates(Collections.singletonList(edit),Collections.emptyList(),null,Collections.singletonList(loaded),0).isEmpty()); + assertNull(DjLogic.replacement(androidx.test.platform.app.InstrumentationRegistry.getInstrumentation().getTargetContext(),null, + Collections.singletonList(edit),new org.json.JSONObject(),Collections.emptyList(),Collections.singletonList(loaded))); + } +} diff --git a/android/app/src/main/java/cloud/gitwide/ampverse/DjEngine.java b/android/app/src/main/java/cloud/gitwide/ampverse/DjEngine.java index 281b3cb6..e57bf2c9 100644 --- a/android/app/src/main/java/cloud/gitwide/ampverse/DjEngine.java +++ b/android/app/src/main/java/cloud/gitwide/ampverse/DjEngine.java @@ -145,21 +145,32 @@ private void planAuto(int current,int other){ if((!Double.isFinite(target)||target<0||target>1)&&rankingRules.optJSONObject("energy_progression")==null) rankingRules.put("energy",SharedDjLogic.styleTarget(mixStyle(),(nextAuto+1)/(double)Math.max(1,autoQueue.size()))); }catch(JSONException error){message="Upcoming mix settings could not be read.";return;} - MediaItem next=DjLogic.replacement(context,decks[current].getCurrentMediaItem(),pending,rankingRules,Collections.emptyList()); + MediaItem next=DjLogic.replacement(context,decks[current].getCurrentMediaItem(),pending,rankingRules,Collections.emptyList(),loadedAutoItems(other)); if(next!=null){int index=nextAuto+autoQueue.subList(nextAuto,autoQueue.size()).indexOf(next);autoQueue.remove(index);autoQueue.add(nextAuto,next);} } - private void prepareAutoDeck(int deck){ + private boolean prepareAutoDeck(int deck){ + int selected=-1; + for(int candidate=nextAuto;candidate autoSource=new ArrayList<>(); private final Deque recentAuto=new ArrayDeque<>(); - private void rememberAuto(MediaItem item){if(item==null)return;recentAuto.addLast(item.mediaId);while(recentAuto.size()>Math.max(1,autoRules.optInt("recent_repeat",5)))recentAuto.removeFirst();} - private boolean refillAuto(){if(!autoRules.optBoolean("smart")||autoRules.optString("fallback","relax_recent").equals("stop")||autoSource.isEmpty())return false;String current=decks[fader<.5?0:1].getCurrentMediaItem()==null?"":decks[fader<.5?0:1].getCurrentMediaItem().mediaId;List next=DjLogic.repeatCandidates(autoSource,recentAuto,current,autoRules.optInt("recent_repeat",5));if(next.isEmpty())return false;autoQueue.clear();autoQueue.addAll(next);nextAuto=0;plannedAuto=-1;return true;} + private final Deque recentAutoItems=new ArrayDeque<>(); + private List loadedAutoItems(int destination){List result=new ArrayList<>();for(int n=0;nlimit)recentAuto.removeFirst();while(recentAutoItems.size()>limit)recentAutoItems.removeFirst();} + private boolean refillAuto(){if(!autoRules.optBoolean("smart")||autoRules.optString("fallback","relax_recent").equals("stop")||autoSource.isEmpty())return false;int active=fader<.5?0:1;MediaItem current=decks[active].getCurrentMediaItem();List next=PhoneSmartRules.repeatCandidates(autoSource,recentAutoItems,current,loadedAutoItems(1-active),autoRules.optInt("recent_repeat",5));if(next.isEmpty())return false;autoQueue.clear();autoQueue.addAll(next);nextAuto=0;plannedAuto=-1;return true;} private final Runnable autoTick=this::advanceAuto; float fader=0,master=.75f; @@ -278,12 +289,13 @@ void mixNext(){ if(auto){ if(nextAuto>=autoQueue.size()&&!refillAuto()){message="No next song available in this playlist.";return;} planAuto(mixOutgoing,next); - prepareAutoDeck(next); + if(!prepareAutoDeck(next))return; } if(decks[next].getCurrentMediaItem()==null){message="Load the other deck before mixing.";return;} beginMixTo(mixOutgoing,next); } private void beginMixTo(int outgoing,int next){ + if(auto&&PhoneSongIdentity.same(decks[outgoing].getCurrentMediaItem(),decks[next].getCurrentMediaItem())){message="Auto Mix skipped the same song; current deck retained.";return;} mixOutgoing=outgoing; if(auto)decks[next].setPlaybackParameters(new PlaybackParameters(DjLogic.tempoRatio(decks[mixOutgoing].getCurrentMediaItem(),decks[next].getCurrentMediaItem(),decks[mixOutgoing].getPlaybackParameters().speed),1)); play(next);if(!active(next))return;mixFrom=fader;mixTo=next;mixStarted=0;mixWaitingSince=SystemClock.uptimeMillis();mixing=true; @@ -296,7 +308,7 @@ boolean remoteMixNext(){ int outgoing=fader<.5?0:1,other=1-outgoing;if(active(other)){message="The other main deck is already playing.";return false;} if(auto){mixNext();return mixing;} int queued=nextAuto;MediaItem current=decks[outgoing].getCurrentMediaItem(); - while(queued=autoQueue.size())refillAuto(); List pending=new ArrayList<>(autoQueue.subList(Math.min(nextAuto,autoQueue.size()),autoQueue.size())); - MediaItem replacement=DjLogic.replacement(context,outgoing,pending,autoRules,recentAuto); - if(replacement==null&&!autoRules.optString("fallback","relax_recent").equals("stop"))replacement=DjLogic.replacement(context,outgoing,pending,autoRules,Collections.emptyList()); + MediaItem replacement=DjLogic.replacement(context,outgoing,pending,autoRules,recentAutoItems,loadedAutoItems(target)); + if(replacement==null&&!autoRules.optString("fallback","relax_recent").equals("stop"))replacement=DjLogic.replacement(context,outgoing,pending,autoRules,Collections.emptyList(),loadedAutoItems(target)); if(replacement==null){if(!live){pause(target);decks[target].clearMediaItems();checkpoint();}message="Removed from this playlist. No eligible replacement is available.";return;} int index=autoQueue.indexOf(replacement);autoQueue.remove(index);autoQueue.add(nextAuto,replacement); pause(target);load(target,replacement,DjLogic.entry(replacement,autoRules)); @@ -348,7 +360,7 @@ boolean queue(List items){ try{LibraryOffline.requireCurrent(context,items);}catch(Exception unavailable){message=unavailable.getMessage();return false;} notificationPauseAt=0;java.util.Arrays.fill(notificationResume,false); liveStyleOverride=false;plannedAuto=-1;styleRevision++; - autoRules=new JSONObject();autoSource.clear();autoSource.addAll(items);autoStreamed=items.stream().anyMatch(item->{android.net.Uri uri=item.localConfiguration==null?null:item.localConfiguration.uri;return PrivateLibraryPlayback.owns(item)||uri!=null&&("https".equals(uri.getScheme())||"http".equals(uri.getScheme()));});recentAuto.clear();auto=false;cancelMix();handler.removeCallbacks(autoTick);autoQueue.clear();requests.clear();autoQueue.addAll(items);nextAuto=0;message="Loaded "+items.size()+" songs for Auto DJ. Press Start Auto DJ.";return true; + autoRules=new JSONObject();autoSource.clear();autoSource.addAll(items);autoStreamed=items.stream().anyMatch(item->{android.net.Uri uri=item.localConfiguration==null?null:item.localConfiguration.uri;return PrivateLibraryPlayback.owns(item)||uri!=null&&("https".equals(uri.getScheme())||"http".equals(uri.getScheme()));});recentAuto.clear();recentAutoItems.clear();auto=false;cancelMix();handler.removeCallbacks(autoTick);autoQueue.clear();requests.clear();autoQueue.addAll(items);nextAuto=0;message="Loaded "+items.size()+" songs for Auto DJ. Press Start Auto DJ.";return true; } /** Explicit playlist playback, unlike staging a queue or loading a manual deck. */ boolean startPlaylist(List items,JSONObject rules){ @@ -377,7 +389,7 @@ private void advanceAuto(){ if(sectionLoops[current]!=null){handler.postDelayed(autoTick,200);return;} if(nextAuto>=autoQueue.size()&&!refillAuto()){if(!active(current)){auto=false;message="Playlist finished.";}else handler.postDelayed(autoTick,200);return;} planAuto(current,other); - prepareAutoDeck(other); + if(!prepareAutoDeck(other))return; long duration=PhoneMixSections.exit(preparation(decks[current].getCurrentMediaItem()),autoRules,loadedEntry[current],cueOut(decks[current].getCurrentMediaItem(),decks[current].getDuration()),fadeSeconds*decks[current].getPlaybackParameters().speed);if(duration>0&&duration-decks[current].getCurrentPosition()<=fadeSeconds*1000L*decks[current].getPlaybackParameters().speed){mixNext();} else if(decks[current].getPlaybackState()==Player.STATE_ENDED){mixNext();} } diff --git a/android/app/src/main/java/cloud/gitwide/ampverse/DjLogic.java b/android/app/src/main/java/cloud/gitwide/ampverse/DjLogic.java index 0f345a71..e3456b9f 100644 --- a/android/app/src/main/java/cloud/gitwide/ampverse/DjLogic.java +++ b/android/app/src/main/java/cloud/gitwide/ampverse/DjLogic.java @@ -11,16 +11,19 @@ final class DjLogic { static long entry(MediaItem item,JSONObject rules){return PhoneSmartRules.entry(item,rules);} static List repeatCandidates(List source,Collection recent,String current,int avoid){return PhoneSmartRules.repeatCandidates(source,recent,current,avoid);} /** One pass over already eligible songs, using the shared tempo/key/energy scoring. */ - static MediaItem replacement(android.content.Context context,MediaItem outgoing,List candidates,JSONObject rules,Collection recent){ + static MediaItem replacement(android.content.Context context,MediaItem outgoing,List candidates,JSONObject rules,Collection recent,Collection loaded){ MediaItem best=null;double bestCost=Double.POSITIVE_INFINITY; + Set blocked=new HashSet<>(PhoneSongIdentity.keys(outgoing)),heard=new HashSet<>(); + for(MediaItem item:loaded)blocked.addAll(PhoneSongIdentity.keys(item)); + for(MediaItem item:recent)heard.addAll(PhoneSongIdentity.keys(item)); android.content.SharedPreferences details=context.getSharedPreferences("phone-track-details",0); double fromTempo=outgoing==null?0:PhonePlaylists.bpm(context,outgoing),fromEnergy=outgoing==null?Double.NaN:PhonePlaylists.knownEnergy(context,outgoing); String fromKey=outgoing==null?"":details.getString(outgoing.mediaId+":key",DjEngine.preparation(outgoing).optString("harmonic_key","")); double target=rules.optDouble("energy",-1);if(!Double.isFinite(target)||target<0||target>1)target=fromEnergy; String style=rules.optString("style","steady"); for(MediaItem item:candidates){ - if(outgoing!=null&&(item.mediaId.equals(outgoing.mediaId)||!PhonePlaylistDislike.serverKey(outgoing).isEmpty()&&PhonePlaylistDislike.serverKey(outgoing).equals(PhonePlaylistDislike.serverKey(item))))continue; - if(recent.contains(item.mediaId))continue; + Set identity=PhoneSongIdentity.keys(item); + if(!Collections.disjoint(identity,blocked)||!Collections.disjoint(identity,heard))continue; double energy=PhoneMixSections.sectionEnergy(DjEngine.preparation(item),entry(item,rules)); if(!Double.isFinite(energy))energy=PhonePlaylists.knownEnergy(context,item); double cost=SharedDjLogic.pairCost(fromTempo,PhonePlaylists.bpm(context,item),fromEnergy,energy,target,SharedDjLogic.keyCode(fromKey),SharedDjLogic.keyCode(details.getString(item.mediaId+":key",DjEngine.preparation(item).optString("harmonic_key","")))); diff --git a/android/app/src/main/java/cloud/gitwide/ampverse/PhoneSmartRules.java b/android/app/src/main/java/cloud/gitwide/ampverse/PhoneSmartRules.java index 4b33f014..fb4794be 100644 --- a/android/app/src/main/java/cloud/gitwide/ampverse/PhoneSmartRules.java +++ b/android/app/src/main/java/cloud/gitwide/ampverse/PhoneSmartRules.java @@ -31,7 +31,23 @@ static String genre(String s){ static double number(Context c,MediaItem item,String f){JSONObject p=DjEngine.preparation(item),x=extensions(p),a=object(p,"analysis"),props=object(x,"audio_properties");switch(f){case "Bpm":double bpm=PhonePlaylists.bpm(c,item);return bpm>0?bpm:Double.NaN;case "Energy":double e=PhonePlaylists.knownEnergy(c,item);return Double.isFinite(e)?1+9*e:Double.NaN;case "Duration":return a.optDouble("duration",props.optDouble("duration",p.optDouble("cue_out",Double.NaN)));case "TempoConfidence":return a.optDouble("tempo_confidence",Double.NaN)*100;case "KeyConfidence":return a.optDouble("key_confidence",Double.NaN)*100;case "CueCount":return array(p,"cues").length()+array(p,"manual_cues").length();case "ManualCueCount":return array(p,"manual_cues").length();case "SectionCount":return x.has("energy_profile")?array(object(x,"energy_profile"),"sections").length():Double.NaN;case "StemCount":return array(p,"stems").length();case "BeatOffset":return p.optDouble("beat_offset",Double.NaN);case "CueIn":return p.optDouble("cue_in",0);case "CueOut":return p.optDouble("cue_out",Double.NaN);case "Rating":return c.getSharedPreferences("phone-track-details",0).contains(item.mediaId+":rating")?c.getSharedPreferences("phone-track-details",0).getInt(item.mediaId+":rating",0):x.optDouble("rating",Double.NaN);case "Bitrate":return props.optDouble("bitrate",Double.NaN);case "SampleRate":return props.optDouble("sample_rate",Double.NaN);case "Channels":return props.optDouble("channels",Double.NaN);default:return Double.NaN;}} static boolean flag(MediaItem item,String f){return flag(DjEngine.preparation(item),f);} static boolean flag(JSONObject p,String f){switch(f){case "Clean":return ContentAdvisory.isKnownClean(p);case "AiGenerated":case "Acappella":case "Instrumental":case "Clip":return TrackCategories.marked(p,f);case "Analyzed":return p.optJSONObject("analysis")!=null;case "Reviewed":return object(p,"analysis").optBoolean("reviewed");case "BeatGrid":return !p.isNull("bpm")&&p.has("bpm")&&p.has("beat_offset")&&!p.isNull("beat_offset");case "ManualEdits":return p.optBoolean("manual_override")||array(p,"manual_cues").length()>0;case "EnergyProfile":return extensions(p).has("energy_profile");default:return false;}} - static List repeatCandidates(List source,Collection recent,String current,int avoid){List next=new ArrayList<>();for(MediaItem item:source)if(!item.mediaId.equals(current)&&(avoid==0||!recent.contains(item.mediaId)))next.add(item);if(next.isEmpty())for(MediaItem item:source)if(!item.mediaId.equals(current))next.add(item);return next;} + static List repeatCandidates(List source,Collection recent,String current,int avoid){ + MediaItem playing=null;List heard=new ArrayList<>(); + for(MediaItem item:source){if(item.mediaId.equals(current))playing=item;if(avoid>0&&recent.contains(item.mediaId))heard.add(item);} + return repeatCandidates(source,heard,playing,Collections.emptyList(),avoid); + } + static List repeatCandidates(List source,Collection heard,MediaItem playing,Collection loaded,int avoid){ + Set blocked=new HashSet<>(PhoneSongIdentity.keys(playing)),recent=new HashSet<>(); + for(MediaItem item:loaded)blocked.addAll(PhoneSongIdentity.keys(item)); + if(avoid>0)for(MediaItem item:heard)recent.addAll(PhoneSongIdentity.keys(item)); + List eligible=new ArrayList<>(),next=new ArrayList<>(); + for(MediaItem item:source){ + Set keys=PhoneSongIdentity.keys(item); + if(!Collections.disjoint(keys,blocked))continue; + eligible.add(item);if(Collections.disjoint(keys,recent))next.add(item); + } + return next.isEmpty()?eligible:next; + } static long entry(MediaItem item,JSONObject rules){return PhoneMixSections.entry(DjEngine.preparation(item),rules,DjEngine.cueIn(item));} static boolean contains(JSONArray a,String id){if(a!=null)for(int i=0;i0){List tags=genres(item);boolean match=false;for(int i=0;i values=text(c,item,f);String[] terms=filter.optString("terms").toLowerCase(Locale.ROOT).split(";");boolean match=false;for(String value:values){String v=value.trim().toLowerCase(Locale.ROOT);if(v.isEmpty())continue;boolean hasTerm=false;for(String term:terms)if(!term.trim().isEmpty()){hasTerm=true;if(filter.optBoolean("exact",true)?v.equals(term.trim()):v.contains(term.trim()))match=true;}if(!hasTerm)match=true;}if(!match)return false;}else{double lo=filter.optDouble("min",Double.NaN),hi=filter.optDouble("max",Double.NaN);if(!Double.isFinite(lo)||!Double.isFinite(hi)||lo>hi||lomax(f))return false;boolean match=false;if(f.equals("TempoAlternative")||f.equals("SectionEnergy")){JSONObject prepared=DjEngine.preparation(item);if(f.equals("SectionEnergy")&&!PhoneMixSections.comparableProfile(prepared))return false;JSONObject x=extensions(prepared);JSONArray values=f.equals("TempoAlternative")?array(x,"tempo_alternatives"):array(object(x,"energy_profile"),"sections");for(int j=0;j=lo&&n<=hi;}}else{double n=number(c,item,f);match=Double.isFinite(n)&&n>=lo&&n<=hi;}if(!match)return false;}}return true;} diff --git a/android/app/src/main/java/cloud/gitwide/ampverse/PhoneSongIdentity.java b/android/app/src/main/java/cloud/gitwide/ampverse/PhoneSongIdentity.java new file mode 100644 index 00000000..b3478d9d --- /dev/null +++ b/android/app/src/main/java/cloud/gitwide/ampverse/PhoneSongIdentity.java @@ -0,0 +1,50 @@ +package cloud.gitwide.ampverse; + +import androidx.media3.common.MediaItem; +import java.util.*; +import org.json.JSONObject; + +/** Repeat aliases never replace persistent library IDs or modify preparation. */ +final class PhoneSongIdentity { + private PhoneSongIdentity() {} + static String normalize(String value) { + StringBuilder out=new StringBuilder(),bracket=new StringBuilder();boolean inside=false; + for(char c:value.toLowerCase(Locale.ROOT).toCharArray()) { + if((c=='('||c=='[')&&!inside){inside=true;bracket.setLength(0);} + else if((c==')'||c==']')&&inside){if(!bracket.toString().matches(".*(?:^|[^\\p{L}\\p{N}])(mix|remix|edit)(?:[^\\p{L}\\p{N}]|$).*"))out.append(bracket);out.append(' ');inside=false;} + else if(inside)bracket.append(c);else out.append(c); + } + if(inside)out.append(bracket); + String text=out.toString().replaceAll("[^\\p{L}\\p{N}]+"," ").trim(); + return text.replaceFirst("(?:^| )(?:feat|ft|featuring)(?: |$).*","").trim(); + } + private static String tag(JSONObject p,String key,String embedded,String display) { + Object value=p.opt(key);if(!(value instanceof String)){JSONObject tags=p.optJSONObject("embedded_tags");value=tags==null?null:tags.opt(embedded);} + return value instanceof String?(String)value:display; + } + private static boolean hash(JSONObject a,JSONObject b,String key) { + String left=a.optString(key,"");return left.matches("[a-fA-F0-9]{64}")&&left.equalsIgnoreCase(b.optString(key,"")); + } + static boolean same(JSONObject a,String aTitle,String aArtist,JSONObject b,String bTitle,String bArtist) { + a=PhoneSmartRules.extensions(a);b=PhoneSmartRules.extensions(b); + if(hash(a,b,"audio_sha256")||hash(a,b,"source_sha256"))return true; + String artist=normalize(tag(a,"artist","TrackArtist",aArtist)),title=normalize(tag(a,"title","TrackTitle",aTitle)); + return !artist.isEmpty()&&!artist.equals("unknown")&&!artist.equals("unknown artist")&&!title.isEmpty() + &&artist.equals(normalize(tag(b,"artist","TrackArtist",bArtist)))&&title.equals(normalize(tag(b,"title","TrackTitle",bTitle))); + } + static boolean same(MediaItem a,MediaItem b) { + if(a==null||b==null)return false; + return !Collections.disjoint(keys(a),keys(b)); + } + static Set keys(MediaItem item) { + Set result=new HashSet<>();if(item==null)return result; + if(!item.mediaId.isEmpty())result.add("id:"+item.mediaId); + if(item.localConfiguration!=null)result.add("uri:"+item.localConfiguration.uri); + JSONObject p=PhoneSmartRules.extensions(DjEngine.preparation(item)); + for(String key:new String[]{"audio_sha256","source_sha256"}){String hash=p.optString(key,"");if(hash.matches("[a-fA-F0-9]{64}"))result.add(key+":"+hash.toLowerCase(Locale.ROOT));} + String artist=normalize(tag(p,"artist","TrackArtist",item.mediaMetadata.artist==null?"":item.mediaMetadata.artist.toString())); + String title=normalize(tag(p,"title","TrackTitle",item.mediaMetadata.title==null?"":item.mediaMetadata.title.toString())); + if(!artist.isEmpty()&&!artist.equals("unknown")&&!artist.equals("unknown artist")&&!title.isEmpty())result.add("name:"+artist+"\0"+title); + return result; + } +} diff --git a/android/app/src/test/java/cloud/gitwide/ampverse/PhoneSongIdentityTest.java b/android/app/src/test/java/cloud/gitwide/ampverse/PhoneSongIdentityTest.java new file mode 100644 index 00000000..0fa0eef7 --- /dev/null +++ b/android/app/src/test/java/cloud/gitwide/ampverse/PhoneSongIdentityTest.java @@ -0,0 +1,21 @@ +package cloud.gitwide.ampverse; + +import static org.junit.Assert.*; +import org.json.JSONObject; +import org.junit.Test; + +public class PhoneSongIdentityTest { + @Test public void differentEditsAndFeatureCreditsAreTheSameSong() throws Exception { + assertTrue(PhoneSongIdentity.same(new JSONObject(),"Song (Radio Edit)","ARTIST feat. Guest",new JSONObject(),"Song [Extended Mix]","Artist")); + assertFalse(PhoneSongIdentity.same(new JSONObject(),"Song (Part Two)","Artist",new JSONObject(),"Song","Artist")); + assertFalse(PhoneSongIdentity.same(new JSONObject(),"Song","",new JSONObject(),"Song","")); + for(String title:new String[]{"Song (Radio-Edit)","Song (Club_Remix)","Song [Extended Mix]"}) + assertTrue(title,PhoneSongIdentity.same(new JSONObject(),title,"Artist",new JSONObject(),"Song","Artist")); + } + @Test public void matchingAudioHashWinsOverMetadataAtAnotherPath() throws Exception { + String hash=new String(new char[64]).replace('\0','a'); + JSONObject a=new JSONObject().put("audio_sha256",hash),b=new JSONObject().put("audio_sha256",hash); + assertTrue(PhoneSongIdentity.same(a,"One","Artist",b,"Other","Other artist")); + assertFalse(PhoneSongIdentity.same(new JSONObject().put("audio_sha256",""),"","",new JSONObject().put("audio_sha256",""),"","")); + } +} diff --git a/apps/amp-cast/src/radio.rs b/apps/amp-cast/src/radio.rs index da4bfe89..1d9806a3 100644 --- a/apps/amp-cast/src/radio.rs +++ b/apps/amp-cast/src/radio.rs @@ -264,11 +264,18 @@ fn pick( show::choose(p, &cast.tracks, current, recent, target, 0) .ok_or_else(|| "No eligible songs remain in Smart Playlist".into()) } else { - let index = *indices - .get(*cursor % indices.len().max(1)) - .ok_or("Playlist is empty")?; - *cursor += 1; - Ok(index) + for _ in 0..indices.len() { + let index = indices[*cursor % indices.len()]; + *cursor += 1; + if !current + .and_then(|i| cast.tracks.get(i)) + .zip(cast.tracks.get(index)) + .is_some_and(|(out, next)| amp_core::song_identity::same_song(out, next)) + { + return Ok(index); + } + } + Err("No distinct next song remains in this playlist".into()) } } /// A corrupt/missing candidate must not take an otherwise healthy station down. @@ -318,6 +325,12 @@ async fn prepare_next( .take(indices.len()) .copied() .filter(|i| !failed.contains(i)) + .filter(|i| { + !current + .and_then(|current| cast.tracks.get(current)) + .zip(cast.tracks.get(*i)) + .is_some_and(|(out, next)| amp_core::song_identity::same_song(out, next)) + }) .collect(); if candidates.is_empty() { break; diff --git a/apps/amp-player/src/performance.rs b/apps/amp-player/src/performance.rs index 818036e0..2919e03d 100644 --- a/apps/amp-player/src/performance.rs +++ b/apps/amp-player/src/performance.rs @@ -887,12 +887,38 @@ impl Player { fn preload_smart(&mut self) -> Result<(), String> { self.preload_variant(0) } + fn auto_loaded_conflict(&self, candidate: &_core::Track) -> bool { + // Reuse the inactive destination's retained song; never create another + // copy on top of any other loaded deck, including the four side decks. + self.loaded_track(self.active_deck()) + .is_some_and(|playing| amp_core::song_identity::same_song(candidate, playing)) + || self + .auto_loaded_conflict_except(candidate, Some(self.requested_deck(Deck::Auto, true))) + } + fn auto_loaded_conflict_except( + &self, + candidate: &_core::Track, + except: Option, + ) -> bool { + (0..self.loaded.len()) + .filter(|deck| Some(*deck) != except) + .filter_map(|deck| self.loaded_track(deck)) + .any(|loaded| amp_core::song_identity::same_song(candidate, loaded)) + } fn preload_variant(&mut self, alternate: usize) -> Result<(), String> { self.commit_smart_audible(); if self.cancel_changed_regular_queue() { return Err(self.status.clone()); } - if self.run.preloaded.is_some() { + if let Some((deck, _)) = self.run.preloaded { + if self + .loaded_track(deck) + .is_some_and(|track| self.auto_loaded_conflict_except(track, Some(deck))) + { + return Err( + "Auto Mix stopped: the staged song is already loaded on another deck".into(), + ); + } return Ok(()); } while let Some(id) = self.run.requests.front().cloned() { @@ -900,6 +926,9 @@ impl Player { .library .as_ref() .and_then(|l| l.tracks.iter().position(|t| show::song_id(t) == id)) + .filter(|index| { + !self.auto_loaded_conflict(&self.library.as_ref().unwrap().tracks[*index]) + }) .filter(|index| { self.run.profile.as_ref().is_none_or(|p| { let track = &self.library.as_ref().unwrap().tracks[*index]; @@ -945,6 +974,15 @@ impl Player { .clone(); p.style = self.run.style; p.excluded.extend(self.run.failed_songs.iter().cloned()); + if let Some(library) = &self.library { + p.excluded.extend( + library + .tracks + .iter() + .filter(|track| self.auto_loaded_conflict(track)) + .map(show::song_id), + ); + } if let Some(library) = &self.library { p.excluded.extend( library @@ -1221,7 +1259,10 @@ impl Player { .filter_map(|(slot, &index)| { tracks .get(index) - .filter(|t| !self.run.failed_songs.contains(&show::song_id(t))) + .filter(|t| { + !self.run.failed_songs.contains(&show::song_id(t)) + && !self.auto_loaded_conflict(t) + }) .map(|_| (slot, index)) }) .collect(); @@ -2398,6 +2439,14 @@ impl Player { } self.run.active = self.active_deck(); if let Some((incoming, started)) = self.run.pending { + if self + .loaded_track(incoming) + .is_some_and(|track| self.auto_loaded_conflict_except(track, Some(incoming))) + { + self.run.cancel_automation(); + self.status = "Auto Mix stopped: this song is already loaded on another deck; current audio retained".into(); + return; + } let feedback_skip = self.run.feedback_handoff == Some(started); let ready = self.audio.as_ref().is_some_and(|a| { a.load_current(incoming) @@ -3084,6 +3133,29 @@ impl Player { #[cfg(test)] mod tests { + #[test] + fn automatic_repeat_guard_checks_each_of_the_six_loaded_snapshots() { + let candidate = amp_core::Track { + path: "song.mp3".into(), + title: "Song".into(), + preparation: Default::default(), + }; + for deck in 0..6 { + let mut player = Player::default(); + player.loaded_snapshot[deck] = Some(candidate.clone()); + assert!( + player.auto_loaded_conflict_except(&candidate, None), + "deck {deck} must be excluded even outside the live pair" + ); + assert_eq!( + player.auto_loaded_conflict(&candidate), + deck == player.active_deck() || deck != player.requested_deck(Deck::Auto, true), + "only the reusable destination may retain this song for a later occurrence" + ); + player.loaded_snapshot[deck] = None; + assert!(!player.auto_loaded_conflict_except(&candidate, None)); + } + } fn takeover_effect(style: crate::transition_styles::Style) -> EffectBridge { EffectBridge { deck: 2, diff --git a/crates/amp-core/src/analysis.rs b/crates/amp-core/src/analysis.rs index dc3a2a90..30d25058 100644 --- a/crates/amp-core/src/analysis.rs +++ b/crates/amp-core/src/analysis.rs @@ -4,6 +4,7 @@ use crate::{ Preparation, preparation::{self, AnalysisInfo, Cue}, }; +use sha2::{Digest, Sha256}; use std::{io::Read, path::Path, process::Stdio}; const RATE: f64 = 11025.; const BLOCK: usize = 110; @@ -474,6 +475,8 @@ pub fn analyze(path: &Path, existing: &Preparation) -> Result Result RATE * 21600. { return Err("Preparation currently supports tracks up to six hours".into()); @@ -607,6 +611,10 @@ pub fn analyze(path: &Path, existing: &Preparation) -> Result = + recent.iter().rev().take(p.recent_repeat).collect(); + let recent_keys: std::collections::HashSet<_> = tracks + .iter() + .filter(|t| recent_ids.contains(&song_id(t))) + .flat_map(crate::song_identity::keys) + .collect(); let mut candidates: Vec<_> = tracks .iter() .enumerate() - .filter(|(i, t)| Some(*i) != current && eligible(p, t)) + .filter(|(i, t)| { + Some(*i) != current + && eligible(p, t) + && !current + .and_then(|i| tracks.get(i)) + .is_some_and(|out| crate::song_identity::same_song(out, t)) + && !context + .preparation + .is_some_and(|out| crate::song_identity::matches_preparation(t, out)) + }) .collect(); let fresh: Vec<_> = candidates .iter() .copied() .filter(|(_, t)| { - !recent - .iter() - .rev() - .take(p.recent_repeat) - .any(|id| *id == song_id(t)) + !recent_ids.contains(&song_id(t)) + && !crate::song_identity::keys(t) + .iter() + .any(|key| recent_keys.contains(key)) }) .collect(); if !fresh.is_empty() { @@ -665,6 +680,66 @@ impl Progression { #[cfg(test)] mod tests { use super::*; + fn repeat_track(path: &str, title: &str, hash: &str) -> Track { + let mut preparation = Preparation::default(); + preparation + .extensions + .insert("artist".into(), serde_json::json!("Artist")); + preparation + .extensions + .insert("title".into(), serde_json::json!(title)); + preparation + .extensions + .insert("audio_sha256".into(), serde_json::json!(hash)); + Track { + path: path.into(), + title: title.into(), + preparation, + } + } + #[test] + fn playing_identity_is_never_relaxed_into_another_index_or_edit() { + let playlist = Settings::default().playlists.remove(0); + let tracks = vec![ + repeat_track("one.mp3", "Song (Radio Edit)", &"a".repeat(64)), + repeat_track("one.mp3", "Song (Radio Edit)", &"a".repeat(64)), + repeat_track("copy.mp3", "Different metadata", &"a".repeat(64)), + repeat_track("edit.mp3", "Song (Extended Mix)", &"b".repeat(64)), + ]; + assert_eq!(choose(&playlist, &tracks, Some(0), &[], None, 0), None); + assert_eq!( + choose_with_snapshot( + &playlist, + &tracks, + None, + &[], + None, + 0, + Some(&tracks[0].preparation) + ), + None + ); + } + #[test] + fn recent_identity_covers_another_edit_when_alternatives_exist() { + let playlist = Settings::default().playlists.remove(0); + let tracks = vec![ + repeat_track("old.mp3", "Song (Radio Edit)", &"a".repeat(64)), + repeat_track("edit.mp3", "Song (Extended Mix)", &"b".repeat(64)), + repeat_track("next.mp3", "Another song", &"c".repeat(64)), + ]; + assert_eq!( + ranked_with_snapshot( + &playlist, + &tracks, + Some(0), + &[song_id(&tracks[0])], + None, + None + ), + vec![2] + ); + } #[test] fn f07_arcs_advance_only_on_completed_handoffs_and_legacy_defaults() { let legacy: EnergyPlan = diff --git a/crates/amp-core/src/smart.rs b/crates/amp-core/src/smart.rs index 6e37d83e..12b136b9 100644 --- a/crates/amp-core/src/smart.rs +++ b/crates/amp-core/src/smart.rs @@ -59,6 +59,9 @@ pub(crate) fn cost_with_sections( exit: Option, entry: Option, ) -> f64 { + if crate::song_identity::same_preparation(a, b) { + return 1_000_000.; + } let confidence = |p: &Preparation| { if p.manual_override || p.analysis.as_ref().is_some_and(|a| a.reviewed) { 1. @@ -139,9 +142,43 @@ pub fn order_with_style( if target.is_none() { refine_style_order(songs, &mut result, style); } + separate_adjacent_repeats(songs, &mut result); result } +fn separate_adjacent_repeats(songs: &[&Preparation], route: &mut Vec) { + // Only repair a collision. Keep the energy order and anchor otherwise. Moving + // one repeated occurrence into a clean gap reduces collisions and loses no entries. + loop { + let mut moved = false; + for from in 1..route.len() { + if !crate::song_identity::same_preparation(songs[route[from - 1]], songs[route[from]]) { + continue; + } + if let Some(to) = (1..route.len()).find(|&to| { + from != to + && !crate::song_identity::same_preparation( + songs[route[from]], + songs[relocated_index(route, from, to, to - 1)], + ) + && (to + 1 == route.len() + || !crate::song_identity::same_preparation( + songs[route[from]], + songs[relocated_index(route, from, to, to + 1)], + )) + }) { + let value = route.remove(from); + route.insert(to, value); + moved = true; + break; + } + } + if !moved { + break; + } + } +} + /// Whole-set shaping needs to reserve songs for the release after a peak. A short /// greedy horizon can consume those songs too early. Improve the complete route /// through bounded local moves, retaining its anchor and every repeated entry. @@ -317,6 +354,58 @@ pub fn curate_with_soft_keys( mod tests { use super::*; #[test] + fn regular_order_preserves_repeated_entries_without_adjacent_edits() { + let song = |title: &str| { + let mut p = Preparation::default(); + p.extensions + .insert("artist".into(), serde_json::json!("Artist")); + p.extensions + .insert("title".into(), serde_json::json!(title)); + p + }; + let songs = [ + song("Song (Radio Edit)"), + song("Song (Extended Mix)"), + song("Other"), + song("Last"), + ]; + let refs: Vec<_> = songs.iter().collect(); + let ordered = order(&refs); + let mut all = ordered.clone(); + all.sort_unstable(); + assert_eq!(all, vec![0, 1, 2, 3]); + assert!( + ordered + .windows(2) + .all(|pair| !crate::song_identity::same_preparation( + &songs[pair[0]], + &songs[pair[1]] + )) + ); + let songs = [ + song("A"), + song("B"), + song("C"), + song("D"), + song("A (Radio-Edit)"), + song("A (Club_Remix)"), + ]; + let refs: Vec<_> = songs.iter().collect(); + let ordered = order_with_style(&refs, amp_dj_policy::EnergyStyle::Steady, Some(0.5)); + assert_eq!(ordered[0], 0); + let mut all = ordered.clone(); + all.sort_unstable(); + assert_eq!(all, vec![0, 1, 2, 3, 4, 5]); + assert!( + ordered + .windows(2) + .all(|pair| !crate::song_identity::same_preparation( + &songs[pair[0]], + &songs[pair[1]] + )) + ); + } + #[test] fn generated_legacy_energy_is_unknown_but_manual_values_survive() { let mut p = Preparation::default(); p.extensions.insert("energy".into(), serde_json::json!(0.8)); diff --git a/crates/amp-core/src/smart_cycle.rs b/crates/amp-core/src/smart_cycle.rs index 5d50f1ab..103ea5b6 100644 --- a/crates/amp-core/src/smart_cycle.rs +++ b/crates/amp-core/src/smart_cycle.rs @@ -9,6 +9,7 @@ use std::collections::HashSet; pub struct SmartCycle { scope: String, played: HashSet, + heard: HashSet, failed: HashSet, seed: u64, } @@ -26,6 +27,7 @@ impl SmartCycle { pub fn played(&mut self, library: &str, playlist: &str, track: &Track) { self.bind(library, playlist); self.played.insert(show::song_id(track)); + self.heard.extend(crate::song_identity::keys(track)); } pub fn failed(&mut self, library: &str, playlist: &str, track: &Track) { self.bind(library, playlist); @@ -75,26 +77,31 @@ impl SmartCycle { if pool.is_empty() { return vec![]; } - if pool.is_subset(&self.played) { + if tracks + .iter() + .filter(|t| pool.contains(&show::song_id(t))) + .all(|t| { + crate::song_identity::keys(t) + .iter() + .any(|key| self.heard.contains(key)) + }) + { if p.fallback == show::Fallback::Stop { return Vec::new(); } self.played.clear(); + self.heard.clear(); self.seed = self.seed.wrapping_add(0x9e3779b97f4a7c15); } let mut rules = p.clone(); rules.recent_repeat = 0; rules.excluded.extend(self.failed.iter().cloned()); let mut ranked = show::ranked_candidates(&rules, tracks, current, &[], target, context); - ranked.retain(|(_, i)| !self.played.contains(&show::song_id(&tracks[*i]))); - if ranked.is_empty() - && pool.len() == 1 - && let Some(index) = tracks.iter().position(|t| { - pool.contains(&show::song_id(t)) && !self.played.contains(&show::song_id(t)) - }) - { - ranked.push((0., index)); - } + ranked.retain(|(_, i)| { + !crate::song_identity::keys(&tracks[*i]) + .iter() + .any(|key| self.heard.contains(key)) + }); // Randomize only equal-cost choices. A small library must not make an // energy/key/tempo mismatch beat the actual best candidate. let window = ranked.first().map_or(0, |(best, _)| { @@ -122,6 +129,30 @@ fn entropy() -> u64 { mod tests { use super::*; #[test] + fn alternate_edits_do_not_prevent_a_completed_cycle_from_restarting() { + let mut songs = tracks(3); + for (i, title) in ["Song (Radio Edit)", "Song (Extended Mix)", "Other"] + .iter() + .enumerate() + { + songs[i] + .preparation + .extensions + .insert("artist".into(), serde_json::json!("Artist")); + songs[i] + .preparation + .extensions + .insert("title".into(), serde_json::json!(title)); + } + let p = show::Settings::default().playlists.remove(0); + let mut cycle = SmartCycle::default(); + cycle.played("l", &p.id, &songs[0]); + cycle.played("l", &p.id, &songs[2]); + let next = cycle.ranked("l", &p, &songs, Some(2), None, None); + assert!(!next.is_empty()); + assert!(next.iter().all(|&i| i != 2)); + } + #[test] fn small_pool_keeps_energy_ranking_and_explicit_exit_context() { let mut songs = tracks(3); for (song, energy) in songs.iter_mut().zip([0.8, 0.2, 0.8]) { @@ -258,9 +289,14 @@ mod tests { "a repeated query must not restart a completed Stop cycle" ); p.fallback = show::Fallback::RelaxRecent; - let next = cycle.ranked("l", &p, &tracks, current, None, None)[0]; + let next = cycle.ranked("l", &p, &tracks, current, None, None); if count > 1 { - assert_ne!(Some(next), current); + assert_ne!(Some(next[0]), current); + } else { + assert!( + next.is_empty(), + "Relaxing recent history must never replay the current song" + ); } } } @@ -291,7 +327,7 @@ mod tests { assert!(cycle.ranked("l", &p, &[], None, None, None).is_empty()); let one = tracks(1); for _ in 0..3 { - assert_eq!(cycle.ranked("l", &p, &one, Some(0), None, None), vec![0]); + assert!(cycle.ranked("l", &p, &one, Some(0), None, None).is_empty()); cycle.played("l", &p.id, &one[0]); } let two = tracks(2); diff --git a/crates/amp-core/src/song_identity.rs b/crates/amp-core/src/song_identity.rs new file mode 100644 index 00000000..1f9e9e8a --- /dev/null +++ b/crates/amp-core/src/song_identity.rs @@ -0,0 +1,123 @@ +//! Repeat identity is separate from stable, path-based library IDs. +use crate::{Preparation, Track}; + +fn normalized(value: &str) -> String { + let mut plain = String::new(); + let mut bracket = String::new(); + let mut inside = false; + for c in value.to_lowercase().chars() { + match c { + '(' | '[' if !inside => { + inside = true; + bracket.clear(); + } + ')' | ']' if inside => { + if !bracket + .split(|c: char| !c.is_alphanumeric()) + .any(|s| matches!(s, "mix" | "remix" | "edit")) + { + plain.push_str(&bracket); + } + plain.push(' '); + inside = false; + } + _ if inside => bracket.push(c), + _ => plain.push(c), + } + } + if inside { + plain.push_str(&bracket); + } + plain + .split(|c: char| !c.is_alphanumeric()) + .filter(|s| !s.is_empty()) + .take_while(|s| !matches!(*s, "feat" | "ft" | "featuring")) + .collect::>() + .join(" ") +} +fn tag<'a>(p: &'a Preparation, manual: &str, embedded: &str) -> Option<&'a str> { + p.extensions + .get(manual) + .or_else(|| p.extensions.get("embedded_tags")?.get(embedded))? + .as_str() +} +fn hash<'a>(p: &'a Preparation, key: &str) -> Option<&'a str> { + p.extensions + .get(key)? + .as_str() + .filter(|s| s.len() == 64 && s.bytes().all(|b| b.is_ascii_hexdigit())) +} +fn metadata(p: &Preparation, title: Option<&str>) -> Option<(String, String)> { + let artist = normalized(tag(p, "artist", "TrackArtist")?); + let title = normalized(tag(p, "title", "TrackTitle").or(title)?); + if artist.is_empty() + || title.is_empty() + || matches!(artist.as_str(), "unknown" | "unknown artist") + { + None + } else { + Some((artist, title)) + } +} +pub fn same_preparation(a: &Preparation, b: &Preparation) -> bool { + same(a, None, b, None) +} +fn same(a: &Preparation, at: Option<&str>, b: &Preparation, bt: Option<&str>) -> bool { + let a = preparation_keys(a, at); + preparation_keys(b, bt).iter().any(|key| a.contains(key)) +} +pub fn matches_preparation(track: &Track, p: &Preparation) -> bool { + same(&track.preparation, Some(&track.title), p, None) +} +pub fn same_song(a: &Track, b: &Track) -> bool { + a.path == b.path + || same( + &a.preparation, + Some(&a.title), + &b.preparation, + Some(&b.title), + ) +} +/// A song has several aliases: matching any one excludes the same recording or edit. +pub fn keys(track: &Track) -> Vec { + let mut keys = preparation_keys(&track.preparation, Some(&track.title)); + keys.push(format!( + "path:{}", + track.path.to_string_lossy().replace('\\', "/") + )); + keys +} +pub fn preparation_keys(p: &Preparation, title: Option<&str>) -> Vec { + let mut keys = Vec::new(); + if let Some(hash) = hash(p, "audio_sha256") { + keys.push(format!("audio:{}", hash.to_ascii_lowercase())); + } + if let Some(hash) = &p.source_sha256 + && hash.len() == 64 + && hash.bytes().all(|b| b.is_ascii_hexdigit()) + { + keys.push(format!("file:{}", hash.to_ascii_lowercase())); + } + if let Some((artist, title)) = metadata(p, title) { + keys.push(format!("name:{artist}\0{title}")); + } + keys +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn names_keep_meaningful_parentheses_and_ignore_mix_and_feature_credits() { + assert_eq!(normalized("Song (Extended Mix) feat. Guest"), "song"); + assert_eq!(normalized("Song (Part Two)"), "song part two"); + assert_eq!(normalized("ARTIST ft. Guest"), "artist"); + } + #[test] + fn empty_preparation_does_not_make_unrelated_songs_equal() { + assert!(!same_preparation( + &Preparation::default(), + &Preparation::default() + )); + } +} diff --git a/docs/AUTO_MIX_REPEAT_GUARD.md b/docs/AUTO_MIX_REPEAT_GUARD.md new file mode 100644 index 00000000..03bd7339 --- /dev/null +++ b/docs/AUTO_MIX_REPEAT_GUARD.md @@ -0,0 +1,61 @@ +# Auto Mix repeat identity — Task 22 + +Source candidate, not an installed update. This task builds on the grid-review +and trick-selection drafts. The owner queue remains +`AMP_VERSE_IMPROVEMENT_QUEUE.md`. + +## Selection rules + +Library song IDs remain path-based: playlists, exclusions and saved references +keep their existing IDs. Repeat detection additionally recognizes matching +decoded-audio hashes, exact source-file hashes, or normalized artist/title pairs. +It ignores case, feature credits and bracketed mix/remix/edit qualifiers, including +punctuation-separated labels. Meaningful parentheses such as “Part Two” survive. +Missing artist/title values do not identify unrelated songs as duplicates. + +The current song is excluded before recent-history relaxation. Desktop Auto Mix +checks all six deck snapshots; it may reuse its own inactive destination's retained +song for a later occurrence, but cannot create a copy of another loaded deck. +Staged and pending transitions recheck identities before starting. Android uses +the same policy for automatic loading and replacement, retaining actual playing +and recent item snapshots even after those items leave the source playlist. + +Smart shuffle completion uses heard identities, so an alternate edit cannot keep +a cycle permanently unfinished. Regular ordering keeps every deliberate repeated +entry and separates adjacent copies when a valid gap exists. The playback guard +stops rather than mixing a song into itself when no distinct next song exists. + +## Hashes and existing preparation + +New explicit analysis also hashes the decoder's mono 11,025 Hz float stream, +with a versioned domain prefix, as `audio_sha256`. Tags and container bytes are +excluded. It is an exact hash of this canonical decoder representation, not an +acoustic-similarity score. Differently encoded audio may have different hashes. +`source_sha256` remains the full-file integrity hash. + +Existing preparation is not automatically reanalyzed. Older songs use available +file hashes and known artist/title metadata until analysis is requested. No cues, +reviewed grids, key estimates, audio files or artwork are rewritten by selection. + +The red X beside a desktop deck title is the existing Clear deck control; it is +not a failed-analysis marker. The reported alternate edits' different keys cannot +be adjudicated without listening to and analyzing those specific source files. + +## Verification + +The original duplicate-index regression failed before the fix: the picker chose +index 1 when every candidate was the playing song or an alternate edit. Coverage +includes current-index loss, equal audio hashes at different paths, recent edits, +alias-cycle completion, explicit-target ordering, all six loaded snapshots and +destination reuse. The real-decoder fixture compares two differently tagged WAV +files and requires different file hashes with the same decoded-audio hash. + +Android unit cases cover normalization and hash identity. `SongIdentityDeviceTest` +uses actual MediaItems to check removed-source snapshots, history relaxation and +loaded-deck replacement; it runs in the existing Android card emulator workflow. +CI and physical-device results must be recorded separately from source completion. + +Local base-engine verification: 211 tests passed, with two explicit codec cases +excluded from the ordinary unit run. Strict Clippy passed for all core, desktop +and server targets. The codec case is run separately with the optional `analysis` +feature enabled; a zero-test filter is not counted as a passing codec check.