diff --git a/.github/workflows/android-card-ui.yml b/.github/workflows/android-card-ui.yml index 504c34bd..49fa3874 100644 --- a/.github/workflows/android-card-ui.yml +++ b/.github/workflows/android-card-ui.yml @@ -6,6 +6,8 @@ on: - 'android/**' - 'crates/amp-dj-policy/**' - 'tools/build_android_dj.py' + - 'tools/run_android_emulator_tests.py' + - 'tools/test_run_android_emulator_tests.py' - '.github/workflows/android-card-ui.yml' permissions: contents: read @@ -41,6 +43,7 @@ jobs: - name: Build emulator-only debug APKs and all optional modules run: | test -z "$AMP_ANDROID_KEYSTORE" + python3 tools/test_run_android_emulator_tests.py python3 tools/test_build_android_dj.py gradle -p android :app:assembleFullDebug :app:assembleFullDebugAndroidTest :app:testFullDebugUnitTest :app:lintFullDebug :amp-dj:assembleRelease :amp-lab:assembleRelease :amp-cast:assembleRelease :amp-podcasts:assembleRelease :amp-remote:assembleRelease python3 - <<'PY' @@ -67,9 +70,14 @@ jobs: adb shell input keyevent KEYCODE_WAKEUP adb shell wm dismiss-keyguard adb shell am force-stop com.google.android.apps.nexuslauncher + # This image's Messages carrier-config receiver also ANRs over the app + # (run 47110335905, clean-library.png and logcat). Disable only that + # unrelated package on this disposable image so later carrier broadcasts + # cannot relaunch it. Do not suppress ANRs or change app assertions. + adb shell pm disable-user --user 0 com.google.android.apps.messaging sleep 10 set +e - gradle -p android :app:connectedFullDebugAndroidTest -Pandroid.testInstrumentationRunnerArguments.class=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,cloud.gitwide.ampverse.lab.UrlImportDeviceTest + 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,cloud.gitwide.ampverse.lab.UrlImportDeviceTest result=$? mkdir -p test-output/android-card-ui adb logcat -d > test-output/android-card-ui/logcat.txt diff --git a/.github/workflows/android-owned-pcm-native.yml b/.github/workflows/android-owned-pcm-native.yml index 8ff6261e..2871ade2 100644 --- a/.github/workflows/android-owned-pcm-native.yml +++ b/.github/workflows/android-owned-pcm-native.yml @@ -6,6 +6,8 @@ on: - 'android/**' - 'tools/test_android_owned_pcm.py' - 'tools/verify_android_owned_native.py' + - 'tools/run_android_emulator_tests.py' + - 'tools/test_run_android_emulator_tests.py' - '.github/workflows/android-owned-pcm-native.yml' permissions: contents: read @@ -43,6 +45,7 @@ jobs: - name: Compile all editions, modules and native fixture run: | test -z "$AMP_ANDROID_KEYSTORE" + python3 tools/test_run_android_emulator_tests.py python3 tools/test_android_rc.py gradle -p android :app:assembleLiteDebug :app:assembleFullDebug :app:assembleFullDebugAndroidTest :app:testFullDebugUnitTest :app:lintFullDebug :app:lintLiteDebug :amp-dj:assembleDebug :amp-lab:assembleDebug :amp-cast:assembleDebug :amp-podcasts:assembleDebug :amp-remote:assembleDebug cargo build --locked -p amp-cast --bin amp-cast @@ -71,12 +74,12 @@ jobs: disk-size: 4096M disable-animations: true emulator-options: -no-window -gpu swiftshader_indirect -noaudio -no-boot-anim -camera-back none - script: python3 tools/verify_android_owned_native.py --server-binary target/debug/amp-cast --output test-output/android-owned-native -- gradle -p android :app:connectedFullDebugAndroidTest -Pandroid.testInstrumentationRunnerArguments.class=cloud.gitwide.ampverse.OwnedMasterNativeDeviceTest,cloud.gitwide.ampverse.OwnedMixerSettingsDeviceTest,cloud.gitwide.ampverse.ExternalAudioDeviceTest -Pandroid.testInstrumentationRunnerArguments.amp_server=http://10.0.2.2:28987 + script: python3 tools/verify_android_owned_native.py --server-binary target/debug/amp-cast --output test-output/android-owned-native -- python3 tools/run_android_emulator_tests.py --output test-output/android-owned-native/instrumentation --classes cloud.gitwide.ampverse.OwnedMasterNativeDeviceTest,cloud.gitwide.ampverse.OwnedMixerSettingsDeviceTest,cloud.gitwide.ampverse.ExternalAudioDeviceTest --argument amp_server=http://127.0.0.1:28987 - name: Collect emulator logs if: always() run: | mkdir -p test-output/android-owned-native - timeout 10s adb logcat -d > test-output/android-owned-native/logcat.txt || true + timeout 10s adb logcat -d > test-output/android-owned-native/logcat-after-emulator.txt || true - uses: actions/upload-artifact@v4 if: always() with: diff --git a/Cargo.lock b/Cargo.lock index ef3af947..32d58112 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -63,7 +63,7 @@ dependencies = [ [[package]] name = "amp-cast" -version = "1.1.0-rc.33" +version = "1.1.0-rc.34" dependencies = [ "amp-core", "amp-updater", @@ -117,7 +117,7 @@ dependencies = [ [[package]] name = "amp-engine" -version = "1.0.22" +version = "1.0.23" dependencies = [ "amp-core", "serde_json", @@ -125,7 +125,7 @@ dependencies = [ [[package]] name = "amp-player" -version = "1.1.0-rc.33" +version = "1.1.0-rc.34" dependencies = [ "amp-cast", "amp-core", @@ -162,7 +162,7 @@ dependencies = [ [[package]] name = "amp-plugin" -version = "1.1.0-rc.33" +version = "1.1.0-rc.34" dependencies = [ "serde", "serde_json", @@ -188,7 +188,7 @@ version = "1.0.22" [[package]] name = "amp-updater" -version = "1.1.0-rc.33" +version = "1.1.0-rc.34" dependencies = [ "libc", "serde", diff --git a/Cargo.toml b/Cargo.toml index 9ebd34f8..21becc58 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -3,7 +3,7 @@ members = ["crates/amp-plugin", "crates/amp-updater", "crates/amp-stems", "crate resolver = "2" [workspace.package] -version = "1.1.0-rc.33" +version = "1.1.0-rc.34" edition = "2024" license = "MIT" 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 3ec5bec4..dc2d2840 100644 --- a/android/app/src/androidTest/java/cloud/gitwide/ampverse/DjLoadPadsDeviceTest.java +++ b/android/app/src/androidTest/java/cloud/gitwide/ampverse/DjLoadPadsDeviceTest.java @@ -15,6 +15,40 @@ @RunWith(AndroidJUnit4.class) @androidx.annotation.OptIn(markerClass=androidx.media3.common.util.UnstableApi.class) public class DjLoadPadsDeviceTest { + @Test public void mixStyleButtonsChangeUpcomingEnergyWithoutChangingTransport()throws Exception { + Context context=InstrumentationRegistry.getInstrumentation().getTargetContext(); + Intent intent=new Intent(context,MainActivity.class).putExtra("module","AMP DJ").putExtra("phone-ui",true); + SharedPreferences details=context.getSharedPreferences("phone-track-details",0); + MediaItem current=new MediaItem.Builder().setMediaId("style-current").setUri("file:///style-current.wav").build(),low=new MediaItem.Builder().setMediaId("style-low").setUri("file:///style-low.wav").build(),high=new MediaItem.Builder().setMediaId("style-high").setUri("file:///style-high.wav").build(); + details.edit().putFloat(current.mediaId+":energy",.5f).putFloat(low.mediaId+":energy",.2f).putFloat(high.mediaId+":energy",.8f).commit(); + org.json.JSONObject rules=new org.json.JSONObject().put("name","Style fixture").put("style","Chill"); + try(ActivityScenario scenario=ActivityScenario.launch(intent)){ + scenario.onActivity(a->{try{ + DjEngine e=PlaybackService.dj();assertNotNull(e);e.pauseAll();assertTrue(e.queue(Arrays.asList(low,high),rules));e.decks[0].setMediaItem(current);e.setFader(.25f); + DjPanel panel=new DjPanel(a,new Appearance(a),e,new DjPanel.Host(){public void effect(int s,int p){}public void beforeMainPlay(){}public void equalizer(){}}); + assertEquals(3,tags(panel,"dj-mix-style-"));assertTrue(panel.findViewWithTag("dj-mix-style-Chill").isSelected()); + java.lang.reflect.Method plan=DjEngine.class.getDeclaredMethod("planAuto",int.class,int.class);plan.setAccessible(true); + assertTrue(panel.findViewWithTag("dj-mix-style-Hype").performClick());plan.invoke(e,0,1);assertEquals(high,e.autoQueue.get(0)); + assertEquals("Chill",rules.getString("style"));assertEquals("Style fixture",e.playlistName());assertFalse(e.auto);assertFalse(e.active(0));assertFalse(e.active(1));assertEquals(.25f,e.fader,0f);assertEquals(current,e.decks[0].getCurrentMediaItem()); + assertTrue(panel.findViewWithTag("dj-mix-style-Chill").performClick());plan.invoke(e,0,1);assertEquals(low,e.autoQueue.get(0)); + assertTrue(panel.findViewWithTag("dj-mix-style-Steady").performClick());assertEquals("Steady",e.mixStyle()); + // A new source must use its own rules, not the previous session override. + assertTrue(e.queue(Arrays.asList(low,high),rules));assertEquals("Chill",e.mixStyle()); + 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())); + 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))); + android.os.Bundle metadata=new android.os.Bundle();metadata.putString("amp-preparation",new org.json.JSONObject().put("cue_out",120).put("manual_cues",new org.json.JSONArray().put(new org.json.JSONObject().put("kind","drop").put("seconds",24))).toString()); + MediaItem sameSong=high.buildUpon().setMediaMetadata(new androidx.media3.common.MediaMetadata.Builder().setExtras(metadata).build()).build(); + assertTrue(e.queue(Collections.singletonList(sameSong),new org.json.JSONObject().put("style","Steady")));e.load(1,sameSong,0);assertEquals(0,e.loadedEntry[1]);e.mixStyle("Hype"); + java.lang.reflect.Method prepare=DjEngine.class.getDeclaredMethod("prepareAutoDeck",int.class);prepare.setAccessible(true);prepare.invoke(e,1);assertEquals("Retarget an already preloaded song to its marked drop",24000,e.loadedEntry[1]);assertFalse(e.active(1));assertEquals(.25f,e.fader,0f);assertEquals(current,e.decks[0].getCurrentMediaItem()); + e.decks[0].clearMediaItems();e.decks[1].clearMediaItems(); + }catch(Exception error){throw new AssertionError(error);}}); + }finally{details.edit().remove(current.mediaId+":energy").remove(low.mediaId+":energy").remove(high.mediaId+":energy").commit();} + } @Test public void explicitPlaylistStartsAutoButQueueStagingStaysManual()throws Exception { Context context=InstrumentationRegistry.getInstrumentation().getTargetContext(); java.io.File source=OwnedMixerSettingsDeviceTest.input(context); @@ -52,9 +86,11 @@ public class DjLoadPadsDeviceTest { while(returns.get()<4&&android.os.SystemClock.elapsedRealtime()=4); scenario.onActivity(a->{DjEngine e=PlaybackService.dj();playing[0]=e.decks[0].getPlayWhenReady()&&e.decks[0].getPlayerError()==null;e.decks[0].removeListener(loopObserver);e.holdLoop(0);assertFalse(e.sectionLoopActive(0));}); - assertTrue("Loop keeps play intent and has no decoder error",playing[0]);deadline=android.os.SystemClock.elapsedRealtime()+3000; + // Releasing near the loop start can require the entire captured span + // before passing its end; a fixed three-second limit is not sufficient. + assertTrue("Loop keeps play intent and has no decoder error",playing[0]);deadline=android.os.SystemClock.elapsedRealtime()+loopSpan[0]+3000; do{scenario.onActivity(a->position[0]=PlaybackService.dj().decks[0].getCurrentPosition());if(position[0]>loopStart[0]+loopSpan[0]+50)break;Thread.sleep(25);}while(android.os.SystemClock.elapsedRealtime()loopStart[0]+loopSpan[0]+50); + assertTrue("After tap playback passes the captured loop end: at="+position[0]+" start="+loopStart[0]+" span="+loopSpan[0],position[0]>loopStart[0]+loopSpan[0]+50); }finally{InstrumentationRegistry.getInstrumentation().runOnMainSync(()->{DjEngine e=PlaybackService.existingDj();if(e!=null){if(observerRef[0]!=null)e.decks[0].removeListener(observerRef[0]);e.cancelSectionLoop(0);e.pauseAll();e.decks[0].clearMediaItems();}});assertTrue(source.delete());} } @Test public void dislikeButtonSavesSmartExclusionWithoutDeletingTheSong()throws Exception { 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 53bfe7eb..d27ab502 100644 --- a/android/app/src/androidTest/java/cloud/gitwide/ampverse/LibrarySyncCardsDeviceTest.java +++ b/android/app/src/androidTest/java/cloud/gitwide/ampverse/LibrarySyncCardsDeviceTest.java @@ -117,7 +117,10 @@ private interface Check {boolean ready()throws Exception;} } @Test public void castPlaylistCanBeSentOnlyToDjAndPrivateDeckAudioActuallyAdvances()throws Exception{ Context c=ApplicationProvider.getApplicationContext(); - try(Fixture fixture=new Fixture();ActivityScenario screen=ActivityScenario.launch(new Intent(c,MainActivity.class).putExtra("module","AMP Cast"))){ + // A one-second fixture can consume/refill the entire queue during the + // three-second automatic handoff before the UI assertion observes it. + // Keep the playback long enough to observe the initial two-song queue. + try(Fixture fixture=new Fixture(30);ActivityScenario screen=ActivityScenario.launch(new Intent(c,MainActivity.class).putExtra("module","AMP Cast"))){ await(()->{AtomicBoolean ready=new AtomicBoolean();screen.onActivity(a->ready.set(PlaybackService.player()!=null&&PlaybackService.dj()!=null));return ready.get();}); CastClient client=new CastClient(fixture.base(),"fixture-secret");JSONObject identity=client.connect();AtomicReference view=new AtomicReference<>(); screen.onActivity(a->{try{PlaybackService.dj().auto(false);PlaybackService.dj().pauseAll();PlaybackService.dj().queue(Collections.emptyList());PlaybackService.player().stop();PlaybackService.player().setMediaItem(new MediaItem.Builder().setMediaId("unchanged-player-queue").setUri("file:///not-started.wav").build());java.lang.reflect.Field f=MainActivity.class.getDeclaredField("appearance");f.setAccessible(true);CastLibraryView panel=new CastLibraryView(a,(Appearance)f.get(a),new CastPanel.Listener(){public void listen(String url,String name){throw new AssertionError("Must not start station listening");}public void stopListening(){}},()->client,id->{});a.setContentView(panel);view.set(panel);panel.bind(client,identity);}catch(Exception e){throw new AssertionError(e);}}); diff --git a/android/app/src/androidTest/java/cloud/gitwide/ampverse/OwnedMasterNativeDeviceTest.java b/android/app/src/androidTest/java/cloud/gitwide/ampverse/OwnedMasterNativeDeviceTest.java index dad2606e..474bf4e9 100644 --- a/android/app/src/androidTest/java/cloud/gitwide/ampverse/OwnedMasterNativeDeviceTest.java +++ b/android/app/src/androidTest/java/cloud/gitwide/ampverse/OwnedMasterNativeDeviceTest.java @@ -18,7 +18,7 @@ /** Disposable emulator + isolated actual host only; not physical speaker/latency acceptance. */ @RunWith(AndroidJUnit4.class) public final class OwnedMasterNativeDeviceTest { - private static final String SERVER = "http://10.0.2.2:28987", PASSWORD = "android-owned-fixture"; + private static final String SERVER = "http://127.0.0.1:28987", PASSWORD = "android-owned-fixture"; private static void await(java.util.function.BooleanSupplier ready, long milliseconds) throws Exception { @@ -73,6 +73,9 @@ public void generatedMasterUsesActualNativeMp3AndGuardedHttpWithoutSavedAudio() PhoneMasterBroadcast broadcast = null; List voices = new ArrayList<>(); AtomicInteger uploads = new AtomicInteger(); + AtomicInteger starts = new AtomicInteger(); + AtomicLong preparationMs = new AtomicLong(-1), firstPacketMs = new AtomicLong(-1), + maxControlMs = new AtomicLong(), maxUploadMs = new AtomicLong(); AtomicReference latest = new AtomicReference<>(); AtomicReference lastEvent = new AtomicReference<>(""); AtomicReference encoderFailure = new AtomicReference<>(); @@ -88,15 +91,21 @@ public void generatedMasterUsesActualNativeMp3AndGuardedHttpWithoutSavedAudio() PhoneLiveSession.Transport counted = new PhoneLiveSession.Transport() { public PhoneLiveSession.Identity verify() throws IOException { - return actual.verify(); + long began = System.nanoTime(); + try { return actual.verify(); } + finally { maxControlMs.accumulateAndGet(TimeUnit.NANOSECONDS.toMillis(System.nanoTime()-began), Math::max); } } public PhoneLiveSession.Started start(String previous) throws IOException { - return actual.start(previous); + starts.incrementAndGet();long began = System.nanoTime(); + try { return actual.start(previous); } + finally { maxControlMs.accumulateAndGet(TimeUnit.NANOSECONDS.toMillis(System.nanoTime()-began), Math::max); } } public long upload(String token, long sequence, byte[] data) throws IOException { - long next = actual.upload(token, sequence, data); + long began = System.nanoTime(), next; + try { next = actual.upload(token, sequence, data); } + finally { maxUploadMs.accumulateAndGet(TimeUnit.NANOSECONDS.toMillis(System.nanoTime()-began), Math::max); } latest.set(data.clone()); uploads.incrementAndGet(); return next; @@ -139,11 +148,14 @@ public void abort() { .newInstance(context); return new PhoneMasterBroadcast.Encoder() { public void prepare() throws IOException { + long began = System.nanoTime(); try { nativeEncoder.prepare(); } catch (IOException error) { encoderFailure.set(error); throw error; + } finally { + preparationMs.set(TimeUnit.NANOSECONDS.toMillis(System.nanoTime()-began)); } } @@ -153,7 +165,11 @@ public void encode( PhoneMasterBroadcast.PacketSink packets) throws IOException { try { - nativeEncoder.encode(pcm, cancel, packets); + long began = System.nanoTime(); + nativeEncoder.encode(pcm, cancel, (packet,count)->{ + firstPacketMs.compareAndSet(-1,TimeUnit.NANOSECONDS.toMillis(System.nanoTime()-began)); + packets.packet(packet,count); + }); } catch (IOException error) { encoderFailure.set(error); throw error; @@ -200,14 +216,22 @@ public void close() { } Thread.sleep(10); } - Throwable problem = encoderFailure.get(); + Throwable problem = broadcast.failure()!=null?broadcast.failure():encoderFailure.get(); String diagnostic = ""; for (int depth = 0; problem != null && depth < 4; depth++, problem = problem.getCause()) diagnostic += " / " + problem; assertTrue( - "Native MP3/HTTP never delivered: " + lastEvent.get() + diagnostic, uploads.get() > 50); - assertTrue(broadcast.active()); - assertTrue(status().optBoolean("on_air")); + "Native MP3/HTTP never delivered: " + lastEvent.get() + diagnostic + + " [uploads=" + uploads.get() + " starts=" + starts.get() + + " preparationMs=" + preparationMs.get() + " firstPacketMs=" + firstPacketMs.get() + + " maxControlMs=" + maxControlMs.get() + " maxUploadMs=" + maxUploadMs.get() + "]", + uploads.get() > 50); + assertTrue("Sender stopped after delivery: " + lastEvent.get() + diagnostic + + " [uploads=" + uploads.get() + " starts=" + starts.get() + + " maxControlMs=" + maxControlMs.get() + " maxUploadMs=" + maxUploadMs.get() + "]", + broadcast.active()); + assertTrue("Server went off air after delivery: " + lastEvent.get() + diagnostic, + status().optBoolean("on_air")); // An explicitly replaced session must survive the old sender's upload/cleanup. PhoneLiveSession replacement = new PhoneLiveSession(identity, new PhoneLiveHttpTransport(SERVER, PASSWORD, identity)); diff --git a/android/app/src/androidTest/java/cloud/gitwide/ampverse/OwnedMixerSettingsDeviceTest.java b/android/app/src/androidTest/java/cloud/gitwide/ampverse/OwnedMixerSettingsDeviceTest.java index 0e2167d2..6e714b15 100644 --- a/android/app/src/androidTest/java/cloud/gitwide/ampverse/OwnedMixerSettingsDeviceTest.java +++ b/android/app/src/androidTest/java/cloud/gitwide/ampverse/OwnedMixerSettingsDeviceTest.java @@ -31,6 +31,125 @@ private static void await(java.util.function.BooleanSupplier condition) throws E } } + @SuppressWarnings("deprecation") + private static android.app.ActivityManager.RunningServiceInfo playbackServiceInfo(Context context){ + android.app.ActivityManager manager=(android.app.ActivityManager)context.getSystemService(Context.ACTIVITY_SERVICE); + for(android.app.ActivityManager.RunningServiceInfo service:manager.getRunningServices(100)) + if(service.service.getClassName().equals(PlaybackService.class.getName())) + return service; + return null; + } + private static String playbackServiceStatus(Context context){ + android.app.ActivityManager.RunningServiceInfo service=playbackServiceInfo(context); + return service==null?" service-not-running":" foreground="+service.foreground+" started="+service.started+" clients="+service.clientCount; + } + + /** Exercise the actual notification's platform token, not a direct decoder call. */ + private static void assertNotificationTransport(Context context,String expectedId) throws Exception { + AtomicReference expected=new AtomicReference<>(); + main(()->{ + try { + java.lang.reflect.Field field=PlaybackService.class.getDeclaredField("instance");field.setAccessible(true); + PlaybackService service=(PlaybackService)field.get(null); + java.util.List sessions=new java.util.ArrayList<>(service.getSessions()); + java.lang.reflect.Field primary=PlaybackService.class.getDeclaredField("session");primary.setAccessible(true); + sessions.add((androidx.media3.session.MediaSession)primary.get(service)); + for(androidx.media3.session.MediaSession item:sessions) + if(item.getId().equals(expectedId))expected.set(item.getPlatformToken()); + assertNotNull("Expected playback session exists",expected.get()); + }catch(ReflectiveOperationException error){throw new AssertionError(error);} + }); + android.app.NotificationManager manager=(android.app.NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE); + try{await(()->{ + android.service.notification.StatusBarNotification[] notices=manager.getActiveNotifications(); + android.app.ActivityManager.RunningServiceInfo service=playbackServiceInfo(context); + // A normal notification refresh can replace its foreground bit while the + // OS still runs the service in foreground. Assert that actual lifecycle + // state, rather than inferring it from mutable notification decoration. + return notices.length==1&¬ices[0].getId()==1001 + &&service!=null&&service.foreground + &&expected.get().equals(notices[0].getNotification().extras.getParcelable(android.app.Notification.EXTRA_MEDIA_SESSION)); + });}catch(AssertionError failure){ + StringBuilder observed=new StringBuilder(); + for(android.service.notification.StatusBarNotification notice:manager.getActiveNotifications()){ + android.media.session.MediaSession.Token token=notice.getNotification().extras.getParcelable(android.app.Notification.EXTRA_MEDIA_SESSION); + observed.append(" id=").append(notice.getId()).append(" flags=").append(notice.getNotification().flags).append(" token=").append(token); + } + AtomicReference decks=new AtomicReference<>(); + main(()->{ + DjEngine dj=PlaybackService.existingDj(); + if(dj==null){decks.set(" no-dj");return;} + StringBuilder states=new StringBuilder(" selected=").append(dj.notificationDeck()); + for(int i=0;i<2;i++)states.append(" deck").append(i).append("=") + .append(dj.decks[i].getPlayWhenReady()).append("/").append(dj.decks[i].isPlaying()) + .append(" state=").append(dj.decks[i].getPlaybackState()); + decks.set(states.toString()); + }); + throw new AssertionError("Expected foreground notification source="+expectedId+" token="+expected.get()+"; observed"+observed+playbackServiceStatus(context)+decks.get(),failure); + } + android.media.session.MediaController controller=new android.media.session.MediaController(context,expected.get()); + controller.getTransportControls().pause(); + AtomicBoolean active=new AtomicBoolean(); + await(()->{main(()->active.set(expectedId.isEmpty()?PlaybackService.player().isPlaying():PlaybackService.existingDj().decks[0].isPlaying()||PlaybackService.existingDj().decks[1].isPlaying()));return !active.get();}); + if(!expectedId.isEmpty()){ + main(()->{ + DjEngine dj=PlaybackService.existingDj(); + dj.load(2,dj.decks[expectedId.equals("dj-1")?1:0].getCurrentMediaItem(),0);dj.play(2); + assertFalse("Private cue cannot resume deck A",dj.decks[0].getPlayWhenReady()); + assertFalse("Private cue cannot resume deck B",dj.decks[1].getPlayWhenReady()); + assertTrue("Private cue is independently playable",dj.decks[2].getPlayWhenReady());dj.pause(2); + }); + } + if(expectedId.equals("dj-1")){ + // Deliver a delayed STOP at the registered retired session's real command + // boundary. Current Pause/Play above and below still use platform transport. + main(()->{ + try{ + java.lang.reflect.Field field=PlaybackService.class.getDeclaredField("instance");field.setAccessible(true); + PlaybackService service=(PlaybackService)field.get(null); + androidx.media3.session.MediaSession retired=null; + for(androidx.media3.session.MediaSession item:service.getSessions()) + if(item.getId().equals("dj-0"))retired=item; + assertNotNull("Retired deck session exists",retired); + Player current=PlaybackService.existingDj().decks[1];current.seekTo(600); + long beforeStop=current.getCurrentPosition();retired.getPlayer().stop(); + assertEquals("Retired Stop must not reset the current deck",beforeStop,current.getCurrentPosition()); + }catch(ReflectiveOperationException error){throw new AssertionError(error);} + }); + } + controller.getTransportControls().play(); + int deck=expectedId.equals("dj-1")?1:0; + await(()->{main(()->active.set(expectedId.isEmpty()?PlaybackService.player().isPlaying():PlaybackService.existingDj().decks[deck].isPlaying()));return active.get();}); + } + + private static void traceNotificationProvider(PlaybackService service){ + androidx.media3.session.MediaNotification.Provider delegate= + new androidx.media3.session.DefaultMediaNotificationProvider.Builder(service).setNotificationId(1001).build(); + androidx.media3.session.MediaNotification.Provider trace=new androidx.media3.session.MediaNotification.Provider(){ + @Override public androidx.media3.session.MediaNotification createNotification( + androidx.media3.session.MediaSession source, + com.google.common.collect.ImmutableList buttons, + androidx.media3.session.MediaNotification.ActionFactory actions, + androidx.media3.session.MediaNotification.Provider.Callback callback){ + android.util.Log.i("AMPNotificationFixture","create id="+source.getId()+" token="+source.getPlatformToken() + +" owner="+PlaybackService.owner()+" selected="+PlaybackService.existingDj().notificationDeck() + +" ready="+source.getPlayer().getPlayWhenReady()+" state="+source.getPlayer().getPlaybackState()); + return delegate.createNotification(source,buttons,actions,notification->{ + android.util.Log.i("AMPNotificationFixture","callback id="+source.getId()+" token="+source.getPlatformToken()); + callback.onNotificationChanged(notification); + }); + } + @Override public boolean handleCustomCommand(androidx.media3.session.MediaSession source,String action,android.os.Bundle extras){ + return delegate.handleCustomCommand(source,action,extras); + } + }; + try{ + java.lang.reflect.Method install=androidx.media3.session.MediaSessionService.class.getDeclaredMethod( + "setMediaNotificationProvider",androidx.media3.session.MediaNotification.Provider.class); + install.setAccessible(true);install.invoke(service,trace); + }catch(ReflectiveOperationException error){throw new AssertionError(error);} + } + private static boolean playing() { AtomicBoolean value = new AtomicBoolean(); main(() -> value.set(PlaybackService.player() != null && PlaybackService.player().isPlaying())); @@ -67,7 +186,7 @@ public void betaMixerOptInWaitsForStoppedPlaybackAndNeverCutsOverLive() throws E String endpoint = InstrumentationRegistry.getArguments().getString("amp_server", ""); org.junit.Assume.assumeTrue("Isolated fixture argument required", !endpoint.isEmpty()); assertEquals( - "Never alter household settings in this fixture", "http://10.0.2.2:28987", endpoint); + "Never alter household settings in this fixture", "http://127.0.0.1:28987", endpoint); assertEquals("full", BuildConfig.EDITION); assertTrue(android.os.Build.VERSION.SDK_INT >= 30); Context context = InstrumentationRegistry.getInstrumentation().getTargetContext(); @@ -219,7 +338,7 @@ public void legacyPadRecoveryStopsOnlyLoopedPadsAndKeepsDeckAndPrivateCueGates() throws Exception { String endpoint = InstrumentationRegistry.getArguments().getString("amp_server", ""); org.junit.Assume.assumeTrue("Isolated fixture argument required", !endpoint.isEmpty()); - assertEquals("http://10.0.2.2:28987", endpoint); + assertEquals("http://127.0.0.1:28987", endpoint); Context context = InstrumentationRegistry.getInstrumentation().getTargetContext(); context.stopService(new Intent(context, PlaybackService.class)); AtomicBoolean retired = new AtomicBoolean(); @@ -318,11 +437,11 @@ public void legacyPadRecoveryStopsOnlyLoopedPadsAndKeepsDeckAndPrivateCueGates() } } - @Test(timeout = 45000) + @Test(timeout = 90000) public void playerDjFocusHandoffsKeepTheSharedHardwareClockMoving() throws Exception { String endpoint = InstrumentationRegistry.getArguments().getString("amp_server", ""); org.junit.Assume.assumeTrue("Disposable native fixture required", !endpoint.isEmpty()); - assertEquals("http://10.0.2.2:28987", endpoint); + assertEquals("http://127.0.0.1:28987", endpoint); Context context = InstrumentationRegistry.getInstrumentation().getTargetContext(); SharedPreferences prefs = context.getSharedPreferences("settings", Context.MODE_PRIVATE); boolean previous = prefs.getBoolean("owned-pcm-master-candidate", false); @@ -330,12 +449,25 @@ public void playerDjFocusHandoffsKeepTheSharedHardwareClockMoving() throws Excep AtomicBoolean ready = new AtomicBoolean(); await(() -> {main(() -> ready.set(PlaybackService.player() == null));return ready.get();}); prefs.edit().putBoolean("owned-pcm-master-candidate", true).commit(); + if(android.os.Build.VERSION.SDK_INT>=33) + InstrumentationRegistry.getInstrumentation().getUiAutomation().grantRuntimePermission( + context.getPackageName(),android.Manifest.permission.POST_NOTIFICATIONS); File source = input(context); ActivityScenario home = null; try { home = ActivityScenario.launch(MainActivity.class); await(() -> {main(() -> ready.set(PlaybackService.player() != null));return ready.get();}); assertNotNull(PlaybackService.ownedOutput()); + main(()->{ + PlaybackService.dj(); + try{ + java.lang.reflect.Field owner=PlaybackService.class.getDeclaredField("instance");owner.setAccessible(true); + PlaybackService service=(PlaybackService)owner.get(null); + traceNotificationProvider(service); + for(androidx.media3.session.MediaSession transport:service.getSessions()) + assertFalse("Private cue must not publish a platform transport",transport.getId().equals("dj-2")||transport.getId().equals("dj-3")); + }catch(ReflectiveOperationException error){throw new AssertionError(error);} + }); main(() -> PlaybackService.player().addListener(new Player.Listener() { @Override public void onPlaybackStateChanged(int state) { if(state==Player.STATE_IDLE)android.util.Log.w("AMPMixerFixture","Focus fixture Player became idle",new Throwable("Player stop origin")); @@ -346,13 +478,34 @@ public void playerDjFocusHandoffsKeepTheSharedHardwareClockMoving() throws Excep for (int cycle = 0; cycle < 3; cycle++) { main(() -> {Player player = PlaybackService.player();player.setMediaItem(playerItem);player.setRepeatMode(Player.REPEAT_MODE_ONE);player.prepare();player.play();}); await(() -> {main(() -> ready.set(PlaybackService.player().isPlaying() && PlaybackService.player().getCurrentPosition() > 200));return ready.get();}); + assertNotificationTransport(context, ""); long playerFrames = PlaybackService.ownedOutput().presentedFrames(); + main(() -> { + DjEngine dj=PlaybackService.dj(); + for(int cue:new int[]{2,3}){dj.decks[cue].setMediaItem(djItem);dj.decks[cue].clearMediaItems();} + }); + await(() -> {main(() -> ready.set(PlaybackService.player().isPlaying() + && PlaybackService.ownedOutput().presentedFrames()>playerFrames+9600));return ready.get();}); main(() -> {DjEngine dj = PlaybackService.dj();dj.queue(java.util.Collections.singletonList(djItem));dj.auto(true);}); await(() -> {main(() -> {DjEngine dj = PlaybackService.existingDj();assertNull(dj.decks[0].getPlayerError());ready.set("dj".equals(PlaybackService.owner()) && dj.decks[0].isPlaying() && dj.decks[0].getCurrentPosition() > 500 && PlaybackService.ownedOutput().presentedFrames() > playerFrames + 9600);});return ready.get();}); + main(()->{DjEngine dj=PlaybackService.existingDj();dj.auto(false);dj.decks[0].setRepeatMode(Player.REPEAT_MODE_ONE);dj.setFader(.6f);}); + assertNotificationTransport(context, "dj-0"); + main(()->{ + DjEngine dj=PlaybackService.existingDj(); + dj.decks[0].setRepeatMode(Player.REPEAT_MODE_ONE); + dj.load(1,djItem,0);dj.decks[1].setRepeatMode(Player.REPEAT_MODE_ONE);dj.play(1);dj.setFader(.6f); + }); + await(()->{main(()->ready.set(PlaybackService.existingDj().decks[0].isPlaying()&&PlaybackService.existingDj().decks[1].isPlaying()));return ready.get();}); + assertNotificationTransport(context,"dj-1"); + await(()->{main(()->ready.set(PlaybackService.existingDj().decks[0].isPlaying()&&PlaybackService.existingDj().decks[1].isPlaying()));return ready.get();}); + main(()->{DjEngine dj=PlaybackService.existingDj();dj.setFader(1);dj.pause(0);}); + assertNotificationTransport(context,"dj-1"); + main(()->assertFalse("Notification resume must not restart the outgoing deck",PlaybackService.existingDj().decks[0].getPlayWhenReady())); long djFrames = PlaybackService.ownedOutput().presentedFrames(); main(PlaybackService::switchToPlayer); await(() -> {main(() -> {Player player = PlaybackService.player();assertNull(player.getPlayerError());ready.set("player".equals(PlaybackService.owner()) && player.isPlaying() && PlaybackService.ownedOutput().presentedFrames() > djFrames + 9600);});return ready.get();}); } + assertNotificationTransport(context, ""); android.media.AudioManager manager = (android.media.AudioManager)context.getSystemService(Context.AUDIO_SERVICE); android.media.AudioFocusRequest external = new android.media.AudioFocusRequest.Builder(android.media.AudioManager.AUDIOFOCUS_GAIN_TRANSIENT).setAudioAttributes(new android.media.AudioAttributes.Builder().setUsage(android.media.AudioAttributes.USAGE_MEDIA).build()).setOnAudioFocusChangeListener(change -> {}).build(); try { 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 b5c04e70..281b3cb6 100644 --- a/android/app/src/main/java/cloud/gitwide/ampverse/DjEngine.java +++ b/android/app/src/main/java/cloud/gitwide/ampverse/DjEngine.java @@ -37,6 +37,9 @@ void releaseLoop(int deck){ } final MediaItem[] staged=new MediaItem[4]; final long[] stagedPosition=new long[4]; + final long[] loadedEntry=new long[4]; + private long styleRevision; + private final long[] loadedStyleRevision=new long[4]; final boolean[] cueMode=new boolean[2],collapsed=new boolean[2]; final float[] samplerVolume={.7f,.7f}; final String[][] samples=new String[2][9], names=new String[2][9]; @@ -58,6 +61,54 @@ void releaseLoop(int deck){ int fadeSeconds=3; private int mixOutgoing; private boolean mixing,closed; + private long notificationPauseAt; + private final boolean[] notificationResume=new boolean[2]; + private int notificationFocus; + private boolean notificationBatch; + boolean notificationTransportBatch(){return notificationBatch;} + int notificationDeck(){ + if(notificationBatch)return notificationFocus; + int preferred=fader<.5f?0:1,other=1-preferred; + if(active(preferred))notificationFocus=preferred; + else if(active(other))notificationFocus=other; + else if(decks[notificationFocus].getCurrentMediaItem()==null){ + if(decks[preferred].getCurrentMediaItem()!=null)notificationFocus=preferred; + else if(decks[other].getCurrentMediaItem()!=null)notificationFocus=other; + } + return notificationFocus; + } + private void pauseFromNotification(){ + if(notificationPauseAt!=0)return; + notificationDeck();notificationPauseAt=SystemClock.uptimeMillis(); + for(int side=0;side<2;side++)notificationResume[side]=decks[side].getPlayWhenReady(); + handler.removeCallbacks(autoTick);handler.removeCallbacks(mixTick); + notificationBatch=true; + try{ + if(scratch!=null)scratch.pauseAll(); + for(int side=0;side<2;side++)decks[side].pause(); + stopSamplerPads(); + }finally{notificationBatch=false;} + PlaybackService.djNotificationChanged(); + } + private void playFromNotification(int selected){ + if(notificationPauseAt==0){play(selected);return;} + long elapsed=SystemClock.uptimeMillis()-notificationPauseAt;notificationPauseAt=0; + if(mixStarted!=0)mixStarted+=elapsed; + if(mixWaitingSince!=0)mixWaitingSince+=elapsed; + notificationBatch=true; + try{for(int side=0;side<2;side++){boolean resume=notificationResume[side];notificationResume[side]=false;if(resume)play(side);}} + finally{notificationBatch=false;} + PlaybackService.djNotificationChanged(); + if(mixing)handler.post(mixTick); + if(auto)handler.post(autoTick); + } + private void stopFromNotification(){ + notificationDeck();notificationBatch=true; + try{notificationPauseAt=0;java.util.Arrays.fill(notificationResume,false);pauseAll();stop(0);stop(1);} + finally{notificationBatch=false;} + PlaybackService.djNotificationChanged(); + } + private float remoteMaster=Float.NaN,remoteFader=Float.NaN; private VinylScratch scratch; final List autoQueue=new ArrayList<>(); @@ -65,13 +116,50 @@ void releaseLoop(int deck){ private final Set requests=new LinkedHashSet<>(); private int nextAuto; private JSONObject autoRules=new JSONObject(); + private boolean liveStyleOverride; + private int plannedAuto=-1; + String mixStyle(){String value=autoRules.optString("style","Steady");return value.equalsIgnoreCase("Hype")?"Hype":value.equalsIgnoreCase("Chill")?"Chill":"Steady";} + /** Session-only controls: never edit the playlist or interrupt either live deck. */ + void mixStyle(String style){ + if(!Arrays.asList("Hype","Steady","Chill").contains(style))throw new IllegalArgumentException("Unknown mixing style"); + if(!mixStyle().equals(style))styleRevision++; + try{autoRules.put("style",style);}catch(JSONException error){throw new IllegalStateException(error);} + liveStyleOverride=true;plannedAuto=-1; + message=style+" · applies to upcoming mixes.";PlaybackService.phoneStateChanged(); + } + private void planAuto(int current,int other){ + if(!(liveStyleOverride||autoRules.optBoolean("smart"))||plannedAuto==nextAuto||nextAuto>=autoQueue.size()||active(other)||mixing)return; + plannedAuto=nextAuto; + // Explicit requests keep their place. Score remaining songs once, not + // each UI/audio tick, using the existing tempo/key/energy policy. + if(requests.contains(autoQueue.get(nextAuto).mediaId))return; + // The queue already contains the user's explicit progression. A style + // change may alter entry/exit policy, but must not rewrite that ramp. + if(autoRules.optJSONObject("energy_progression")!=null)return; + List pending=new ArrayList<>(autoQueue.subList(nextAuto,autoQueue.size())); + pending.removeIf(item->requests.contains(item.mediaId)); + JSONObject rankingRules; + try{ + rankingRules=new JSONObject(autoRules.toString()); + double target=rankingRules.optDouble("energy",Double.NaN); + 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()); + 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){ + MediaItem next=autoQueue.get(nextAuto),loaded=decks[deck].getCurrentMediaItem(); + if(!active(deck)&&(loaded==null||!next.mediaId.equals(loaded.mediaId)||loadedStyleRevision[deck]!=styleRevision)) + load(deck,next,DjLogic.entry(next,autoRules)); + } private boolean autoStreamed; String playlistName(){if(autoSource.isEmpty())return "";String name=autoRules.optString("name","").trim();JSONObject envelope=autoRules.optJSONObject("_sync_envelope");if(name.isEmpty()&&envelope!=null){JSONObject document=envelope.optJSONObject("document");if(document!=null)name=document.optString("name","").trim();}return name.isEmpty()?"Playlist":name;} boolean playlistStreamed(){return !autoSource.isEmpty()&&autoStreamed;} private final List 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;return true;} + 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 Runnable autoTick=this::advanceAuto; float fader=0,master=.75f; @@ -86,18 +174,26 @@ void releaseLoop(int deck){ decks[i].setAudioAttributes(new androidx.media3.common.AudioAttributes.Builder().setUsage(C.USAGE_MEDIA).setContentType(C.AUDIO_CONTENT_TYPE_MUSIC).build(),false); decks[i].setHandleAudioBecomingNoisy(true);decks[i].setWakeMode(C.WAKE_MODE_LOCAL); final int deck=i; - decks[i].addListener(new Player.Listener(){@Override public void onPlaybackStateChanged(int state){if(deck<2)PlaybackService.phoneStateChanged();}@Override public void onMediaMetadataChanged(androidx.media3.common.MediaMetadata metadata){if(deck<2)PlaybackService.phoneStateChanged();}@Override public void onPlayWhenReadyChanged(boolean ready,int reason){if(deck<2)PlaybackService.phoneControlChanged();if(ready&&decks[deck].getPlayWhenReady()){if(scratch!=null&&scratch.busy(deck))scratch.invalidate(deck);if(deck<2)PlaybackService.claimDj();}}@Override public void onPlayerError(PlaybackException error){if(scratch!=null)scratch.invalidate(deck);message=title(deck)+": "+error.getErrorCodeName();}@Override public void onMediaItemTransition(MediaItem item,int reason){if(sectionLoops[deck]!=null&&!sectionLoops[deck].source.equals(loopSource(deck)))cancelSectionLoop(deck);if(deck<2)PlaybackService.phoneSourceChanged();if(scratch!=null)scratch.invalidate(deck);}@Override public void onPositionDiscontinuity(Player.PositionInfo oldPosition,Player.PositionInfo newPosition,int reason){if(deck<2)PlaybackService.phoneControlChanged();if(scratch!=null&&scratch.busy(deck))scratch.invalidate(deck);}}); + decks[i].addListener(new Player.Listener(){@Override public void onIsPlayingChanged(boolean playing){if(deck<2&&PlaybackService.djNotificationCurrent(deck))PlaybackService.djNotificationChanged();}@Override public void onPlaybackStateChanged(int state){if(deck<2)PlaybackService.phoneStateChanged();}@Override public void onMediaMetadataChanged(androidx.media3.common.MediaMetadata metadata){if(deck<2)PlaybackService.phoneStateChanged();}@Override public void onPlayWhenReadyChanged(boolean ready,int reason){if(deck<2)PlaybackService.phoneControlChanged();if(ready&&decks[deck].getPlayWhenReady()){if(scratch!=null&&scratch.busy(deck))scratch.invalidate(deck);if(deck<2)PlaybackService.claimDj();}}@Override public void onPlayerError(PlaybackException error){if(scratch!=null)scratch.invalidate(deck);message=title(deck)+": "+error.getErrorCodeName();}@Override public void onMediaItemTransition(MediaItem item,int reason){if(sectionLoops[deck]!=null&&!sectionLoops[deck].source.equals(loopSource(deck)))cancelSectionLoop(deck);if(deck<2)PlaybackService.phoneSourceChanged();if(scratch!=null)scratch.invalidate(deck);}@Override public void onPositionDiscontinuity(Player.PositionInfo oldPosition,Player.PositionInfo newPosition,int reason){if(deck<2)PlaybackService.phoneControlChanged();if(scratch!=null&&scratch.busy(deck))scratch.invalidate(deck);}}); + // Private cue decks are local audition paths, never platform media sessions. + if(i<2){ // Remote/notification commands silence scratch before the normal player can run. Player guarded=new ForwardingPlayer(decks[i]){ private void stopScratch(){if(scratch!=null)scratch.invalidate(deck);} - @Override public void play(){stopScratch();super.play();} - @Override public void pause(){stopScratch();super.pause();} - @Override public void setPlayWhenReady(boolean ready){stopScratch();super.setPlayWhenReady(ready);} + @Override public void play(){stopScratch();if(deck<2)playFromNotification(deck);else super.play();} + @Override public void pause(){stopScratch();if(deck<2)pauseFromNotification();else super.pause();} + @Override public void setPlayWhenReady(boolean ready){stopScratch();if(deck<2){if(ready)playFromNotification(deck);else pauseFromNotification();}else super.setPlayWhenReady(ready);} @Override public void seekTo(long position){stopScratch();super.seekTo(position);} @Override public void seekTo(int index,long position){stopScratch();super.seekTo(index,position);} - @Override public void stop(){stopScratch();super.stop();} + @Override public void stop(){ + // Android can retire an old card after its token has been replaced. + // A command for that old source cannot stop the current room mix. + if(deck<2&&!PlaybackService.djNotificationCurrent(deck))return; + stopScratch();if(deck<2)stopFromNotification();else super.stop(); + } }; MediaSession session=new MediaSession.Builder(service,guarded).setId("dj-"+i).build();sessions.add(session);service.addSession(session); + } } scratch=new VinylScratch(service,decks,text->message=text,PlaybackService::claimDjForScratch); OwnedAudioOutput owned=PlaybackService.ownedOutput(); @@ -117,7 +213,7 @@ void releaseLoop(int deck){ } private static boolean readable(Context context,android.net.Uri uri){try(android.content.res.AssetFileDescriptor descriptor=context.getContentResolver().openAssetFileDescriptor(uri,"r")){return descriptor!=null;}catch(Exception e){return false;}} - static JSONObject preparation(MediaItem item){try{JSONObject prep=new JSONObject(item!=null&&item.mediaMetadata.extras!=null?item.mediaMetadata.extras.getString("amp-preparation","{}"):"{}");if(prep.optBoolean("sync_source_changed")&&!prep.optBoolean("manual_override")){for(String key:new String[]{"bpm","beat_offset","key","harmonic_key","analysis","energy_profile","energy","stems","cues"})prep.remove(key);prep.put("cue_in",0).remove("cue_out");}return prep;}catch(Exception e){return new JSONObject();}} + static JSONObject preparation(MediaItem item){try{JSONObject prep=new JSONObject(item!=null&&item.mediaMetadata.extras!=null?item.mediaMetadata.extras.getString("amp-preparation","{}"):"{}");if(prep.optBoolean("sync_source_changed")&&!prep.optBoolean("manual_override")){for(String key:new String[]{"bpm","beat_offset","key","harmonic_key","analysis","energy_profile","energy","perceptual_energy","energy_profile_method","section_activity","auto_mix_sections","stems","cues"})prep.remove(key);prep.put("cue_in",0).remove("cue_out");}return prep;}catch(Exception e){return new JSONObject();}} static Bundle preparedExtras(String json){Bundle extras=new Bundle();extras.putString("amp-preparation",json);return extras;} void usedPrivateTokens(java.util.Set active){ for(ExoPlayer deck:decks)if(deck!=null)for(int n=0;nwithin){message="That request window is full; wait for a song to play.";return;} for(int i=nextAuto;i=autoQueue.size()&&!refillAuto()){message="No next song available in this playlist.";return;} - MediaItem queued=autoQueue.get(nextAuto),loaded=decks[next].getCurrentMediaItem(); - if(!active(next)&&(loaded==null||!queued.mediaId.equals(loaded.mediaId)))load(next,queued,DjLogic.entry(queued,autoRules)); + planAuto(mixOutgoing,next); + prepareAutoDeck(next); } if(decks[next].getCurrentMediaItem()==null){message="Load the other deck before mixing.";return;} beginMixTo(mixOutgoing,next); @@ -222,7 +318,7 @@ void dislike(int deck){ String key=PhonePlaylistDislike.serverKey(item); java.util.function.Predicate rejected=value->item.mediaId.equals(value.mediaId)||!key.isEmpty()&&key.equals(PhonePlaylistDislike.serverKey(value)); int removedBefore=0;for(int n=0;n items,JSONObject rules){ } 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; } /** Explicit playlist playback, unlike staging a queue or loading a manual deck. */ @@ -278,8 +376,9 @@ private void advanceAuto(){ if(!mixing){int current=fader<.5?0:1,other=1-current; 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;} - if(!active(other)){MediaItem next=autoQueue.get(nextAuto);MediaItem loaded=decks[other].getCurrentMediaItem();if(loaded==null||!next.mediaId.equals(loaded.mediaId)){load(other,next,DjLogic.entry(next,autoRules));}} - long duration=cueOut(decks[current].getCurrentMediaItem(),decks[current].getDuration());if(duration>0&&duration-decks[current].getCurrentPosition()<=fadeSeconds*1000L){mixNext();} + planAuto(current,other); + prepareAutoDeck(other); + 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();} } if(auto)handler.postDelayed(autoTick,200); @@ -328,11 +427,11 @@ List playerQueue(){ if(playerRepeats())for(MediaItem item:autoSource){boolean included=false;for(MediaItem existing:result)if(existing.mediaId.equals(item.mediaId)){included=true;break;}if(!included)result.add(item);} return result; } - void pauseForPlayer(){if(scratch!=null)scratch.pauseAll();auto(false);for(ExoPlayer deck:decks)deck.pause();for(int side=0;side<2;side++)for(int pad=0;pad<9;pad++)stopPad(side,pad);} + void pauseForPlayer(){notificationPauseAt=0;java.util.Arrays.fill(notificationResume,false);if(scratch!=null)scratch.pauseAll();auto(false);for(ExoPlayer deck:decks)deck.pause();for(int side=0;side<2;side++)for(int pad=0;pad<9;pad++)stopPad(side,pad);} void stopPad(int side,int pad){if(streams[side][pad]!=0)stopSample(streams[side][pad]);streams[side][pad]=0;} void clearPad(int side,int pad){SamplerStore.clear(prefs,side,pad);stopPad(side,pad);unloadSample(sampleIds[side][pad]);ready.remove(sampleIds[side][pad]);sampleIds[side][pad]=0;samples[side][pad]="";names[side][pad]="PAD "+(pad+1);} void loop(int side,int pad,boolean value){SamplerStore.save(prefs,side,pad,samples[side][pad],names[side][pad],value);loops[side][pad]=value;if(streams[side][pad]!=0)loopSample(streams[side][pad],value);} - void pauseAll(){if(scratch!=null)scratch.pauseAll();auto=false;handler.removeCallbacks(autoTick);cancelMix();for(ExoPlayer deck:decks)deck.pause();for(int s=0;s<2;s++)for(int p=0;p<9;p++)stopPad(s,p);} + void pauseAll(){notificationPauseAt=0;java.util.Arrays.fill(notificationResume,false);if(scratch!=null)scratch.pauseAll();auto=false;handler.removeCallbacks(autoTick);cancelMix();for(ExoPlayer deck:decks)deck.pause();for(int s=0;s<2;s++)for(int p=0;p<9;p++)stopPad(s,p);} void prepareScratch(){if(scratch!=null)for(int deck=0;deck<4;deck++)scratch.prepare(deck);} boolean beginScratch(int deck){if(scratch==null)return false;if(!scratch.ready(deck))return scratch.begin(deck);if(manager.requestAudioFocus(focus)!=AudioManager.AUDIOFOCUS_REQUEST_GRANTED){message="Audio focus unavailable. Current playback was not changed.";return false;}if(!scratch.begin(deck))return false;cancelMix();return true;} long scratchToken(int deck){return scratch==null?0:scratch.token(deck);} 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 68216c94..0f345a71 100644 --- a/android/app/src/main/java/cloud/gitwide/ampverse/DjLogic.java +++ b/android/app/src/main/java/cloud/gitwide/ampverse/DjLogic.java @@ -14,16 +14,17 @@ final class DjLogic { static MediaItem replacement(android.content.Context context,MediaItem outgoing,List candidates,JSONObject rules,Collection recent){ MediaItem best=null;double bestCost=Double.POSITIVE_INFINITY; android.content.SharedPreferences details=context.getSharedPreferences("phone-track-details",0); - double fromTempo=outgoing==null?0:PhonePlaylists.bpm(context,outgoing),fromEnergy=outgoing==null?.5:PhonePlaylists.energy(context,outgoing); + 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; - double energy=PhonePlaylists.energy(context,item); + 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","")))); - if(style.equalsIgnoreCase("hype"))cost+=Math.max(0,fromEnergy-energy);if(style.equalsIgnoreCase("chill"))cost+=Math.max(0,energy-fromEnergy); + if(Double.isFinite(fromEnergy)&&Double.isFinite(energy)){if(style.equalsIgnoreCase("hype"))cost+=Math.max(0,fromEnergy-energy);if(style.equalsIgnoreCase("chill"))cost+=Math.max(0,energy-fromEnergy);} if(PhoneSmartRules.contains(rules.optJSONArray("preferred"),item.mediaId))cost-=.15; if(costOwnedPcmMixer.RATE)throw new IllegalArgumentException("Export queue bounded to one second");this.capacity=capacity;pcm=new short[capacity*2];} boolean offer(short[] input,int frames,long masterFrame){ + if(closed)return rejectOffer(Rejection.CLOSED); + if(frames<0||(long)frames*2>input.length)return rejectOffer(Rejection.INVALID_RANGE); + if(captureSuspended)return true; + long epoch=captureEpoch;if(producerEpoch!=epoch){nextMasterFrame=-1;producerEpoch=epoch;} long at=write,consumed=read; - if(closed||frames<0||(long)frames*2>input.length||frames>capacity-(at-consumed)||(nextMasterFrame>=0&&masterFrame!=nextMasterFrame))return false; + if(frames>capacity-(at-consumed))return rejectOffer(Rejection.CAPACITY); + if(nextMasterFrame>=0&&masterFrame!=nextMasterFrame)return rejectOffer(Rejection.DISCONTINUITY); for(int i=0;ioutput.length)throw new IllegalArgumentException("Invalid PCM read range"); - if(closed)return 0;long at=read;int frames=(int)Math.min(maxFrames,write-at); + if(closed)return 0; + long epoch=captureEpoch; + if(captureSuspended){ + read=write;consumerEpoch=epoch; + // Only the consumer can release capture, after discarding old occupancy. + // Render offers keep being skipped until this acknowledgment; no render waits. + if(resumeRequested){resumeRequested=false;captureSuspended=false;} + return 0; + } + if(consumerEpoch!=epoch){read=write;consumerEpoch=epoch;} + long at=read;int frames=(int)Math.min(maxFrames,write-at); for(int i=0;i events) { @@ -54,6 +56,7 @@ synchronized void start( throw new IOException("Stop the current phone broadcast before choosing another source"); if (!stillSelected.getAsBoolean()) throw new IOException("Playback or host selection changed; choose the source again"); + failure=null; Job job = new Job(session, stillSelected, eligible); current = job; update("Preparing this phone’s master broadcast"); @@ -75,7 +78,7 @@ String status() { synchronized void stop() { Job job = current; if (job != null && job.cancelled.compareAndSet(false, true)) { - job.session.cancel(); + job.session.cancel();job.encodingCancelled.set(true); Encoder encoder = job.encoder; if (encoder != null) encoder.cancel(); } @@ -94,6 +97,7 @@ private void update(String text) { private void run(Job job) { try { for (int attempt = 0; !job.cancelled.get(); attempt++) { + job.encodingCancelled.set(false); MasterPcmQueue queue = new MasterPcmQueue(OwnedPcmMixer.RATE / 4); Encoder encoder = null; try { @@ -102,32 +106,26 @@ private void run(Job job) { // Native pipe/codec startup may take seconds; export only current audio once ready. encoder.prepare(); if (job.cancelled.get()) break; + // A guarded reconnect is control traffic, not part of the live PCM deadline. + // Keep rendering locally and attach fresh capture only after the owner is ready. + if (job.session.state() == PhoneLiveSession.State.RECONNECTING) { + if (!job.eligible.getAsBoolean()) + throw new PhoneLiveSession.Rejected("Source changed during reconnect"); + job.session.resume(); + } + if (job.cancelled.get()) break; mixer.fanout(queue); - encoder.encode( - queue, - job.cancelled, - (packet, count) -> { - if (job.cancelled.get()) - throw new PhoneLiveSession.Rejected("Phone broadcast cancelled"); - if (!job.eligible.getAsBoolean()) - throw new PhoneLiveSession.Rejected("Phone switched to receiving a station"); - // Claim the host only after a real encoded packet exists. Startup failure preserves - // its program. - if (job.session.state() == PhoneLiveSession.State.IDLE) { - if (!job.selected.getAsBoolean()) - throw new PhoneLiveSession.Rejected( - "Playback source changed during preparation"); - job.session.begin(); - } else if (job.session.state() == PhoneLiveSession.State.RECONNECTING) { - if (!job.eligible.getAsBoolean()) - throw new PhoneLiveSession.Rejected("Source changed during reconnect"); - job.session.resume(); - } - job.session.send(packet, count); - synchronized(PhoneMasterBroadcast.this){if(current==job&&!job.cancelled.get())onAir(true); } - update("This phone’s master is broadcasting"); - }); - if (!job.cancelled.get()) throw new IOException("Phone encoder stopped unexpectedly"); + Encoder activeEncoder=encoder; + try(PhoneMasterUpload uploads=new PhoneMasterUpload(job.session,queue,job.encodingCancelled, + job.selected,job.eligible,activeEncoder::cancel,()->{ + synchronized(PhoneMasterBroadcast.this){if(current==job&&!job.cancelled.get())onAir(true);} + update("This phone's master is broadcasting"); + })){ + try{encoder.encode(queue,job.encodingCancelled,uploads::packet);} + catch(IOException error){IOException uploadError=uploads.failure();if(uploadError!=null)throw uploadError;throw error;} + IOException uploadError=uploads.failure();if(uploadError!=null)throw uploadError; + if(!job.cancelled.get())throw new IOException("Phone encoder stopped unexpectedly"); + } break; } catch (IOException error) { onAir(false); @@ -151,8 +149,10 @@ private void run(Job job) { } } } catch (IOException | RuntimeException error) { - if (!job.cancelled.get()) + if (!job.cancelled.get()){ + failure=error; update("Phone broadcast stopped. Playback continues locally; reconnect explicitly."); + } } finally { onAir(false); job.session.finish(); @@ -173,6 +173,7 @@ private static final class Job { final PhoneLiveSession session; final BooleanSupplier selected, eligible; final AtomicBoolean cancelled = new AtomicBoolean(); + final AtomicBoolean encodingCancelled = new AtomicBoolean(); volatile Encoder encoder; Job(PhoneLiveSession session, BooleanSupplier selected, BooleanSupplier eligible) { diff --git a/android/app/src/main/java/cloud/gitwide/ampverse/PhoneMasterUpload.java b/android/app/src/main/java/cloud/gitwide/ampverse/PhoneMasterUpload.java new file mode 100644 index 00000000..edb650ed --- /dev/null +++ b/android/app/src/main/java/cloud/gitwide/ampverse/PhoneMasterUpload.java @@ -0,0 +1,108 @@ +package cloud.gitwide.ampverse; + +import java.io.IOException; +import java.util.Arrays; +import java.util.concurrent.ArrayBlockingQueue; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; +import java.util.function.BooleanSupplier; + +/** Ordered network worker. HTTP acknowledgments never block PCM encoding. */ +final class PhoneMasterUpload implements AutoCloseable { + // At192kbps this is about1.37seconds queued, plus one8KiB in-flight packet. + // The session also owns its retry copy; HTTP/codec working buffers are separate. + // A sustained slow receiver fails explicitly; encoded packets are never dropped. + static final int MAX_QUEUED_BYTES=32768; + private final ArrayBlockingQueue packets=new ArrayBlockingQueue<>(64); + private final AtomicInteger queuedBytes=new AtomicInteger(); + private final AtomicReference failure=new AtomicReference<>(); + private final PhoneLiveSession session; + private final MasterPcmQueue pcm; + private final AtomicBoolean encodingCancelled; + private final BooleanSupplier selected,eligible; + private final Runnable cancelEncoder,delivered; + private final boolean initial; + private final Thread worker; + private volatile boolean ready,closing; + private boolean proofQueued; + + PhoneMasterUpload(PhoneLiveSession session,MasterPcmQueue pcm,AtomicBoolean encodingCancelled, + BooleanSupplier selected,BooleanSupplier eligible,Runnable cancelEncoder,Runnable delivered){ + this.session=session;this.pcm=pcm;this.encodingCancelled=encodingCancelled; + this.selected=selected;this.eligible=eligible;this.cancelEncoder=cancelEncoder;this.delivered=delivered; + initial=session.state()==PhoneLiveSession.State.IDLE;ready=!initial; + worker=new Thread(this::run,"amp-phone-upload");worker.setDaemon(true);worker.start(); + } + + /** Only the encoder producer calls this; it never waits for network I/O. */ + void packet(byte[] encoded,int length)throws IOException{ + IOException problem=failure.get();if(problem!=null)throw problem; + if(closing||encodingCancelled.get())throw new PhoneLiveSession.Rejected("Phone broadcast cancelled"); + if(encoded==null||length<1||length>PhoneLiveSession.MAX_PACKET||length>encoded.length) + throw new IllegalArgumentException("Invalid encoded packet"); + if(!eligible.getAsBoolean())throw new PhoneLiveSession.Rejected("Phone switched to receiving a station"); + if(initial&&!ready){ + if(!proofQueued){ + if(!selected.getAsBoolean())throw new PhoneLiveSession.Rejected("Playback source changed during preparation"); + proofQueued=true;pcm.suspendCapture(); + } + // Retain every encoded byte, including partial-frame pipe reads. The PCM + // gate bounds startup output; deleting encoded chunks would splice MP3 frames. + } + int bytes=queuedBytes.addAndGet(length); + if(bytes>MAX_QUEUED_BYTES){queuedBytes.addAndGet(-length);throw new IOException("Phone live upload backlog exceeded its bounded budget");} + if(!packets.offer(Arrays.copyOf(encoded,length))){ + queuedBytes.addAndGet(-length);throw new IOException("Phone live upload packet budget exceeded"); + } + } + + IOException failure(){return failure.get();} + + private void run(){ + try{ + while(!closing&&!encodingCancelled.get()){ + byte[] packet=packets.take();queuedBytes.addAndGet(-packet.length); + if(closing||encodingCancelled.get())break; + if(!eligible.getAsBoolean())throw new PhoneLiveSession.Rejected("Phone switched to receiving a station"); + if(initial&&!ready){ + if(!selected.getAsBoolean())throw new PhoneLiveSession.Rejected("Playback source changed during preparation"); + session.begin(); + if(closing||encodingCancelled.get())break; + ready=true;pcm.resumeCapture(); + } + session.send(packet,packet.length); + if(!closing&&!encodingCancelled.get())delivered.run(); + } + }catch(InterruptedException interrupted){ + Thread.currentThread().interrupt(); + if(!closing)failed(new IOException("Phone upload interrupted",interrupted)); + }catch(IOException error){if(!closing)failed(error);} + catch(RuntimeException error){ + PhoneLiveSession.Rejected invalid=new PhoneLiveSession.Rejected("Phone upload failed"); + invalid.initCause(error);if(!closing)failed(invalid); + } + } + + private void failed(IOException error){ + failure.compareAndSet(null,error);encodingCancelled.set(true);cancelEncoder.run(); + } + + @Override public void close()throws IOException{ + closing=true;worker.interrupt(); + boolean interrupted=false,aborted=false; + try{worker.join(5000);} + catch(InterruptedException stop){interrupted=true;} + if(worker.isAlive()){ + // A send may be in its same-sequence retry. Abort that request, then join + // before this owner can be cleaned up or any replacement attempt can run. + aborted=true;session.cancel();worker.interrupt(); + try{worker.join(5000);} + catch(InterruptedException stop){interrupted=true;} + } + if(interrupted)Thread.currentThread().interrupt(); + if(worker.isAlive())throw new PhoneLiveSession.Rejected("Phone upload did not stop; reconnect explicitly"); + packets.clear();queuedBytes.set(0); + if(aborted||interrupted)throw new PhoneLiveSession.Rejected("Phone upload shutdown cancelled; reconnect explicitly"); + } +} diff --git a/android/app/src/main/java/cloud/gitwide/ampverse/PhoneMixSections.java b/android/app/src/main/java/cloud/gitwide/ampverse/PhoneMixSections.java new file mode 100644 index 00000000..4849d7ee --- /dev/null +++ b/android/app/src/main/java/cloud/gitwide/ampverse/PhoneMixSections.java @@ -0,0 +1,82 @@ +package cloud.gitwide.ampverse; + +import org.json.*; +import java.util.Locale; + +/** Consumes the offline engine's portable decisions. No phone-side analysis. */ +final class PhoneMixSections { + private static Object field(JSONObject p,String key){JSONObject nested=p.optJSONObject("extensions");return p.has(key)?p.opt(key):nested==null?null:nested.opt(key);} + private static JSONObject object(JSONObject p,String key){Object value=field(p,key);return value instanceof JSONObject?(JSONObject)value:null;} + private static boolean version(JSONObject profile,long expected){Object value=profile==null?null:profile.opt("version");return (value instanceof Integer||value instanceof Long)&&((Number)value).longValue()==expected;} + static boolean comparableProfile(JSONObject p){return version(object(p,"energy_profile"),2);} + private static double validEnergy(JSONObject p,String key){Object measured=field(p,key);double value=measured instanceof Number?((Number)measured).doubleValue():Double.NaN;return Double.isFinite(value)&&value>=0&&value<=1?value:Double.NaN;} + static double trackEnergy(JSONObject p){ + JSONObject analysis=object(p,"analysis"),profile=object(p,"energy_profile"); + if("manual".equals(field(p,"energy_source")))return validEnergy(p,"energy"); + if(field(p,"perceptual_energy")!=null)return validEnergy(p,"perceptual_energy"); + String engine=analysis==null?"":analysis.optString("engine"); + boolean legacy=version(profile,1)||engine.matches("amp-prep-heuristic-[1-5]"); + boolean protectedValue=Boolean.TRUE.equals(field(p,"manual_override"))||analysis!=null&&analysis.optBoolean("reviewed"); + return legacy&&!protectedValue?Double.NaN:validEnergy(p,"energy"); + } + static double sectionEnergy(JSONObject p,long milliseconds){ + if(milliseconds<0||!comparableProfile(p))return Double.NaN; + JSONObject profile=object(p,"energy_profile");double seconds=milliseconds/1000.; + double duration=profile.optDouble("duration",Double.NaN);if(!Double.isFinite(duration)||seconds>=duration)return Double.NaN; + JSONArray sections=profile.optJSONArray("sections"); + if(sections!=null)for(int i=0;i=section.optDouble("start",Double.NaN)&&seconds=0&&value<=1?value:Double.NaN;}} + JSONArray curve=profile.optJSONArray("curve");double step=profile.optDouble("step",Double.NaN); + if(curve==null||!Double.isFinite(step)||step<=0)return Double.NaN; + double value=curve.optDouble((int)(seconds/step),Double.NaN);return Double.isFinite(value)&&value>=0&&value<=1?value:Double.NaN; + } + private static boolean hype(JSONObject rules){return rules.optString("style","Steady").equalsIgnoreCase("Hype");} + private static double end(JSONObject p){return p.optDouble("cue_out",p.optJSONObject("analysis")==null?Double.POSITIVE_INFINITY:p.optJSONObject("analysis").optDouble("duration",Double.POSITIVE_INFINITY));} + private static JSONObject plan(JSONObject p){ + JSONObject plan=object(p,"auto_mix_sections"),analysis=object(p,"analysis"); + JSONArray manual=p.optJSONArray("manual_cues"); + if(p.optBoolean("manual_override")||manual!=null&&manual.length()>0||analysis!=null&&analysis.optBoolean("reviewed")||Boolean.FALSE.equals(field(p,"energy_section_mixing"))||plan==null||!comparableProfile(p))return null; + double duration=plan.optDouble("duration",Double.NaN),entry=plan.optDouble("entry",Double.NaN); + double measured=analysis==null?Double.NaN:analysis.optDouble("duration",Double.NaN),passage=plan.optDouble("minimum_passage",Double.NaN); + if(plan.optInt("version")!=1||!plan.optString("method").equals("amp-section-activity-1")||!plan.optString("engine").equals("amp-prep-heuristic-6")||!Double.isFinite(duration)||duration<=0||duration>21600||analysis==null||!analysis.optString("engine").equals(plan.optString("engine"))||!Double.isFinite(measured)||Math.abs(measured-duration)>.01||!Double.isFinite(entry)||entry<0||entry>=duration||!Double.isFinite(passage)||passage<12||passage>120||entry+passage>duration||entry+passage>end(p))return null; + return plan; + } + private static boolean exitKind(String kind){return kind.equals("drop_end")||kind.equals("chorus_end")||kind.equals("mix_out")||kind.equals("section_end");} + static long entry(JSONObject p,JSONObject rules,long prepared){ + if(!hype(rules))return prepared; + double end=end(p),marked=Double.POSITIVE_INFINITY; + JSONArray cues=p.optJSONArray("manual_cues"); + if(rules.optBoolean("use_manual_cues",true)&&cues!=null)for(int i=0;i=prepared/1000.&&seconds=prepared/1000.&&at16384)return preparedEnd; + double previous=-1,selected=Double.NaN; + for(int i=0;iplan.optDouble("duration"))return preparedEnd; + previous=candidate; + if(!Double.isFinite(selected)&&candidate>=entry+passage+fadeSeconds&&candidate<=preparedEnd/1000.)selected=candidate; + } + return Double.isFinite(selected)?(long)(selected*1000):preparedEnd; + } + if(plan.has("exit_candidates"))return preparedEnd; + if(!Double.isFinite(at)||!Double.isFinite(fadeSeconds)||fadeSeconds<0||atpreparedEnd/1000.)return preparedEnd; + return (long)(at*1000); + } +} diff --git a/android/app/src/main/java/cloud/gitwide/ampverse/PhonePlaylists.java b/android/app/src/main/java/cloud/gitwide/ampverse/PhonePlaylists.java index 110fa0bb..179e8700 100644 --- a/android/app/src/main/java/cloud/gitwide/ampverse/PhonePlaylists.java +++ b/android/app/src/main/java/cloud/gitwide/ampverse/PhonePlaylists.java @@ -13,7 +13,7 @@ final class PhonePlaylists { static void remove(Context context,String id)throws JSONException{JSONArray next=new JSONArray(),all=local(context);for(int i=0;i=0&&value<=1?value:Double.NaN;} static List tracks(Context context,JSONObject list)throws JSONException{if(list.has("_sync_envelope"))try{if(LibraryOffline.saved(context,list)!=null)return LibraryOffline.items(context,list);return PlaylistSync.items(context,list);}catch(Exception e){throw new IllegalStateException("Cannot resolve saved server playlist",e);}return tracks(context,list,new HashSet<>());} private static List tracks(Context context,JSONObject list,Set visited)throws JSONException { if(list.has("_sync_envelope"))try{if(LibraryOffline.saved(context,list)!=null)return LibraryOffline.items(context,list);return PlaylistSync.items(context,list);}catch(Exception error){throw new IllegalStateException("Saved server playlist unavailable",error);} @@ -31,10 +31,10 @@ private static List tracks(Context context,JSONObject list,Setenergy(context,song)).average().orElse(.5); - Map tempos=new HashMap<>(),energies=new HashMap<>();Map keys=new HashMap<>();android.content.SharedPreferences details=context.getSharedPreferences("phone-track-details",0);for(MediaItem song:songs){tempos.put(song.mediaId,bpm(context,song));energies.put(song.mediaId,energy(context,song));keys.put(song.mediaId,details.getString(song.mediaId+":key",DjEngine.preparation(song).optString("harmonic_key","")));} + String style=list.optString("style","Steady");double target=list.optDouble("energy",-1);boolean explicitTarget=Double.isFinite(target)&&target>=0&&target<=1;if(!explicitTarget)target=SharedDjLogic.styleTarget(style,0); + Map tempos=new HashMap<>(),energies=new HashMap<>();Map keys=new HashMap<>();android.content.SharedPreferences details=context.getSharedPreferences("phone-track-details",0);for(MediaItem song:songs){tempos.put(song.mediaId,bpm(context,song));energies.put(song.mediaId,knownEnergy(context,song));keys.put(song.mediaId,details.getString(song.mediaId+":key",DjEngine.preparation(song).optString("harmonic_key","")));} final double desired=target;Comparator start=Comparator.comparingDouble(song->Math.abs(energies.get(song.mediaId)-desired)-(PhoneSmartRules.contains(list.optJSONArray("preferred"),song.mediaId)?.15:0));songs.sort(start);String recognition=list.optString("recognition_song");for(int i=0;i order=new ArrayList<>();order.add(songs.remove(0)); - while(!songs.isEmpty()){MediaItem previous=order.get(order.size()-1);double best=Double.MAX_VALUE;int selected=0;for(int i=0;i=1)desiredNow=desired;}double score=SharedDjLogic.pairCost(a,b,last,e,desiredNow,SharedDjLogic.keyCode(keys.get(previous.mediaId)),SharedDjLogic.keyCode(keys.get(next.mediaId)))-(PhoneSmartRules.contains(list.optJSONArray("preferred"),next.mediaId)?.15:0);if(style.equals("Hype"))score+=Math.max(0,last-e);if(style.equals("Chill"))score+=Math.max(0,e-last);if(score order=new ArrayList<>();order.add(songs.remove(0)); + while(!songs.isEmpty()){MediaItem previous=order.get(order.size()-1);double best=Double.MAX_VALUE;int selected=0;for(int i=0;i=1)desiredNow=desired;}double score=SharedDjLogic.pairCost(a,b,last,e,desiredNow,SharedDjLogic.keyCode(keys.get(previous.mediaId)),SharedDjLogic.keyCode(keys.get(next.mediaId)))-(PhoneSmartRules.contains(list.optJSONArray("preferred"),next.mediaId)?.15:0);if(Double.isFinite(last)&&Double.isFinite(e)){if(style.equals("Hype"))score+=Math.max(0,last-e);if(style.equals("Chill"))score+=Math.max(0,e-last);}if(score0;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 long entry(MediaItem item,JSONObject rules){long fallback=DjEngine.cueIn(item);if(!rules.optString("style","Steady").equalsIgnoreCase("Hype")||!rules.optBoolean("use_manual_cues",true))return fallback;JSONObject p=DjEngine.preparation(item);JSONArray cues=array(p,"manual_cues");double end=p.optDouble("cue_out",Double.POSITIVE_INFINITY);for(int i=0;i=0&&seconds0){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 x=extensions(DjEngine.preparation(item));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;} + static boolean matches(Context c,MediaItem item,JSONObject list){if(contains(list.optJSONArray("excluded"),item.mediaId))return false;JSONArray chosen=list.optJSONArray("genres");if(chosen!=null&&chosen.length()>0){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/PlaybackNotificationGate.java b/android/app/src/main/java/cloud/gitwide/ampverse/PlaybackNotificationGate.java new file mode 100644 index 00000000..502c5b99 --- /dev/null +++ b/android/app/src/main/java/cloud/gitwide/ampverse/PlaybackNotificationGate.java @@ -0,0 +1,42 @@ +package cloud.gitwide.ampverse; + +/** Main-thread, trailing latest-state publication. Idle instances schedule no work. */ +final class PlaybackNotificationGate implements AutoCloseable { + interface Scheduler { + long now(); + void post(Runnable task,long delayMs); + void remove(Runnable task); + } + // Stay below Android's per-package notification enqueue quota, including + // duplicate Media3 state events during rapid Player/deck handoffs. + static final long INTERVAL_MS=350; + private final Scheduler scheduler; + private final Runnable publish; + private final Runnable flush=this::flush; + private long next; + private boolean pending,closed; + + PlaybackNotificationGate(Scheduler scheduler,Runnable publish){ + this.scheduler=scheduler;this.publish=publish; + } + + void request(){ + if(closed||pending)return; + pending=true; + scheduler.post(flush,Math.max(0,next-scheduler.now())); + } + + private void flush(){ + if(closed)return; + pending=false; + next=scheduler.now()+INTERVAL_MS; + // Resolve the selected source at publication, never replay an old snapshot. + publish.run(); + } + + @Override public void close(){ + closed=true; + if(pending)scheduler.remove(flush); + pending=false; + } +} diff --git a/android/app/src/main/java/cloud/gitwide/ampverse/PlaybackService.java b/android/app/src/main/java/cloud/gitwide/ampverse/PlaybackService.java index dbfbb80b..224aa26c 100644 --- a/android/app/src/main/java/cloud/gitwide/ampverse/PlaybackService.java +++ b/android/app/src/main/java/cloud/gitwide/ampverse/PlaybackService.java @@ -13,6 +13,48 @@ @androidx.annotation.OptIn(markerClass = androidx.media3.common.util.UnstableApi.class) public final class PlaybackService extends MediaSessionService { private MediaSession session; + // One room output has one notification; the current owner's session supplies controls. + private static final int PLAYBACK_NOTIFICATION_ID=1001; + @Override public void onUpdateNotification(MediaSession changed,boolean startInForegroundRequired){ + // Private cue transports never own the room's notification. Filter by source + // ownership before Media3 queues its asynchronous controller/provider work. + String id=changed.getId(); + if(id.equals("dj-2")||id.equals("dj-3"))return; + if(djOwner?changed==session:changed!=session)return; + if(djOwner&&dj!=null){ + if(dj.notificationTransportBatch())return; + String selected="dj-"+dj.notificationDeck(); + if(!changed.getId().equals(selected))return; + } + notificationForegroundRequired=startInForegroundRequired; + notificationGate.request(); + } + private void publishNotification(){ + if(instance!=this||session==null)return; + MediaSession changed=session; + if(djOwner&&dj!=null){ + if(dj.notificationTransportBatch())return; + String selected="dj-"+dj.notificationDeck(); + changed=null; + for(MediaSession candidate:getSessions())if(candidate.getId().equals(selected)){changed=candidate;break;} + if(changed==null)return; + } + Player source=changed.getPlayer(); + if(source.getMediaItemCount()==0||source.getPlaybackState()==Player.STATE_IDLE){ + // Media3's default manager removes the service notification for an empty + // session. An unprepared cue must not remove a different live transport. + for(MediaSession peer:getSessions()){ + Player other=peer.getPlayer();int state=other.getPlaybackState(); + if(peer!=changed&&other.getPlayWhenReady() + &&(state==Player.STATE_READY||state==Player.STATE_BUFFERING))return; + } + } + super.onUpdateNotification(changed,notificationForegroundRequired||notificationNeedsForeground(changed)); + } + private static boolean notificationNeedsForeground(MediaSession source){ + Player player=source.getPlayer();int state=player.getPlaybackState(); + return player.getPlayWhenReady()&&(state==Player.STATE_READY||state==Player.STATE_BUFFERING); + } private static volatile PlaybackService instance; private DjEngine dj; private volatile OwnedAudioOutput ownedOutput; @@ -109,6 +151,13 @@ static String startPhoneBroadcast(CastClient selected){ private String hlsAttemptUri=""; private boolean hlsReady; private final android.os.Handler handler=new android.os.Handler(android.os.Looper.getMainLooper()); + private boolean notificationForegroundRequired; + private final PlaybackNotificationGate notificationGate=new PlaybackNotificationGate( + new PlaybackNotificationGate.Scheduler(){ + public long now(){return android.os.SystemClock.uptimeMillis();} + public void post(Runnable task,long delayMs){handler.postDelayed(task,delayMs);} + public void remove(Runnable task){handler.removeCallbacks(task);} + },this::publishNotification); static void claimDj(){if(instance!=null){instance.djOwner=true;instance.notePhoneSource();suppressOwnedOutput(false);if(instance.ownedOutput!=null)instance.ownedOutput.mixer.owner(OwnedPcmMixer.Owner.DJ);if(instance.session!=null)instance.session.getPlayer().pause();}} static void claimDjForScratch(Runnable afterPause){ PlaybackService service=instance; @@ -119,6 +168,15 @@ static void claimDjForScratch(Runnable afterPause){ } private void claimPlayer(){suppressOwnedOutput(false);if(ownedOutput!=null)ownedOutput.mixer.owner(OwnedPcmMixer.Owner.PLAYER);if(djOwner){djOwner=false;if(dj!=null)dj.pauseForPlayer();}notePhoneSource();} static void switchToPlayer(){if(instance!=null)instance.adoptDjPlaylist();} + static boolean djNotificationCurrent(int deck){ + PlaybackService service=instance; + return service!=null&&service.djOwner&&service.dj!=null&&service.dj.notificationDeck()==deck; + } + static void djNotificationChanged(){ + PlaybackService service=instance;if(service==null||!service.djOwner||service.dj==null)return; + String selected="dj-"+service.dj.notificationDeck(); + for(MediaSession candidate:service.getSessions())if(candidate.getId().equals(selected)){service.onUpdateNotification(candidate,notificationNeedsForeground(candidate));return;} + } static String owner(){return instance!=null&&instance.djOwner?"dj":"player";} private void adoptDjPlaylist(){ if(!djOwner||dj==null||session==null)return; @@ -146,6 +204,8 @@ private void adoptDjPlaylist(){ }; @Override public void onCreate() { super.onCreate(); + setMediaNotificationProvider(new androidx.media3.session.DefaultMediaNotificationProvider.Builder(this) + .setNotificationId(PLAYBACK_NOTIFICATION_ID).build()); instance=this; // Candidate cutover stays off until sampler, scratch and handset acceptance pass. if(getSharedPreferences("settings",MODE_PRIVATE).getBoolean("owned-pcm-master-candidate",false))ownedOutput=new OwnedAudioOutput(); @@ -270,6 +330,7 @@ static androidx.media3.exoplayer.DefaultRenderersFactory renderers(android.conte return session; } @Override public void onDestroy() { + notificationGate.close(); handler.removeCallbacks(fades);handler.removeCallbacks(liveWatchdog);cancelRadioRetry(); if(phoneBroadcast!=null){phoneBroadcast.close();phoneBroadcast=null;}if(phoneAudioStream!=null){phoneAudioStream.close();phoneAudioStream=null;}receiverReady=null; phoneRemoteVersion++;if(phoneRemote!=null){phoneRemote.close();phoneRemote=null;} diff --git a/android/app/src/main/java/cloud/gitwide/ampverse/SharedDjLogic.java b/android/app/src/main/java/cloud/gitwide/ampverse/SharedDjLogic.java index 43a3c86c..653991a4 100644 --- a/android/app/src/main/java/cloud/gitwide/ampverse/SharedDjLogic.java +++ b/android/app/src/main/java/cloud/gitwide/ampverse/SharedDjLogic.java @@ -3,6 +3,8 @@ final class SharedDjLogic { static {System.loadLibrary("amp_dj_policy");if(version()!=1)throw new IllegalStateException("Unsupported DJ Logic version");} static native int version(); + private static native double styleTarget(int style,double progress); + static double styleTarget(String style,double progress){return styleTarget(style.equalsIgnoreCase("Hype")?1:style.equalsIgnoreCase("Chill")?2:0,progress);} static native double tempoRate(double outgoing,double rate,double incoming,double limit); static native double distance(double outgoing,double incoming); static native double boundary(double anchor,double period,double position); diff --git a/android/app/src/test/java/cloud/gitwide/ampverse/OwnedPcmMixerTest.java b/android/app/src/test/java/cloud/gitwide/ampverse/OwnedPcmMixerTest.java index b03c0639..7de8f2d4 100644 --- a/android/app/src/test/java/cloud/gitwide/ampverse/OwnedPcmMixerTest.java +++ b/android/app/src/test/java/cloud/gitwide/ampverse/OwnedPcmMixerTest.java @@ -97,6 +97,7 @@ public void CongestedOrFailedExportNeverInterruptsLocalOutput() { mixer.render(out, 2); assertArrayEquals(tone(2, 700), out); assertEquals(2, mixer.rejectedFanoutFrames()); + assertEquals(MasterPcmQueue.Rejection.CAPACITY,queue.lastRejection()); mixer.render(out, 2); assertArrayEquals(tone(2, 700), out); assertEquals(0, queue.frames()); @@ -188,6 +189,7 @@ public void voiceAndQueueBoundsRemainFixedAndClosedVoicesCannotReturn() { } MasterPcmQueue q = new MasterPcmQueue(2); assertFalse(q.offer(new short[2], Integer.MAX_VALUE, 0)); + assertEquals(MasterPcmQueue.Rejection.INVALID_RANGE,q.lastRejection()); } @Test @@ -195,12 +197,14 @@ public void exportRejectsDiscontinuousFramesRatherThanSilentlyJoiningThem() { MasterPcmQueue q = new MasterPcmQueue(8); assertTrue(q.offer(tone(2, 100), 2, 20)); assertFalse(q.offer(tone(2, 200), 2, 24)); + assertEquals(MasterPcmQueue.Rejection.DISCONTINUITY,q.lastRejection()); assertTrue(q.offer(tone(2, 200), 2, 22)); short[] out = new short[8]; assertEquals(4, q.read(out, 4)); assertArrayEquals(new short[] {100, 100, 100, 100, 200, 200, 200, 200}, out); q.close(); assertFalse(q.offer(tone(1, 100), 1, 24)); + assertEquals(MasterPcmQueue.Rejection.CLOSED,q.lastRejection()); assertEquals(0, q.frames()); } @@ -281,6 +285,19 @@ public void headroomPolicyMakesSaturationObservable() { assertArrayEquals(out, network); } + @Test + public void initialControlResumeWaitsForConsumerBeforeUnblockingFullQueue(){ + MasterPcmQueue queue=new MasterPcmQueue(2);short[] old={1,1,2,2},fresh={3,3,4,4},out=new short[4]; + assertTrue(queue.offer(old,2,0)); + queue.suspendCapture();queue.resumeCapture(); + assertTrue("Capture stays gated until consumer discards old occupancy",queue.captureSuspended()); + assertTrue("Producer running first cannot overflow stale occupancy",queue.offer(fresh,2,48000)); + assertEquals(0,queue.read(out,2));assertFalse(queue.captureSuspended()); + assertTrue(queue.offer(fresh,2,48480));assertEquals(2,queue.read(out,2));assertArrayEquals(fresh,out); + assertFalse("Live continuity checks remain enforced",queue.offer(fresh,2,96000)); + assertEquals(0,queue.rejectedFrames()); + } + @Test public void spscRingPreservesSamplesUnderConcurrentPressure() throws Exception { MasterPcmQueue queue = new MasterPcmQueue(31); diff --git a/android/app/src/test/java/cloud/gitwide/ampverse/PhoneMasterBroadcastTest.java b/android/app/src/test/java/cloud/gitwide/ampverse/PhoneMasterBroadcastTest.java index b7cd5f30..16d494c3 100644 --- a/android/app/src/test/java/cloud/gitwide/ampverse/PhoneMasterBroadcastTest.java +++ b/android/app/src/test/java/cloud/gitwide/ampverse/PhoneMasterBroadcastTest.java @@ -43,6 +43,134 @@ static void await(java.util.function.BooleanSupplier condition) throws Exception } } + static void awaitEncoding(java.util.function.BooleanSupplier condition)throws IOException{ + try{await(condition);}catch(Exception error){throw new IOException(error);} + } + + @Test + public void slowUploadDoesNotBlockCurrentPcmEncoding() throws Exception { + OwnedPcmMixer mixer=new OwnedPcmMixer(); + CountDownLatch uploading=new CountDownLatch(1),release=new CountDownLatch(1); + Semaphore drained=new Semaphore(0);AtomicLong rejected=new AtomicLong(-1); + AtomicReference capture=new AtomicReference<>(); + Transport transport=new Transport(){ + @Override public long upload(String token,long sequence,byte[] data){ + uploading.countDown(); + try{if(!release.await(2,TimeUnit.SECONDS))throw new AssertionError("Upload fixture timed out");} + catch(InterruptedException error){Thread.currentThread().interrupt();} + return super.upload(token,sequence,data); + } + }; + PhoneMasterBroadcast broadcast=new PhoneMasterBroadcast(mixer,()->new PhoneMasterBroadcast.Encoder(){ + public void encode(MasterPcmQueue pcm,AtomicBoolean stopped,PhoneMasterBroadcast.PacketSink packets)throws IOException{ + capture.set(pcm);packets.packet(new byte[]{1},1);short[] samples=new short[960]; + while(!stopped.get()){ + if(pcm.read(samples,480)>0)drained.release(); + rejected.set(pcm.rejectedFrames()); + Thread.yield(); + } + } + public void cancel(){} + public void close(){} + },status->{}); + try{ + broadcast.start(new PhoneLiveSession(ID,transport),()->true); + assertTrue(uploading.await(2,TimeUnit.SECONDS)); + await(()->capture.get()!=null&&!capture.get().captureSuspended()); + short[] block=new short[960]; + for(int n=0;n<100;n++){ + mixer.render(block,480); + assertTrue("A network wait must not block PCM encoding",drained.tryAcquire(100,TimeUnit.MILLISECONDS)); + } + assertEquals(48000,mixer.frames());assertEquals(0,rejected.get()); + }finally{release.countDown();broadcast.close();await(()->!broadcast.active());} + } + + @Test + public void slowInitialClaimDoesNotConsumeTheCurrentAudioBudget() throws Exception { + OwnedPcmMixer mixer=new OwnedPcmMixer(); + CountDownLatch claiming=new CountDownLatch(1),release=new CountDownLatch(1), + encoded=new CountDownLatch(1),finish=new CountDownLatch(1); + AtomicLong rejected=new AtomicLong(-1); + Transport transport=new Transport(){ + @Override public PhoneLiveSession.Started start(String previous){ + claiming.countDown(); + try{if(!release.await(2,TimeUnit.SECONDS))throw new AssertionError("Claim fixture timed out");} + catch(InterruptedException error){throw new AssertionError(error);} + return super.start(previous); + } + }; + PhoneMasterBroadcast broadcast=new PhoneMasterBroadcast(mixer,()->new PhoneMasterBroadcast.Encoder(){ + public void encode(MasterPcmQueue pcm,AtomicBoolean stopped,PhoneMasterBroadcast.PacketSink packets)throws IOException{ + packets.packet(new byte[]{1},1);awaitEncoding(()->transport.starts==1); + rejected.set(pcm.rejectedFrames());encoded.countDown(); + try{finish.await(2,TimeUnit.SECONDS);}catch(InterruptedException error){throw new IOException(error);} + } + public void cancel(){finish.countDown();} + public void close(){} + },status->{}); + try{ + broadcast.start(new PhoneLiveSession(ID,transport),()->true); + assertTrue(claiming.await(2,TimeUnit.SECONDS)); + short[] block=new short[960];for(int n=0;n<100;n++)mixer.render(block,480); + assertEquals("Local playback advances during initial authorization",48000,mixer.frames()); + release.countDown();assertTrue(encoded.await(2,TimeUnit.SECONDS)); + assertEquals("Initial control claim must not spend live audio latency",0,rejected.get()); + assertEquals(1,transport.starts); + }finally{release.countDown();finish.countDown();broadcast.close();await(()->!broadcast.active());} + } + + @Test + public void slowGuardedResumeDoesNotConsumeTheCurrentAudioBudget() throws Exception { + OwnedPcmMixer mixer = new OwnedPcmMixer(); + CountDownLatch resuming = new CountDownLatch(1), release = new CountDownLatch(1), + encoded = new CountDownLatch(1), finish = new CountDownLatch(1); + AtomicInteger instances = new AtomicInteger(); + AtomicLong rejected = new AtomicLong(-1); + Transport transport = new Transport() { + @Override public PhoneLiveSession.Started start(String previous) { + if (previous != null) { + resuming.countDown(); + try { + if (!release.await(2, TimeUnit.SECONDS)) throw new AssertionError("Resume fixture timed out"); + } catch (InterruptedException error) { throw new AssertionError(error); } + } + return super.start(previous); + } + }; + PhoneMasterBroadcast broadcast = new PhoneMasterBroadcast(mixer, () -> { + int instance = instances.incrementAndGet(); + return new PhoneMasterBroadcast.Encoder() { + public void encode(MasterPcmQueue pcm, AtomicBoolean stopped, PhoneMasterBroadcast.PacketSink packets) + throws IOException { + packets.packet(new byte[] {1}, 1); + awaitEncoding(()->transport.uploads>=instance); + if (instance == 1) throw new IOException("Generated encoder interruption"); + rejected.set(pcm.rejectedFrames()); + encoded.countDown(); + try { finish.await(2, TimeUnit.SECONDS); } + catch (InterruptedException error) { throw new IOException(error); } + } + public void cancel() { finish.countDown(); } + public void close() {} + }; + }, status -> {}); + try { + broadcast.start(new PhoneLiveSession(ID, transport), () -> true); + assertTrue(resuming.await(2, TimeUnit.SECONDS)); + short[] block = new short[960]; + for (int n = 0; n < 100; n++) mixer.render(block, 480); + assertEquals("Local render keeps advancing during reconnect", 48000, mixer.frames()); + release.countDown(); + assertTrue(encoded.await(2, TimeUnit.SECONDS)); + assertEquals("Control reconnect must finish before attaching current audio", 0, rejected.get()); + assertEquals(2, transport.starts); + } finally { + release.countDown();finish.countDown();broadcast.close(); + await(() -> !broadcast.active()); + } + } + @Test public void coldEncoderPreparationDoesNotFillOrAttachTheLiveQueue() throws Exception { OwnedPcmMixer mixer = new OwnedPcmMixer(); @@ -219,6 +347,7 @@ public void encode( PhoneMasterBroadcast.PacketSink packets) throws IOException { packets.packet(new byte[] {1}, 1); + awaitEncoding(()->transport.uploads==1); eligible.set(false); packets.packet(new byte[] {2}, 1); } @@ -259,6 +388,7 @@ public void encode( MasterPcmQueue pcm, AtomicBoolean stop, PhoneMasterBroadcast.PacketSink packets) throws IOException { packets.packet(new byte[] {(byte) attempt}, 1); + awaitEncoding(()->transport.uploads>=attempt); if (attempt == 1) throw new IOException("Fresh stream required"); while (!stop.get()) try { diff --git a/android/app/src/test/java/cloud/gitwide/ampverse/PhoneMasterUploadTest.java b/android/app/src/test/java/cloud/gitwide/ampverse/PhoneMasterUploadTest.java new file mode 100644 index 00000000..e04e2e6f --- /dev/null +++ b/android/app/src/test/java/cloud/gitwide/ampverse/PhoneMasterUploadTest.java @@ -0,0 +1,115 @@ +package cloud.gitwide.ampverse; + +import static org.junit.Assert.*; +import java.io.IOException; +import java.util.*; +import java.util.concurrent.*; +import java.util.concurrent.atomic.*; +import org.junit.Test; + +public final class PhoneMasterUploadTest { + static final PhoneLiveSession.Identity ID=new PhoneLiveSession.Identity("server","station","library"); + static class Transport implements PhoneLiveSession.Transport { + volatile int starts,stops; + final List sent=new CopyOnWriteArrayList<>(); + public PhoneLiveSession.Identity verify(){return ID;} + public PhoneLiveSession.Started start(String previous){starts++;return new PhoneLiveSession.Started("owner",0,true,true);} + public long upload(String token,long sequence,byte[] data)throws IOException{sent.add(data.clone());return sequence+1;} + public void stop(String token){stops++;} + public void abort(){} + } + static void await(java.util.function.BooleanSupplier ready)throws Exception{ + long end=System.nanoTime()+TimeUnit.SECONDS.toNanos(3); + while(!ready.getAsBoolean()){if(System.nanoTime()>end)fail("Upload worker stalled");Thread.sleep(1);} + } + static void waitOn(CountDownLatch latch)throws IOException{ + try{if(!latch.await(2,TimeUnit.SECONDS))throw new IOException("Fixture wait timed out");} + catch(InterruptedException error){Thread.currentThread().interrupt();throw new IOException(error);} + } + + @Test public void networkBacklogPreservesOrderAndCopiesProducerPackets()throws Exception{ + CountDownLatch blocked=new CountDownLatch(1),release=new CountDownLatch(1); + Transport transport=new Transport(){@Override public long upload(String token,long sequence,byte[] bytes)throws IOException{ + if(sequence==0){blocked.countDown();waitOn(release);}return super.upload(token,sequence,bytes); + }}; + PhoneLiveSession session=new PhoneLiveSession(ID,transport);session.begin();AtomicInteger delivered=new AtomicInteger(); + try(PhoneMasterUpload upload=new PhoneMasterUpload(session,new MasterPcmQueue(4),new AtomicBoolean(),()->true,()->true,()->{},delivered::incrementAndGet)){ + upload.packet(new byte[]{1},1);assertTrue(blocked.await(2,TimeUnit.SECONDS)); + byte[] reused=new byte[1];for(int value=2;value<=20;value++){reused[0]=(byte)value;upload.packet(reused,1);}reused[0]=99; + release.countDown();await(()->delivered.get()==20);assertNull(upload.failure()); + for(int value=1;value<=20;value++)assertArrayEquals(new byte[]{(byte)value},transport.sent.get(value-1)); + }finally{release.countDown();session.finish();} + } + + @Test public void boundedBacklogRejectsAdditionalLivePackets()throws Exception{ + CountDownLatch blocked=new CountDownLatch(1),release=new CountDownLatch(1); + Transport transport=new Transport(){@Override public long upload(String token,long sequence,byte[] bytes)throws IOException{ + blocked.countDown();waitOn(release);return super.upload(token,sequence,bytes); + }}; + PhoneLiveSession session=new PhoneLiveSession(ID,transport);session.begin(); + PhoneMasterUpload upload=new PhoneMasterUpload(session,new MasterPcmQueue(4),new AtomicBoolean(),()->true,()->true,()->{},()->{}); + try{ + byte[] packet=new byte[PhoneLiveSession.MAX_PACKET];upload.packet(packet,packet.length); + assertTrue(blocked.await(2,TimeUnit.SECONDS)); + for(int i=0;iupload.packet(packet,packet.length)); + assertTrue(error.getMessage().contains("bounded budget")); + }finally{release.countDown();upload.close();session.finish();} + } + + @Test public void rejectedOwnerStopsEncodingAndKeepsOriginalFailure()throws Exception{ + Transport transport=new Transport(){@Override public long upload(String token,long sequence,byte[] bytes)throws IOException{ + throw new PhoneLiveSession.Rejected("Owner replaced"); + }}; + PhoneLiveSession session=new PhoneLiveSession(ID,transport);session.begin();AtomicBoolean stopped=new AtomicBoolean();CountDownLatch cancelled=new CountDownLatch(1); + try(PhoneMasterUpload upload=new PhoneMasterUpload(session,new MasterPcmQueue(4),stopped,()->true,()->true,cancelled::countDown,()->fail("Unacknowledged audio cannot be on air"))){ + upload.packet(new byte[]{1},1);assertTrue(cancelled.await(2,TimeUnit.SECONDS)); + assertTrue(stopped.get());assertTrue(upload.failure() instanceof PhoneLiveSession.Rejected);assertEquals("Owner replaced",upload.failure().getMessage()); + }finally{session.finish();} + } + + @Test public void noProofNeverClaimsHost()throws Exception{ + Transport transport=new Transport();PhoneLiveSession session=new PhoneLiveSession(ID,transport); + try(PhoneMasterUpload upload=new PhoneMasterUpload(session,new MasterPcmQueue(4),new AtomicBoolean(),()->true,()->true,()->{},()->{})){} + session.finish();assertEquals(0,transport.starts);assertEquals(0,transport.stops); + } + + @Test public void splitMp3FramesSurviveDelayedInitialClaimByteForByte()throws Exception{ + CountDownLatch claiming=new CountDownLatch(1),release=new CountDownLatch(1);AtomicInteger delivered=new AtomicInteger(); + Transport transport=new Transport(){@Override public PhoneLiveSession.Started start(String previous){ + claiming.countDown();try{waitOn(release);}catch(IOException error){throw new AssertionError(error);}return super.start(previous); + }}; + PhoneLiveSession session=new PhoneLiveSession(ID,transport);MasterPcmQueue pcm=new MasterPcmQueue(4); + byte[] stream=new byte[576*3];for(int i=0;i<3;i++)System.arraycopy(PhoneMp3WarmupTest.frame(),0,stream,i*576,576); + try(PhoneMasterUpload upload=new PhoneMasterUpload(session,pcm,new AtomicBoolean(),()->true,()->true,()->{},delivered::incrementAndGet)){ + byte[] proof=Arrays.copyOfRange(stream,0,581);upload.packet(proof,proof.length); + assertTrue(claiming.await(2,TimeUnit.SECONDS));assertTrue(pcm.captureSuspended()); + byte[] middle=Arrays.copyOfRange(stream,581,700),more=Arrays.copyOfRange(stream,700,1190); + upload.packet(middle,middle.length);upload.packet(more,more.length); + release.countDown();await(()->delivered.get()==3);pcm.read(new short[2],1);assertFalse(pcm.captureSuspended()); + byte[] tail=Arrays.copyOfRange(stream,1190,stream.length);upload.packet(tail,tail.length);await(()->delivered.get()==4); + java.io.ByteArrayOutputStream received=new java.io.ByteArrayOutputStream();for(byte[] bytes:transport.sent)received.write(bytes); + assertArrayEquals("No partial-frame byte holes around startup control",stream,received.toByteArray()); + }finally{release.countDown();session.finish();} + } + + @Test public void closeAbortsAndJoinsARequestThatIgnoresThreadInterruption()throws Exception{ + CountDownLatch sending=new CountDownLatch(1),aborted=new CountDownLatch(1),exited=new CountDownLatch(1); + Transport transport=new Transport(){ + @Override public long upload(String token,long sequence,byte[] bytes)throws IOException{ + sending.countDown();try{ + while(true)try{aborted.await();break;}catch(InterruptedException ignored){} + throw new IOException("Request aborted"); + }finally{exited.countDown();} + } + @Override public void abort(){aborted.countDown();} + }; + PhoneLiveSession session=new PhoneLiveSession(ID,transport);session.begin(); + PhoneMasterUpload upload=new PhoneMasterUpload(session,new MasterPcmQueue(4),new AtomicBoolean(),()->true,()->true,()->{},()->{}); + upload.packet(new byte[]{1},1);assertTrue(sending.await(2,TimeUnit.SECONDS)); + try{ + assertThrows(PhoneLiveSession.Rejected.class,upload::close); + assertEquals("Close joins the aborted request before returning",0,exited.getCount()); + }finally{aborted.countDown();session.finish();} + } +} diff --git a/android/app/src/test/java/cloud/gitwide/ampverse/PhoneMixSectionsTest.java b/android/app/src/test/java/cloud/gitwide/ampverse/PhoneMixSectionsTest.java new file mode 100644 index 00000000..4b1f8449 --- /dev/null +++ b/android/app/src/test/java/cloud/gitwide/ampverse/PhoneMixSectionsTest.java @@ -0,0 +1,55 @@ +package cloud.gitwide.ampverse; +import org.json.*; +import org.junit.Test; +import java.nio.charset.StandardCharsets; +import static org.junit.Assert.*; +public class PhoneMixSectionsTest { + @Test public void topLevelPreparationWinsOverLegacyNestedFieldsWithoutMutatingEither()throws Exception{ + JSONObject p=fixture(),nested=new JSONObject().put("energy",0.9).put("energy_profile",new JSONObject().put("version",1)); + p.put("extensions",nested).put("energy",0.3).put("energy_source","manual").put("perceptual_energy",0.7); + String before=p.toString(); + assertEquals(0.3,PhoneMixSections.trackEnergy(p),.00001);assertTrue(PhoneMixSections.comparableProfile(p)); + assertEquals(0.85,PhoneMixSections.sectionEnergy(p,24000),.00001);assertEquals(before,p.toString()); + p.remove("energy_source");assertEquals(0.7,PhoneMixSections.trackEnergy(p),.00001); + p.getJSONObject("energy_profile").put("version","2");assertFalse(PhoneMixSections.comparableProfile(p)); + p.getJSONObject("energy_profile").put("version",2.0);assertFalse(PhoneMixSections.comparableProfile(p)); + } + @Test public void legacyGeneratedTrackEnergyIsUnknownButProtectedAndManualValuesSurvive()throws Exception{ + JSONObject p=new JSONObject().put("energy",0.8).put("energy_profile",new JSONObject().put("version",1)); + assertTrue(Double.isNaN(PhoneMixSections.trackEnergy(p))); + p.put("manual_override",true);assertEquals(0.8,PhoneMixSections.trackEnergy(p),.00001); + p.remove("manual_override");p.remove("energy_profile");assertEquals(0.8,PhoneMixSections.trackEnergy(p),.00001); + JSONObject analysis=new JSONObject().put("engine","amp-prep-heuristic-5").put("reviewed",false);p.put("analysis",analysis); + assertTrue(Double.isNaN(PhoneMixSections.trackEnergy(p))); + analysis.put("reviewed",true);assertEquals(0.8,PhoneMixSections.trackEnergy(p),.00001); + analysis.put("reviewed",false);p.put("perceptual_energy",0.2);assertEquals(0.2,PhoneMixSections.trackEnergy(p),.00001); + p.put("energy_source","manual");assertEquals(0.8,PhoneMixSections.trackEnergy(p),.00001); + p.remove("energy");assertTrue(Double.isNaN(PhoneMixSections.trackEnergy(p))); + } + @Test public void actualFadeCanSelectALaterPreparedLullAndRejectMalformedOptions()throws Exception{ + JSONObject p=fixture();p.getJSONObject("auto_mix_sections").put("exit_candidates",new JSONArray().put(42).put(72)); + assertEquals(42000,PhoneMixSections.exit(p,hype(),24000,120000,1)); + assertEquals(72000,PhoneMixSections.exit(p,hype(),24000,120000,3)); + p.getJSONObject("auto_mix_sections").put("exit_candidates",new JSONArray().put(72).put(42)); + assertEquals(120000,PhoneMixSections.exit(p,hype(),24000,120000,3)); + } + @Test public void entrySectionScoreDoesNotGetShadowedByWholeTrackScore()throws Exception{ + JSONObject p=fixture().put("perceptual_energy",0.5);assertEquals(0.15,PhoneMixSections.sectionEnergy(p,0),.00001);assertEquals(0.85,PhoneMixSections.sectionEnergy(p,24000),.00001); + p.getJSONObject("energy_profile").put("version",1);assertTrue(Double.isNaN(PhoneMixSections.sectionEnergy(p,24000)));p.remove("perceptual_energy");assertTrue("Legacy raw sections stay incomparable without a track score",Double.isNaN(PhoneMixSections.sectionEnergy(p,24000))); + } + private JSONObject fixture()throws Exception{try(java.io.InputStream input=getClass().getResourceAsStream("/mix-sections-v1.json")){assertNotNull(input);return new JSONObject(new String(input.readAllBytes(),StandardCharsets.UTF_8));}} + private JSONObject hype()throws Exception{return new JSONObject().put("style","Hype");} + @Test public void portableCorePlanEntersStrongPassageAndExitsAtLull()throws Exception{ + JSONObject p=fixture();assertEquals(24000,PhoneMixSections.entry(p,hype(),0));assertEquals(72000,PhoneMixSections.exit(p,hype(),24000,120000,3));assertEquals(120000,PhoneMixSections.exit(p,hype(),90000,120000,3));assertEquals(0,PhoneMixSections.entry(p,new JSONObject().put("style","Chill"),0)); + } + @Test public void dropHasPriorityOverEarlierBuildAndEndMarker()throws Exception{ + JSONObject p=fixture().put("manual_cues",new JSONArray().put(new JSONObject().put("label","Build").put("seconds",8)).put(new JSONObject().put("label","Drop end").put("seconds",50)).put(new JSONObject().put("label","Big drop").put("seconds",24))); + assertEquals(24000,PhoneMixSections.entry(p,hype(),0));assertEquals(120000,PhoneMixSections.exit(p,hype(),24000,120000,3));assertEquals(0,PhoneMixSections.entry(p,hype().put("use_manual_cues",false),0)); + } + @Test public void staleUnknownManualAndTooShortPlansCannotMoveBounds()throws Exception{ + for(String mode:new String[]{"unknown","stale","manual","reviewed","missing-duration","short-passage","short-entry"}){ + JSONObject p=fixture();if(mode.equals("unknown"))p.getJSONObject("auto_mix_sections").put("version",2);if(mode.equals("stale"))p.getJSONObject("auto_mix_sections").put("duration",999);if(mode.equals("manual"))p.put("manual_override",true);if(mode.equals("reviewed"))p.getJSONObject("analysis").put("reviewed",true);if(mode.equals("missing-duration"))p.getJSONObject("analysis").remove("duration");if(mode.equals("short-passage"))p.getJSONObject("auto_mix_sections").put("exit",30);if(mode.equals("short-entry"))p.getJSONObject("auto_mix_sections").put("entry",115); + if(!mode.equals("short-passage"))assertEquals(mode,0,PhoneMixSections.entry(p,hype(),0));assertEquals(mode,120000,PhoneMixSections.exit(p,hype(),24000,120000,3)); + } + } +} diff --git a/android/app/src/test/java/cloud/gitwide/ampverse/PlaybackNotificationGateTest.java b/android/app/src/test/java/cloud/gitwide/ampverse/PlaybackNotificationGateTest.java new file mode 100644 index 00000000..eb879b28 --- /dev/null +++ b/android/app/src/test/java/cloud/gitwide/ampverse/PlaybackNotificationGateTest.java @@ -0,0 +1,44 @@ +package cloud.gitwide.ampverse; + +import static org.junit.Assert.*; +import java.util.*; +import org.junit.Test; + +public final class PlaybackNotificationGateTest { + private static final class Clock implements PlaybackNotificationGate.Scheduler { + long now,due;Runnable task; + public long now(){return now;} + public void post(Runnable task,long delay){assertNull("Only one pending update",this.task);this.task=task;due=now+delay;} + public void remove(Runnable task){if(this.task==task)this.task=null;} + void advance(long time){ + while(task!=null&&due<=time){now=due;Runnable next=task;task=null;next.run();} + now=time; + } + } + + @Test public void aBurstPublishesTheLatestSourceAndThenStopsScheduling(){ + Clock clock=new Clock();List sent=new ArrayList<>();String[] source={"player"}; + PlaybackNotificationGate gate=new PlaybackNotificationGate(clock,()->sent.add(source[0])); + gate.request();clock.advance(0);assertEquals(Arrays.asList("player"),sent); + for(int event=0;event<100;event++){source[0]="deck-a";gate.request();} + source[0]="deck-b";gate.request();clock.advance(349);assertEquals(1,sent.size()); + clock.advance(350);assertEquals(Arrays.asList("player","deck-b"),sent);assertNull(clock.task); + clock.advance(10000);assertEquals(2,sent.size());assertNull(clock.task); + } + + @Test public void sustainedStateChangesStayBelowAndroidsQuota(){ + Clock clock=new Clock();List times=new ArrayList<>(); + PlaybackNotificationGate gate=new PlaybackNotificationGate(clock,()->times.add(clock.now)); + for(int time=0;time<5000;time+=5){clock.advance(time);gate.request();} + clock.advance(5500); + for(int i=1;i=350); + assertTrue(times.size()<=16);assertNull(clock.task); + } + + @Test public void reentrantEventsAreDeferredAndCloseCancelsPendingWork(){ + Clock clock=new Clock();int[] calls={0};PlaybackNotificationGate[] gate=new PlaybackNotificationGate[1]; + gate[0]=new PlaybackNotificationGate(clock,()->{calls[0]++;gate[0].request();}); + gate[0].request();clock.advance(0);assertEquals(1,calls[0]);assertEquals(350,clock.due); + gate[0].close();gate[0].request();clock.advance(1000);assertEquals(1,calls[0]);assertNull(clock.task); + } +} diff --git a/android/features/cast/java/cloud/gitwide/ampverse/FullPhoneMp3Encoder.java b/android/features/cast/java/cloud/gitwide/ampverse/FullPhoneMp3Encoder.java index 2a3d3499..2b8e7c2d 100644 --- a/android/features/cast/java/cloud/gitwide/ampverse/FullPhoneMp3Encoder.java +++ b/android/features/cast/java/cloud/gitwide/ampverse/FullPhoneMp3Encoder.java @@ -138,6 +138,7 @@ public void encode( } else packets.packet(packet, count); last = System.nanoTime(); } else { + if(source.captureSuspended())last=System.nanoTime(); if (terminal(session) || System.nanoTime() - last > 3000000000L) throw new IOException("Phone encoder stopped producing live MP3"); pause(); @@ -163,9 +164,14 @@ private void feed(MasterPcmQueue source, AtomicBoolean cancelled) { short[] samples = new short[960]; byte[] pcm = new byte[1920]; try { + // This consumer has the same real-time deadline as the master producer. + // Keep it in Android's audio scheduling group; HTTP runs on its own worker. + // Ring capacity and write deadlines remain unchanged. + android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_AUDIO); while (!stopped.get() && !cancelled.get()) { if (source.rejectedFrames() > 0) - throw new IOException("Phone master buffer exceeded latency budget"); + throw new IOException("Phone master PCM rejected: "+source.lastRejection()+" ("+source.rejectedFrames()+" frames)"); + long captureEpoch=source.captureEpoch(); int frames = source.read(samples, 480); if (frames == 0) { pause(); @@ -178,12 +184,14 @@ private void feed(MasterPcmQueue source, AtomicBoolean cancelled) { int offset = 0; long deadline = System.nanoTime() + 250000000L; while (offset < frames * 4 && !stopped.get() && !cancelled.get()) { + if(source.captureSuspended()||source.captureEpoch()!=captureEpoch)break; try { FileDescriptor descriptor = input; if (descriptor == null) return; offset += Os.write(descriptor, pcm, offset, frames * 4 - offset); } catch (ErrnoException wait) { if (wait.errno != OsConstants.EAGAIN) throw wait; + if(source.captureSuspended()||source.captureEpoch()!=captureEpoch)break; if (System.nanoTime() > deadline) throw new IOException("Phone encoder fell behind live audio"); pause(); diff --git a/android/features/dj/java/cloud/gitwide/ampverse/DjPanel.java b/android/features/dj/java/cloud/gitwide/ampverse/DjPanel.java index 5c6c713b..108c08bd 100644 --- a/android/features/dj/java/cloud/gitwide/ampverse/DjPanel.java +++ b/android/features/dj/java/cloud/gitwide/ampverse/DjPanel.java @@ -31,6 +31,8 @@ interface Host {void effect(int side,int pad);void beforeMainPlay();void equaliz private boolean updatingAuto; static final int STREAM_BLUE=0xff4da6ff; private Button playlistSource; + private final Button[] mixStyles=new Button[3]; + private String paintedMixStyle=""; private int playlistSourceTint=Integer.MIN_VALUE; private int visibleDeck; private final android.os.Handler timer=new android.os.Handler(android.os.Looper.getMainLooper()); @@ -47,13 +49,17 @@ interface Host {void effect(int side,int pad);void beforeMainPlay();void equaliz private void row(LinearLayout parent,Button...buttons){LinearLayout row=new LinearLayout(activity);for(Button b:buttons){LayoutParams p=new LayoutParams(0,-2,1);p.setMargins(dp(2),dp(2),dp(2),dp(2));row.addView(b,p);}parent.addView(row);} private SeekBar slider(LinearLayout parent,int max,int value,java.util.function.IntConsumer changed){SeekBar bar=new SeekBar(activity);Chrome.slider(bar,colors.accent);bar.setMax(max);bar.setProgress(value);bar.setMinimumHeight(dp(48));bar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener(){public void onStartTrackingTouch(SeekBar b){}public void onStopTrackingTouch(SeekBar b){}public void onProgressChanged(SeekBar b,int p,boolean user){if(user)changed.accept(p);}});parent.addView(bar,new LayoutParams(-1,dp(48)));return bar;} private void draw(){ - removeAllViews();Arrays.fill(info,null);Arrays.fill(timelines,null);Arrays.fill(covers,null);Arrays.fill(coverIds,null);Arrays.fill(coverData,null);Arrays.fill(deckSelectors,null);secondaryInfo=null; + removeAllViews();paintedMixStyle="";Arrays.fill(info,null);Arrays.fill(timelines,null);Arrays.fill(covers,null);Arrays.fill(coverIds,null);Arrays.fill(coverData,null);Arrays.fill(deckSelectors,null);secondaryInfo=null; boolean wide=getResources().getConfiguration().screenWidthDp>=700; LinearLayout toolbar=card(this);toolbar.setBackground(Chrome.highlighted(colors,colors.accent)); LinearLayout quick=new LinearLayout(activity);quick.setGravity(Gravity.CENTER_VERTICAL);toolbar.addView(quick); playlistSource=button("Choose playlist ›",colors.accent,this::chooseAutoSource);playlistSource.setTag("dj-choose-playlist");playlistSource.setMaxLines(2);playlistSource.setMinHeight(dp(wide?48:56));playlistSource.setEllipsize(android.text.TextUtils.TruncateAt.END);playlistSourceTint=Integer.MIN_VALUE;refreshPlaylistSource();quick.addView(playlistSource,new LayoutParams(0,-2,1)); autoToggle=new Switch(activity);autoToggle.setText("Auto Mix");autoToggle.setTextColor(colors.text);Chrome.toggle(autoToggle,colors);autoToggle.setMinHeight(dp(48));autoToggle.setPadding(dp(8),0,dp(4),0);autoToggle.setContentDescription("Phone Auto Mix");autoToggle.setChecked(engine.auto);autoToggle.setOnCheckedChangeListener((v,on)->{if(updatingAuto)return;if(on&&engine.autoQueue.isEmpty()){updatingAuto=true;autoToggle.setChecked(false);updatingAuto=false;chooseAutoSource(true);return;}if(on)host.beforeMainPlay();engine.auto(on);refresh();});quick.addView(autoToggle,new LayoutParams(-2,dp(wide?48:56))); - status=label(engine.message,13);status.setTextColor(colors.muted);status.setAccessibilityLiveRegion(View.ACCESSIBILITY_LIVE_REGION_POLITE);if(wide){toolbar.setOrientation(HORIZONTAL);toolbar.setPadding(dp(8),dp(4),dp(8),dp(4));quick.setLayoutParams(new LayoutParams(0,-2,2));status.setMaxLines(2);toolbar.addView(status,new LayoutParams(0,-2,1));}else toolbar.addView(status); + String[] styles={"Hype","Steady","Chill"}; + for(int i=0;iengine.mixStyle(style));mixStyles[i].setTag("dj-mix-style-"+style);mixStyles[i].setContentDescription("Auto Mix style: "+style);} + row(toolbar,mixStyles); + status=label(engine.message,13);status.setTextColor(colors.muted);status.setAccessibilityLiveRegion(View.ACCESSIBILITY_LIVE_REGION_POLITE);toolbar.addView(status); + if(wide){toolbar.setOrientation(HORIZONTAL);toolbar.setPadding(dp(8),dp(4),dp(8),dp(4));quick.setLayoutParams(new LayoutParams(0,-2,2));toolbar.getChildAt(1).setLayoutParams(new LayoutParams(0,-2,1.25f));status.setMaxLines(2);status.setLayoutParams(new LayoutParams(0,-2,1));} LinearLayout mains=new LinearLayout(activity);mains.setOrientation(wide?HORIZONTAL:VERTICAL);addView(mains); if(!wide){Button a=button("DECK A",DjEngine.AMBER,()->{visibleDeck=0;engine.destination(0);draw();}),b=button("DECK B",DjEngine.CYAN,()->{visibleDeck=1;engine.destination(1);draw();});deckSelectors[0]=a;deckSelectors[1]=b;Button selected=visibleDeck==0?a:b;selected.setSelected(true);selected.setBackground(Chrome.highlighted(colors,visibleDeck==0?DjEngine.AMBER:DjEngine.CYAN));a.setTag("deck-select-a");b.setTag("deck-select-b");a.setMaxLines(2);b.setMaxLines(2);row(mains,a,b);} for(int deck=0;deck<2;deck++){if(!wide&&deck!=visibleDeck)continue;LinearLayout column=new LinearLayout(activity);column.setOrientation(VERTICAL);mains.addView(column,new LayoutParams(wide?0:-1,-2,wide?1:0));deck(column,deck);} @@ -171,6 +177,7 @@ private void refreshPlaylistSource(){ } void refresh(){ refreshPlaylistSource(); + String style=engine.mixStyle();if(!style.equals(paintedMixStyle)){for(Button choice:mixStyles)if(choice!=null){boolean selected=style.equals(choice.getText().toString());choice.setSelected(selected);choice.setBackground(Chrome.button(colors,selected));choice.setTextColor(selected?Color.BLACK:colors.text);}paintedMixStyle=style;} engine.prepareScratch(); for(int i=0;i<4;i++)if(info[i]!=null){ExoPlayer deck=engine.decks[i];long duration=deck.getDuration();MediaItem item=deck.getCurrentMediaItem();String id=item==null?"":item.mediaId;if(!Objects.equals(coverIds[i],id)||!Arrays.equals(coverData[i],item==null?null:item.mediaMetadata.artworkData)){coverIds[i]=id;coverData[i]=item==null?null:item.mediaMetadata.artworkData;Chrome.artwork(covers[i],item,i%2==0?DjEngine.AMBER:DjEngine.CYAN);} double bpm=item==null?0:PhonePlaylists.bpm(activity,item);String key=item==null?"":activity.getSharedPreferences("phone-track-details",0).getString(item.mediaId+":key",""); diff --git a/android/release.properties b/android/release.properties index f1cd2f50..2a8f3a99 100644 --- a/android/release.properties +++ b/android/release.properties @@ -1,2 +1,2 @@ -versionName=1.1.0-rc.33 -versionCode=77 +versionName=1.1.0-rc.34 +versionCode=78 diff --git a/apps/amp-cast/src/radio.rs b/apps/amp-cast/src/radio.rs index e56fded2..da4bfe89 100644 --- a/apps/amp-cast/src/radio.rs +++ b/apps/amp-cast/src/radio.rs @@ -48,7 +48,7 @@ fn entry(p: &Preparation, profile: Option<&SmartPlaylist>, target: Option) // Finite queues use profile=None. Keep their existing entry behavior; // this shared automatic policy applies to Smart station selection only. if amp_core::energy_profile::mixing_allowed(p) - && let Some(activity) = amp_core::energy_profile::read(p) + && let Some(activity) = amp_core::energy_profile::mixing_profile(p) && let Some(section) = activity.entry( target.map_or(0.5, |e| (e - 1.) / 9.), amp_core::energy_profile::entry_bound(p), @@ -699,6 +699,12 @@ pub(super) async fn broadcast(cast: Arc, owner: u64) -> Result<(), String> target = Some(plan.next()); } let candidate = if let Some(p) = &profile { + // Continuous stations shape a thirty-minute audible-time cycle; + // explicit user targets/progression always take precedence. + let target = target.or_else(|| { + let progress = (clock.frames as f64 / RATE as f64).rem_euclid(1800.) / 1800.; + show::style_target(p.style, progress) + }); cycle.pick(&cast, p, Some(current.index), target) } else { pick( @@ -847,7 +853,7 @@ mod automatic_entry_tests { p.extensions.insert( amp_core::energy_profile::FIELD.into(), serde_json::json!({ - "version":1,"duration":150.,"step":1.,"curve":[],"sections":[ + "version":2,"duration":150.,"step":1.,"curve":[],"sections":[ {"id":"intro","name":"Intro","start":0.,"end":30.,"energy":0.2}, {"id":"early","name":"Early","start":30.,"end":80.,"energy":0.6}, {"id":"late","name":"Late","start":132.,"end":150.,"energy":0.9} diff --git a/apps/amp-engine/Cargo.toml b/apps/amp-engine/Cargo.toml index 1d4c87b7..69793a33 100644 --- a/apps/amp-engine/Cargo.toml +++ b/apps/amp-engine/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "amp-engine" -version = "1.0.22" +version = "1.0.23" edition.workspace = true license.workspace = true [dependencies] diff --git a/apps/amp-player/src/engine_download.rs b/apps/amp-player/src/engine_download.rs index 8e2e5078..c9bdd21b 100644 --- a/apps/amp-player/src/engine_download.rs +++ b/apps/amp-player/src/engine_download.rs @@ -431,6 +431,8 @@ mod tests { #[test] fn rejects_missing_assets_unpublished_and_incompatible_metadata() { + let (family, version) = amp_core::engine_api::ENGINE_ID.rsplit_once('-').unwrap(); + let version = version.parse::().unwrap(); for index in 0..3 { let mut release = fixture("v0.3.0"); release["assets"].as_array_mut().unwrap().remove(index); @@ -446,8 +448,14 @@ mod tests { ("component", serde_json::json!("android")), ("release", serde_json::json!("v0.2.5")), ("platform", serde_json::json!("linux-x86_64")), - ("engine_id", serde_json::json!("amp-prep-heuristic-4")), - ("engine_id", serde_json::json!("amp-prep-heuristic-6")), + ( + "engine_id", + serde_json::json!(format!("{family}-{}", version.saturating_sub(1))), + ), + ( + "engine_id", + serde_json::json!(format!("{family}-{}", version + 1)), + ), ("protocol", serde_json::json!(2)), ("asset", serde_json::json!("other.exe")), ] { diff --git a/apps/amp-player/src/performance.rs b/apps/amp-player/src/performance.rs index fcf066b3..2b6923e1 100644 --- a/apps/amp-player/src/performance.rs +++ b/apps/amp-player/src/performance.rs @@ -98,6 +98,7 @@ pub struct Run { pub scratch_assist: bool, scratch_bridge: Option<(usize, Instant)>, completed_handoffs: u32, + pub(crate) arc_handoffs: u32, pub future_candidates: VecDeque, failed_songs: Vec, smart_cycle: amp_core::smart_cycle::SmartCycle, @@ -139,6 +140,7 @@ impl Default for Run { scratch_assist: transitions.enabled, scratch_bridge: None, completed_handoffs: 0, + arc_handoffs: 0, future_candidates: VecDeque::new(), failed_songs: Vec::new(), smart_cycle: Default::default(), @@ -163,6 +165,7 @@ impl Run { } pub(super) fn load_regular_playlist(&mut self, name: String) { self.cancel_automation(); + self.arc_handoffs = 0; self.profile = None; self.playlist = Some(name); self.requests.clear(); @@ -934,7 +937,18 @@ impl Player { .progression .as_ref() .map(|p| p.next()) - .or(self.run.target); + .or(self.run.target) + .or(p.target_energy) + .or_else(|| { + let count = tracks + .iter() + .filter(|t| show::eligible(&p, t)) + .count() + .max(1); + let progress = (self.run.arc_handoffs as usize % count) as f64 + / count.saturating_sub(1).max(1) as f64; + show::style_target(p.style, progress) + }); let cycle_candidates = self.run.smart_cycle.ranked( &self.root.to_string_lossy(), &p, @@ -953,10 +967,6 @@ impl Player { let mut snapshot = self .loaded_track(self.active_deck()) .map(|t| t.preparation.clone()); - if let (Some(p), Some(energy)) = (&mut snapshot, self.exit_energy()) { - p.extensions - .insert("energy".into(), serde_json::json!(energy)); - } if let (Some(snapshot), Some(audio)) = (&mut snapshot, &self.audio) { let active = self.active_deck(); let available = audio.controls.key_lock_available[active].load(Relaxed); @@ -971,13 +981,17 @@ impl Player { .extensions .insert("runtime_rank_next_key_lock".into(), json!(available)); } - let ranked = self.run.smart_cycle.ranked( + let outgoing_energy = self.exit_energy(); + let ranked = self.run.smart_cycle.ranked_with_context( &self.root.to_string_lossy(), &p, tracks, current, target, - snapshot.as_ref(), + show::RankingContext { + preparation: snapshot.as_ref(), + outgoing_energy, + }, ); let mut index=*ranked.get(alternate.min(ranked.len().saturating_sub(1))).ok_or("Auto Mix stopped: no playable next song matches this playlist's source and repeat rules")?; let wants_mashup = self.run.force_mashup @@ -1869,6 +1883,7 @@ impl Player { self.run.failed_songs.clear(); self.run.smart_cycle = Default::default(); self.run.smart_audible = None; + self.run.arc_handoffs = 0; self.run.choice = p.id.clone(); self.run.planned_progression = p.energy_progression.clone(); self.run.planned_force = false; @@ -2263,7 +2278,7 @@ impl Player { fn exit_energy(&self) -> Option { let active = self.active_deck(); let t = self.loaded_track(active)?; - let profile = amp_core::energy_profile::read(&t.preparation)?; + let profile = amp_core::energy_profile::mixing_profile(&t.preparation)?; let end = self .automatic_exit(active) .unwrap_or_else(|| t.preparation.cue_out.unwrap_or(profile.duration)); @@ -2281,7 +2296,7 @@ impl Player { return None; } self.loaded_track(active).and_then(|t| { - amp_core::energy_profile::read(&t.preparation) + amp_core::energy_profile::mixing_profile(&t.preparation) .and_then(|p| { self.audio .as_ref() @@ -2941,6 +2956,7 @@ impl Player { self.run.cancel_effects(audio); } self.run.completed_handoffs = self.run.completed_handoffs.wrapping_add(1); + self.run.arc_handoffs = self.run.arc_handoffs.wrapping_add(1); self.run.active = incoming; self.run.transition = None; self.run.preloaded = None; @@ -3080,7 +3096,7 @@ mod tests { use amp_core::energy_profile::{FIELD, Profile, Section}; use amp_core::preparation::Cue; let profile = Profile { - version: 1, + version: 2, duration: 150., step: 1., curve: vec![0.2; 150], @@ -3967,7 +3983,7 @@ mod tests { ..Default::default() }); prep.extensions.insert("energy_profile".into(), serde_json::json!({ - "version":1,"duration":16.,"step":1.,"curve":[0.2,0.8], + "version":2,"duration":16.,"step":1.,"curve":[0.2,0.8], "sections":[{"id":"drop","name":"High energy","start":8.,"end":16.,"energy":0.8}] })); amp_core::preparation::save(root.path(), std::path::Path::new(name), &prep).unwrap(); @@ -4397,6 +4413,8 @@ mod tests { collision.id = "wrong-id".into(); collision.name = target.id.clone(); player.run.settings.playlists = vec![collision, target]; + player.run.completed_handoffs = 42; + player.run.arc_handoffs = 17; player .execute_control(Action::LoadSmartPlaylist { playlist: "target-id".into(), @@ -4406,6 +4424,8 @@ mod tests { }) .unwrap(); assert_eq!(player.run.playlist.as_deref(), Some("target-id")); + assert_eq!(player.run.arc_handoffs, 0); + assert_eq!(player.run.completed_handoffs, 42); assert_eq!( player.run.profile.as_ref().unwrap().name, "Intended playlist" diff --git a/apps/amp-player/src/preparer.rs b/apps/amp-player/src/preparer.rs index 04dabc80..b1d0ce73 100644 --- a/apps/amp-player/src/preparer.rs +++ b/apps/amp-player/src/preparer.rs @@ -242,6 +242,9 @@ impl Preparer { } } let profile = amp_core::energy_profile::read(&self.draft); + if profile.as_ref().is_some_and(|p| p.version == 1) { + ui.weak("Legacy loudness sections · review a new analysis for normalized energy."); + } let duration = profile .as_ref() .map(|p| p.duration) @@ -1237,12 +1240,13 @@ self.status=match queued{Ok(path)=>format!("{e}. Draft kept locally at {}. Recon if ui.add(egui::Slider::new(&mut rating, 0..=5)).changed() { self.draft.extensions.insert("rating".into(), serde_json::json!(rating)); } let mut known = amp_core::smart::energy(&self.draft).is_some(); if ui.checkbox(&mut known, "Energy known").changed() { + self.draft.extensions.insert("energy_source".into(), serde_json::json!("manual")); if known { self.draft.extensions.insert("energy".into(), serde_json::json!(0.5)); } else { self.draft.extensions.remove("energy"); } } if known { let mut energy = amp_core::smart::energy(&self.draft).unwrap_or(0.5); - if ui.add(egui::Slider::new(&mut energy, 0. ..=1.).text("Energy")).changed() { self.draft.extensions.insert("energy".into(), serde_json::json!(energy)); } + if ui.add(egui::Slider::new(&mut energy, 0. ..=1.).text("Energy")).changed() { self.draft.extensions.insert("energy".into(), serde_json::json!(energy));self.draft.extensions.insert("energy_source".into(),serde_json::json!("manual")); } } }); ui.horizontal(|ui|{ diff --git a/apps/amp-player/src/session.rs b/apps/amp-player/src/session.rs index ea6919dd..3df6ee6a 100644 --- a/apps/amp-player/src/session.rs +++ b/apps/amp-player/src/session.rs @@ -107,6 +107,8 @@ pub struct Snapshot { choice: String, style: amp_core::show::Style, target: Option, + #[serde(default)] + arc_handoffs: u32, profile: Option, transitions: transition_styles::Settings, crossfade: bool, @@ -586,6 +588,7 @@ impl Player { choice: self.run.choice.clone(), style: self.run.style, target: self.run.target, + arc_handoffs: self.run.arc_handoffs, profile: self.run.profile.clone(), transitions: self.run.transitions, crossfade: self.run.crossfade, @@ -762,6 +765,7 @@ impl Player { } self.run.style = snapshot.style; self.run.target = snapshot.target; + self.run.arc_handoffs = snapshot.arc_handoffs; self.run.transitions = snapshot.transitions; self.run.crossfade = snapshot.crossfade; self.run.auto = false; @@ -844,6 +848,13 @@ mod tests { let snapshot = Player::default().session_snapshot(); let mut value = serde_json::to_value(snapshot).unwrap(); value.as_object_mut().unwrap().remove("automatic_restore"); + value.as_object_mut().unwrap().remove("arc_handoffs"); + assert_eq!( + serde_json::from_value::(value.clone()) + .unwrap() + .arc_handoffs, + 0 + ); assert!( serde_json::from_value::(value.clone()) .unwrap() @@ -872,7 +883,9 @@ mod tests { }), ..Default::default() }; + player.run.arc_handoffs = 7; player.recovery.pending = Some(player.session_snapshot()); + player.run.arc_handoffs = 0; player.recovery.automatic_restore = true; let (_tx, rx) = std::sync::mpsc::channel(); player.scan = Some(rx); @@ -883,6 +896,7 @@ mod tests { ); assert!(player.scan.is_some()); assert!(player.recovery.pending.is_none()); + assert_eq!(player.run.arc_handoffs, 7); assert!( player.audio.is_none(), "an empty session must not open an audio output" diff --git a/crates/amp-core/Cargo.toml b/crates/amp-core/Cargo.toml index 4cf3cd94..6047138b 100644 --- a/crates/amp-core/Cargo.toml +++ b/crates/amp-core/Cargo.toml @@ -17,7 +17,8 @@ amp-dj-policy = { path = "../amp-dj-policy" } lofty = "0.25.5" rusqlite = { version = "0.37", features = ["bundled", "blob"] } serde.workspace = true -serde_json.workspace = true +# Preparation and content identities must retain measured f64 values on reload. +serde_json = { workspace = true, features = ["float_roundtrip"] } sha2 = "0.10" tempfile = "3" uuid = { version = "1", features = ["v4"] } diff --git a/crates/amp-core/src/analysis.rs b/crates/amp-core/src/analysis.rs index bfbaf201..dc3a2a90 100644 --- a/crates/amp-core/src/analysis.rs +++ b/crates/amp-core/src/analysis.rs @@ -12,6 +12,8 @@ const FFT: usize = 4096; mod chroma_engine; #[path = "energy_cues.rs"] mod energy_cues; +#[path = "section_activity.rs"] +mod section_activity; #[cfg(test)] fn chroma(samples: &[f32], sum: &mut [f64; 12]) { chroma_engine::Analyzer::new().accumulate(samples, sum); @@ -105,12 +107,24 @@ fn windowed_tempo(energy: &[f64]) -> (Option, Option, f64) { cluster.iter().map(|(_, c)| c).sum::() / votes.len() as f64, ) } +#[cfg(test)] fn result( energy: &[f64], rhythmic: &[f64], chroma: &[f64; 12], duration: f64, existing: &Preparation, +) -> Result { + result_with_activity(energy, rhythmic, chroma, duration, existing, None, None) +} +fn result_with_activity( + energy: &[f64], + rhythmic: &[f64], + chroma: &[f64; 12], + duration: f64, + existing: &Preparation, + activity: Option<(crate::energy_profile::Profile, section_activity::Features)>, + bass: Option<&[f64]>, ) -> Result { let max = energy.iter().copied().fold(0., f64::max); let threshold = (max * 0.01).max(0.0001); @@ -142,10 +156,25 @@ fn result( alternatives.push(value / 2.); bpm = Some(value / 2.); // Display the slower pulse; the double-time candidate remains reviewable. } - let rhythm_quality = bpm + let mut rhythm_quality = bpm .zip(offset) .map(|(bpm, offset)| rhythm::stability(energy, RATE / BLOCK as f64, bpm, offset)); let stable = rhythm_quality.as_ref().and_then(|q| q["stable"].as_bool()) != Some(false); + let downbeat = if rhythm_quality.as_ref().and_then(|q| q["stable"].as_bool()) == Some(true) { + bass.zip(bpm.zip(offset)).and_then(|(bass, (bpm, offset))| { + rhythm::downbeat_hypothesis(bass, RATE / BLOCK as f64, bpm, offset) + }) + } else { + None + }; + if let Some(quality) = rhythm_quality.as_mut().and_then(|v| v.as_object_mut()) { + quality.insert( + "downbeat_confidence".into(), + serde_json::json!(downbeat.map(|(_, confidence)| confidence)), + ); + quality.insert("downbeat_estimate".into(), serde_json::json!(downbeat.map(|(seconds, confidence)| + serde_json::json!({"seconds":seconds,"confidence":confidence,"assumed_beats_per_bar":4,"source":"heuristic_low_band_accent","verified":false})))); + } let (key, harmonic_key, key_confidence) = key(chroma); let audio_start = first as f64 * BLOCK as f64 / RATE; let mut energy_cues = energy_cues::candidates(energy, first, last); @@ -154,7 +183,12 @@ fn result( && stable { for (seconds, _) in &mut energy_cues { - *seconds = rhythm::snap(*seconds, bpm, offset).clamp(audio_start, duration); + let beat = rhythm::snap(*seconds, bpm, offset); + let at = downbeat + .map(|(downbeat, _)| rhythm::snap(*seconds, bpm / 4., downbeat)) + .filter(|at| (*at - *seconds).abs() <= 30. / bpm) + .unwrap_or(beat); + *seconds = at.clamp(audio_start, duration); } } let cue_out = ((last + 1) as f64 * BLOCK as f64 / RATE).min(duration); @@ -171,16 +205,60 @@ fn result( .insert("tempo_alternatives".into(), serde_json::json!(alternatives)); } { - p.extensions.insert( - crate::energy_profile::FIELD.into(), - serde_json::to_value(crate::energy_profile::build( + p.extensions.remove("auto_mix_sections"); + let mut profile = if let Some((profile, features)) = activity { + p.extensions.insert( + "section_activity".into(), + serde_json::to_value(features).map_err(|e| e.to_string())?, + ); + p.extensions.insert( + "energy_profile_method".into(), + serde_json::json!(section_activity::METHOD), + ); + profile + } else { + p.extensions.remove("section_activity"); + p.extensions.insert( + "energy_profile_method".into(), + serde_json::json!("amp-rms-1"), + ); + crate::energy_profile::build( energy, RATE / BLOCK as f64, + -14., duration, bpm.filter(|_| stable), offset.filter(|_| stable), - )) - .map_err(|e| e.to_string())?, + )? + }; + if let Some((anchor, _)) = downbeat + && let Some(bpm) = bpm + { + let phrase = 32. * 60. / bpm; + for i in 1..profile.sections.len() { + let at = profile.sections[i].start; + let snapped = anchor + ((at - anchor) / phrase).round() * phrase; + if (snapped - at).abs() <= 60. / bpm + && snapped > profile.sections[i - 1].start + && snapped < profile.sections[i].end + { + profile.sections[i - 1].end = snapped; + profile.sections[i].start = snapped; + } + } + for section in &mut profile.sections { + section.energy = crate::energy_profile::mean_between( + &profile.curve, + profile.step, + section.start, + section.end, + ); + } + profile.validate()?; + } + p.extensions.insert( + crate::energy_profile::FIELD.into(), + serde_json::to_value(profile).map_err(|e| e.to_string())?, ); } if let Some(quality) = rhythm_quality { @@ -189,10 +267,14 @@ fn result( p.extensions.remove("rhythm_quality"); } p.schema_version = Some(1); - // Relative loudness/activity proxy, not a calibrated perceptual energy detector. - if !p.extensions.contains_key("energy") { - let rms = (energy.iter().map(|x| x * x).sum::() / energy.len().max(1) as f64).sqrt(); - let energy_score = ((20. * rms.max(1e-6).log10() + 48.) / 42.).clamp(0., 1.); + // Legacy field is written only for a new value, on the same normalized + // scale. Explicit existing user values remain protected. + if !p.extensions.contains_key("energy") + && p.extensions.get("energy_source").and_then(|v| v.as_str()) != Some("manual") + { + let energy_score = crate::energy_profile::read(&p) + .and_then(|profile| profile.mean_energy()) + .ok_or("Normalized activity profile is unavailable")?; p.extensions .insert("energy".into(), serde_json::json!(energy_score)); } @@ -321,6 +403,19 @@ fn result( key_confidence, reviewed: false, }); + if p.extensions + .get("energy_profile_method") + .and_then(|v| v.as_str()) + == Some(section_activity::METHOD) + && let Some(entry) = crate::hype_sections::entry(&p) + { + let mut played = p.clone(); + played.cue_in = entry; + let exit = crate::hype_sections::exit(&played, 0.); + let exits = crate::hype_sections::automatic_exit_candidates(&played) + .ok_or("Prepared passage has no compatible activity profile")?; + p.extensions.insert("auto_mix_sections".into(),serde_json::json!({"version":1,"method":section_activity::METHOD,"entry":entry,"exit":exit,"exit_candidates":exits,"duration":duration,"minimum_passage":crate::hype_sections::minimum_passage(&p),"engine":ENGINE_ID})); + } if locked { let mut suggested = p; suggested.cue_in = cue_in; @@ -368,7 +463,7 @@ pub fn analyze(path: &Path, existing: &Preparation) -> Result Result Result= FFT { - chroma.accumulate(&spectral[..FFT], &mut chroma_sum); + let mut frame_chroma = [0.; 12]; + chroma.accumulate(&spectral[..FFT], &mut frame_chroma); + for (sum, value) in chroma_sum.iter_mut().zip(frame_chroma) { + *sum += value; + } + spectra.push(section_activity::Spectrum { + seconds: (spectra.len() * FFT) as f64 / RATE, + brightness: chroma.brightness(), + low_weight: chroma.band_weight(30., 150.), + mid_weight: chroma.band_weight(150., 2500.), + high_weight: chroma.band_weight(2500., RATE / 2.), + flux: chroma.flux(), + chroma: frame_chroma, + }); spectral.drain(..FFT); } if n < buffer.len() { @@ -443,15 +569,30 @@ pub fn analyze(path: &Path, existing: &Preparation) -> Result Result, im: Vec, power: Vec, + previous_shape: Vec, + flux: f64, } impl Analyzer { + /// Fraction of spectral power in a physically supported frequency band. + pub(super) fn band_weight(&self, low: f64, high: f64) -> f64 { + let total = self.power.iter().sum::(); + if total <= 1e-15 { + return 0.; + } + (self + .power + .iter() + .enumerate() + .filter(|(i, _)| { + let hz = *i as f64 * RATE / FFT as f64; + hz >= low && hz < high + }) + .map(|(_, power)| power) + .sum::() + / total) + .clamp(0., 1.) + } + pub(super) fn flux(&self) -> f64 { + self.flux + } + pub(super) fn brightness(&self) -> f64 { + let total = self.power.iter().sum::(); + if total <= 1e-15 { + return 0.; + } + (self + .power + .iter() + .enumerate() + .map(|(i, p)| i as f64 * p) + .sum::() + / total + / (FFT / 2) as f64) + .clamp(0., 1.) + } pub(super) fn new() -> Self { let _ = plan(); Self { re: vec![0.; FFT], im: vec![0.; FFT], power: vec![0.; FFT / 2], + previous_shape: vec![0.; FFT / 2], + flux: 0., } } pub(super) fn accumulate(&mut self, samples: &[f32], sum: &mut [f64; 12]) { @@ -92,6 +133,24 @@ impl Analyzer { for (i, value) in self.power.iter_mut().enumerate() { *value = self.re[i] * self.re[i] + self.im[i] * self.im[i]; } + // Positive change in L1-normalized magnitude. Spectral shape changes, + // not mastering gain, drive this bounded flux. First frame has no onset. + let magnitude = self.power.iter().map(|p| p.sqrt()).sum::(); + let had_previous = self.previous_shape.iter().any(|v| *v > 0.); + self.flux = 0.; + for (power, previous) in self.power.iter().zip(&mut self.previous_shape) { + let shape = if magnitude > 1e-12 { + power.sqrt() / magnitude + } else { + 0. + }; + self.flux += (shape - *previous).max(0.); + *previous = shape; + } + if !had_previous { + self.flux = 0.; + } + self.flux = self.flux.clamp(0., 1.); let peak = self.power.iter().copied().fold(0., f64::max); if peak < 1e-8 { return; @@ -126,6 +185,43 @@ impl Analyzer { #[cfg(test)] mod tests { use super::*; + #[test] + fn spectral_bands_and_positive_flux_are_gain_invariant() { + let measure = |gain: f64| { + let mut analyzer = Analyzer::new(); + let tone = |hz: f64| { + (0..FFT) + .map(|i| (gain * (std::f64::consts::TAU * hz * i as f64 / RATE).sin()) as f32) + .collect::>() + }; + analyzer.accumulate(&tone(80.), &mut [0.; 12]); + assert_eq!(analyzer.flux(), 0.); + assert!(analyzer.band_weight(30., 150.) > 0.99); + analyzer.accumulate(&tone(80.), &mut [0.; 12]); + assert!(analyzer.flux() < 1e-10); + analyzer.accumulate(&tone(4000.), &mut [0.; 12]); + assert!(analyzer.band_weight(2500., RATE / 2.) > 0.99); + assert!(analyzer.flux() > 0.99); + analyzer.flux() + }; + assert!((measure(0.1) - measure(0.2)).abs() < 1e-8); + } + #[test] + fn brightness_reuses_the_fft_and_is_gain_invariant() { + let measure = |frequency: f64, gain: f64| { + let samples = (0..FFT) + .map(|i| { + (gain * (std::f64::consts::TAU * frequency * i as f64 / RATE).sin()) as f32 + }) + .collect::>(); + let mut analyzer = Analyzer::new(); + analyzer.accumulate(&samples, &mut [0.; 12]); + analyzer.brightness() + }; + assert!(measure(220., 0.2) < 0.1); + assert!(measure(4000., 0.2) > 0.6); + assert!((measure(220., 0.2) - measure(220., 0.4)).abs() < 1e-8); + } fn reference_chroma(samples: &[f32], sum: &mut [f64; 12]) { let mut re = vec![0.; FFT]; let mut im = vec![0.; FFT]; diff --git a/crates/amp-core/src/energy_profile.rs b/crates/amp-core/src/energy_profile.rs index 0c1cd8c0..99474b78 100644 --- a/crates/amp-core/src/energy_profile.rs +++ b/crates/amp-core/src/energy_profile.rs @@ -2,6 +2,19 @@ use crate::Preparation; use serde::{Deserialize, Serialize}; pub const FIELD: &str = "energy_profile"; +pub(crate) fn mean_between(curve: &[f64], step: f64, start: f64, end: f64) -> f64 { + if end <= start || step <= 0. { + return 0.; + } + curve + .iter() + .enumerate() + .map(|(i, value)| { + value * ((end.min((i + 1) as f64 * step) - start.max(i as f64 * step)).max(0.)) + }) + .sum::() + / (end - start) +} pub fn mixing_allowed(p: &Preparation) -> bool { p.extensions .get("energy_section_mixing") @@ -36,7 +49,7 @@ pub struct Profile { } impl Profile { pub fn validate(&self) -> Result<(), String> { - if self.version != 1 + if !matches!(self.version, 1 | 2) || !self.duration.is_finite() || !(0. ..=21600.).contains(&self.duration) || !self.step.is_finite() @@ -82,6 +95,33 @@ impl Profile { .copied() }) } + /// Common track/section scale, weighted by the actual final partial bin. + pub fn mean_energy(&self) -> Option { + if self.version != 2 || self.duration <= 0. { + return None; + } + let covered = self.sections.first().is_some_and(|s| s.start == 0.) + && self + .sections + .last() + .is_some_and(|s| (s.end - self.duration).abs() < 1e-6) + && self + .sections + .windows(2) + .all(|w| (w[0].end - w[1].start).abs() < 1e-6); + if covered { + Some( + self.sections + .iter() + .map(|s| s.energy * (s.end - s.start)) + .sum::() + / self.duration, + ) + } else { + (!self.curve.is_empty() && self.curve.len() as f64 * self.step >= self.duration) + .then(|| mean_between(&self.curve, self.step, 0., self.duration)) + } + } pub fn entry(&self, target: f64, first: f64, last: f64, minimum: f64) -> Option<&Section> { self.sections .iter() @@ -100,6 +140,11 @@ pub fn read(p: &Preparation) -> Option { profile.validate().ok()?; Some(profile) } +/// Legacy RMS sections remain viewable, but cannot be compared to normalized +/// analyzed track scores. Saved cues and explicit track values remain separate. +pub fn mixing_profile(p: &Preparation) -> Option { + read(p).filter(|profile| profile.version == 2) +} #[derive(Clone, Copy, Debug, PartialEq)] pub struct AutomaticEntry { pub seconds: f64, @@ -115,7 +160,7 @@ pub fn automatic_entry(p: &Preparation, target: f64, minimum: f64) -> Option Result<(), String> { } Ok(()) } -/// Absolute level curve shared across tracks. Deliberately not per-track min/max scaling. +/// Normalized activity on the same scale as track scoring. No per-track min/max scaling. #[cfg(feature = "analysis")] pub(crate) fn build( rms: &[f64], hz: f64, + integrated_lufs: f64, duration: f64, bpm: Option, offset: Option, -) -> Profile { +) -> Result { + if rms.len() < 2 + || !hz.is_finite() + || hz <= 0. + || !integrated_lufs.is_finite() + || !duration.is_finite() + || duration <= 0. + || rms.iter().any(|v| !v.is_finite() || *v < 0.) + { + return Err("Invalid normalized energy input".into()); + } let bin = (hz * 2.).round().max(1.) as usize; let curve: Vec = rms .chunks(bin) .map(|xs| { - let rms = (xs.iter().map(|v| v * v).sum::() / xs.len() as f64).sqrt(); - ((20. * rms.max(1e-6).log10() + 48.) / 42.).clamp(0., 1.) + if xs.len() < 2 { + Ok(0.) + } else { + crate::perceptual_energy::from_rms(xs, hz, integrated_lufs) + .ok_or_else(|| "Invalid section activity measurement".to_string()) + } }) - .collect(); + .collect::, _>>()?; let step = bin as f64 / hz; let width = bpm .filter(|b| b.is_finite() && *b > 0.) @@ -193,14 +253,7 @@ pub(crate) fn build( .enumerate() .filter(|(_, w)| w[1] > w[0]) .map(|(i, w)| { - let a = (w[0] / step).floor() as usize; - let b = ((w[1] / step).ceil() as usize).min(curve.len()); - let values = &curve[a.min(b)..b]; - let energy = if values.is_empty() { - 0. - } else { - values.iter().sum::() / values.len() as f64 - }; + let energy = mean_between(&curve, step, w[0], w[1]); Section { id: format!("section-{}", i + 1), name: format!("Section {}", i + 1), @@ -210,17 +263,25 @@ pub(crate) fn build( } }) .collect(); - Profile { - version: 1, + let profile = Profile { + version: 2, duration, step, curve, sections, - } + }; + profile.validate()?; + Ok(profile) } #[cfg(test)] mod tests { use super::*; + #[cfg(feature = "analysis")] + #[test] + fn normalized_profile_rejects_missing_activity_evidence() { + assert!(build(&[], 20., -14., 10., None, None).is_err()); + assert!(build(&[0.5], 20., -14., 10., None, None).is_err()); + } fn sample() -> Profile { Profile { version: 1, @@ -261,7 +322,7 @@ mod tests { p.extensions.insert( FIELD.into(), serde_json::json!({ - "version":1,"duration":150.,"step":1.,"curve":[],"sections":[ + "version":2,"duration":150.,"step":1.,"curve":[],"sections":[ {"id":"intro","name":"Intro","start":0.,"end":16.,"energy":0.2}, {"id":"strong","name":"Strong","start":16.,"end":32.,"energy":0.9}, {"id":"quiet","name":"Quiet","start":32.,"end":150.,"energy":0.1} @@ -291,7 +352,7 @@ mod tests { p.extensions.insert( FIELD.into(), serde_json::json!({ - "version":1,"duration":150.,"step":1.,"curve":[],"sections":[ + "version":2,"duration":150.,"step":1.,"curve":[],"sections":[ {"id":"intro","name":"Intro","start":0.,"end":30.,"energy":0.2}, {"id":"strong","name":"Strong","start":30.,"end":80.,"energy":0.6}, {"id":"tail","name":"Tail","start":80.,"end":150.,"energy":0.1} @@ -334,13 +395,51 @@ mod tests { } #[cfg(feature = "analysis")] #[test] - fn different_songs_keep_comparable_energy_and_known_grid_sections() { - let a = build(&vec![0.01; 6000], 100., 60., Some(120.), Some(0.)); - let b = build(&vec![0.2; 6000], 100., 60., Some(120.), Some(0.)); + fn normalized_sections_ignore_gain_and_distinguish_rhythm_from_a_loud_pad() { + let dance = (0..6000) + .map(|i| if i % 50 < 4 { 0.25 } else { 0.02 }) + .collect::>(); + let a = build(&dance, 100., -15.8, 60., Some(120.), Some(0.)).unwrap(); + let b = build(&vec![0.7; 6000], 100., -3.6, 60., Some(120.), Some(0.)).unwrap(); + let loud = build( + &dance.iter().map(|v| v * 2.).collect::>(), + 100., + -15.8 + 20. * 2f64.log10(), + 60., + Some(120.), + Some(0.), + ) + .unwrap(); a.validate().unwrap(); b.validate().unwrap(); - assert!(b.sections[0].energy > a.sections[0].energy + 0.3); + assert!(a.sections[0].energy > b.sections[0].energy + 0.1); + for (a, b) in a.curve.iter().zip(loud.curve) { + assert!((a - b).abs() < 0.01); + } + assert_eq!(a.version, 2); + assert!( + (a.mean_energy().unwrap() + - a.sections + .iter() + .map(|s| s.energy * (s.end - s.start)) + .sum::() + / a.duration) + .abs() + < 1e-12 + ); assert_eq!(a.sections[0].end, 8.); assert_eq!(a.sections.last().unwrap().end, 60.); } + #[test] + fn legacy_profiles_load_without_being_ranked_against_normalized_track_energy() { + let mut p = Preparation::default(); + p.extensions + .insert(FIELD.into(), serde_json::to_value(sample()).unwrap()); + assert!(read(&p).is_some()); + assert!(mixing_profile(&p).is_none()); + p.extensions + .insert("perceptual_energy".into(), serde_json::json!(0.5)); + assert!(read(&p).is_some()); + assert!(mixing_profile(&p).is_none()); + } } diff --git a/crates/amp-core/src/engine_api.rs b/crates/amp-core/src/engine_api.rs index b33dba72..27831c16 100644 --- a/crates/amp-core/src/engine_api.rs +++ b/crates/amp-core/src/engine_api.rs @@ -3,7 +3,7 @@ use crate::Preparation; use serde::{Deserialize, Serialize}; use std::path::PathBuf; pub const PROTOCOL: u32 = 1; -pub const ENGINE_ID: &str = "amp-prep-heuristic-5"; +pub const ENGINE_ID: &str = "amp-prep-heuristic-6"; pub const JOB_TYPE: &str = "preparation"; #[derive(Serialize, Deserialize)] pub struct Request { diff --git a/crates/amp-core/src/hype_sections.rs b/crates/amp-core/src/hype_sections.rs index 544b6a67..588c5e5d 100644 --- a/crates/amp-core/src/hype_sections.rs +++ b/crates/amp-core/src/hype_sections.rs @@ -10,6 +10,9 @@ fn activity(p: &Preparation) -> Option { { return None; } + // Only relative changes within this recording select times here. Legacy + // curves remain usable for those unverified local estimates; their numeric + // levels never enter cross-track ranking through mixing_profile(). let profile = crate::energy_profile::read(p)?; if p.analysis.as_ref().is_some_and(|a| { !a.duration.is_finite() || (a.duration - profile.duration).abs() > profile.step @@ -29,6 +32,9 @@ fn beats(p: &Preparation, count: f64, fallback: f64) -> f64 { fallback } } +pub fn minimum_passage(p: &Preparation) -> f64 { + beats(p, 32., 16.).max(12.) +} /// Explicitly marked drops/hooks take priority over build-up labels. pub fn marked_entry(p: &Preparation) -> Option { let end = p @@ -74,7 +80,7 @@ pub fn entry(p: &Preparation) -> Option { let threshold = low + (high - low) * 0.65; let before = (4. / profile.step).ceil().max(1.) as usize; let hold = (8. / profile.step).ceil().max(2.) as usize; - let minimum = beats(p, 32., 16.).max(12.); + let minimum = minimum_passage(p); let mut candidates = Vec::new(); for i in before..profile.curve.len().saturating_sub(hold) { let at = i as f64 * profile.step; @@ -125,7 +131,7 @@ pub fn exit(p: &Preparation, transition: f64) -> Option { if !transition.is_finite() || transition < 0. { return None; } - let minimum = beats(p, 32., 16.).max(12.); + let minimum = minimum_passage(p); let bound = p .cue_out .or_else(|| p.analysis.as_ref().map(|a| a.duration)) @@ -145,39 +151,62 @@ pub fn exit(p: &Preparation, transition: f64) -> Option { { return Some(mark.seconds); } + automatic_exit_candidates(p)? + .into_iter() + .find(|at| *at >= p.cue_in + minimum + transition) +} +/// Portable choices let a client apply its actual fade horizon without repeating +/// audio analysis or discarding a valid later lull when the first is too soon. +pub fn automatic_exit_candidates(p: &Preparation) -> Option> { let profile = activity(p)?; + let minimum = minimum_passage(p); let end = p.cue_out.unwrap_or(profile.duration).min(profile.duration); let first = p.cue_in; let window = (8. / profile.step).ceil().max(2.) as usize; let start = (first / profile.step).ceil() as usize; let mut peak: f64 = 0.; + let mut candidates = Vec::new(); for i in start..profile.curve.len().saturating_sub(window) { let next = mean(&profile.curve, i, window)?; let at = i as f64 * profile.step; if at + window as f64 * profile.step > end { break; } - if at >= first + minimum + transition && peak >= 0.35 && peak - next >= 0.10 { + if at >= first + minimum && peak >= 0.35 && peak - next >= 0.10 { let weak = profile.curve[i..i + window] .iter() .filter(|v| **v <= peak - 0.08) .count(); if profile.curve[i] <= peak - 0.08 && weak * 4 >= window * 3 { - return Some(at); + candidates.push(at); } } peak = peak.max(next); } - None + Some(candidates) } #[cfg(test)] mod tests { use super::*; + #[test] + fn android_portable_plan_matches_the_core_section_policy() { + let mut p: Preparation = + serde_json::from_str(include_str!("../tests/fixtures/mix-sections-v1.json")).unwrap(); + p.validate().unwrap(); + let plan = p.extensions["auto_mix_sections"].clone(); + assert_eq!(entry(&p), plan["entry"].as_f64()); + p.cue_in = entry(&p).unwrap(); + assert_eq!(exit(&p, 3.), plan["exit"].as_f64()); + assert_eq!( + minimum_passage(&p), + plan["minimum_passage"].as_f64().unwrap() + ); + } fn song(curve: Vec) -> Preparation { let duration = curve.len() as f64 * 2.; let profile = crate::energy_profile::Profile { - version: 1, + version: 2, duration, step: 2., curve, @@ -268,6 +297,10 @@ mod tests { let mut p: Preparation = serde_json::from_value(example["preparation"].clone()).unwrap(); let source = p.clone(); + assert!( + crate::energy_profile::mixing_profile(&p).is_none(), + "The legacy recording must remain excluded from normalized ranking" + ); let at = entry(&p).expect("reported pair has a sustained rise"); assert!(at > 20. && at < 100., "{}: {at}", example["title"]); p.cue_in = at; diff --git a/crates/amp-core/src/perceptual_energy.rs b/crates/amp-core/src/perceptual_energy.rs index 18c906ce..b7aad9ec 100644 --- a/crates/amp-core/src/perceptual_energy.rs +++ b/crates/amp-core/src/perceptual_energy.rs @@ -10,24 +10,48 @@ pub fn from_rms(rms: &[f64], frames_per_second: f64, integrated_lufs: f64) -> Op return None; } let gain = 10f64.powf((-14. - integrated_lufs) / 20.); - let peak = rms + if !gain.is_finite() { + return None; + } + let fluxes = rms .windows(2) .map(|w| ((w[1] - w[0]) * gain).max(0.)) - .fold(0., f64::max); + .collect::>(); + if fluxes.iter().any(|v| !v.is_finite()) { + return None; + } + let peak = fluxes.iter().copied().fold(0., f64::max); let threshold = 0.04f64.max(peak * 0.25); let refractory = (0.12 * frames_per_second).ceil() as usize; - let mut last = None; - let mut hits = 0; - let mut sum = 0.; - for (i, w) in rms.windows(2).enumerate() { - let flux = ((w[1] - w[0]) * gain).max(0.); - sum += flux; - if flux >= threshold && last.is_none_or(|last| i - last >= refractory) { - hits += 1; - last = Some(i); + let mut last: Option<(usize, f64, f64)> = None; + let mut hits = 0.; + let sum = fluxes.iter().sum::(); + for (i, &flux) in fluxes.iter().enumerate() { + let left = if i > 0 { fluxes[i - 1] } else { 0. }; + let right = fluxes.get(i + 1).copied().unwrap_or(0.); + if flux < left || flux <= right { + continue; + } + // A hard hit/no-hit threshold turns tiny rounded-LUFS errors into a + // full extra onset. Use a continuous peak weight around that threshold. + let strength = (flux / threshold - 0.5).clamp(0., 1.); + if strength <= 0. { + continue; + } + match last { + Some((at, previous, previous_flux)) if i - at < refractory => { + if flux > previous_flux { + hits += strength - previous; + last = Some((i, strength, flux)); + } + } + _ => { + hits += strength; + last = Some((i, strength, flux)); + } } } - let density = hits as f64 / (rms.len() as f64 / frames_per_second); + let density = hits / (rms.len() as f64 / frames_per_second); Some( (0.55 * (density / 3.5).min(1.) + 0.45 * (sum / (rms.len() - 1) as f64 / 0.06).min(1.)) .clamp(0., 1.), @@ -37,6 +61,16 @@ pub fn from_rms(rms: &[f64], frames_per_second: f64, integrated_lufs: f64) -> Op mod tests { use super::*; #[test] + fn rounded_lufs_near_an_onset_threshold_does_not_flip_whole_hits() { + let reference = (0..1600) + .map(|i| if i % 50 < 4 { 0.04499 } else { 0.005 }) + .collect::>(); + let louder = reference.iter().map(|v| v * 2.).collect::>(); + let a = from_rms(&reference, 100., -14.).unwrap(); + let b = from_rms(&louder, 100., -8.).unwrap(); // Rounded +6.02 dB measurement. + assert!((a - b).abs() < 0.01, "{a} versus {b}"); + } + #[test] fn f07_mastering_gain_does_not_change_rhythmic_energy() { let dance: Vec<_> = (0..1600) .map(|i| if i % 50 < 4 { 0.25 } else { 0.02 }) diff --git a/crates/amp-core/src/preparation.rs b/crates/amp-core/src/preparation.rs index 7837f1b5..dfcf0c90 100644 --- a/crates/amp-core/src/preparation.rs +++ b/crates/amp-core/src/preparation.rs @@ -632,6 +632,25 @@ mod tests { assert_eq!(crate::scan(d.path()).unwrap().tracks.len(), 1); } #[test] + fn saved_spectral_measurements_round_trip_exactly() { + let dir = tempfile::tempdir().unwrap(); + let audio = dir.path().join("song.wav"); + fs::write(&audio, b"unchanged source").unwrap(); + let mut prepared = Preparation::default(); + prepared.extensions.insert( + "section_activity".into(), + serde_json::json!({ + "mid_weight": [0.9999999975788693, 0.9999999974301035], + "spectral_flux": [0.00009602439788158921], + }), + ); + save(dir.path(), Path::new("song.wav"), &prepared).unwrap(); + let mut loaded = load(&audio).unwrap(); + loaded.extensions.remove("_amp_sync"); + assert_eq!(loaded, prepared); + assert_eq!(fs::read(audio).unwrap(), b"unchanged source"); + } + #[test] fn bad_cues_and_versions_rejected() { let mut p = Preparation { schema_version: Some(2), diff --git a/crates/amp-core/src/review.rs b/crates/amp-core/src/review.rs index 4e121dcd..4aa3eabc 100644 --- a/crates/amp-core/src/review.rs +++ b/crates/amp-core/src/review.rs @@ -1,5 +1,11 @@ //! Explicit field-level review; analysis never grants itself permission to replace approved data. use crate::Preparation; +const ENERGY_COMPANIONS: [&str; 4] = [ + "perceptual_energy", + "energy_profile_method", + "section_activity", + "auto_mix_sections", +]; const FIELDS: [&str; 10] = [ "energy_profile", "cue_in", @@ -19,6 +25,19 @@ pub fn proposal(p: &Preparation) -> Option { } fn value(p: &Preparation, field: &str) -> serde_json::Value { let mut v = serde_json::to_value(p).unwrap_or_default()[field].clone(); + if field == "energy_profile" + && crate::energy_profile::read(p).is_some_and(|profile| profile.version == 2) + { + let mut group = serde_json::Map::new(); + group.insert("profile".into(), v); + for companion in ENERGY_COMPANIONS { + group.insert( + companion.into(), + p.extensions.get(companion).cloned().unwrap_or_default(), + ); + } + v = serde_json::Value::Object(group); + } if field == "analysis" && let Some(o) = v.as_object_mut() { @@ -40,16 +59,38 @@ pub fn changes(p: &Preparation) -> Vec<(String, serde_json::Value, serde_json::V .collect() } pub fn decide(p: &Preparation, fields: &[String], accept: bool) -> Result { + for field in fields { + if !FIELDS.contains(&field.as_str()) { + return Err("Unsupported review field".into()); + } + } + let mut selected = fields.to_vec(); let mut candidate = proposal(p).ok_or("No pending recommendation")?; + if fields.iter().any(|field| field == "energy_profile") + && crate::energy_profile::read(&candidate).is_some_and(|profile| profile.version == 2) + { + // Approval/rejection of section measurements is atomic with its scale, + // normalized track aggregate and provenance; cues are never included. + selected.extend(ENERGY_COMPANIONS.into_iter().map(str::to_owned)); + if !candidate + .extensions + .get("perceptual_energy") + .is_some_and(|v| v.is_number()) + { + let energy = crate::energy_profile::read(&candidate) + .and_then(|profile| profile.mean_energy()) + .ok_or("Proposed sections have no complete normalized energy measurement")?; + candidate + .extensions + .insert("perceptual_energy".into(), serde_json::json!(energy)); + } + } candidate.validate()?; let mut current = p.clone(); current.extensions.remove("analysis_recommendation"); let mut a = serde_json::to_value(¤t).map_err(|e| e.to_string())?; let mut b = serde_json::to_value(&candidate).map_err(|e| e.to_string())?; - for f in fields { - if !FIELDS.contains(&f.as_str()) { - return Err("Unsupported review field".into()); - } + for f in &selected { if accept { a[f] = b[f].clone(); } else { @@ -67,7 +108,7 @@ pub fn decide(p: &Preparation, fields: &[String], accept: bool) -> Result Result f64 { let period = 60. / bpm; (offset + ((seconds - offset) / period).round() * period).max(0.) } +/// A conservative 4/4 hypothesis from repeated low-band beat accents. This is +/// not a verified meter/downbeat: equal four-on-the-floor kicks stay unknown. +pub(super) fn downbeat_hypothesis( + bass: &[f64], + hz: f64, + bpm: f64, + offset: f64, +) -> Option<(f64, f64)> { + if bass.iter().any(|v| !v.is_finite() || *v < 0.) + || ![hz, bpm, offset].iter().all(|v| v.is_finite()) + || hz <= 0. + || bpm <= 0. + || offset < 0. + { + return None; + } + let period = hz * 60. / bpm; + if period < 4. { + return None; + } + let beats = ((bass.len() as f64 - offset * hz) / period).floor().max(0.) as usize; + if beats < 32 { + return None; + } + let mut totals = [0.; 4]; + let mut winners = [0usize; 4]; + for bar in 0..beats / 4 { + let mut strength = [0.; 4]; + for (phase, score) in strength.iter_mut().enumerate() { + let center = offset * hz + (bar * 4 + phase) as f64 * period; + let first = (center - period * 0.08).max(1.) as usize; + let last = ((center + period * 0.08).ceil() as usize).min(bass.len()); + for at in first..last { + *score += (bass[at] - bass[at - 1]).max(0.); + } + totals[phase] += *score; + } + if let Some((phase, best)) = strength + .iter() + .enumerate() + .max_by(|a, b| a.1.total_cmp(b.1)) + && *best > 1e-8 + { + winners[phase] += 1; + } + } + let mut ranked = [0, 1, 2, 3]; + ranked.sort_by(|a, b| totals[*b].total_cmp(&totals[*a])); + let best = ranked[0]; + let confidence = if totals[best] > 1e-8 { + (1. - totals[ranked[1]] / totals[best]) * winners[best] as f64 / (beats / 4) as f64 + } else { + 0. + }; + (confidence >= 0.35).then_some((offset + best as f64 * 60. / bpm, confidence)) +} pub(super) fn estimate(energy: &[f64], hz: f64) -> (Option, Option, f64) { if energy.len() < 500 { @@ -131,6 +187,21 @@ pub(super) fn stability(energy: &[f64], hz: f64, bpm: f64, offset: f64) -> serde mod tests { use super::*; #[test] + fn downbeat_requires_repeated_asymmetric_accents_not_just_a_stable_grid() { + let mut bass = vec![0.; 8000]; + for beat in 0..160 { + bass[20 + beat * 50] = if beat % 4 == 2 { 1. } else { 0.2 }; + } + let (at, confidence) = downbeat_hypothesis(&bass, 100., 120., 0.2).unwrap(); + assert!((at - 1.2).abs() < 1e-9); + assert!(confidence > 0.7); + for beat in 0..160 { + bass[20 + beat * 50] = 1.; + } + assert!(downbeat_hypothesis(&bass, 100., 120., 0.2).is_none()); + assert!(downbeat_hypothesis(&bass[..500], 100., 120., 0.2).is_none()); + } + #[test] fn stability_distinguishes_steady_grid_from_sustained_drift_without_claiming_downbeats() { let mut steady = vec![0.; 12000]; let mut drift = steady.clone(); diff --git a/crates/amp-core/src/section_activity.rs b/crates/amp-core/src/section_activity.rs new file mode 100644 index 00000000..bc434de4 --- /dev/null +++ b/crates/amp-core/src/section_activity.rs @@ -0,0 +1,652 @@ +//! Original bounded descriptors for offline arrangement estimates. These are +//! activity/novelty proxies, not semantic vocals, choruses or a proprietary score. +use crate::energy_profile::Profile; +use serde::Serialize; + +pub const METHOD: &str = "amp-section-activity-1"; +#[derive(Clone)] +pub(super) struct Spectrum { + pub seconds: f64, + pub brightness: f64, + pub low_weight: f64, + pub mid_weight: f64, + pub high_weight: f64, + pub flux: f64, + pub chroma: [f64; 12], +} +#[derive(Serialize)] +pub(super) struct Features { + pub method: &'static str, + pub energy_weights: [f64; 5], + pub high_band_hz: [f64; 2], + pub step: f64, + pub onset_activity: Vec, + pub high_onset_activity: Vec, + pub bass_weight: Vec, + pub low_weight: Vec, + pub bass_drive: Vec, + pub brightness: Vec, + pub mid_weight: Vec, + pub high_weight: Vec, + pub spectral_flux: Vec, + pub normalized_loudness: Vec, + pub harmonic_change: Vec, + pub novelty: Vec, + pub boundary_method: &'static str, +} +// Original provisional weights, not a calibrated proprietary energy scale. +// Bass/brightness are gated by activity so a loud sustained pad cannot become +// a drop merely by being bass-heavy. High band is 2.5 kHz–Nyquist (5.5125 kHz). +const ENERGY_WEIGHTS: [f64; 5] = [0.30, 0.25, 0.20, 0.10, 0.15]; +/// Local checkerboard contrast: cross-window dissimilarity minus within-window +/// dissimilarity. Bounded memory; never allocates a whole-song similarity matrix. +fn checkerboard(vectors: &[[f64; 19]], at: usize, window: usize) -> f64 { + let distance = |a: &[f64; 19], b: &[f64; 19]| { + let activity = a[..7] + .iter() + .zip(&b[..7]) + .zip([0.30, 0.25, 0.10, 0.05, 0.05, 0.10, 0.15]) + .map(|((a, b), w)| (a - b).abs() * w) + .sum::(); + let harmony = a[7..] + .iter() + .zip(&b[7..]) + .map(|(a, b)| (a - b).abs()) + .sum::() + / 2.; + 0.9 * activity + 0.1 * harmony + }; + let (left, right) = (&vectors[at - window..at], &vectors[at..at + window]); + let mut score = 0.; + for i in 0..window { + for j in 0..window { + score += distance(&left[i], &right[j]) + - 0.5 * distance(&left[i], &left[j]) + - 0.5 * distance(&right[i], &right[j]); + } + } + (score / (window * window) as f64).clamp(0., 1.) +} +fn rms(values: &[f64]) -> f64 { + (values.iter().map(|v| v * v).sum::() / values.len().max(1) as f64).sqrt() +} +fn chroma_change(a: &[f64; 12], b: &[f64; 12]) -> f64 { + let norm = |v: &[f64; 12]| v.iter().map(|v| v * v).sum::().sqrt(); + let denominator = norm(a) * norm(b); + if denominator <= 1e-15 { + return 0.; + } + (1. - a.iter().zip(b).map(|(a, b)| a * b).sum::() / denominator).clamp(0., 1.) +} +/// Refine a coarse novelty peak using bounded, already-decoded evidence. +/// Retains the compact energy curve; this is not a semantic section/bar label. +fn refine_boundary( + channels: [&[f64]; 3], + spectra: &[Spectrum], + hz: f64, + at: f64, + radius: f64, + bpm: Option, +) -> f64 { + let window = bpm + .filter(|b| b.is_finite() && *b > 0.) + .map_or(1., |b| (120. / b).clamp(0.5, 2.)); + let first = ((at - radius - window).max(0.) * hz).floor() as usize; + let last = (((at + radius + window) * hz).ceil() as usize).min(channels[0].len()); + if first >= last { + return at; + } + let mut power = vec![[0.; 3]; last - first + 1]; + for i in first..last { + for band in 0..3 { + power[i - first + 1][band] = power[i - first][band] + channels[band][i].powi(2); + } + } + let spectrum_first = spectra.partition_point(|s| s.seconds < first as f64 / hz); + let spectrum_last = spectra.partition_point(|s| s.seconds <= last as f64 / hz); + let spectra = &spectra[spectrum_first..spectrum_last]; + let mut spectral = vec![[0.; 16]; spectra.len() + 1]; + for (i, frame) in spectra.iter().enumerate() { + let norm = frame.chroma.iter().sum::().max(1e-15); + let mut vector = [0.; 16]; + vector[..4].copy_from_slice(&[ + frame.brightness, + frame.low_weight, + frame.mid_weight, + frame.high_weight, + ]); + for (output, value) in vector[4..].iter_mut().zip(frame.chroma) { + *output = value / norm; + } + for (dimension, value) in vector.iter().enumerate() { + spectral[i + 1][dimension] = spectral[i][dimension] + value; + } + } + let stride = (hz * 0.05).round().max(1.) as usize; + let from = ((at - radius).max(0.) * hz).ceil() as usize; + let to = (((at + radius) * hz).floor() as usize).min(last.saturating_sub(1)); + let mut best = at; + let mut strength = 0.; + for position in (from..=to).step_by(stride) { + let time = position as f64 / hz; + let left = ((time - window).max(0.) * hz).round() as usize; + let right = (((time + window) * hz).round() as usize).min(last); + if left < first || left >= position || position >= right { + continue; + } + let mut contrast = 0.; + for (band, weight) in [0.50, 0.30, 0.20].iter().enumerate() { + let before = (power[position - first][band] - power[left - first][band]) + / (position - left) as f64; + let after = (power[right - first][band] - power[position - first][band]) + / (right - position) as f64; + contrast += weight * (after - before).abs() / (before + after).max(1e-15); + } + let a = spectra.partition_point(|s| s.seconds < time - window); + let b = spectra.partition_point(|s| s.seconds < time); + let c = spectra.partition_point(|s| s.seconds < time + window); + if a < b && b < c { + let mut shape = 0.; + for dimension in 0..16 { + let before = (spectral[b][dimension] - spectral[a][dimension]) / (b - a) as f64; + let after = (spectral[c][dimension] - spectral[b][dimension]) / (c - b) as f64; + let weight = match dimension { + 0 => 0.10, + 1..=3 => 0.15, + _ => 0.30, + }; + shape += weight * (after - before).abs(); + } + contrast = 0.6 * contrast + 0.4 * shape; + } + if contrast > strength + 1e-9 + || (strength > 1e-9 + && (contrast - strength).abs() <= 1e-9 + && (time - at).abs() < (best - at).abs()) + { + strength = contrast; + best = time; + } + } + best +} +/// Linear in envelope and spectrum frames; retains two-second descriptors only. +/// A matched LUFS measurement makes the activity curve invariant to mastering gain. +#[allow(clippy::too_many_arguments)] +pub(super) fn build_with_high( + envelope: &[f64], + bass: &[f64], + high: &[f64], + spectra: &[Spectrum], + hz: f64, + duration: f64, + lufs: f64, + bpm: Option, + offset: Option, +) -> Option<(Profile, Features)> { + if envelope.len() != bass.len() + || envelope.len() != high.len() + || envelope.len() < 2 + || !hz.is_finite() + || hz <= 0. + || !duration.is_finite() + || duration <= 0. + || !lufs.is_finite() + || envelope + .iter() + .chain(bass) + .chain(high) + .any(|v| !v.is_finite() || *v < 0.) + || spectra.iter().any(|s| { + !s.seconds.is_finite() + || !(0. ..=1.).contains(&s.brightness) + || [s.low_weight, s.mid_weight, s.high_weight, s.flux] + .iter() + .any(|v| !(0. ..=1.).contains(v)) + || s.chroma.iter().any(|v| !v.is_finite() || *v < 0.) + }) + || spectra + .windows(2) + .any(|pair| pair[0].seconds > pair[1].seconds) + { + return None; + } + let mut profile = + crate::energy_profile::build(envelope, hz, lufs, duration, bpm, offset).ok()?; + let bin = (hz * 2.).round().max(1.) as usize; + let mut features = Features { + method: METHOD, + energy_weights: ENERGY_WEIGHTS, + high_band_hz: [2500., super::RATE / 2.], + step: profile.step, + onset_activity: vec![], + high_onset_activity: vec![], + bass_weight: vec![], + low_weight: vec![], + bass_drive: vec![], + brightness: vec![], + mid_weight: vec![], + high_weight: vec![], + spectral_flux: vec![], + normalized_loudness: vec![], + harmonic_change: vec![], + novelty: vec![], + boundary_method: "fixed_grid_unverified", + }; + let gain = 10f64.powf((-14. - lufs) / 20.); + if !gain.is_finite() { + return None; + } + let mut spectral_index = 0; + let mut vectors = Vec::new(); + let mut previous_chroma = [0.; 12]; + for (i, values) in envelope.chunks(bin).enumerate() { + let first = i * bin; + let bass = &bass[first..(first + values.len())]; + let high = &high[first..(first + values.len())]; + let level = rms(values); + // A final single-envelope-frame tail contains no measurable onset. + let density = if values.len() > 1 { + crate::perceptual_energy::from_rms(values, hz, lufs)? + } else { + 0. + }; + let kick = if bass.len() > 1 { + crate::perceptual_energy::from_rms(bass, hz, lufs)? + } else { + 0. + }; + let hats = if high.len() > 1 { + crate::perceptual_energy::from_rms(high, hz, lufs)? + } else { + 0. + }; + let activity = (0.50 * density + 0.35 * kick + 0.15 * hats).clamp(0., 1.); + let weight = if level > 1e-8 { + (rms(bass) / level).clamp(0., 1.) + } else { + 0. + }; + let mut chroma = [0.; 12]; + let mut bright = 0.; + let mut bands = [0.; 3]; + let mut flux = 0.; + let mut count = 0; + while let Some(s) = spectra.get(spectral_index) { + if s.seconds >= (i + 1) as f64 * profile.step { + break; + } + spectral_index += 1; + bright += s.brightness; + bands[0] += s.low_weight; + bands[1] += s.mid_weight; + bands[2] += s.high_weight; + flux += s.flux; + count += 1; + for (sum, value) in chroma.iter_mut().zip(s.chroma) { + *sum += value; + } + } + let bright = bright / count.max(1) as f64; + for band in &mut bands { + *band /= count.max(1) as f64; + } + let flux = flux / count.max(1) as f64; + let harmony = chroma_change(&previous_chroma, &chroma); + previous_chroma = chroma; + let normalized = ((20. * (level * gain).max(1e-6).log10() + 48.) / 42.).clamp(0., 1.); + // Sustained loud/bassy/bright audio alone cannot look like a drum drop. + let bass_drive = (0.65 * kick + 0.35 * bands[0] * activity).clamp(0., 1.); + profile.curve[i] = [bass_drive, activity, flux, bright * activity, normalized] + .iter() + .zip(ENERGY_WEIGHTS) + .map(|(v, w)| v * w) + .sum::() + .clamp(0., 1.); + features.onset_activity.push(activity); + features.high_onset_activity.push(hats); + features.bass_weight.push(weight); + features.low_weight.push(bands[0]); + features.bass_drive.push(bass_drive); + features.brightness.push(bright); + features.mid_weight.push(bands[1]); + features.high_weight.push(bands[2]); + features.spectral_flux.push(flux); + features.normalized_loudness.push(normalized); + features.harmonic_change.push(harmony); + let mut vector = [0.; 19]; + vector[..7].copy_from_slice(&[ + profile.curve[i], + activity, + bands[0], + bands[1], + bands[2], + bright, + flux, + ]); + let chroma_total = chroma.iter().sum::(); + if chroma_total > 1e-15 { + for (value, pc) in vector[7..].iter_mut().zip(chroma) { + *value = pc / chroma_total; + } + } + vectors.push(vector); + } + let bins = profile.curve.len(); + features.novelty = vec![0.; bins]; + let window = (8. / profile.step).ceil().max(2.) as usize; + let mut boundaries = vec![0.]; + for i in window..bins.saturating_sub(window) { + let novelty = 0.9 * checkerboard(&vectors, i, window) + 0.10 * features.harmonic_change[i]; + features.novelty[i] = novelty.clamp(0., 1.); + } + for i in window..bins.saturating_sub(window) { + let novelty = features.novelty[i]; + let at = i as f64 * profile.step; + if novelty >= 0.10 + && novelty >= features.novelty[i - 1] + && novelty > features.novelty[i + 1] + && at - boundaries.last().copied().unwrap_or(0.) >= 8. + && duration - at >= 8. + { + let at = refine_boundary([envelope, bass, high], spectra, hz, at, profile.step, bpm); + // A beat estimate is not a verified bar/downbeat or phrase anchor. + let at = match bpm.zip(offset) { + Some((b, a)) if b.is_finite() && b > 0. && a.is_finite() => { + a + ((at - a) * b / 60.).round() * 60. / b + } + _ => at, + }; + if at - boundaries.last().copied().unwrap_or(0.) >= 8. && duration - at >= 8. { + boundaries.push(at); + } + } + } + if boundaries.len() == 1 { + // No detected change: retain only explicitly labelled heuristic blocks. + for (i, section) in profile.sections.iter_mut().enumerate() { + section.name = format!("Estimated block {} (unverified)", i + 1); + section.energy = crate::energy_profile::mean_between( + &profile.curve, + profile.step, + section.start, + section.end, + ); + } + profile.validate().ok()?; + return Some((profile, features)); + } + features.boundary_method = "local_checkerboard_novelty"; + boundaries.push(duration); + profile.sections = boundaries + .windows(2) + .enumerate() + .map(|(i, w)| crate::energy_profile::Section { + id: format!("activity-{}", i + 1), + name: format!("Activity section {}", i + 1), + start: w[0], + end: w[1], + energy: crate::energy_profile::mean_between(&profile.curve, profile.step, w[0], w[1]), + }) + .collect(); + profile.validate().ok()?; + Some((profile, features)) +} + +#[cfg(test)] +#[allow(clippy::too_many_arguments)] +fn build( + envelope: &[f64], + bass: &[f64], + spectra: &[Spectrum], + hz: f64, + duration: f64, + lufs: f64, + bpm: Option, + offset: Option, +) -> Option<(Profile, Features)> { + build_with_high( + envelope, + bass, + &vec![0.; envelope.len()], + spectra, + hz, + duration, + lufs, + bpm, + offset, + ) +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn high_band_percussion_adds_activity_without_a_mastering_gain_bias() { + let full = vec![0.10; 2400]; + let low = pulse(24, 50); + let high = pulse(24, 25); + let score = |gain: f64, hats: bool| { + let high = if hats { + high.iter().map(|v| v * gain).collect::>() + } else { + vec![0.; high.len()] + }; + build_with_high( + &full.iter().map(|v| v * gain).collect::>(), + &low.iter().map(|v| v * gain).collect::>(), + &high, + &[], + 100., + 24., + -14. + 20. * gain.log10(), + None, + None, + ) + .unwrap() + }; + let (plain, _) = score(1., false); + let (percussive, features) = score(1., true); + let (louder, _) = score(2., true); + assert!(percussive.mean_energy().unwrap() > plain.mean_energy().unwrap()); + assert!(features.high_onset_activity.iter().all(|v| *v > 0.)); + assert!((percussive.mean_energy().unwrap() - louder.mean_energy().unwrap()).abs() < 1e-10); + } + #[test] + fn checkerboard_detects_a_sustained_change_without_inventing_one_on_flat_audio() { + let mut a = [0.; 19]; + a[..7].fill(0.1); + a[7] = 1.; + let mut b = [0.; 19]; + b[..7].fill(0.8); + b[8] = 1.; + let vectors = [vec![a; 16], vec![b; 16]].concat(); + assert!(checkerboard(&vectors, 16, 4) > 0.65); + assert!(checkerboard(&vectors, 8, 4) < 1e-12); + assert!(checkerboard(&vectors, 16, 4) > checkerboard(&vectors, 14, 4)); + b[..7].copy_from_slice(&a[..7]); + let harmonic_only = [vec![a; 16], vec![b; 16]].concat(); + assert!(checkerboard(&harmonic_only, 16, 4) > 0.09); + } + #[test] + fn fine_boundary_uses_harmonic_evidence_and_does_not_invent_changes() { + let constant = vec![0.1; 400]; + assert_eq!( + refine_boundary([&constant; 3], &[], 100., 1.37, 0.5, None), + 1.37 + ); + let spectra = (0..80) + .map(|i| { + let mut chroma = [0.; 12]; + chroma[if i < 29 { 0 } else { 7 }] = 1.; + Spectrum { + seconds: i as f64 * 0.05, + brightness: 0.2, + low_weight: 0.3, + mid_weight: 0.5, + high_weight: 0.2, + flux: 0., + chroma, + } + }) + .collect::>(); + let boundary = refine_boundary([&constant; 3], &spectra, 100., 2., 1., None); + assert!((boundary - 1.45).abs() <= 0.1, "{boundary}"); + } + #[test] + fn section_changes_at_non_round_tempos_stay_within_one_beat() { + for bpm in [128., 130., 137.] { + let beat: f64 = 60. / bpm; + let first = 128. * beat; + let second = 256. * beat; + let duration = 320. * beat; + let start = (first * 100.).round() as usize; + let end = (second * 100.).round() as usize; + let period = (beat * 50.).round() as usize; + let envelope = (0..(duration * 100.).round() as usize) + .map(|i| { + if (start..end).contains(&i) { + if (i - start) % period < 3 { 1. } else { 0.03 } + } else { + 0.10 + } + }) + .collect::>(); + for offset in [0., beat] { + let (profile, _) = build( + &envelope, + &envelope, + &[], + 100., + duration, + -14., + Some(bpm), + Some(offset), + ) + .unwrap(); + for boundary in [first, second] { + assert!( + profile + .sections + .iter() + .any(|s| (s.start - boundary).abs() <= beat), + "{bpm} BPM change {boundary}: {:?}", + profile.sections + ); + } + } + } + } + #[test] + fn known_32_bar_sections_survive_a_one_beat_grid_offset() { + // 120 BPM, 4/4: 32 quiet bars, 32 rhythmic bars, 16 quiet bars. + let envelope = [vec![0.10; 6400], pulse(64, 25), vec![0.10; 3200]].concat(); + for offset in [0., 0.5] { + let (profile, features) = build( + &envelope, + &envelope, + &[], + 100., + 160., + -14., + Some(120.), + Some(offset), + ) + .unwrap(); + assert_eq!(features.boundary_method, "local_checkerboard_novelty"); + for boundary in [64., 128.] { + assert!( + profile + .sections + .iter() + .any(|s| (s.start - boundary).abs() <= 0.5), + "missing {boundary}: {:?}", + profile.sections + ); + } + } + } + #[test] + fn kick_drive_raises_activity_and_breakdown_removes_it() { + let pad = vec![0.10; 2400]; + let kicks = pulse(24, 50); + let make = |envelope: &[f64], bass: &[f64]| { + build(envelope, bass, &[], 100., 24., -14., None, None) + .unwrap() + .0 + .mean_energy() + .unwrap() + }; + let pad_energy = make(&pad, &vec![0.03; 2400]); + let kick_energy = make(&pad, &kicks); + assert!(kick_energy > pad_energy + 0.05); + let envelope = [pad.clone(), pulse(24, 25), pad.clone()].concat(); + let bass = [vec![0.03; 2400], kicks, vec![0.03; 2400]].concat(); + let (profile, _) = build(&envelope, &bass, &[], 100., 72., -14., None, None).unwrap(); + assert!(profile.curve[18] > profile.curve[6] + 0.10); + assert!(profile.curve[18] > profile.curve[30] + 0.10); + assert!((ENERGY_WEIGHTS.iter().sum::() - 1.).abs() < 1e-12); + } + #[test] + fn a_partial_tail_and_flat_harmony_remain_finite() { + let envelope = vec![0.1; 10001]; + let spectral = (0..50) + .map(|i| Spectrum { + seconds: i as f64 * 2., + brightness: 0.2, + low_weight: 0.3, + mid_weight: 0.4, + high_weight: 0.3, + flux: 0., + chroma: [1.; 12], + }) + .collect::>(); + let (profile, features) = build( + &envelope, &envelope, &spectral, 100., 100.01, -14., None, None, + ) + .unwrap(); + profile.validate().unwrap(); + assert!(features.harmonic_change.iter().all(|v| v.abs() < 1e-12)); + assert!(features.novelty.iter().all(|v| v.is_finite())); + } + fn pulse(seconds: usize, period: usize) -> Vec { + (0..seconds * 100) + .map(|i| if i % period < 4 { 0.4 } else { 0.005 }) + .collect() + } + #[test] + fn rhythm_changes_at_similar_level_are_visible_and_gain_invariant() { + let envelope = [vec![0.10; 2000], pulse(32, 25), vec![0.10; 2000]].concat(); + let make = |gain: f64| { + build( + &envelope.iter().map(|v| v * gain).collect::>(), + &envelope.iter().map(|v| v * 0.7 * gain).collect::>(), + &[], + 100., + 72., + -14. + 20. * gain.log10(), + None, + None, + ) + .unwrap() + }; + let (p, f) = make(1.); + let (louder, _) = make(2.); + assert!(p.curve[15] > p.curve[3] + 0.15); + assert!(f.novelty.iter().any(|v| *v >= 0.10)); + assert!(p.sections.len() >= 3); + for (a, b) in p.curve.iter().zip(louder.curve) { + assert!((a - b).abs() < 1e-10); + } + } + #[test] + fn sustained_tone_single_transient_and_silence_are_not_high_activity() { + for mut envelope in [vec![0.8; 4000], vec![0.; 4000]] { + envelope[2000] = 1.; + let (profile, _) = + build(&envelope, &envelope, &[], 100., 40., -14., None, None).unwrap(); + assert!(profile.curve.iter().all(|v| *v < 0.3)); + } + assert!(build(&[f64::NAN; 4], &[0.; 4], &[], 100., 1., -14., None, None).is_none()); + } +} diff --git a/crates/amp-core/src/show.rs b/crates/amp-core/src/show.rs index 418ab465..a175463e 100644 --- a/crates/amp-core/src/show.rs +++ b/crates/amp-core/src/show.rs @@ -17,6 +17,15 @@ pub enum Style { Steady, Chill, } +/// Public UI energy units (1–10); shared policy stores normalized values. +pub fn style_target(style: Style, progress: f64) -> Option { + let style = match style { + Style::Hype => amp_dj_policy::EnergyStyle::Hype, + Style::Steady => amp_dj_policy::EnergyStyle::Steady, + Style::Chill => amp_dj_policy::EnergyStyle::Chill, + }; + amp_dj_policy::style_energy_target(style, progress).map(|energy| 1. + 9. * energy) +} #[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Default)] #[serde(rename_all = "snake_case")] pub enum Fallback { @@ -469,6 +478,11 @@ pub fn choose_with_snapshot( .get(alternate.min(ranked.len().saturating_sub(1))) .copied() } +#[derive(Clone, Copy, Default)] +pub struct RankingContext<'a> { + pub preparation: Option<&'a Preparation>, + pub outgoing_energy: Option, +} pub fn ranked_with_snapshot( p: &SmartPlaylist, tracks: &[Track], @@ -477,7 +491,32 @@ pub fn ranked_with_snapshot( target: Option, snapshot: Option<&Preparation>, ) -> Vec { - let playing = snapshot.or_else(|| current.and_then(|i| tracks.get(i)).map(|t| &t.preparation)); + ranked_candidates( + p, + tracks, + current, + recent, + target, + RankingContext { + preparation: snapshot, + outgoing_energy: None, + }, + ) + .into_iter() + .map(|(_, index)| index) + .collect() +} +pub(crate) fn ranked_candidates( + p: &SmartPlaylist, + tracks: &[Track], + current: Option, + recent: &[String], + target: Option, + context: RankingContext<'_>, +) -> Vec<(f64, usize)> { + let playing = context + .preparation + .or_else(|| current.and_then(|i| tracks.get(i)).map(|t| &t.preparation)); let mut candidates: Vec<_> = tracks .iter() .enumerate() @@ -499,40 +538,53 @@ pub fn ranked_with_snapshot( } else if p.fallback == Fallback::Stop { return Vec::new(); } - let wanted = target.or(p.target_energy).or(playing.and_then(energy)); + let wanted = target + .or(p.target_energy) + .or(context + .outgoing_energy + .filter(|e| e.is_finite() && (0. ..=1.).contains(e)) + .map(|e| 1. + 9. * e)) + .or(playing.and_then(energy)); let score = |t: &Track| { - let mut prepared = t.preparation.clone(); + let prepared = &t.preparation; let entry = if p.style == Style::Hype { let at = if p.use_manual_cues { - crate::hype_sections::marked_entry(&prepared) + crate::hype_sections::marked_entry(prepared) } else { None } - .or_else(|| crate::hype_sections::entry(&prepared)) + .or_else(|| crate::hype_sections::entry(prepared)) .unwrap_or(prepared.cue_in); - crate::energy_profile::read(&prepared).and_then(|profile| profile.at(at)) + crate::energy_profile::mixing_profile(prepared).and_then(|profile| profile.at(at)) } else { crate::energy_profile::automatic_entry( - &prepared, + prepared, wanted.map_or(0.5, |e| (e - 1.) / 9.), 8., ) .map(|entry| entry.energy) } .or_else(|| { - crate::energy_profile::read(&prepared).and_then(|profile| profile.at(prepared.cue_in)) + crate::energy_profile::mixing_profile(prepared) + .and_then(|profile| profile.at(prepared.cue_in)) }); - if let Some(e) = entry { - prepared - .extensions - .insert("energy".into(), serde_json::json!(e)); - } playing.map_or_else( - || match (wanted, energy(&prepared)) { + || match ( + wanted, + entry.map(|e| 1. + 9. * e).or_else(|| energy(prepared)), + ) { (Some(a), Some(b)) => (a - b).abs(), _ => 3., }, - |p| crate::smart::cost(p, &prepared, wanted.map(|e| (e - 1.) / 9.)), + |p| { + crate::smart::cost_with_sections( + p, + prepared, + wanted.map(|e| (e - 1.) / 9.), + context.outgoing_energy, + entry, + ) + }, ) - if p.preferred.contains(&song_id(t)) { 0.25 } else { @@ -541,7 +593,7 @@ pub fn ranked_with_snapshot( }; let mut scored: Vec<_> = candidates.iter().map(|(i, t)| (score(t), *i)).collect(); scored.sort_by(|a, b| a.0.total_cmp(&b.0).then(a.1.cmp(&b.1))); - scored.into_iter().map(|(_, i)| i).collect() + scored } #[derive(Debug, Clone, Serialize)] pub struct Progression { @@ -638,7 +690,7 @@ mod tests { let make = |name: &str, opening: f64, peak: f64| { let mut preparation = Preparation::default(); preparation.extensions.insert("energy_profile".into(), serde_json::json!({ - "version":1,"duration":160.,"step":2., + "version":2,"duration":160.,"step":2., "curve":([vec![opening;40],vec![peak;30],vec![0.2;10]].concat()), "sections":[{"id":"intro","name":"Intro","start":0.,"end":80.,"energy":opening},{"id":"drop","name":"Strong","start":80.,"end":140.,"energy":peak},{"id":"tail","name":"Tail","start":140.,"end":160.,"energy":0.2}] })); @@ -664,6 +716,77 @@ mod tests { saved ); } + #[test] + fn legacy_raw_sections_cannot_win_a_normalized_entry_comparison() { + let make = |name: &str, version: u32, section: f64, average: f64| { + let mut preparation = Preparation { + bpm: Some(120.), + harmonic_key: Some("8A".into()), + cue_out: Some(60.), + analysis: Some(crate::preparation::AnalysisInfo { + engine: if version == 1 { + "amp-prep-heuristic-5" + } else { + "amp-prep-heuristic-6" + } + .into(), + duration: 60., + tempo_confidence: 1., + key_confidence: 1., + reviewed: false, + }), + ..Default::default() + }; + preparation + .extensions + .insert("energy".into(), serde_json::json!(average)); + if version == 2 { + preparation + .extensions + .insert("perceptual_energy".into(), serde_json::json!(average)); + } + preparation.extensions.insert("energy_profile".into(),serde_json::json!({"version":version,"duration":60.,"step":2.,"curve":[],"sections":[{"id":"main","name":"Main","start":0.,"end":60.,"energy":section}]})); + Track { + path: name.into(), + title: name.into(), + preparation, + } + }; + let tracks = vec![ + make("playing.wav", 2, 0.8, 0.8), + make("raw.wav", 1, 0.8, 0.1), + make("normalized.wav", 2, 0.7, 0.1), + ]; + let saved = tracks + .iter() + .map(|track| track.preparation.clone()) + .collect::>(); + let playlist = Settings::default().playlists.remove(0); + let ranked = ranked_candidates( + &playlist, + &tracks, + Some(0), + &[], + None, + RankingContext { + preparation: Some(&tracks[0].preparation), + outgoing_energy: Some(0.8), + }, + ); + assert_eq!( + ranked[0].1, 2, + "A raw legacy number must not look like a normalized exact match" + ); + assert!(crate::energy_profile::read(&tracks[1].preparation).is_some()); + assert_eq!( + tracks + .iter() + .map(|track| track.preparation.clone()) + .collect::>(), + saved + ); + } + #[test] fn selection_uses_entry_section_energy_instead_of_only_song_average() { let make = |name: &str, average: f64, local: f64| { @@ -674,7 +797,7 @@ mod tests { }; p.extensions .insert("energy".into(), serde_json::json!(average)); - p.extensions.insert("energy_profile".into(),serde_json::json!({"version":1,"duration":60.,"step":2.,"curve":[local],"sections":[{"id":"one","name":"Main","start":0.,"end":60.,"energy":local}]})); + p.extensions.insert("energy_profile".into(),serde_json::json!({"version":2,"duration":60.,"step":2.,"curve":[local],"sections":[{"id":"one","name":"Main","start":0.,"end":60.,"energy":local}]})); Track { path: name.into(), title: name.into(), @@ -686,11 +809,31 @@ mod tests { make("matched-section.wav", 0.1, 0.8), make("wrong-section.wav", 0.8, 0.1), ]; + // Real analyzed tracks have this field; it must not shadow the selected + // entry section as it did when ranking rewrote only legacy `energy`. + let mut tracks = tracks; + for track in &mut tracks { + track + .preparation + .extensions + .insert("perceptual_energy".into(), serde_json::json!(0.5)); + } + let saved = tracks + .iter() + .map(|t| t.preparation.clone()) + .collect::>(); let profile = Settings::default().playlists.remove(0); assert_eq!( choose(&profile, &tracks, Some(0), &[], Some(8.2), 0), Some(1) ); + assert_eq!( + tracks + .iter() + .map(|t| t.preparation.clone()) + .collect::>(), + saved + ); } #[test] fn selection_does_not_rank_an_unreachable_late_energy_section() { @@ -702,7 +845,7 @@ mod tests { preparation.extensions.insert( "energy_profile".into(), serde_json::json!({ - "version":1,"duration":150.,"step":1.,"curve":[],"sections":[ + "version":2,"duration":150.,"step":1.,"curve":[],"sections":[ {"id":"early","name":"Early","start":0.,"end":132.,"energy":early}, {"id":"late","name":"Late","start":132.,"end":150.,"energy":late} ] @@ -735,7 +878,7 @@ mod tests { unreachable.extensions.insert( "energy_profile".into(), serde_json::json!({ - "version":1,"duration":150.,"step":1.,"curve":[0.2],"sections":[ + "version":2,"duration":150.,"step":1.,"curve":[0.2],"sections":[ {"id":"late","name":"Late","start":80.,"end":150.,"energy":0.9} ] }), @@ -744,7 +887,7 @@ mod tests { available.extensions.insert( "energy_profile".into(), serde_json::json!({ - "version":1,"duration":150.,"step":1.,"curve":[0.8],"sections":[ + "version":2,"duration":150.,"step":1.,"curve":[0.8],"sections":[ {"id":"early","name":"Early","start":0.,"end":150.,"energy":0.8} ] }), @@ -779,7 +922,7 @@ mod tests { protected.extensions.insert( "energy_profile".into(), serde_json::json!({ - "version":1,"duration":150.,"step":1.,"curve":[],"sections":[ + "version":2,"duration":150.,"step":1.,"curve":[],"sections":[ {"id":"saved","name":"Saved entry","start":0.,"end":16.,"energy":0.2}, {"id":"strong","name":"Strong","start":16.,"end":150.,"energy":0.9} ] @@ -792,7 +935,7 @@ mod tests { playable.extensions.insert( "energy_profile".into(), serde_json::json!({ - "version":1,"duration":150.,"step":1.,"curve":[],"sections":[ + "version":2,"duration":150.,"step":1.,"curve":[],"sections":[ {"id":"main","name":"Main","start":0.,"end":150.,"energy":0.8} ] }), diff --git a/crates/amp-core/src/smart.rs b/crates/amp-core/src/smart.rs index 82319c18..6e37d83e 100644 --- a/crates/amp-core/src/smart.rs +++ b/crates/amp-core/src/smart.rs @@ -1,14 +1,64 @@ //! Deterministic preparation-based ordering shared by desktop and server consumers. use crate::Preparation; pub fn energy(p: &Preparation) -> Option { - p.extensions - .get("perceptual_energy") - .or_else(|| p.extensions.get("energy")) - .and_then(|v| v.as_f64()) - .filter(|v| v.is_finite() && (0. ..=1.).contains(v)) + let value = |key: &str| { + p.extensions + .get(key) + .and_then(|v| v.as_f64()) + .filter(|v| v.is_finite() && (0. ..=1.).contains(v)) + }; + if p.extensions.get("energy_source").and_then(|v| v.as_str()) == Some("manual") { + return value("energy"); + } + if p.extensions.contains_key("perceptual_energy") { + return value("perceptual_energy"); + } + let legacy_profile = p + .extensions + .get("energy_profile") + .and_then(|profile| profile.get("version")) + .and_then(|v| v.as_u64()) + == Some(1); + let legacy_engine = p.analysis.as_ref().is_some_and(|a| { + matches!( + a.engine.as_str(), + "amp-prep-heuristic-1" + | "amp-prep-heuristic-2" + | "amp-prep-heuristic-3" + | "amp-prep-heuristic-4" + | "amp-prep-heuristic-5" + ) + }); + let protected = p.manual_override || p.analysis.as_ref().is_some_and(|a| a.reviewed); + // Older generated RMS values have no normalized interpretation. Historical + // protected records are ambiguous, so retain their approved numeric value; + // new field-specific manual provenance removes that ambiguity going forward. + if (legacy_profile || legacy_engine) && !protected { + None + } else { + value("energy") + } } use amp_dj_policy::harmonic; pub(crate) fn cost(a: &Preparation, b: &Preparation, target: Option) -> f64 { + cost_with_entry(a, b, target, None) +} +/// The audible incoming section is an explicit session input, never a metadata edit. +pub(crate) fn cost_with_entry( + a: &Preparation, + b: &Preparation, + target: Option, + entry: Option, +) -> f64 { + cost_with_sections(a, b, target, None, entry) +} +pub(crate) fn cost_with_sections( + a: &Preparation, + b: &Preparation, + target: Option, + exit: Option, + entry: Option, +) -> f64 { let confidence = |p: &Preparation| { if p.manual_override || p.analysis.as_ref().is_some_and(|a| a.reviewed) { 1. @@ -37,8 +87,13 @@ pub(crate) fn cost(a: &Preparation, b: &Preparation, target: Option) -> f64 amp_dj_policy::pair_cost_with_context( a.bpm.unwrap_or(f64::NAN), b.bpm.unwrap_or(f64::NAN), - energy(a).unwrap_or(f64::NAN), - energy(b).unwrap_or(f64::NAN), + exit.filter(|e| e.is_finite() && (0. ..=1.).contains(e)) + .or_else(|| energy(a)) + .unwrap_or(f64::NAN), + entry + .filter(|e| e.is_finite() && (0. ..=1.).contains(e)) + .or_else(|| energy(b)) + .unwrap_or(f64::NAN), target.unwrap_or(f64::NAN), amp_dj_policy::key_code(a.harmonic_key.as_deref().unwrap_or("")), amp_dj_policy::key_code(b.harmonic_key.as_deref().unwrap_or("")), @@ -51,16 +106,25 @@ pub(crate) fn cost(a: &Preparation, b: &Preparation, target: Option) -> f64 ) } /// Keeps the first song as the anchor. Returns an exact permutation, including repeats. -/// Greedy ordering is a recommendation; it is not beat synchronization or a guarantee of a mix. +/// Ordering is a recommendation; it is not beat synchronization or a guarantee of a mix. pub fn order(songs: &[&Preparation]) -> Vec { + order_with_style(songs, amp_dj_policy::EnergyStyle::Steady, None) +} +/// Default style arc, unless the caller supplies an explicit normalized target. +pub fn order_with_style( + songs: &[&Preparation], + style: amp_dj_policy::EnergyStyle, + target: Option, +) -> Vec { if songs.is_empty() { return vec![]; } - let target = energy(songs[0]); let mut remaining: Vec<_> = (1..songs.len()).collect(); let mut result = vec![0]; while !remaining.is_empty() { let previous = songs[*result.last().unwrap()]; + let progress = result.len() as f64 / songs.len().saturating_sub(1).max(1) as f64; + let target = target.or_else(|| amp_dj_policy::style_energy_target(style, progress)); let best = (0..remaining.len()) .min_by(|&a, &b| { cost(previous, songs[remaining[a]], target).total_cmp(&cost( @@ -72,8 +136,106 @@ pub fn order(songs: &[&Preparation]) -> Vec { .unwrap(); result.push(remaining.remove(best)); } + if target.is_none() { + refine_style_order(songs, &mut result, style); + } result } + +/// 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. +fn refine_style_order( + songs: &[&Preparation], + route: &mut Vec, + style: amp_dj_policy::EnergyStyle, +) { + const PASSES: usize = 4; + const RADIUS: usize = 8; + if route.len() < 3 { + return; + } + // Capture length separately so the scoring closure never borrows the route + // while an accepted move changes its ordering. + let length = route.len(); + let edge = |position: usize, a: usize, b: usize| { + let progress = position as f64 / (length - 1) as f64; + style_order_cost(songs[a], songs[b], style, progress) + }; + for _ in 0..PASSES { + let mut changed = false; + for from in 1..length { + let mut best = None; + let mut best_delta = -1e-9; + for to in from.saturating_sub(RADIUS).max(1)..=(from + RADIUS).min(length - 1) { + if from == to { + continue; + } + let mut delta = 0.; + // Only these incoming edges change. Scoring the entire route + // for every candidate would add an unnecessary length factor. + for position in from.min(to)..=(from.max(to) + 1).min(length - 1) { + delta -= edge(position, route[position - 1], route[position]); + delta += edge( + position, + relocated_index(route, from, to, position - 1), + relocated_index(route, from, to, position), + ); + } + if delta < best_delta { + best_delta = delta; + best = Some(to); + } + } + if let Some(to) = best { + let song = route.remove(from); + route.insert(to, song); + changed = true; + } + } + if !changed { + break; + } + } +} + +fn relocated_index(route: &[usize], from: usize, to: usize, position: usize) -> usize { + if position == to { + route[from] + } else if from < to && (from..to).contains(&position) { + route[position + 1] + } else if from > to && (to + 1..=from).contains(&position) { + route[position - 1] + } else { + route[position] + } +} + +/// Retain all tempo, harmonic-confidence and runtime-rate terms from pair cost. +/// For a default set arc, target fit has weight 8 instead of 6. Add a soft +/// one-point squared penalty per excess level beyond two (Hype) or one (other +/// styles). These original, provisional weights are not musical calibration. +fn style_order_cost( + a: &Preparation, + b: &Preparation, + style: amp_dj_policy::EnergyStyle, + progress: f64, +) -> f64 { + let target = amp_dj_policy::style_energy_target(style, progress); + let fit = target + .zip(energy(b)) + .map_or(0., |(target, incoming)| 2. * (target - incoming).abs()); + let jump = energy(a).zip(energy(b)).map_or(0., |(outgoing, incoming)| { + let levels = if style == amp_dj_policy::EnergyStyle::Hype { + 2. + } else { + 1. + }; + let excess = ((outgoing - incoming).abs() * 9. - levels).max(0.); + excess * excess + }); + cost(a, b, target) + fit + jump +} /// Expands seed songs with prepared neighbors, preserving the first seed as anchor. /// Unknown candidates are excluded rather than assigned fictional measurements. pub fn curate(songs: &[&Preparation], seeds: &[usize], limit: usize) -> Result, String> { @@ -144,11 +306,163 @@ pub fn curate_with_soft_keys( chosen.push(i); } let refs: Vec<_> = chosen.iter().map(|&i| songs[i]).collect(); - Ok(order(&refs).iter().map(|&i| chosen[i]).collect()) + Ok( + order_with_style(&refs, amp_dj_policy::EnergyStyle::Steady, Some(target)) + .iter() + .map(|&i| chosen[i]) + .collect(), + ) } #[cfg(test)] mod tests { use super::*; + #[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)); + p.extensions + .insert("energy_profile".into(), serde_json::json!({"version":1})); + assert_eq!(energy(&p), None); + p.manual_override = true; + assert_eq!(energy(&p), Some(0.8)); + p.manual_override = false; + p.extensions.remove("energy_profile"); + assert_eq!(energy(&p), Some(0.8)); + p.analysis = Some(crate::preparation::AnalysisInfo { + engine: "amp-prep-heuristic-5".into(), + duration: 60., + tempo_confidence: 1., + key_confidence: 1., + reviewed: false, + }); + assert_eq!(energy(&p), None); + p.analysis.as_mut().unwrap().reviewed = true; + assert_eq!(energy(&p), Some(0.8)); + p.analysis.as_mut().unwrap().reviewed = false; + p.extensions + .insert("perceptual_energy".into(), serde_json::json!(0.2)); + assert_eq!(energy(&p), Some(0.2)); + p.extensions + .insert("energy_source".into(), serde_json::json!("manual")); + assert_eq!(energy(&p), Some(0.8)); + p.extensions.remove("energy"); + assert_eq!( + energy(&p), + None, + "Explicit unknown energy must not expose a generated value" + ); + } + #[test] + fn hype_order_reserves_a_release_after_its_peak_when_the_pool_allows_it() { + let pool = (3..=9) + .map(|level| song(128., "8A", (level as f64 - 1.) / 9.)) + .collect::>(); + let refs = pool.iter().collect::>(); + let route = order_with_style(&refs, amp_dj_policy::EnergyStyle::Hype, None); + let levels = route.iter().map(|&i| i + 3).collect::>(); + assert_eq!(levels[0], 3); + let peak = levels.iter().position(|&level| level == 9).unwrap(); + assert!( + peak >= 3 && peak < levels.len() - 1, + "No rise and release: {levels:?}" + ); + assert!( + levels.windows(2).all(|pair| pair[0].abs_diff(pair[1]) <= 2), + "Avoidable large jump: {levels:?}" + ); + } + + #[test] + fn steady_order_keeps_available_one_level_steps_and_all_repeated_entries() { + let pool = [5, 7, 3, 4, 6, 5, 4, 6].map(|level| song(128., "8A", (level as f64 - 1.) / 9.)); + let refs = pool.iter().collect::>(); + let route = order_with_style(&refs, amp_dj_policy::EnergyStyle::Steady, None); + assert_eq!(route[0], 0); + assert!(route.windows(2).all(|pair| { + (energy(&pool[pair[0]]).unwrap() - energy(&pool[pair[1]]).unwrap()).abs() + <= 1. / 9. + 1e-12 + })); + let mut sorted = route; + sorted.sort_unstable(); + assert_eq!(sorted, (0..pool.len()).collect::>()); + } + + #[test] + fn local_moves_never_raise_full_native_route_cost_or_lose_entries() { + // Varied tempos, keys, confidences and missing measurements exercise the + // real ranking function. The whole-route oracle is deliberately distinct + // from the production local-delta computation. + for seed in 0..48 { + let pool = (0..7 + seed % 14) + .map(|index| { + if (index + seed) % 11 == 0 { + return Preparation::default(); + } + let mut p = song( + 100. + ((index * 17 + seed * 7) % 55) as f64, + ["1A", "8A", "9A", "3B", "12B"][(index + seed) % 5], + ((index * 13 + seed * 11) % 10) as f64 / 9., + ); + p.manual_override = index % 3 != 0; + p + }) + .collect::>(); + let refs = pool.iter().collect::>(); + for style in [ + amp_dj_policy::EnergyStyle::Hype, + amp_dj_policy::EnergyStyle::Steady, + amp_dj_policy::EnergyStyle::Chill, + ] { + let mut route = (0..pool.len()).collect::>(); + let score = |route: &[usize]| { + route + .windows(2) + .enumerate() + .map(|(index, pair)| { + style_order_cost( + &pool[pair[0]], + &pool[pair[1]], + style, + (index + 1) as f64 / (pool.len() - 1) as f64, + ) + }) + .sum::() + }; + let before = score(&route); + refine_style_order(&refs, &mut route, style); + assert!( + score(&route) <= before + 1e-9, + "Route cost increased for seed {seed}, style {style:?}" + ); + assert_eq!(route[0], 0); + route.sort_unstable(); + assert_eq!(route, (0..pool.len()).collect::>()); + } + } + } + + #[test] + fn style_order_preserves_repeats_and_explicit_targets() { + let pool = (3..=9) + .map(|level| song(128., "8A", (level as f64 - 1.) / 9.)) + .collect::>(); + let refs = pool.iter().collect::>(); + for style in [ + amp_dj_policy::EnergyStyle::Hype, + amp_dj_policy::EnergyStyle::Chill, + amp_dj_policy::EnergyStyle::Steady, + ] { + let order = order_with_style(&refs, style, None); + assert_eq!(order[0], 0); + let mut sorted = order; + sorted.sort_unstable(); + assert_eq!(sorted, (0..pool.len()).collect::>()); + } + assert_eq!( + order_with_style(&refs, amp_dj_policy::EnergyStyle::Hype, Some(0.5)), + order_with_style(&refs, amp_dj_policy::EnergyStyle::Chill, Some(0.5)) + ); + } fn song(bpm: f64, key: &str, e: f64) -> Preparation { let mut p = Preparation { bpm: Some(bpm), diff --git a/crates/amp-core/src/smart_cycle.rs b/crates/amp-core/src/smart_cycle.rs index d2094230..5d50f1ab 100644 --- a/crates/amp-core/src/smart_cycle.rs +++ b/crates/amp-core/src/smart_cycle.rs @@ -39,6 +39,28 @@ impl SmartCycle { current: Option, target: Option, snapshot: Option<&Preparation>, + ) -> Vec { + self.ranked_with_context( + library, + p, + tracks, + current, + target, + show::RankingContext { + preparation: snapshot, + outgoing_energy: None, + }, + ) + } + #[allow(clippy::too_many_arguments)] + pub fn ranked_with_context( + &mut self, + library: &str, + p: &SmartPlaylist, + tracks: &[Track], + current: Option, + target: Option, + context: show::RankingContext<'_>, ) -> Vec { self.bind(library, &p.id); let known: HashSet<_> = tracks.iter().map(show::song_id).collect(); @@ -63,27 +85,33 @@ impl SmartCycle { let mut rules = p.clone(); rules.recent_repeat = 0; rules.excluded.extend(self.failed.iter().cloned()); - let mut ranked = show::ranked_with_snapshot(&rules, tracks, current, &[], target, snapshot); - ranked.retain(|i| !self.played.contains(&show::song_id(&tracks[*i]))); + 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(index); + ranked.push((0., index)); } - // Vary the best mix-compatible unplayed window, rather than always - // choosing the same deterministic catalog-index tie winner. - let window = ranked.len().min(8); - ranked[..window].sort_by_cached_key(|i| { + // 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, _)| { + ranked + .iter() + .take(8) + .take_while(|(cost, _)| cost.total_cmp(best).is_eq()) + .count() + }); + ranked[..window].sort_by_cached_key(|(_, i)| { let mut hash = Sha256::new(); hash.update(self.seed.to_le_bytes()); hash.update(show::song_id(&tracks[*i])); let bytes = hash.finalize(); u64::from_le_bytes(bytes[..8].try_into().unwrap()) }); - ranked + ranked.into_iter().map(|(_, index)| index).collect() } } fn entropy() -> u64 { @@ -93,6 +121,49 @@ fn entropy() -> u64 { #[cfg(test)] mod tests { use super::*; + #[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]) { + song.preparation + .extensions + .insert("perceptual_energy".into(), serde_json::json!(energy)); + } + let before = songs + .iter() + .map(|t| t.preparation.clone()) + .collect::>(); + let mut p = show::Settings::default().playlists.remove(0); + p.target_energy = None; + for seed in 0..64 { + let mut cycle = SmartCycle::default(); + cycle.bind("library", &p.id); + cycle.seed = seed; + assert_eq!( + cycle.ranked("library", &p, &songs, Some(0), None, None)[0], + 2 + ); + let ranked = cycle.ranked_with_context( + "library", + &p, + &songs, + Some(0), + None, + show::RankingContext { + preparation: Some(&songs[0].preparation), + outgoing_energy: Some(0.2), + }, + ); + assert_eq!(ranked[0], 1); + } + assert_eq!( + songs + .iter() + .map(|t| t.preparation.clone()) + .collect::>(), + before + ); + } fn tracks(n: usize) -> Vec { (0..n) .map(|i| Track { diff --git a/crates/amp-core/src/smart_filters.rs b/crates/amp-core/src/smart_filters.rs index 24a627ad..39c54a23 100644 --- a/crates/amp-core/src/smart_filters.rs +++ b/crates/amp-core/src/smart_filters.rs @@ -282,6 +282,9 @@ fn numbers(field: Field, p: &Preparation) -> Vec { .unwrap_or_default(); } if field == Field::SectionEnergy { + if crate::energy_profile::mixing_profile(p).is_none() { + return vec![]; + } return sections(p) .map(|a| { a.iter() diff --git a/crates/amp-core/tests/fixtures/mix-sections-v1.json b/crates/amp-core/tests/fixtures/mix-sections-v1.json new file mode 100644 index 00000000..ec4131d4 --- /dev/null +++ b/crates/amp-core/tests/fixtures/mix-sections-v1.json @@ -0,0 +1,12 @@ +{ + "cue_in": 0, + "cue_out": 120, + "bpm": 120, + "beat_offset": 0, + "manual_override": false, + "manual_cues": [], + "analysis": {"engine":"amp-prep-heuristic-6","duration":120,"tempo_confidence":0.9,"key_confidence":0.8,"reviewed":false}, + "energy_profile_method":"amp-section-activity-1", + "auto_mix_sections": {"version":1,"engine":"amp-prep-heuristic-6","method":"amp-section-activity-1","duration":120,"entry":24,"exit":72,"minimum_passage":16}, + "energy_profile": {"version":2,"duration":120,"step":2,"sections":[],"curve":[0.15,0.15,0.15,0.15,0.15,0.15,0.15,0.15,0.15,0.15,0.15,0.15,0.85,0.85,0.85,0.85,0.85,0.85,0.85,0.85,0.85,0.85,0.85,0.85,0.85,0.85,0.85,0.85,0.85,0.85,0.85,0.85,0.85,0.85,0.85,0.85,0.2,0.2,0.2,0.2,0.2,0.2,0.2,0.2,0.2,0.2,0.2,0.2,0.2,0.2,0.2,0.2,0.2,0.2,0.2,0.2,0.2,0.2,0.2,0.2]} +} diff --git a/crates/amp-dj-policy/src/energy.rs b/crates/amp-dj-policy/src/energy.rs new file mode 100644 index 00000000..d5a6adde --- /dev/null +++ b/crates/amp-dj-policy/src/energy.rs @@ -0,0 +1,64 @@ +//! Original set-shaping policy shared across playback platforms. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum EnergyStyle { + Chill, + Steady, + Hype, +} + +/// Normalized 0..1 target; progress is a finite fraction of the planned set. +/// Callers choose the duration/cycle explicitly and preserve user target curves. +pub fn style_energy_target(style: EnergyStyle, progress: f64) -> Option { + if !progress.is_finite() { + return None; + } + let knots: &[(f64, f64)] = match style { + EnergyStyle::Chill => &[(0., 3.), (0.5, 5.), (1., 4.)], + EnergyStyle::Steady => &[(0., 5.), (0.33, 6.), (0.67, 6.), (1., 5.)], + EnergyStyle::Hype => &[(0., 5.), (0.35, 7.), (0.7, 8.5), (1., 7.)], + }; + let progress = progress.clamp(0., 1.); + let pair = knots.windows(2).find(|p| progress <= p[1].0)?; + let fraction = (progress - pair[0].0) / (pair[1].0 - pair[0].0); + let level = pair[0].1 + (pair[1].1 - pair[0].1) * fraction; + Some((level - 1.) / 9.) +} + +/// Adjacent energy levels remain inexpensive; larger leaps grow quadratically. +pub fn energy_jump_cost(a: f64, b: f64) -> f64 { + if ![a, b] + .iter() + .all(|v| v.is_finite() && (0. ..=1.).contains(v)) + { + return 1.; + } + let delta = (a - b).abs(); + let excess = (delta - 1. / 9.).max(0.); + 4. * delta + 24. * excess * excess +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn style_curves_peak_and_relax_without_invalid_targets() { + for style in [EnergyStyle::Chill, EnergyStyle::Steady, EnergyStyle::Hype] { + for n in 0..=100 { + assert!((0. ..=1.).contains(&style_energy_target(style, n as f64 / 100.).unwrap())); + } + assert!(style_energy_target(style, f64::NAN).is_none()); + } + let hype = |t| style_energy_target(EnergyStyle::Hype, t).unwrap(); + assert!(hype(0.) < hype(0.35)); + assert!(hype(0.35) < hype(0.7)); + assert!(hype(1.) < hype(0.7)); + } + #[test] + fn one_level_is_gentle_but_three_levels_are_more_than_triple() { + let one = energy_jump_cost(0., 1. / 9.); + assert!((one - 4. / 9.).abs() < 1e-12); + assert!(energy_jump_cost(0., 3. / 9.) > 3. * one); + assert_eq!(energy_jump_cost(0.2, 0.7), energy_jump_cost(0.7, 0.2)); + assert_eq!(energy_jump_cost(f64::NAN, 0.5), 1.); + } +} diff --git a/crates/amp-dj-policy/src/lib.rs b/crates/amp-dj-policy/src/lib.rs index 5f1ef494..d8856500 100644 --- a/crates/amp-dj-policy/src/lib.rs +++ b/crates/amp-dj-policy/src/lib.rs @@ -1,5 +1,7 @@ //! Device-independent DJ decisions. No codecs, analysis, filesystem or audio devices. +mod energy; mod transition; +pub use energy::{EnergyStyle, energy_jump_cost, style_energy_target}; pub use transition::*; #[derive(Clone, Copy, Debug, PartialEq, serde::Serialize, serde::Deserialize)] pub struct TempoMatch { @@ -83,7 +85,7 @@ pub fn pair_cost(a: f64, b: f64, ae: f64, be: f64, target: f64, ak: i32, bk: i32 + groove + key + if known(ae) && known(be) { - (ae - be).abs() * 4. + energy_jump_cost(ae, be) } else { 1. } @@ -167,6 +169,21 @@ mod android { use super::*; use std::ffi::c_void; #[unsafe(no_mangle)] + pub extern "system" fn Java_cloud_gitwide_ampverse_SharedDjLogic_styleTarget( + _: *mut c_void, + _: *mut c_void, + style: i32, + progress: f64, + ) -> f64 { + let style = match style { + 0 => EnergyStyle::Steady, + 1 => EnergyStyle::Hype, + 2 => EnergyStyle::Chill, + _ => return f64::NAN, + }; + style_energy_target(style, progress).unwrap_or(f64::NAN) + } + #[unsafe(no_mangle)] pub extern "system" fn Java_cloud_gitwide_ampverse_SharedDjLogic_version( _: *mut c_void, _: *mut c_void, diff --git a/docs/AMP_VERSE_IMPROVEMENT_QUEUE.md b/docs/AMP_VERSE_IMPROVEMENT_QUEUE.md new file mode 100644 index 00000000..b346001f --- /dev/null +++ b/docs/AMP_VERSE_IMPROVEMENT_QUEUE.md @@ -0,0 +1,175 @@ +# AMP Verse — owner improvement queue + +Accepted 2026-12-03 from the owner's chat. Requirements and acceptance gates, +not completion claims. This order supersedes earlier backlog ordering. + +## Build order + +1. Engines: Tasks 1–5, then 6–10. Detailed requirements and corrections are in + [AUTO_MIX_ENERGY_TASKS.md](AUTO_MIX_ENERGY_TASKS.md). +2. LAN Library and remote playing: Tasks 17–21. +3. Reliability: Task 16, before relying on unattended runs. +4. Companion / meeting show control: Tasks 11–14, last. + +Task 15 is independent and may run at any time. Queued means authorized scope, +not evidence that work has been implemented, tested or released. + +## Tasks 1–10 — engines + +Keep the existing detailed contract: explicit incoming section-energy ranking; +normalized track/section scoring; richer rhythmic/band/flux features; supported +section boundaries/downbeat confidence; style energy arcs; optional Beat This +beat/downbeat analysis; optional All-In-One labeled sections and real bar counts; +key timeline; section-aware controls/cue rules; phrase-aware Auto Mix. + +Models remain optional, outside the base player. Preserve reviewed/manual +preparation, propose changes separately, and do not trigger unsolicited library +reanalysis. Keep the hand-annotated 10–20-song set and 20-transition listening +gate; tests and actual listening are distinct evidence. + +## Part 3 — meeting show control (build last) + +Meeting machine: amp-player desktop feeds the mixer. Control chain: +Node-RED → OnTime → Companion → AMP Verse. Library owns cues/regions; Player +handles instant intros/walk-ups; DJ handles background/recognition; Lab makes +sampler clips. Keep the existing simple optional-password trusted-LAN model. + +### Task 11 — named intro regions and instant Player playback + +Library stores non-destructive named regions: start/end, fade-in/out, gain and +after-action (stop / hand back to DJ / next region). Player obeys exact bounds. +Companion arm_intro pre-decodes; fire_intro always starts at region start. +Second-press behavior is configurable restart / ignore / fade out. Support an +ordered intro run sheet and optional next-intro auto-arm. + +Companion actions: arm_intro, fire_intro, stop_intro, intro next/previous. +Feedback: armed amber, playing green, failed red; variables: armed name and +time remaining. Armed command-accepted → first non-silent output frame target +is <100 ms, 50/50 trials. Verify sample-accurate fades/end and unchanged source +hash. Render latency does not by itself prove physical output latency. + +### Task 12 — Player and DJ sharing the room + +Allow independent output device/channel pairs for Player, DJ master and Sampler; +default remains shared output. An intro coordinates DJ duck/pause with per-intro +level/fade settings, then restores/resumes. Keep an interrupt stack so a +recognition/intro returns to the prior playlist/style/energy. Emergency mute is +global. Verify shared output never runs both at full level; separate routing +only reaches assigned channels; resume restores prior context. + +### Task 13 — recognition and pre-meeting checks + +Preload assigned recognition music; land on saved cue, otherwise a supported +chorus/drop from Task 7, play N bars, then hand back. A configured backup hype +song is explicitly authorized if assigned audio is missing/unprepared/unloadable; +show red Companion feedback. This is a visible configured backup, not a hidden +success path. Target backup within two seconds. + +One pre-meeting check validates all Companion/run-sheet/show file references, +preparation, cues/regions and output devices. Show a green/red result and problem +list. Test deleted/renamed files and invalid cues. Merge docs/COMPANION.md into +the integration module README so the current setup has one authoritative guide. + +### Task 14 — Lab clip and sampler maker + +Export Lab clips directly into the sampler library with name/color/gain/trim/ +fades. Assign banks from Library; add Companion bank selection and feedback to +existing sampler actions. Import a folder or AIMP playlist of existing clips as +a sampler bank or intro list; preserve source material and remapping identity. + +### Task 15 — remove integrated YouTube and Suno downloads (independent) + +Remove desktop lab_youtube/lab_suno and wiring in lab, lab_music_source and main; +Android SunoImport/UrlDownload and download-only YouTubeUrl/ImportUrl code/tests; +setup_lab_youtube tools/fixtures; yt-dlp/Deno paths in music-import verification, +music-import-engine/build workflows; obsolete LAB_YOUTUBE/SUNO_DOWNLOAD_RESEARCH +docs and related yt-dlp/Deno notices/assets. Inspect actual dependencies before +deleting shared utilities. Update distribution/module metadata accordingly. + +Keep local-file import, recording and every existing user clip. Workspace builds +and tests must pass; search yt-dlp/suno/youtube for remaining download code paths. +Historical documentation mentions are allowed. This supersedes earlier requests +to implement these integrated downloaders; the downloader is a separate app. + +### Task 16 — unattended reliability (after LAN, before unattended reliance) + +Audit unwrap/expect on control/file/decode/network paths and replace reachable +failures with logged, visible errors. Audio rendering must be panic-free. Bad +files, missing network storage and dropped outputs must skip/recover explicitly +rather than terminate the app. Keep minimized operation/autostart usable and +prevent modal dialogs blocking Companion. + +Separate render/control/automation modules in mixer/main/performance without +behavior change. Qualify with a real 24-hour Auto DJ soak plus periodic intro/ +recognition commands; record memory, handles, underruns and stalls. Start that +combined soak after its dependent meeting actions exist; do not claim it passed +from an engine-only run or add a perpetual polling monitor to the product. + +## Part 4 — LAN library and remote playing (after engines) + +Server serves music/playlists/preparation on demand. Clients play and mix +locally; serving a playlist does not mean the server plays it continuously. +Finish and prove [LIBRARY-LIVE-REMOTE.md](LIBRARY-LIVE-REMOTE.md), not a redesign. +Run each existing workflow on real devices and record the baseline before fixes. + +### Task 17 — acceptance of current Library/Remote behavior + +Turn every contract bullet into a script or written scenario. Run on one server +(Windows/Linux), Windows desktop and Android phone on the same LAN. Record +build-specific evidence in docs/ACCEPTANCE_LAN.md. Fix in order: discovery/pairing, +browse, play, offline download, sync. Every row needs an honest result; unavailable +equipment is blocked/not run, never pass. All discovery/browse/play rows must pass. + +### Task 18 — complete offline Auto Mix bundles + +Define one shared playlist bundle: audio; BPM/variable beat/downbeat grid; +key/timeline; energy profile/sections; cues/regions; loudness; playlist order/ +rules; hash manifest and analyzer version. Android uses the shared JNI policy and +the same preparation versions as desktop. New server analysis shows update +available; unchanged audio hashes mean analysis-only refresh transfers zero +audio bytes. Download then airplane-mode Auto Mix a complete 20-song playlist. + +### Task 19 — guest takeover of room audio + +Primary: guest desktop/Android broadcasts live Player/DJ master to server +(existing live_dj source). One Take over room button; server/Remote show Now +playing from device; owner Return to server music. Secondary: server temporarily +pulls a guest-shared playlist and mixes it; no main-library addition without +owner approval. Approve takeover per paired device once; guests get no library +editing rights. + +Fade station→guest and back without double audio; restore previous server +playlist/energy. Provide a latency/buffer setting. On source disconnect/sleep, +explicitly restore server music within five seconds. This owner-requested return +policy supersedes the earlier blanket no-fallback instruction only for this +case; show the source change, do not hide it. Use connection/stream events rather +than reintroducing server polling. Test 20 takeovers/returns with no silent gap +>1 s or overlapping audio, plus cable-pull recovery within five seconds. + +### Task 20 — USB offline path + +Use Task 18's bundle for playlist export to USB, with incremental changed-file +writes. Desktop/server open read-only without network/import. Optional import +deduplicates by audio hash and treats incoming cues as proposals where server +preparation exists. Android supports read-only USB-OTG where available. Verify +export→different computer→Auto Mix preserving cues/analysis; one-song change +rewrites only its changed files and necessary manifest/index metadata. + +### Task 21 — separate-downloader ingestion + +Watch a server Inbox using filesystem events. Hash/deduplicate incoming audio; +identify using existing MusicBrainz lookup, plus AcoustID when tags are absent; +organize verified results as Artist/Album/Artist - Title.ext and queue analysis. +Unknown identification goes to review, never a guessed destination/tag. + +Never directly overwrite/rename prepared or referenced songs. Any approved +rename goes through Library identity/reference updates for playlists/cues/ +Companion. Test duplicate drop leaves one copy and unidentified audio enters +review. Verify service availability/credentials before enabling optional lookup. + +## Shared exclusions and protections + +No Spotify-style recommendations, new stem models/effects, stronger control API +security redesign, or overwriting saved cues/manual/reviewed preparation. Keep +optional passwords. Preserve existing user audio. The explicit backup/return +behaviors above do not authorize hidden generic fallbacks or recurring polling. diff --git a/docs/ANDROID_CAST_PATHS.md b/docs/ANDROID_CAST_PATHS.md index 88cbbeb2..eec3b760 100644 --- a/docs/ANDROID_CAST_PATHS.md +++ b/docs/ANDROID_CAST_PATHS.md @@ -139,3 +139,43 @@ API gate: actual Android lint correctly identified bounded pipe-size control as GitHub native run [45324642211](https://github.com/gitwide-cloud/amp-verse/actions/runs/45324642211) passed at feature head `19fb4996`, tested PR merge `6bc3d92f61fec00f0a29cb1a00f4c0f616c52eb3`. The complete edition/module/unit/lint build and actual isolated server build passed. The native instrumentation test ran (10.691 seconds), and the host decoded 207,405 received MP3 bytes into 8.616 seconds of PCM, RMS 1406.95. Uploaded JUnit reports total 140 tests with zero failures/errors/skips. The server binary SHA256 is `f55e2841f42a99f0e36cc67aa225129ac6ba0978fab2e943d61ded91093d9232`; evidence artifact 14889367737 digest is `04b91c4316e1ec2dce88d4fd282b4834d163c5b61f6f115024f081f5f9467b02`. Beta packaging run 45324642109 also passed. This qualifies the generated-PCM Android native encoder/virtual AudioTrack/protocol path, including stale-owner rejection and cleanup. It does not qualify physical speakers, real-phone background/foreground-service continuity, sampler file decoding/UI gesture integration or LAN latency. The candidate remains off by default pending those checks. A final, tested idempotent-stop change prevents repeated Stop/close from aborting the sender's own guarded cleanup; current focused coverage is 53 tests. Final canonical-source CI is rerun before release integration. No APK has been installed or published by this work. + + +### Upload/notification correction candidate (2026-12-03) + +This is source under qualification, not a published or installed app update. +A real fixture caught a 662 ms upload acknowledgment blocking the MP3 reader and +then overflowing the quarter-second PCM export ring. `PhoneMasterUpload` now +owns ordered HTTP work on a separate worker. Encoding offers packets without +waiting for HTTP; the network worker blocks on its queue rather than polling. + +The encoded queue is capped at 32 KiB and 64 packets, plus one logical in-flight +packet of at most 8 KiB. At 192 kbps the queued payload represents about 1.37 seconds. +Session retry copies and codec/HTTP working buffers are additional; these numbers +are queue limits, not a whole-process memory or end-to-end latency guarantee. +Sustained overflow fails explicitly instead of dropping encoded bytes or growing +without a bound. The local audio render path does not wait for this worker. + +The first real Layer III proof still precedes a host claim. During initial control +I/O, PCM export is gated and resumed only after its consumer discards old ring +occupancy. Every already encoded byte is retained in order, including pipe reads +split across frame boundaries. No MP3 byte holes are introduced at startup. +Upload cleanup joins its worker; if a pending request requires cancellation, it +joins again before allowing replacement or reports a fatal cleanup failure. +Fatal sender diagnostics retain the underlying failure; ordinary UI wording +remains about playback and reconnection. + +Focused coverage now has 47 passing JVM checks, including stalled-upload/render +independence (failed before this change), full-queue capture-resume ordering, +packet copy/order/bounds, delayed-claim split MP3 frames, no-proof/no-claim, +rejected ownership and abort-then-join cleanup. Post-delivery fault fixtures +explicitly wait for the real acknowledgment before injecting their fault. +The actual Android codec/HTTP receiver and media controls must still pass on +this source. Physical speakers, real-phone background operation and LAN latency +are separate acceptance gates. + +The notification candidate uses one slot for the current room source. Private +cue players are local audition paths, not public platform sessions. Pause/resume +batches keep notification focus stable; a retired deck's Stop cannot reset the +current deck. Only the selected session's event is forwarded to Media3's own +notification controller; playback-state changes explicitly refresh that source. diff --git a/docs/AUTO_MIX_ENERGY_TASKS.md b/docs/AUTO_MIX_ENERGY_TASKS.md new file mode 100644 index 00000000..40d5f796 --- /dev/null +++ b/docs/AUTO_MIX_ENERGY_TASKS.md @@ -0,0 +1,157 @@ +# Auto Mix energy fixes — implementation contract + +Build order and additional Tasks 11–21 are tracked in the owner's +[master improvement queue](AMP_VERSE_IMPROVEMENT_QUEUE.md). + +User-supplied review of e314628 / RC33, accepted 2026-12-02. Implement in this +order. This file records requirements, not completion claims. See +[primary-source research](research/DJ_ANALYSIS_PRIMARY_SOURCES_20261202.md). + +1. **Explicit entry energy in ranking.** Add `smart::cost_with_entry`; stop + rewriting a cloned `extensions.energy`. Test equal whole-track perceptual + scores with different audible entry scores and preserve all preparation. +2. **One normalized scale.** Apply the -14 LUFS gain and common scoring to + section descriptors. Derive whole-track energy from the duration-weighted + section/curve measurements. Produce profile v2, retain readable v1 with + explicit legacy provenance, engine `amp-prep-heuristic-6`. Never compare raw + legacy RMS sections to normalized track scores. No unsolicited reanalysis. + Check desktop/server selection, review, filters, waveforms and Android readers. + Test +6 dB invariance, percussive loop versus loud sustained pad and weighted means. +3. **Richer original features.** Measure low/mid/high band drive, kick/hats/onset + activity, positive spectral flux, centroid and normalized loudness. Keep + documented tuneable weights together and export constituent descriptors. + Test kick+hats versus equal-loudness pads, adding kicks and removing kicks + for breakdowns. Audition the existing real-song fixtures before quality claims. +4. **Evidence-based boundaries.** Use chroma/timbre/energy feature novelty and + peak picking, with bounded local checkerboard computation rather than an + unbounded whole-song matrix. Estimate downbeat phase/confidence separately. + Stable tempo/beat phase alone must not authorize bar/phrase snapping. Snap + to supported 8/16/32-bar positions only with adequate downbeat evidence. + A no-clear-peak fixed-block estimate must be labelled as such, with confidence; + never present it as a detected structural change. Test known synthetic section + boundaries and one-beat phase errors without modifying saved anchors. +5. **Style energy arcs.** Hype rises to a later peak and resets; Steady stays + within a narrow band; Chill stays lower and relaxes. Use planned set progress + or an explicit repeating time cycle for indefinite stations. Penalize jumps + gently within one level (1/9 on normalized scale) and steeply beyond it. + Preserve explicit target/progression settings and exact queue permutations. + Test rising/falling Hype pools, available smooth steps and Steady neighbors. + +## Scope and constraints + +- Never rewrite manual cues, reviewed preparation, sources, or audio. Put new + analysis of protected records in a separately reviewable recommendation. +- No GPL/AGPL engine code, unlicensed repository code or neural model dependency + is imported into the MIT base player. Research informs an original implementation. +- Key detection, stem separation and new transition effects are out of scope + for Part 1. Part 2 explicitly adds a key timeline and use of prepared stems. +- Keep Android and desktop energy units and prepared decision formats aligned. +- 11.025 kHz sampling has a 5.5125 kHz Nyquist limit. A requested 5–11 kHz band + cannot exist at that rate; choose a supported upper band or explicitly raise + the analysis rate and qualify its CPU/memory cost. +- Strict Clippy, workspace checks, real Android interactions and actual musical + listening remain distinct acceptance gates. Publication/installation is separate. + +## Part 2 — Structure analysis and phrase-aware performance + +User extension accepted 2026-12-02. Execute after Tasks 1–5. Reference behavior +is djay Pro 6 TrackSense; implement independently without proprietary code or +binaries. These are requirements, not implemented or accuracy-qualified features. +See [model and integration research](research/STRUCTURE_MODELS_PRIMARY_SOURCES_20261202.md). + +### Packaging and evidence gates + +- Neural inference and models belong in an optional analysis add-on, never the + base player. Verify code, checkpoint, export and runtime licenses separately. + An optional worker is an isolation mechanism, not a licensing exemption. +- Keep Part 1 usable without the add-on. Record which analyzer produced a result; + a heuristic estimate must never be presented as verified neural analysis. + Explicitly requested model analysis failures must be reported, not silently + replaced with another analyzer's successful result. +- Version structure output separately (proposed engine `amp-prep-structure-1`). + Protect reviewed/manual records through proposals; no automatic reanalysis. +- Before claiming accuracy, establish 10–20 user-owned recordings with human + beat/downbeat, meter, section boundary/label and unusual-bar annotations. + Use `evaluation/structure/README.md`; never invent ground truth from a model. + +### Task 6 — Variable beat and downbeat grid + +Evaluate Beat This! (`CPJKU/beat_this`) and its `final0` checkpoint. Qualify the +actual reference preprocessing, tensor layout, frame rate, postprocessing and +checkpoint license before choosing Rust `ort`/ONNX. An ONNX export is a proposed +integration path, not an assumed upstream artifact. Compare exported inference +with reference Python beat times within 10 ms on representative recordings. + +Store variable beat/downbeat timestamps, meter and per-bar confidence. Keep +median BPM for display/ranking. Low-confidence results retain a clearly marked +unverified heuristic grid. Update rhythm quality and snapping to use supported +downbeats. Report downbeat precision/recall/F-measure on the annotated set and +phase stability through a live-drummer tempo-drift recording. + +### Task 7 — Labeled sections and actual bar counts + +Evaluate `mir-aidj/all-in-one` (`allin1`) for start/end/intro/outro/break/bridge/ +inst/solo/verse/chorus labels. Prefer qualified Rust inference; otherwise use a +separate optional JSON worker. Cross-check model beats against Task 6. Snap +boundaries only when supported by verified downbeats; retain uncertainty and +original time evidence when snapping cannot be justified. + +Profile v3 adds label, bars, start_bar, confidence and source (model/heuristic/ +manual); preserve older readers and odd 9/10/12-bar lengths. Derive build/drop/ +pre_chorus proposals from Task 3 features and neighboring sections, with distinct +heuristic provenance. A build rises over 4–16 bars; a drop follows break/build +with strong low-band/energy increase; pre_chorus is a distinct 2–8-bar region +before chorus. Do not force chorus labels onto verse-only material. + +Show customizable section colors and label + bar count; retain RGB waveform +option. Report boundary hits within one beat, label accuracy, and a verified +9-bar example on the human-annotated set. + +### Task 8 — Key timeline + +Use existing chroma to estimate section and 8-bar keys. Smooth 24-key evidence +with HMM/Viterbi persistence and supported section boundaries. Save start/end, +Camelot key and confidence; track key represents the longest supported stretch. +Harmonic pair cost uses outgoing exit and incoming entry keys. Test a semitone +modulation at bar 33 within one bar, plus a steady-key track with no spurious +changes. Unknown/ambiguous key remains explicit. + +### Task 9 — Section-aware controls and cue rules + +- Shift+click queues a section jump at the current section end using the fixed + landing scheduler; blink queued state and click again to cancel. Optional + boundary actions: prepared-stem mute pattern or pause. Test sample accuracy. +- Phrase Sync shifts by whole beats, at most one section length, to align the + next incoming/outgoing boundaries within one beat; avoid moving the live deck. +- Show current/next section bar countdowns on platter/waveforms and a shared + phrase strip. Unknown meter/phase must not produce invented bar counts. +- Rule-based auto cues: N bars before first verse, first chorus, intro, with + names/colors and banks A/B. Default to uncued tracks only; manual cues win. +- Learn from playlist measures existing cue label/bar offsets and proposes + majority patterns for review. Test 8-bar, 4-bar and verse-start patterns from + ten synthetic cued tracks. Never apply learned rules without user review. +- Share prepared decisions with Android/Remote rather than adding an unrelated + phone analyzer. Preserve existing transport and manual controls. + +### Task 10 — Phrase-aware Auto Mix + +Respect Quick/Balanced/Full duration choices and manual cue-out/mix-out first. +Choose supported outgoing section boundaries and time incoming intro overlap +so a style-selected verse/chorus/drop lands on the outgoing exit. Pick 4/8/16-bar +blends that fit the actual intro, accounting for variable beats/playback speed. + +Avoid two vocal sections overlapping: use already-prepared outgoing vocal mute +when available, otherwise choose instrumental entry or shorter blend. Do not +infer vocal activity solely from a verse/chorus label. Include structural fit +and Task 8 transition keys alongside Task 5 energy arcs in pair ranking. + +Render synthetic labeled transitions with target landing within one beat and +record pass/fail listening notes for 20 real transitions. Preserve all saved +cues, manual overrides and reviewed preparation. New stem models/effects and +external recommendation services remain out of scope. + +## Related queued UI request + +Receiving Player glows and identifies sender device + Player/DJ. AMP Verse's own +active audio navigation tabs replace their icons with the animated spectrum. +These are queued behind this engine work; they are not implemented by this document. diff --git a/docs/ENERGY_NUMERICAL_EVALUATION_20261203.md b/docs/ENERGY_NUMERICAL_EVALUATION_20261203.md new file mode 100644 index 00000000..24c83825 --- /dev/null +++ b/docs/ENERGY_NUMERICAL_EVALUATION_20261203.md @@ -0,0 +1,82 @@ +# Numerical energy evaluation — 2026-12-03 + +Candidate measurement, **not a listening or musical-accuracy qualification**. Four +previously reported EDM recordings were copied from the owner's library into an +isolated local test library. No audio is included in this repository. Original +and copy SHA-256 hashes matched before and after analysis; original preparation +was never written by the test worker. + +## Measurements + +| Recording | Track energy (1–10) | Section range | Sections | Analysis seconds | +| --- | ---: | ---: | ---: | ---: | +| Calabria (Alex Dreamz Mash) | 4.450 | 2.815–5.149 | 5 | 3.000 | +| Dirty Talk (CK Party Starter) Dirty | 4.433 | 2.933–4.962 | 5 | 2.375 | +| Get It Started (Jump Smokers Remix) CK Cut | 4.370 | 3.860–5.131 | 7 | 2.829 | +| Give Me Everything (Intro - Clean) | 4.657 | 3.683–5.379 | 9 | 3.859 | + +These are AMP's provisional activity scores, not Mixed In Key scores or human +ratings. Four similar EDM recordings do not establish calibration across genres. +Durations are one serial local run, not a throughput or real-time guarantee. + +All four downbeat hypotheses remained **unknown**. The analyzer did not turn a +stable tempo or regular kicks into a claimed verified bar 1. No human section, +drop, vocal or downbeat labels were supplied. + +## Mastering-gain regression + +The same Calabria recording was decoded to floating PCM at unity and double +amplitude (+6.02 dB), preserving peaks above full scale without clipping. +A hard onset counter initially failed: maximum normalized curve difference +was **0.0229097068**, above the **0.01** acceptance limit. Rounded LUFS values +could move a small onset across the hit threshold. Continuous peak weighting +with amplitude-based refractory peak selection corrects this discontinuity. + +- Corrected maximum curve difference: **0.0006872363**. +- Corrected maximum section-energy difference: **0.0005211762**. +- Both are below **0.01**; section boundaries and section counts also matched. +- Track energy matched the duration-weighted section mean on each recording. +- A near-threshold rounded-LUFS unit regression accompanies this measured case. + +## Reproducibility and limits + +- Analyzer: `amp-prep-heuristic-6`, Profile v2, Windows MSVC debug build. +- Analyzer binary SHA-256: `ada6547ed6d129a550991b1b5d4f86304bb9adcbb3fcb4cfdbc8d2b400eb4113`. +- Rust toolchain: `1.100.1-x86_64-pc-windows-msvc`. +- Codec: `ffmpeg version 78d2765 Copyright (c) 2000-2026 the FFmpeg developers`. +- Local private evidence contains source identities, copied audio, preparation + and full per-section measurements; these are deliberately not published. + +Human listening, 10–20 hand-annotated recordings, phrase accuracy and 20 actual +transition listening records remain outstanding. These results do not establish +semantic chorus/drop detection, physical speaker output or completion of Tasks +3–10. See [candidate status](ENGINE_UPGRADE_STATUS.md) and the +[annotation protocol](../evaluation/structure/README.md). + +## Broader tag-stratified smoke check + +Ten additional private MP3 copies passed fresh analysis with the same binary +hash above. Existing tags were used only to choose samples; they are not verified +genre labels. Each source and copy retained its SHA-256, and each track score +matched its duration-weighted section mean. No household preparation was written. + +| Unverified sampling tag | Track activity (1–10) | Sections | +| --- | ---: | ---: | +| Rock | 4.535 | 6 | +| Classical | 5.214 | 27 | +| Country | 4.526 | 4 | +| Hip-hop | 5.074 | 6 | +| Pop | 4.837 | 5 | +| Reggae | 4.692 | 7 | +| Latin | 5.367 | 2 | +| R&B | 4.728 | 3 | +| Jazz | 3.678 | 3 | +| Soundtrack | 5.177 | 3 | + +No eligible Gospel sample was selected. All downbeat hypotheses remained unknown. +The sample is small and selected by existing tags, not random or human reviewed. +A Classical-tagged sample scoring above Pop is a reason to inspect the actual +recordings, not evidence that either score is correct. No weights were tuned to +force a genre ordering. Musical calibration and listening acceptance remain open. +The sampling harness rejects fewer than eight tag groups; an initial empty run +caused by selecting audio keys instead of preparation keys is not counted. diff --git a/docs/ENGINE_UPGRADE_STATUS.md b/docs/ENGINE_UPGRADE_STATUS.md new file mode 100644 index 00000000..625702bc --- /dev/null +++ b/docs/ENGINE_UPGRADE_STATUS.md @@ -0,0 +1,80 @@ +# Section-aware engine upgrade — candidate status + +This branch is work in progress, not a published app update. Public version and +update catalogs remain RC33 until the platform and listening gates qualify. + +## Implemented candidate changes + +- Explicit incoming section-energy ranking, normalized Profile v2 and engine 6. + Legacy profiles load without mixing raw loudness into normalized comparisons. +- Legacy generated RMS levels are excluded even when their old preparation has + no perceptual-energy value. Their curves stay readable, and within-recording + relative Hype timing estimates remain available without exporting raw levels + into ranking. Historical protected/standalone numeric values remain usable; + new manual energy edits carry field-specific provenance, including unknown. +- Atomic review of section measurements and companion energy/provenance fields; + existing manual cues and reviewed preparation remain protected. +- Reused FFT band weights, spectral centroid and positive magnitude-shape flux; + bounded normalized rhythm/bass descriptors and exported provisional weights. +- Local checkerboard section-change evidence, with bounded 50 ms refinement using + existing envelope and harmonic evidence before beat snapping. Non-round 128/130/137 + BPM synthetic section tests pass; energy descriptors remain compact two-second bins. + No-clear-change blocks are labelled + unverified estimates. This does not establish semantic chorus/drop accuracy. +- Shared style curves and nonlinear jump costs, with explicit targets/progression + taking precedence. Desktop selection, indefinite server-cycle targets and + Android policy calls are wired for validation. +- Android consumes versioned offline entry/lull decisions and scores entry + section energy instead of silently preferring the whole-track score. +- Smart cycles preserve score ordering and shuffle only equal-cost choices. + Desktop outgoing-section energy is explicit runtime context, not a cloned + metadata override that can be hidden by the whole-track score. +- Android retains explicit progression ordering and refreshes a waiting deck's + planned entry after a style/source change, including when its song is unchanged. +- Continuous onset weights avoid hard hit-count changes from rounded LUFS. + Four real-song copies passed numerical checks; the +6.02 dB comparison passed + both curve and section-energy tolerances with identical section boundaries. +- Prepared exit choices preserve desktop/Android fade-horizon behavior instead + of discarding later lulls when the first is too soon for the current fade. +- Default desktop arcs have their own playlist counter, reset on a new source + and restored through session recovery independently of transition-effect counts. +- Default preparation ordering now refines its greedy seed with at most four + local-move passes and an eight-position radius. It retains native tempo/key + costs, the first song and repeated entries; explicit energy targets bypass + refinement. Provisional target/jump weights address reproduced Hype release + and Steady step regressions. This is a local recommendation, not a guaranteed + energy arc or proof of musical quality. It does not complete live Android or + indefinite-station ordering qualification. + +## Still required + +- Task 3 broader energy calibration and real-song listening. Numerical evidence + is in [the four-recording report](ENERGY_NUMERICAL_EVALUATION_20261203.md). +- Task 4 downbeat-hypothesis qualification and real boundary accuracy. Boundary + search is refined, but current descriptors do not verify bar 1. The + conservative 4/4 accent hypothesis leaves symmetric/weak evidence unknown. +- Task 5 full ordering/arc and playback coverage, including explicit requests, + repeated songs, playlist changes and Android runtime behavior. +- Current-source Windows/Linux workspace tests, strict lint, Android JVM/device + checks and playback/casting regression gates. A synthetic queue-fixture timing + correction requires device confirmation; it does not prove the earlier failure + was solely a test race. +- Human-reviewed song annotations and actual transition listening. No musical + accuracy or physical speaker result is claimed by compilation/unit tests. +- Android native transport passed on engine candidate `ebf05927` (run + `47118588650`) and combined candidate `c61f8efe` (run `47118723874`): seven + checks each, including real encoded audio decoded at an isolated receiver. + RC34's subsequent version and legacy-energy changes require new exact-source + qualification. These results do not establish physical speaker or LAN latency. +- The notification trace identified Android rejecting burst updates at 6.247 + enqueues per second. A requested-only, 350 ms coalescer now resolves the current + source at publication. Its focused tests and the above native runs pass. + Lifecycle acceptance now checks the OS service foreground state directly, + alongside the posted session token and real Pause/Play, rather than inferring + that state from a notification flag that can change on an ordinary refresh. +- Optional neural Tasks 6–10 and remaining master queue tasks are requirements, + not implemented features. No models have been bundled by this candidate. + +See [engine contract](AUTO_MIX_ENERGY_TASKS.md), +[owner queue](AMP_VERSE_IMPROVEMENT_QUEUE.md) and +[annotation protocol](../evaluation/structure/README.md). diff --git a/docs/research/DJ_ANALYSIS_PRIMARY_SOURCES_20261202.md b/docs/research/DJ_ANALYSIS_PRIMARY_SOURCES_20261202.md new file mode 100644 index 00000000..43f8769b --- /dev/null +++ b/docs/research/DJ_ANALYSIS_PRIMARY_SOURCES_20261202.md @@ -0,0 +1,69 @@ +# DJ analysis: verified primary sources and original implementation proposal + +Reviewed 2026-12-02. Research only: no production code, Git changes, benchmark runs, or audio downloads. The recommendations below are design proposals, not measured AMP Verse results. + +## Findings from the supplied papers + +### Vande Veire & De Bie (2018) + +The [publisher full text](https://link.springer.com/article/10.1186/s13636-018-0134-8), sections 3.3, 4, 5.4 and data availability, describes beat/downbeat tracking, RMS and MFCC self-similarity novelty, downbeat snapping, and selection of an eight-measure boundary phase. It labels segments high/low by their mean RMS relative to song-wide mean; low-to-high boundaries approximate drops. This is explicitly a Drum and Bass system, mixing at 175 BPM, not a general semantic chorus model. It reports structurally correct combined annotations for 90.9% of its 220-song holdout. Eight-measure assumptions sometimes fail; reported drop labeling is also imperfect. Offline annotation feeds live cue selection, time stretch, EQ, and crossfade. + +The article is CC BY 4.0. Its data/materials section identifies [code](https://bitbucket.org/ghentdatascience/dj) as AGPLv3. Supplementary data list training/test track identities; do not infer permission to redistribute copyrighted recordings. Use methods as research guidance; do not casually transplant AGPL code into an incompatible product. + +### Zehren, Alunno & Bientinesi (2020 preprint) + +[Full paper](https://arxiv.org/html/2007.08411v1), sections 3–5: switch points identify where musical dominance changes, which differs from first audibility. Features include kick/snare/hi-hat onset counts, harmonic/percussive RMS, CQT and PCP. Strong-beat aggregation, checkerboard novelty, period-phase selection and post-boundary salience filtering select candidates. The implementation uses strong beats because downbeat versus third-beat ambiguity was problematic. Harmonic energy salience is explicitly an approximation. Its approximately 96% good-quality claim includes subjective review; objective precision is 86% and recall 49%, with 0.5-second matching, on constrained annotated portions. These are not AMP Verse guarantees or whole-track drop accuracy. + +The [Automix LICENSE](https://raw.githubusercontent.com/MZehren/Automix/master/LICENSE) is MIT. Check individual vendors, dependencies and model weights separately before reuse. + +### Zehren et al. (Signals 2024, 5(4), 36) + +[Full paper](https://www.mdpi.com/2624-6120/5/4/36), sections 3–4 and conclusions, compares experience rules, LDA, decision trees and boosted trees. It chooses a four-bar phase among 16 beat offsets by mean novelty, restricts switch-in search to before the first core, and defines core using both high energy and bass-drum onset activity. Important features are novelty of energy, timbre, drums and harmony, rather than loudness alone. The study uses a 0.1-second matching window and per-track mean precision, penalizing tracks with no estimate. Its metrics therefore cannot be compared directly with the 2020 figures. Limited data, older music, underrepresented genres and drum-transcription errors remain explicit generalization concerns. Data availability links Automix and M-DJCUE; do not assume the current repository exactly reproduces every paper version. + +### Kim, Yang & Nam (NIME 2021) + +[Full paper](https://nime.pubpub.org/pub/g7avj1a7/release/1) estimates already-performed DJ transitions from a reference mix plus aligned source tracks. It optimizes monotone bounded gains over three sub-bands, using band scaling to avoid low-frequency domination. The inferred gains combine EQ and fader behavior; they are not independently identified knob positions. The paper uses 180 Hz and 3000 Hz splits and evaluates reconstruction on 3,930 filtered transitions. The listening task asks similarity to an existing mix, not preference for newly generated transitions. Its paper is CC BY 4.0. This supports investigating independent band automation, but does not establish a universally optimal bass-handoff recipe. Without a reference mix, its fitting objective is unavailable. + +The [repository](https://github.com/mir-aidj/transition-analysis) describes YouTube download, feature extraction, DTW alignment, segmentation and reproduction scripts. A recursive main-tree inspection found no LICENSE/COPYING file, and the [GitHub license endpoint](https://api.github.com/repos/mir-aidj/transition-analysis/license) returned 404 on review. Treat code reuse as unlicensed until clarified; public visibility is not permission. Metadata links are not a redistributable audio dataset. + +## Other verified implementation references + +- [Mixed In Key official energy guide](https://mixedinkey.com/workflows/use-energy-level-detection/) describes a 1–10 intensity aid, distinguishes energy from tempo, mentions high-frequency content, and asks users to audition intro, breakdown and drop sections. It does not publish a reproducible scoring formula. Learn from the user workflow; do not claim compatible scores, clone a proprietary metric or infer its model. A public explanation also does not establish patent clearance. +- [librosa 0.11 feature API](https://librosa.org/doc/0.11.0/feature.html) provides RMS, MFCC, chroma, spectral centroid/contrast/rolloff and tempo features. These are descriptors, not semantic chorus labels. Its [ISC license](https://github.com/librosa/librosa/blob/main/LICENSE.md) permits use subject to notice retention. Python is useful for offline experiments; this alone establishes no Android runtime integration. +- [Essentia RhythmExtractor2013](https://essentia.upf.edu/reference/std_RhythmExtractor2013.html) returns BPM, ticks, BPM estimates/intervals and confidence; degara confidence is always zero and should be ignored. Input must be 44.1 kHz. [Danceability](https://essentia.upf.edu/reference/std_Danceability.html) uses detrended fluctuation analysis and usually ranges about 0–3; it is neither a 1–10 proprietary energy score nor a drop detector. The [official license page](https://essentia.upf.edu/licensing_information.html) identifies AGPLv3/commercial licensing, model weights under CC BY-NC-SA 4.0 or proprietary terms, and dependency-specific obligations. Do not add the library or pretrained weights merely because an API is convenient. +- [Mixxx AutoDJ source](https://github.com/mixxxdj/mixxx/blob/main/src/library/autodj/autodjprocessor.cpp) has explicit intro/outro marker controls and transition modes. Fade duration respects available intro/outro time and has fallbacks when markers are absent or playback has moved. The [project license](https://github.com/mixxxdj/mixxx/blob/main/LICENSE) is GPL version 2 or later, with dependency/skin qualifications. Its architecture is a useful reference for editable markers and robust transport state; do not describe its AutoDJ as semantic drop-aware solely from that code. A BPM value alone is not an absolute beat/phrase grid. + +## Dataset boundaries + +[M-DJCUE README](https://raw.githubusercontent.com/MZehren/M-DJCUE/master/README.md) describes 134 EDM tracks, 1987–2016, about 60% vinyl digitizations, with JAMS IN/OUT annotations and three annotators per track. IN labels cover intro through first core; OUT labels exclude intro. Scoring unlabeled later IN candidates as false positives is invalid. Audio is explicitly withheld for copyright reasons. Mirrors include timing offsets and playback-speed corrections; naive timestamp reuse is wrong. The [dataset license](https://github.com/MZehren/M-DJCUE/blob/master/LICENSE) is GPL-3.0; this differs from Automix MIT. Obtain appropriate recordings and confirm their version/alignment before evaluation. This dataset is cue-point supervision, not comprehensive chorus/drop/breakdown ground truth. + +## Original AMP Verse implementation proposal + +These are proposed engineering choices, with thresholds to be calibrated, not copied algorithms or proven performance claims. + +1. **Keep evidence separate from labels.** Cache time-indexed loudness, bass/mid/high balance, onset activity, timbre and harmonic-change descriptors. Keep audio loudness normalization separate from within-track arrangement intensity. Store analyzer version and provenance. Silence/near-silence needs a dedicated state so normalization cannot turn noise into a peak. +2. **Build section boundaries before semantic labels.** Aggregate descriptors by verified beats where available; compare multi-bar neighborhoods for novelty, consolidate nearby candidates, and retain confidence/reasons. A lightweight adjacent-window difference is a reasonable mobile approximation to experiment with, but must not be presented as reproducing full self-similarity analysis. Avoid a quadratic whole-track matrix unless profiled. +3. **Treat phrase phase as an estimate.** Assess competing offsets using novelty and rhythmic support; retain ambiguity. Do not assume first decoded sample or first onset is a downbeat. Hardcoded eight-/sixteen-/thirty-two-bar offsets should become soft priors, with fallback to user cue markers or an ordinary fade when grid evidence is weak. +4. **Use honest event names.** A sustained energy/onset rise after a low section can be a candidate lift/drop; a sustained reduction can be a lull. Require persistence to reject transient drum fills. Chorus requires repetition/semantic evidence and separate validation. A bright mastered intro, vocal hook, breakdown, and true drop can have misleadingly similar scalar energy. +5. **Score pairs of actual overlap regions.** Choose outgoing and incoming switchpoints together, accounting for energy direction, phrase alignment, tempo feasibility, vocal/harmonic collision risk and available fade room. Expose useful intent such as maintain/lift/reset. Do not equate a single high-scoring cue with compatibility with every next track. +6. **Separate switch from fade start/end.** Represent all three explicitly, together with the intended incoming/outgoing sections and any bass handoff. Calculate against actual playback rate and remaining playable samples. Validate markers and cancel/replan after seek, manual next, rate change or track replacement. +7. **Make bass handoff an independently auditionable policy.** Prototype smoothed low-band attenuation of one deck while the other supplies bass around a chosen phrase boundary. Keep separate mid/high envelopes and headroom. Test correlated and anti-correlated bass, sustained notes, kicks, limiting and clipped sources; equal-power full-band fading alone cannot prevent bass masking or phase cancellation. No universal EQ cutoff, gain schedule or duration is established by the reviewed papers. +8. **Evaluate the failure modes that matter.** Measure candidate precision and at-least-one-usable-cue coverage, beat/downbeat/phrase error and pair-level audible failures separately. Label the tolerance and evaluated song regions. Use licensed varied tracks plus synthetic fixtures for silence, gain shifts, isolated transients, constant tones and band handoff. Conduct blinded listening on rendered transitions and report observed results only after running it. + +## Suggested delivery sequence + +First ship descriptive section analysis with confidence and editable cues; then pair-aware switch planning; then independent band automation with rendered/listened acceptance. Semantic chorus/drop marketing should wait for relevant labels and validation. Preserve a dependable ordinary crossfade fallback for uncertainty and unsupported material. + +## Flow 8 public workflow and immediate AMP Verse priorities + +The [official Flow 8 product page](https://mixedinkey.com/flow-dj-software/) describes eight playable loop/section choices, smooth crossfading when jumping within a track, per-track energy grouping, and manual volume/EQ/filter controls. The [official features page](https://flow8deck.com/features) describes key-and-energy-compatible dynamic playlists, gentle crossfades into another segment, frequency filtering, and stem controls. These establish public workflow inspiration, not section-detector formulas or evidence of automatic optimal bass swaps. No numerical overlap-length policy or detailed automatic bass-handoff algorithm was verified in those official pages. [Mixed In Key's harmonic-energy workflow](https://mixedinkey.com/workflows/change-energy-with-camelot-wheel/) explicitly advises auditioning actual overlaps and shortening one when melodic parts clash; it supplies no reproducible transition optimizer. + +Parent implementation findings supplied during this review, not independently re-audited here: track `perceptual_energy` already uses a LUFS-normalized RMS/onset envelope, but `energy_profile`/sections still use two-second loudness RMS and fixed sixteen-beat sections; Hype consumes that curve. Android `advanceAuto` fades at `cue_out`, while desktop considers `hype_sections`/`dj_phrasing`. + +Prioritize the missing section analysis, rather than replacing the existing track scalar: + +- Compute a bounded per-window descriptor vector alongside existing PCM decoding: log-RMS, bass/mid/high energy proportions, positive band-energy change/onset proxy, brightness, and sustained activity. These proxies must not be labeled kick transcription, MFCC, calibrated perceptual energy or semantic chorus detection when those methods were not implemented. +- Normalize each descriptor robustly with silence guards, clamp its contribution, and preserve raw loudness separately. A quiet but rhythmically active passage should differ from silence; a loud sustained pad should differ from a drum-heavy passage. Flat or nearly flat features need zero contribution rather than division by a tiny range. +- Build the arrangement/activity curve from several descriptors and detect sustained changes; fixed sixteen-beat bins may remain an aggregation/display unit, but should not be called detected sections. Attach confidence and retain weak-boundary cases. Test gain invariance, density changes at constant RMS, sustained tones and transients explicitly. +- Publish one versioned structure/transition-policy representation for both desktop and Android: section boundaries, activity/confidence, cue candidates, phrase evidence, and transition start/switch/end. Let both transports consume the same decisions while each executes its own playback operations. Android should not independently recreate cue-out-only timing after structure is available. +- Keep analysis collection-bounded and cancellable. Prefer a linear local change detector for the first mobile iteration, explicitly documented as an original approximation, before considering all-pairs matrices or large pretrained models. Reanalyze old cache versions so Hype actually uses the new curve. diff --git a/docs/research/STRUCTURE_MODELS_PRIMARY_SOURCES_20261202.md b/docs/research/STRUCTURE_MODELS_PRIMARY_SOURCES_20261202.md new file mode 100644 index 00000000..f195087a --- /dev/null +++ b/docs/research/STRUCTURE_MODELS_PRIMARY_SOURCES_20261202.md @@ -0,0 +1,48 @@ +# Structure models: primary-source verification + +Reviewed 2026-12-02. Research only; no weights, audio, model packages or production implementation were downloaded. GitHub source and model-card text were inspected. No export, inference, performance or parity result is claimed. + +## Source revisions and license findings + +The inspected Beat This source revision is `b95c8ab0c58c2d9fcfd40508ae8dffbc05ac4f5c`; All-In-One is `18e78903c0365147a2c5d4e5e57ebf88cb7d800e`. The All-In-One Hugging Face model repository revision is `379e5fd010b3fdd0ee8381ff8cbcfa51d70b5c19`. These identify inspected source/card state, not verified checkpoint hashes. [Beat This tree](https://api.github.com/repos/CPJKU/beat_this/git/trees/b95c8ab0c58c2d9fcfd40508ae8dffbc05ac4f5c?recursive=1), [All-In-One tree](https://api.github.com/repos/mir-aidj/all-in-one/git/trees/18e78903c0365147a2c5d4e5e57ebf88cb7d800e?recursive=1), [model metadata](https://huggingface.co/api/models/taejunkim/allinone). + +**Beat This code AND published model weights are explicitly MIT.** The maintainers separately flag copyrighted/restricted training recordings and ask users to assess their use case. This is stronger evidence than inferring weights terms from a repository badge, but does not establish rights to redistribute training audio or a legal clearance for every use. Preserve MIT notices. [README license section](https://github.com/CPJKU/beat_this/blob/b95c8ab0c58c2d9fcfd40508ae8dffbc05ac4f5c/README.md#license), [license](https://github.com/CPJKU/beat_this/blob/b95c8ab0c58c2d9fcfd40508ae8dffbc05ac4f5c/LICENSE). + +**All-In-One code is MIT; its actual weight-host model card also declares MIT.** Its loader points to `taejunkim/allinone`, so the card is evidence for the relevant weights rather than an unrelated model. The card is minimal: it supplies license metadata, not a detailed provenance or training-rights assessment. Do not characterize these weights as noncommercial or unlicensed based solely on uncertainty. Also do not extend this MIT declaration automatically to every dependency and separately downloaded Demucs model. [Code license](https://github.com/mir-aidj/all-in-one/blob/18e78903c0365147a2c5d4e5e57ebf88cb7d800e/LICENSE), [weight card](https://huggingface.co/taejunkim/allinone/blob/379e5fd010b3fdd0ee8381ff8cbcfa51d70b5c19/README.md), [loader](https://github.com/mir-aidj/all-in-one/blob/18e78903c0365147a2c5d4e5e57ebf88cb7d800e/src/allin1/models/loaders.py). + +An optional add-on changes packaging and user choice; it does not itself waive licenses, settle provenance questions or remove dependency notices. Before distributing a worker, inventory its pinned dependencies and auxiliary weights separately. This is an engineering release gate inferred from the distinct artifacts above, not a finding that either main model forbids commercial use. + +## Beat This final0 contract + +The published `final0` is the full model, trained excluding GTZAN, approximately 78 MB. Published artifacts are stripped PyTorch Lightning checkpoints loaded into ordinary PyTorch for inference; the inspected upstream tree does not ship an ONNX artifact or export utility. Exact final0 checkpoint hyperparameters are read from `hyper_parameters`, filtered against the model constructor; they were not independently inspected because this task forbids downloading weights. Architecture defaults alone are not checkpoint verification. [Models and reuse documentation](https://github.com/CPJKU/beat_this/blob/b95c8ab0c58c2d9fcfd40508ae8dffbc05ac4f5c/README.md), [checkpoint loader](https://github.com/CPJKU/beat_this/blob/b95c8ab0c58c2d9fcfd40508ae8dffbc05ac4f5c/beat_this/inference.py). + +The wrapper averages channels along axis 1 for an `(samples, channels)` array, resamples through soxr to **22,050 Hz**, and casts float32. Its frontend uses a **1024-point FFT**, **441-sample hop**, **128 mel bins**, **30–11,000 Hz**, Slaney mel scale, magnitude (`power=1`), `normalized="frame_length"`, then `log1p(1000 * mel)`. It delegates remaining window/centering/padding defaults to torchaudio: pin that dependency and match those defaults instead of substituting an arbitrary STFT. Spectrogram layout is `(time, 128)`; the model accepts `(batch, time, 128)`. [Preprocessing](https://github.com/CPJKU/beat_this/blob/b95c8ab0c58c2d9fcfd40508ae8dffbc05ac4f5c/beat_this/preprocessing.py), [audio wrapper](https://github.com/CPJKU/beat_this/blob/b95c8ab0c58c2d9fcfd40508ae8dffbc05ac4f5c/beat_this/inference.py). + +The output is separate `beat` and `downbeat` **logits**, each `(batch, time)`, at **50 frames/second** (22,050 / 441). They are not timestamps, probabilities, BPM, section labels or confidence-calibrated decisions. SumHead combines its beat and downbeat linear channels for the beat logit. The wrapper processes 1500-frame chunks, with six-frame discarded borders, `keep_first` overlap aggregation and shifted final chunk. Retaining that chunk contract matters for parity. [Model heads](https://github.com/CPJKU/beat_this/blob/b95c8ab0c58c2d9fcfd40508ae8dffbc05ac4f5c/beat_this/model/beat_tracker.py), [chunking](https://github.com/CPJKU/beat_this/blob/b95c8ab0c58c2d9fcfd40508ae8dffbc05ac4f5c/beat_this/inference.py). + +Default `dbn=False` selects minimal postprocessing: seven-frame max pooling at stride one with padding three, positive-logit threshold, adjacent-peak deduplication, division by 50, and snapping downbeats to nearest detected beats followed by uniqueness. The code comment says +/-70 ms; the seven-point window actually spans three frames on either side (60 ms at 50 fps), so preserve code behavior. DBN is a separate optional madmom path with 3/4 beats per bar and 55–215 BPM assumptions. [Postprocessor](https://github.com/CPJKU/beat_this/blob/b95c8ab0c58c2d9fcfd40508ae8dffbc05ac4f5c/beat_this/model/postprocessor.py). + +**ONNX status: feasible experiment, unverified integration.** Source uses rotary embeddings, einops reshapes and PyTorch scaled-dot-product attention. There is no inspected upstream ONNX support contract. Exporting just the spectrogram-to-two-logit network with an explicit tuple wrapper avoids pretending soxr, file decoding and Python/numpy postprocessing are part of the graph. An exporter must prove short/long and chunk-edge numerical parity, operator availability in the chosen ONNX Runtime target, and identical final beat timing before use. Dynamic-length export and Android suitability remain unmeasured. [Attention source](https://github.com/CPJKU/beat_this/blob/b95c8ab0c58c2d9fcfd40508ae8dffbc05ac4f5c/beat_this/model/roformer.py), [upstream source tree](https://api.github.com/repos/CPJKU/beat_this/git/trees/b95c8ab0c58c2d9fcfd40508ae8dffbc05ac4f5c?recursive=1). + +## All-In-One worker contract and limitations + +The supported functional vocabulary, in index order, is **start, end, intro, outro, break, bridge, inst, solo, verse, chorus**. There is no native `drop`, `buildup`, `breakdown`, `pre-chorus` or transition-quality label. Mapping `break` to a DJ breakdown or chorus to a drop would be an additional heuristic requiring its own confidence and validation. [Label configuration](https://github.com/mir-aidj/all-in-one/blob/18e78903c0365147a2c5d4e5e57ebf88cb7d800e/src/allin1/config.py). + +Upstream provides a Python/PyTorch file analyzer, not a lightweight standalone semantic ONNX model. The normal `analyze()` path runs **HTDemucs source separation**, extracts stem spectrograms, loads the structure network, then postprocesses results. The default `harmonix-all` is an ensemble of **eight** fold checkpoints, not one checkpoint. The loader downloads from Hugging Face as needed; Demucs has its own model acquisition. A truly offline worker must provision and pin all required artifacts beforehand and disable accidental retrieval. [Analyzer](https://github.com/mir-aidj/all-in-one/blob/18e78903c0365147a2c5d4e5e57ebf88cb7d800e/src/allin1/analyze.py), [loader](https://github.com/mir-aidj/all-in-one/blob/18e78903c0365147a2c5d4e5e57ebf88cb7d800e/src/allin1/models/loaders.py), [Demucs subprocess](https://github.com/mir-aidj/all-in-one/blob/18e78903c0365147a2c5d4e5e57ebf88cb7d800e/src/allin1/demix.py). + +The documented installation requires PyTorch, NATTEN, current madmom from GitHub, and allin1; FFmpeg is documented for MP3 support. Windows instructions require building NATTEN from source. Package metadata requires Python >=3.8 and lists Demucs, librosa, Hydra/OmegaConf and Hugging Face Hub among dependencies; NATTEN is automatically declared only for Darwin. Therefore `pip install allin1` alone is not a validated Windows worker setup. Exact compatible dependency pins need a tested environment rather than assuming latest NATTEN works with legacy API calls. [Installation](https://github.com/mir-aidj/all-in-one/blob/18e78903c0365147a2c5d4e5e57ebf88cb7d800e/README.md#installation), [package metadata](https://github.com/mir-aidj/all-in-one/blob/18e78903c0365147a2c5d4e5e57ebf88cb7d800e/pyproject.toml). + +The spectrogram path requires bass/drums/other/vocals stem WAVs and stacks four mono spectrograms. It uses madmom framing (2048 samples, 100 fps), STFT, 12 bands per octave between 30 and 17,000 Hz with normalized filters, then logarithmic scaling. Config uses 44,100 Hz, hop 441 and 100 fps. This is a distinct frontend from Beat This; sharing a generic mel tensor between them is incorrect. Worker disk use includes stems and spectrogram files; standard analyzer cleans byproducts unless requested otherwise and supports disabling multiprocessing. [Spectrogram source](https://github.com/mir-aidj/all-in-one/blob/18e78903c0365147a2c5d4e5e57ebf88cb7d800e/src/allin1/spectrogram.py), [configuration](https://github.com/mir-aidj/all-in-one/blob/18e78903c0365147a2c5d4e5e57ebf88cb7d800e/src/allin1/config.py), [analyzer](https://github.com/mir-aidj/all-in-one/blob/18e78903c0365147a2c5d4e5e57ebf88cb7d800e/src/allin1/analyze.py). + +**ONNX is a substantial port, not a verified download option.** The inspected upstream tree contains no ONNX artifact/exporter. Its DiNAT source directly imports and calls NATTEN `natten1dav`, `natten1dqkrpb`, `natten2dav`, and `natten2dqkrpb`. Inference: ordinary ONNX export cannot be assumed to lower these external operations; an implementation would need supported decompositions/custom operators or a parity-tested attention rewrite. Even a successful network export leaves Demucs, stem features and postprocessing to solve. Prefer a separately provisioned Python worker as the initial feasibility boundary; do not describe it as shipped or proven on this machine. [DiNAT implementation](https://github.com/mir-aidj/all-in-one/blob/18e78903c0365147a2c5d4e5e57ebf88cb7d800e/src/allin1/models/dinat.py), [tree](https://api.github.com/repos/mir-aidj/all-in-one/git/trees/18e78903c0365147a2c5d4e5e57ebf88cb7d800e?recursive=1). + +## Practical gates for Tasks 6–10 + +1. Pin upstream source, actual checkpoint checksums, frontend parameters, output layout, postprocessing and dependency versions in the add-on manifest. A source revision is not a checksum for an unexamined downloaded checkpoint. +2. Treat Beat This as beat/downbeat evidence and All-In-One as its explicit functional vocabulary. Derive phrase/energy/drop candidates separately and retain provenance and uncertainty. +3. Ship neither a fake ONNX placeholder nor a silent fallback labeled as successful neural inference. Missing model/runtime must produce an explicit unavailable state while the existing analyzer remains usable. +4. Prove worker installation, cancellation, bounded concurrency, cleanup and offline execution using a separately authorized provisioning/test task. No such runtime proof occurred here. +5. Verify licenses/notices for the complete distributed worker, auxiliary models and any converted artifact. Optional installation alone is not a license resolution. +6. Benchmark real CPU/GPU cost, memory, long-track behavior and target-platform parity before enabling library-wide analysis. Upstream examples/performance claims do not establish AMP Verse acceptance results. + +These gates are engineering conclusions from the inspected sources. This report neither approves a legal use nor claims that packaging or model execution is complete. diff --git a/evaluation/structure/README.md b/evaluation/structure/README.md new file mode 100644 index 00000000..c27081e8 --- /dev/null +++ b/evaluation/structure/README.md @@ -0,0 +1,39 @@ +# Structure analysis qualification set + +Status: annotation protocol only. No human-verified recordings or accuracy +results are supplied by this directory yet. + +Choose 10–20 recordings from the owner's library: EDM with builds/drops, pop, +hip-hop or verse-only material, a live drummer with tempo drift, a sustained +intro, a key modulation, and an unusual section length. Keep audio private; +do not commit MP3s, local NAS paths, or listening credentials. + +For each recording create a JSON annotation with these fields: + +- `schema_version`: 1; `track_id`: private evaluation identifier. +- `audio_sha256`: hash of the exact decoded-source file being annotated. +- `duration_seconds`, `annotator`, `reviewed`: explicit human verification. +- `beats_seconds` and `downbeats_seconds`: ordered human-corrected timestamps. +- `meter_regions`: start/end seconds and beats_per_bar, including changes. +- `sections`: start/end seconds, label, start_bar and actual bars. Preserve odd + lengths and mark uncertain labels/counts with null instead of guessing. +- `key_regions`: optional start/end seconds, key and confidence/uncertainty. +- `notes`: ambiguity, pickup beats, partial bars and source edition details. + +Model output may help place initial markers, but it is never ground truth until +a person listens and corrects it. Hold out tracks from weight/threshold tuning. +Report track coverage, matching tolerance and unresolved annotations with scores. + +Required evidence: + +1. Beat This reference/export parity: timestamp differences, 10 ms target. +2. One-to-one beat/downbeat precision, recall and F-measure with a stated + tolerance; tempo drift and phase errors reported separately. +3. Section boundary hit rate within one annotated beat, label accuracy, and + unusual-bar count correctness; no forced chorus for verse-only material. +4. Twenty transition listening records: track IDs, outgoing exit, incoming + landing, style, blend bars, vocal overlap, pass/fail and audible reason. + +Record analyzer/checkpoint hashes, preprocessing version, platform, and engine +version for reproducibility. Synthetic render tests remain separate from human +musical accuracy and listening results. diff --git a/tools/run_android_emulator_tests.py b/tools/run_android_emulator_tests.py new file mode 100644 index 00000000..58c8b26a --- /dev/null +++ b/tools/run_android_emulator_tests.py @@ -0,0 +1,107 @@ +#!/usr/bin/env python3 +"""Run compiled instrumentation APKs directly, only on a disposable emulator. + +Uses Android's documented am instrument interface, without Gradle/UTP downloads +after compilation: https://developer.android.com/studio/test/command-line +This is the single CI runner, not a retry or alternate application code path. +""" +import argparse +import hashlib +import json +from pathlib import Path +import re +import shlex +import subprocess + + +def result_count(output): + if re.search(r"INSTRUMENTATION_(?:FAILED|ABORTED)|FAILURES!!!|" + r"INSTRUMENTATION_STATUS_CODE: -(?:1|2)\s*$", output, re.M): + raise RuntimeError("Android instrumentation reported a failure") + matches = re.findall(r"^OK \(([1-9][0-9]*) tests?\)\s*$", output, re.M) + if len(matches) != 1 or not re.search(r"^INSTRUMENTATION_CODE: -1\s*$", output, re.M): + raise RuntimeError("Android instrumentation did not finish a nonempty test run") + return int(matches[0]) + + +def emulator_adb(): + serial = subprocess.check_output(["adb", "get-serialno"], text=True, timeout=10).strip() + if not re.fullmatch(r"emulator-[0-9]+", serial): + raise RuntimeError("This fixture cannot install or run tests on a physical device") + adb = ["adb", "-s", serial] + qemu = subprocess.check_output(adb + ["shell", "getprop", "ro.kernel.qemu"], + text=True, timeout=10).strip() + if qemu != "1": + raise RuntimeError("Android device is not a disposable emulator") + return adb + + +def one_apk(folder): + files = list(folder.glob("*.apk")) + if len(files) != 1: + raise RuntimeError(f"Expected exactly one precompiled APK in {folder}") + return files[0] + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--classes", required=True) + parser.add_argument("--argument", action="append", default=[]) + parser.add_argument("--output", type=Path, required=True) + args = parser.parse_args() + if not re.fullmatch(r"[A-Za-z0-9_.$#,]+", args.classes): + parser.error("Expected explicit instrumentation class/method names") + arguments = [] + for value in args.argument: + key, separator, value = value.partition("=") + if (not separator or not re.fullmatch(r"[A-Za-z0-9_.-]+", key) + or key in ("class", "log", "debug", "additionalTestOutputDir")): + parser.error("Invalid or reserved instrumentation argument") + arguments.extend(["-e", key, value]) + # Verify the device before any installation or mutation, even if APKs exist. + adb = emulator_adb() + root = Path(__file__).resolve().parents[1] + app = one_apk(root / "android/app/build/outputs/apk/full/debug") + tests = one_apk(root / "android/app/build/outputs/apk/androidTest/full/debug") + args.output.mkdir(parents=True, exist_ok=True) + receipt = args.output / "instrumentation.json" + if receipt.exists(): + raise RuntimeError("Use a fresh test-output directory; refusing a stale passing receipt") + for apk in (app, tests): + subprocess.run(adb + ["install", "-r", "-t", str(apk)], check=True, timeout=120) + # The Activity's getExternalFilesDir creates this as the application UID. + # Shell-created child directories are not writable by the app on Android 15. + device_output = "/sdcard/Android/data/cloud.gitwide.ampverse/files" + instrument = ["am", "instrument", "-w", "-r", "-e", "class", args.classes, + "-e", "additionalTestOutputDir", device_output] + arguments + [ + "cloud.gitwide.ampverse.test/androidx.test.runner.AndroidJUnitRunner"] + command = adb + ["shell", shlex.join(instrument)] + try: + run = subprocess.run(command, capture_output=True, text=True, timeout=1200) + output = run.stdout + run.stderr + (args.output / "instrumentation.txt").write_text(output, encoding="utf-8") + print(output, flush=True) + run.check_returncode() + count = result_count(output) + present = subprocess.run(adb + ["shell", "test", "-d", device_output], timeout=10) + if present.returncode == 0: + subprocess.run(adb + ["pull", device_output, str(args.output / "device-output")], + check=True, timeout=30) + elif present.returncode != 1: + present.check_returncode() + receipt.write_text(json.dumps({ + "passed": True, "tests": count, "classes": args.classes, + "device": "disposable-emulator", "app_sha256": hashlib.sha256(app.read_bytes()).hexdigest(), + "tests_sha256": hashlib.sha256(tests.read_bytes()).hexdigest(), + }, indent=2) + "\n", encoding="utf-8") + finally: + with (args.output / "logcat.txt").open("w", encoding="utf-8") as log: + try: + subprocess.run(adb + ["logcat", "-d"], stdout=log, stderr=subprocess.STDOUT, + timeout=10, check=False) + except (OSError, subprocess.TimeoutExpired) as error: + log.write(f"Could not collect emulator diagnostics: {error}\n") + + +if __name__ == "__main__": + main() diff --git a/tools/smoke_preparation.py b/tools/smoke_preparation.py index 6a00930e..d8ccdfbc 100644 --- a/tools/smoke_preparation.py +++ b/tools/smoke_preparation.py @@ -45,7 +45,7 @@ subprocess.run([binary,str(folder),"--jobs","3"],check=True) manual = read(folder,manual_sidecar) assert manual["bpm"] == 127 and manual["source_sha256"] == source_hash - assert manual["analysis_recommendation"]["analysis"]["engine"] == "amp-prep-heuristic-5" + assert manual["analysis_recommendation"]["analysis"]["engine"] == "amp-prep-heuristic-6" del manual["analysis_recommendation"]; write(folder,manual_sidecar,manual) declined_bytes = raw(folder,manual_sidecar) subprocess.run([binary,str(folder),"--jobs","3"],check=True) diff --git a/tools/test_android_owned_pcm.py b/tools/test_android_owned_pcm.py index a3fd8ac7..ac15c512 100644 --- a/tools/test_android_owned_pcm.py +++ b/tools/test_android_owned_pcm.py @@ -29,8 +29,8 @@ def main(): classpath = os.pathsep.join([str(classes)] + [str(path) for path in jars]) production = ["OwnedPcmMixer", "MasterPcmQueue", "OwnedPcmOutput", "OwnedAudioOutput", "OwnedMediaAudioSink", "OwnedInputPcm", "AudioDsp", "PhoneLiveSession", - "PhoneLiveHttpTransport", "OwnedSamplerVoices", "OwnedSamplerAudio", "PhoneMasterBroadcast", "PhoneSourceIdentity", "PhoneMp3Warmup", "ReleaseCheck"] - tests = ["OwnedPcmMixerTest", "PhoneLiveSessionTest", "PhoneLiveHttpTransportTest", "OwnedInputPcmTest", "OwnedMediaAudioSinkTest", "OwnedAudioOutputTest", "OwnedSamplerVoicesTest", "PhoneMasterBroadcastTest", "PhoneSourceIdentityTest", "PhoneMp3WarmupTest", "ReleaseChannelTest"] + "PhoneLiveHttpTransport", "OwnedSamplerVoices", "OwnedSamplerAudio", "PhoneMasterBroadcast", "PhoneMasterUpload", "PhoneSourceIdentity", "PhoneMp3Warmup", "PlaybackNotificationGate", "ReleaseCheck"] + tests = ["OwnedPcmMixerTest", "PhoneLiveSessionTest", "PhoneLiveHttpTransportTest", "OwnedInputPcmTest", "OwnedMediaAudioSinkTest", "OwnedAudioOutputTest", "OwnedSamplerVoicesTest", "PhoneMasterBroadcastTest", "PhoneMasterUploadTest", "PhoneSourceIdentityTest", "PhoneMp3WarmupTest", "PlaybackNotificationGateTest", "ReleaseChannelTest"] files = [source / "main/java/cloud/gitwide/ampverse" / (name + ".java") for name in production] files += [source / "test/java/cloud/gitwide/ampverse" / (name + ".java") for name in tests] if args.full_cast: diff --git a/tools/test_engine_release_metadata.py b/tools/test_engine_release_metadata.py index 7ebeccb6..50591c6f 100644 --- a/tools/test_engine_release_metadata.py +++ b/tools/test_engine_release_metadata.py @@ -21,7 +21,7 @@ def test_contract_for_both_platforms(self): self.assertEqual(metadata["asset"], asset) self.assertEqual(metadata["platform"], platform) self.assertEqual(metadata["protocol"], 1) - self.assertEqual(metadata["engine_id"], "amp-prep-heuristic-5") + self.assertEqual(metadata["engine_id"], "amp-prep-heuristic-6") self.assertEqual(metadata["release"], "v0.3.2") write_metadata(root, directory, platform, "v1.1.0-rc.11") self.assertEqual(json.loads((directory / (asset+".json")).read_text())["release"],"v1.1.0-rc.11") diff --git a/tools/test_run_android_emulator_tests.py b/tools/test_run_android_emulator_tests.py new file mode 100644 index 00000000..9ae95bcb --- /dev/null +++ b/tools/test_run_android_emulator_tests.py @@ -0,0 +1,46 @@ +import unittest +import sys +from unittest.mock import patch + +import run_android_emulator_tests as runner + + +class EmulatorRunnerTest(unittest.TestCase): + def test_requires_real_completed_nonempty_result(self): + self.assertEqual(runner.result_count("OK (57 tests)\nINSTRUMENTATION_CODE: -1\n"), 57) + self.assertEqual(runner.result_count("OK (1 test)\nINSTRUMENTATION_CODE: -1\n"), 1) + for invalid in ("", "OK (0 tests)\nINSTRUMENTATION_CODE: -1\n", + "OK (3 tests)\n", "INSTRUMENTATION_CODE: -1\n", + "FAILURES!!!\nOK (1 test)\nINSTRUMENTATION_CODE: -1\n", + "INSTRUMENTATION_STATUS_CODE: -2\nOK (1 test)\nINSTRUMENTATION_CODE: -1\n", + "INSTRUMENTATION_STATUS_CODE: -1\nOK (1 test)\nINSTRUMENTATION_CODE: -1\n", + "INSTRUMENTATION_ABORTED: process crashed"): + with self.subTest(invalid=invalid), self.assertRaises(RuntimeError): + runner.result_count(invalid) + + @patch.object(runner.subprocess, "check_output", return_value="Pixel_7\n") + def test_rejects_physical_phone_before_any_other_command(self, command): + with self.assertRaisesRegex(RuntimeError, "physical device"): + runner.emulator_adb() + self.assertEqual(command.call_count, 1) + + @patch.object(runner.subprocess, "run") + @patch.object(runner.subprocess, "check_output", return_value="Pixel_7\n") + def test_main_never_installs_on_a_physical_phone(self, output, run): + with patch.object(sys, "argv", ["runner", "--classes", "cloud.Test", "--output", "unused"]): + with self.assertRaisesRegex(RuntimeError, "physical device"): + runner.main() + run.assert_not_called() + + @patch.object(runner.subprocess, "check_output", side_effect=["emulator-5554\n", "0\n"]) + def test_requires_emulator_property_as_well_as_serial(self, command): + with self.assertRaisesRegex(RuntimeError, "not a disposable emulator"): + runner.emulator_adb() + + @patch.object(runner.subprocess, "check_output", side_effect=["emulator-5554\n", "1\n"]) + def test_every_later_command_is_pinned_to_verified_emulator(self, command): + self.assertEqual(runner.emulator_adb(), ["adb", "-s", "emulator-5554"]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/verify_android_owned_native.py b/tools/verify_android_owned_native.py index 8a3b6130..7c3858d1 100644 --- a/tools/verify_android_owned_native.py +++ b/tools/verify_android_owned_native.py @@ -15,6 +15,8 @@ import time import urllib.request +from run_android_emulator_tests import emulator_adb + BASE = "http://127.0.0.1:28987" PASSWORD = "android-owned-fixture" @@ -28,6 +30,7 @@ def main(): command = args.command[1:] if args.command[:1] == ["--"] else args.command if not command: parser.error("An instrumentation command is required") + adb = emulator_adb() # Verify disposable identity before routing or running anything. args.output.mkdir(parents=True, exist_ok=True) stop = threading.Event() encoded = bytearray() @@ -83,6 +86,9 @@ def receiver(): if server.poll() is not None or time.monotonic() > deadline: raise RuntimeError("Isolated server did not start") time.sleep(0.05) + # This native codec/HTTP fixture is independent of emulator NAT readiness. + # One explicit loopback transport; physical LAN acceptance is separate. + subprocess.run(adb + ["reverse", "tcp:28987", "tcp:28987"], check=True, timeout=10) listener.start() test = subprocess.run(command, timeout=600) listener.join(5) @@ -101,11 +107,24 @@ def receiver(): raise RuntimeError(f"Invalid decoded generated audio: seconds={seconds}, RMS={rms}") receipt = {"passed": True, "server_binary_sha256": hashlib.sha256(args.server_binary.read_bytes()).hexdigest(), "encoded_bytes": len(encoded), "decoded_seconds": seconds, "decoded_rms": rms, - "scope": "Actual Android FFmpegKit FIFO + owned PCM/virtual AudioTrack + real isolated server + decoded receiver; not physical speaker/LAN latency", + "scope": "Actual Android FFmpegKit FIFO + owned PCM/virtual AudioTrack + real isolated server + decoded receiver; adb reverse loopback, not physical speaker/LAN latency", "source_commit": subprocess.check_output(["git", "rev-parse", "HEAD"], text=True).strip()} (args.output / "receipt.json").write_text(json.dumps(receipt, indent=2) + "\n") print(json.dumps(receipt, indent=2)) finally: + # The emulator action stops its device before later workflow steps run. + # Capture failures while this disposable device is still reachable. + with (args.output / "logcat.txt").open("w", encoding="utf-8") as device_log: + try: + subprocess.run(adb + ["logcat", "-d"], stdout=device_log, + stderr=subprocess.STDOUT, timeout=10, check=False) + except (OSError, subprocess.TimeoutExpired) as error: + device_log.write(f"Could not collect emulator diagnostics: {error}\n") + try: + subprocess.run(adb + ["reverse", "--remove", "tcp:28987"], timeout=10, check=False, + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) + except (OSError, subprocess.TimeoutExpired): + pass stop.set() server.terminate() try: