diff --git a/.github/workflows/android-card-ui.yml b/.github/workflows/android-card-ui.yml index 4cf82034..06c8143d 100644 --- a/.github/workflows/android-card-ui.yml +++ b/.github/workflows/android-card-ui.yml @@ -70,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 - 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 + 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 result=$? mkdir -p test-output/android-card-ui adb logcat -d > test-output/android-card-ui/logcat.txt diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index dbd2e536..10e4b72e 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -69,12 +69,6 @@ jobs: run: | python tools/setup_ci_ffmpeg.py --self-test python tools/setup_ci_ffmpeg.py - - name: Prepare verified official Lab URL-import dependencies - env: - GH_TOKEN: ${{ github.token }} - run: | - python tools/test_setup_lab_youtube.py - python tools/setup_lab_youtube.py --dest test-output/lab-tools - run: python tools/test_engine_release_metadata.py - run: python tools/test_stem_cuda_module.py - uses: actions/setup-node@v4 @@ -168,22 +162,17 @@ jobs: - name: Verify sampler clip export with real codecs if: runner.os == 'Linux' run: cargo test -p amp-player --bin amp-player sample_editor::tests::clip_export_preserves_source_and_respects_selection -- --ignored - - name: Verify Lab URL import with local downloader and real codecs + - name: Verify local MP3 import and source preservation if: runner.os == 'Linux' run: | mkdir -p test-output/lab-import - rustc tools/lab_youtube_fixture.rs -o test-output/lab-import/yt-dlp-fixture - ffmpeg -n -hide_banner -loglevel error -f lavfi -i sine=frequency=440:duration=2 test-output/lab-import/fixture.wav - ffmpeg -n -hide_banner -loglevel error -i test-output/lab-import/fixture.wav -c:a libmp3lame -b:a 256k test-output/lab-import/loaded.mp3 - AMP_LAB_TOOLS="$PWD/test-output/lab-tools" AMP_LAB_YOUTUBE_FIXTURE="$PWD/test-output/lab-import/yt-dlp-fixture" cargo test -p amp-player --bin amp-player lab_youtube::tests::local_pipeline -- --ignored --test-threads=1 - AMP_LAB_LOADED_MP3="$PWD/test-output/lab-import/loaded.mp3" cargo test -p amp-player --bin amp-player lab_editor::tests::downloaded_mp3 -- --ignored + ffmpeg -n -hide_banner -loglevel error -f lavfi -i sine=frequency=440:duration=2 -c:a libmp3lame -b:a 256k test-output/lab-import/loaded.mp3 + AMP_LAB_LOADED_MP3="$PWD/test-output/lab-import/loaded.mp3" cargo test -p amp-player --bin amp-player lab_editor::tests::local_mp3 -- --ignored - name: Verify Lab processing, clip categories and metadata failure recovery run: | cargo test -p amp-player --bin amp-player lab_audio::render_tests::lab_processing_render_eq_changes_audio_and_cancel_preserves_source_and_destination --locked -- --ignored --exact --test-threads=1 cargo test -p amp-player --bin amp-player lab_audio::render_tests::clip_export_records_categories_without_copying_source_timeline --locked -- --ignored --exact --test-threads=1 cargo test -p amp-player --bin amp-player lab_audio::render_tests::exported_mp3_remains_a_clip_when_portable_metadata_cannot_be_written --locked -- --ignored --exact --test-threads=1 - - name: Verify Suno import publication and Lab decoding with real codecs - run: cargo test -p amp-player --bin amp-player lab_youtube::suno::tests::local_codec_import -- --ignored --test-threads=1 - run: cargo build --workspace --release --locked - name: Verify native desktop and server update, restart, rollback and cleanup run: python tools/smoke_in_app_update.py --helper target/release/amp-update${{ matrix.suffix }} --server-helper target/release/amp-server-update${{ matrix.suffix }} --server target/release/amp-cast${{ matrix.suffix }} @@ -280,16 +269,6 @@ jobs: with: name: amp-plugin-example-${{ runner.os }}-${{ github.sha }} path: plugin-dist/ - - name: Package official AMP Lab YouTube tools - shell: bash - run: | - mkdir -p dist/tools - cp -r test-output/lab-tools dist/tools/lab-youtube - - name: Include Lab tool recovery setup - shell: bash - run: | - mkdir -p dist/setup - cp tools/setup_lab_youtube.py dist/setup/ - name: Include canonical updater and legacy installer compatibility if: runner.os == 'Windows' shell: bash @@ -441,7 +420,7 @@ jobs: cd packages # Artifact storage strips executable bits. Restore them before making # Linux ZIPs so the updater can restart the newly installed binaries. - find . -type f \( -name amp-player -o -name amp-update -o -name amp-server-update -o -name amp-cast -o -name amp-prepare -o -name amp-stem-worker -o -name amp-engine -o -name amp-engine-linux-x86_64 -o -name deno -o -name yt-dlp \) -exec chmod +x {} + + find . -type f \( -name amp-player -o -name amp-update -o -name amp-server-update -o -name amp-cast -o -name amp-prepare -o -name amp-stem-worker -o -name amp-engine -o -name amp-engine-linux-x86_64 \) -exec chmod +x {} + for dir in amp-verse-*; do (cd "$dir" && zip -r "../$dir.zip" .); done for dir in amp-analysis-engine-*; do (cd "$dir" && zip -r "../$dir-${GITHUB_REF_NAME}.zip" .); done cp amp-analysis-engine-Windows/amp-engine-windows-x86_64.exe* . diff --git a/.github/workflows/music-import-engine.yml b/.github/workflows/music-import-engine.yml index 3b6efc78..dfe49c20 100644 --- a/.github/workflows/music-import-engine.yml +++ b/.github/workflows/music-import-engine.yml @@ -29,11 +29,7 @@ jobs: - name: Verified Windows audio tools if: runner.os == 'Windows' run: python tools/setup_ci_ffmpeg.py - - name: Verified official extractor and YouTube runtime - env: - GH_TOKEN: ${{ github.token }} - run: python tools/setup_lab_youtube.py --dest test-output/lab-tools - - name: Exercise the actual importer with real codecs + - name: Exercise local audio import and editing with real codecs run: python tools/verify_music_import_engine.py - uses: actions/upload-artifact@v4 if: always() 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/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.md index a095bb20..44da0fbd 100644 --- a/THIRD_PARTY_NOTICES.md +++ b/THIRD_PARTY_NOTICES.md @@ -27,9 +27,7 @@ The optional pitch-preserving playback backend uses Signalsmith Stretch and Sign Genre-tag reading uses Lofty 0.25.5 (MIT OR Apache-2.0), https://github.com/Serial-ATA/lofty-rs. Its licenses are retained in licenses/lofty. Genre reading disables cover-art and audio-property parsing and does not modify source audio. -## AMP Lab YouTube import - -Lab launches yt-dlp, Deno and FFmpeg as separate processes. The pinned official yt-dlp standalone (2026.10.26) includes matching yt-dlp-ejs components, Python and its own third-party dependencies; the full upstream THIRD_PARTY_LICENSES.txt, license and project source archive accompany the tools. yt-dlp original code is Unlicense; bundled executable dependencies retain their upstream terms, including copyleft components described in that inventory. Deno 2.9.8 (MIT) ships with its project source archive, MIT notice and V8/TypeScript license notices under tools/lab-youtube/licenses. Preserve those materials when redistributing the package. FFmpeg remains the separately supplied existing audio dependency; its build-specific codec licenses and source/rebuild materials remain applicable. The optional external-tools directory is not linked into or an add-on to AMP's playback engine. +## Process and URL utilities Process-tree management uses process-wrap 10.0.1 (MIT OR Apache-2.0), with original license texts in licenses/process-wrap. On Windows it creates a Job Object before the process runs; on Unix it owns a process group. URL parsing uses the existing url 2.x dependency (MIT OR Apache-2.0). @@ -50,10 +48,6 @@ Library's Transcribe tool downloads faster-whisper 1.2.1 (MIT) from the official The optional model is Systran/faster-whisper-base, pinned revision ebe41f70d5b6dfa9166e2c581c45c9c0cfc57b66, downloaded from Hugging Face. It is a CTranslate2 conversion of OpenAI Whisper base, under MIT. Upstream sources: https://github.com/SYSTRAN/faster-whisper, https://github.com/OpenNMT/CTranslate2, https://huggingface.co/Systran/faster-whisper-base, https://github.com/openai/whisper. Audio is processed locally, not uploaded. Existing optional Demucs stem-separation terms continue to apply when vocals are prepared for speech recognition. -## Android Full / Lab URL downloader - -Full and the Lab companion include youtubedl-android 0.18.1 (GNU GPL version 3), https://github.com/yausername/youtubedl-android/tree/0.18.1 . Those combined Android binaries are distributed under GPL-3.0; original AMP source notices and other component licenses remain in force. Lite, DJ, Cast, Podcasts and Remote do not link this dependency. The matching release includes the GPL text, exact AMP source/tag, upstream downloader source and build scripts, and the existing FFmpegKit corresponding-source bundle. See android/features/lab/assets/licenses/youtubedl-android/SOURCE.txt. - ## Barlow fonts The native desktop card interface embeds Barlow Regular and SemiBold diff --git a/android/app/build.gradle b/android/app/build.gradle index 4bd1526f..1626ec53 100644 --- a/android/app/build.gradle +++ b/android/app/build.gradle @@ -53,7 +53,6 @@ dependencies { fullImplementation 'com.google.android.gms:play-services-cast-framework:22.3.0' implementation 'androidx.appcompat:appcompat:1.7.1' fullImplementation 'dev.ffmpegkit-maintained:ffmpeg-kit-audio:8.1.9' - fullImplementation 'io.github.junkfood02.youtubedl-android:library:0.18.1' implementation 'androidx.media3:media3-exoplayer:1.8.1' implementation 'androidx.media3:media3-exoplayer-hls:1.8.1' implementation 'androidx.media3:media3-datasource-okhttp:1.8.1' diff --git a/android/app/src/androidTest/java/cloud/gitwide/ampverse/LabNavigationDeviceTest.java b/android/app/src/androidTest/java/cloud/gitwide/ampverse/LabNavigationDeviceTest.java index d1a13a42..600d8fa9 100644 --- a/android/app/src/androidTest/java/cloud/gitwide/ampverse/LabNavigationDeviceTest.java +++ b/android/app/src/androidTest/java/cloud/gitwide/ampverse/LabNavigationDeviceTest.java @@ -23,9 +23,9 @@ public class LabNavigationDeviceTest { UiDevice device=UiDevice.getInstance(InstrumentationRegistry.getInstrumentation()); try(ActivityScenario screen=ActivityScenario.launch(new Intent(context,cloud.gitwide.ampverse.lab.MainActivity.class))){ final Object[] original=new Object[1]; - screen.onActivity(a->{try{original[0]=a;set(a,"duration",69.744);set(a,"start",46.769);set(a,"end",69.744);set(a,"gainDb",3.0);set(a,"name","Lab layout fixture.mp3");((TextView)get(a,"filename")).setText("Lab layout fixture.mp3");float[] peaks=new float[2048];for(int i=0;i{try{original[0]=a;set(a,"duration",69.744);set(a,"start",46.769);set(a,"end",69.744);set(a,"gainDb",3.0);set(a,"name","Lab layout fixture.mp3");((TextView)get(a,"filename")).setText("Lab layout fixture.mp3");float[] peaks=new float[2048];for(int i=0;i{try{((ScrollView)get(a,"editorScroll")).fullScroll(View.FOCUS_DOWN);}catch(Exception e){throw new AssertionError(e);}}); InstrumentationRegistry.getInstrumentation().waitForIdleSync(); diff --git a/android/app/src/androidTest/java/cloud/gitwide/ampverse/ModuleScreenTest.java b/android/app/src/androidTest/java/cloud/gitwide/ampverse/ModuleScreenTest.java index 956a5bbb..1e920a05 100644 --- a/android/app/src/androidTest/java/cloud/gitwide/ampverse/ModuleScreenTest.java +++ b/android/app/src/androidTest/java/cloud/gitwide/ampverse/ModuleScreenTest.java @@ -13,7 +13,7 @@ public final class ModuleScreenTest { @Test public void eachSignedCompanionConnectsAndRendersItsRealScreen()throws Exception{ Context c=InstrumentationRegistry.getInstrumentation().getTargetContext();UiDevice device=UiDevice.getInstance(InstrumentationRegistry.getInstrumentation()); - String[] ids={"dj","cast","podcasts","remote","lab"};String[] labels={"Choose playlist","Find LAN stations","Browse categories","Discover devices","Download MP3"}; + String[] ids={"dj","cast","podcasts","remote","lab"};String[] labels={"Choose playlist","Find LAN stations","Browse categories","Discover devices","Open local audio"}; File captures=new File(c.getFilesDir(),"module-test-screenshots");captures.mkdirs(); for(int i=0;i 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(); @@ -95,6 +122,34 @@ private static void assertNotificationTransport(Context context,String expectedI 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())); @@ -408,6 +463,7 @@ public void playerDjFocusHandoffsKeepTheSharedHardwareClockMoving() throws Excep 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);} diff --git a/android/app/src/androidTest/java/cloud/gitwide/ampverse/lab/EditingSessionTest.java b/android/app/src/androidTest/java/cloud/gitwide/ampverse/lab/EditingSessionTest.java index 28b0a5b4..e07b45c1 100644 --- a/android/app/src/androidTest/java/cloud/gitwide/ampverse/lab/EditingSessionTest.java +++ b/android/app/src/androidTest/java/cloud/gitwide/ampverse/lab/EditingSessionTest.java @@ -73,6 +73,30 @@ void cleanup(File source){ } }finally{cleanup(source);} } + @Test public void previouslyImportedMp3StillOpensWithoutChangingOriginal()throws Exception{ + android.content.Context context=InstrumentationRegistry.getInstrumentation().getTargetContext(); + File directory=new File(context.getFilesDir(),"AMP Lab/downloads");assertTrue(directory.isDirectory()||directory.mkdirs()); + File source=File.createTempFile("retained-audio-",".mp3",directory); + assertTrue(ReturnCode.isSuccess(FFmpegKit.execute("-y -f lavfi -i sine=frequency=440:duration=2 -c:a libmp3lame \""+source+"\"").getReturnCode())); + byte[] original=java.nio.file.Files.readAllBytes(source.toPath()); + try(ActivityScenario screen=ActivityScenario.launch(MainActivity.class)){ + screen.onActivity(a->{a.input=null;findText(a.root,"Previously imported audio").performClick();}); + androidx.test.uiautomator.UiDevice device=androidx.test.uiautomator.UiDevice.getInstance(InstrumentationRegistry.getInstrumentation()); + androidx.test.uiautomator.UiObject2 item=device.wait(androidx.test.uiautomator.Until.findObject(androidx.test.uiautomator.By.text(source.getName())),5000); + assertNotNull("Existing imported MP3 must still be listed",item);item.click(); + java.util.concurrent.atomic.AtomicBoolean loaded=new java.util.concurrent.atomic.AtomicBoolean(); + long deadline=SystemClock.uptimeMillis()+15000; + while(!loaded.get()&&SystemClock.uptimeMillis()loaded.set(!a.busy&&source.getName().equals(a.name)&&a.duration>1&&a.waveform.length>0));SystemClock.sleep(50);} + assertTrue("Existing imported MP3 must open through the real waveform pipeline",loaded.get()); + screen.onActivity(a->{assertNotEquals(source,a.input);assertEquals(0,a.start,0);assertTrue(a.end>1);}); + assertArrayEquals("Opening must preserve the original MP3",original,java.nio.file.Files.readAllBytes(source.toPath())); + }finally{source.delete();} + } + private android.view.View findText(android.view.View root,String value){ + if(root instanceof android.widget.TextView&&value.contentEquals(((android.widget.TextView)root).getText()))return root; + if(root instanceof android.view.ViewGroup){android.view.ViewGroup group=(android.view.ViewGroup)root;for(int i=0;i result=new java.util.concurrent.atomic.AtomicReference<>();java.util.concurrent.atomic.AtomicReference error=new java.util.concurrent.atomic.AtomicReference<>();java.util.concurrent.CountDownLatch done=new java.util.concurrent.CountDownLatch(1);java.util.concurrent.atomic.AtomicInteger requests=new java.util.concurrent.atomic.AtomicInteger(); - try{ - assertTrue(com.arthenica.ffmpegkit.ReturnCode.isSuccess(com.arthenica.ffmpegkit.FFmpegKit.executeWithArguments(new String[]{"-y","-f","lavfi","-i","sine=frequency=440:duration=2","-c:a","pcm_s16le",original.toString()}).getReturnCode())); - byte[] bytes=java.nio.file.Files.readAllBytes(original.toPath()); - okhttp3.OkHttpClient client=new okhttp3.OkHttpClient.Builder().followRedirects(false).addInterceptor(chain->{String url=chain.request().url().toString();requests.incrementAndGet();byte[] body;String type; - if(url.contains("/s/")){body=("").getBytes(java.nio.charset.StandardCharsets.UTF_8);type="text/html";} - else if(url.equals(page)){body=("").getBytes(java.nio.charset.StandardCharsets.UTF_8);type="text/html";} - else if(url.equals(audio)){body=bytes;type="audio/wav";}else throw new IOException("Unexpected provider request"); - return new okhttp3.Response.Builder().request(chain.request()).protocol(okhttp3.Protocol.HTTP_1_1).code(200).message("OK").body(okhttp3.ResponseBody.create(okhttp3.MediaType.parse(type),body)).build();}).build(); - UrlDownload job=new UrlDownload(c,new UrlDownload.Listener(){public void progress(String s){}public void ready(File f){result.set(f);done.countDown();}public void failed(String s){error.set(s);done.countDown();}},new SunoImport(client)); - job.start("https://suno.com/s/fC9zFVvfrx0temjq");assertTrue("Import must complete",done.await(30,java.util.concurrent.TimeUnit.SECONDS));assertNull(error.get(),error.get());assertNotNull(result.get());assertEquals(3,requests.get()); - android.media.MediaMetadataRetriever verify=new android.media.MediaMetadataRetriever();try{verify.setDataSource(result.get().toString());assertTrue(Long.parseLong(verify.extractMetadata(android.media.MediaMetadataRetriever.METADATA_KEY_DURATION))>=1900);assertEquals("Suno import fixture",verify.extractMetadata(android.media.MediaMetadataRetriever.METADATA_KEY_TITLE));}finally{verify.release();} - assertArrayEquals(bytes,java.nio.file.Files.readAllBytes(original.toPath())); - }finally{original.delete();if(result.get()!=null)result.get().delete();} - } - @Test public void cancellationKillsTheNativeDownloadGroupPromptly()throws Exception{ - Context c=InstrumentationRegistry.getInstrumentation().getTargetContext();YoutubeDL.INSTANCE.init(c); - java.net.ServerSocket server=new java.net.ServerSocket(0,1,java.net.InetAddress.getByName("127.0.0.1"));java.util.concurrent.CountDownLatch connected=new java.util.concurrent.CountDownLatch(1),release=new java.util.concurrent.CountDownLatch(1); - Thread host=new Thread(()->{try(java.net.Socket socket=server.accept()){connected.countDown();release.await(15,java.util.concurrent.TimeUnit.SECONDS);}catch(Exception ignored){}});host.start(); - File work=java.nio.file.Files.createTempDirectory(c.getCacheDir().toPath(),"url-cancel-test-").toFile(); - UrlDownload job=new UrlDownload(c,new UrlDownload.Listener(){public void progress(String s){}public void ready(File f){}public void failed(String s){}}); - java.util.concurrent.atomic.AtomicReference result=new java.util.concurrent.atomic.AtomicReference<>(); - Thread worker=new Thread(()->{try{Method method=UrlDownload.class.getDeclaredMethod("execute",File.class,List.class,boolean.class);method.setAccessible(true);method.invoke(job,work,Arrays.asList("--simulate","--","http://127.0.0.1:"+server.getLocalPort()+"/slow"),false);}catch(Throwable error){result.set(error);}}); - try{worker.start();assertTrue("Native downloader must connect to the local fixture",connected.await(10,java.util.concurrent.TimeUnit.SECONDS));job.cancel();worker.join(3000);assertFalse("Cancel must not wait for the network timeout",worker.isAlive());assertNotNull(result.get());} - finally{job.cancel();release.countDown();server.close();host.join(1000);File[] files=work.listFiles();if(files!=null)for(File file:files)file.delete();work.delete();} - } - @Test public void localMp3ConversionPreservesSourceAndProducesPlayableAudio()throws Exception{ - Context c=InstrumentationRegistry.getInstrumentation().getTargetContext();File source=File.createTempFile("url-source-",".wav",c.getCacheDir()),output=File.createTempFile("url-result-",".mp3",c.getCacheDir()); - try{com.arthenica.ffmpegkit.FFmpegSession generated=com.arthenica.ffmpegkit.FFmpegKit.executeWithArguments(new String[]{"-y","-f","lavfi","-i","sine=frequency=440:duration=2","-c:a","pcm_s16le",source.toString()});assertTrue(com.arthenica.ffmpegkit.ReturnCode.isSuccess(generated.getReturnCode()));byte[] before=java.nio.file.Files.readAllBytes(source.toPath()); - com.arthenica.ffmpegkit.FFmpegSession converted=com.arthenica.ffmpegkit.FFmpegKit.executeWithArguments(new String[]{"-y","-i",source.toString(),"-vn","-c:a","libmp3lame","-b:a","256k",output.toString()});assertTrue(converted.getAllLogsAsString(),com.arthenica.ffmpegkit.ReturnCode.isSuccess(converted.getReturnCode()));assertArrayEquals(before,java.nio.file.Files.readAllBytes(source.toPath()));android.media.MediaMetadataRetriever verify=new android.media.MediaMetadataRetriever();try{verify.setDataSource(output.toString());assertTrue(Long.parseLong(verify.extractMetadata(android.media.MediaMetadataRetriever.METADATA_KEY_DURATION))>=1900);}finally{verify.release();} - }finally{source.delete();output.delete();} - } - @Test public void packagedPythonQuickJsAndExtractorExecuteWithoutDesktopBinaries()throws Exception{ - Context c=InstrumentationRegistry.getInstrumentation().getTargetContext();YoutubeDL.INSTANCE.init(c); - File bin=new File(c.getApplicationInfo().nativeLibraryDir);assertTrue(new File(bin,"libpython.so").isFile());assertTrue(new File(bin,"libqjs.so").isFile()); - UrlDownload job=new UrlDownload(c,new UrlDownload.Listener(){public void progress(String s){}public void ready(File f){fail("Version check cannot create a source");}public void failed(String s){fail(s);}}); - File work=java.nio.file.Files.createTempDirectory(c.getCacheDir().toPath(),"url-tools-test-").toFile(); - try{Method method=UrlDownload.class.getDeclaredMethod("execute",File.class,List.class,boolean.class);method.setAccessible(true);String version=(String)method.invoke(job,work,Arrays.asList("--version"),true);assertTrue(version,version.matches("(?s).*20[0-9]{2}\\.[0-9]{2}\\.[0-9]{2}.*"));} - finally{File[] files=work.listFiles();if(files!=null)for(File file:files)file.delete();work.delete();} - } -} diff --git a/android/app/src/main/java/cloud/gitwide/ampverse/MasterPcmQueue.java b/android/app/src/main/java/cloud/gitwide/ampverse/MasterPcmQueue.java index b28ee1c2..50b7d5b7 100644 --- a/android/app/src/main/java/cloud/gitwide/ampverse/MasterPcmQueue.java +++ b/android/app/src/main/java/cloud/gitwide/ampverse/MasterPcmQueue.java @@ -2,6 +2,10 @@ /** Bounded SPSC post-master ring: render producer, encoder consumer, no monitors. */ final class MasterPcmQueue { + enum Rejection { NONE, CLOSED, INVALID_RANGE, CAPACITY, DISCONTINUITY } + private volatile Rejection lastRejection=Rejection.NONE; + Rejection lastRejection(){return lastRejection;} + private boolean rejectOffer(Rejection reason){lastRejection=reason;return false;} private final short[] pcm; private final int capacity; private volatile long read,write,rejected; @@ -17,11 +21,13 @@ final class MasterPcmQueue { private long nextMasterFrame=-1; MasterPcmQueue(int capacity){if(capacity<1||capacity>OwnedPcmMixer.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||frames<0||(long)frames*2>input.length)return false; + 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(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;iaction.run());return b;} - static String description(String id){return switch(id){case "dj"->"Two-deck mixing, prepared playlists, Cue Decks and sampler.";case "lab"->"Trim, fades, gain, normalize and MP3 export. YouTube imports live here.";case "cast"->"Find stations, listen, save playlists with cues and use Google Cast.";case "remote"->"Discover and control your desktop Player or DJ.";default->"Browse public podcasts and RSS feeds; preview, subscribe and save episodes.";};} + static String description(String id){return switch(id){case "dj"->"Two-deck mixing, prepared playlists, Cue Decks and sampler.";case "lab"->"Local audio editing, trim, fades, gain, normalize and MP3 export.";case "cast"->"Find stations, listen, save playlists with cues and use Google Cast.";case "remote"->"Discover and control your desktop Player or DJ.";default->"Browse public podcasts and RSS feeds; preview, subscribe and save episodes.";};} void fetch(){if(fetching)return;fetching=true;new Thread(()->{try{JSONObject result=new ModuleDownloads().catalog();if(result.getInt("schema")!=1)throw new IllegalStateException("Unsupported module catalog");a.runOnUiThread(()->{fetching=false;catalog=result;status.setText("Official GitHub catalog · "+result.optString("version"));draw();});}catch(Exception error){a.runOnUiThread(()->{fetching=false;status.setText(error.getMessage()+". Installed modules still work offline.");draw();});}},"AMP module catalog").start();} String incompatibility(JSONObject entry){if(entry==null)return "No downloadable package is published in this catalog.";if(entry.optInt("api")!=1||entry.optInt("min_core",Integer.MAX_VALUE)>BuildConfig.VERSION_CODE)return "Update AMP Verse before installing this module.";if(entry.optInt("min_sdk",Integer.MAX_VALUE)>Build.VERSION.SDK_INT)return "This package needs a newer Android version.";return "";} ModuleInstallState state(JSONObject entry,PackageInfo installed,boolean included){return ModuleInstallState.resolve(included,BuildConfig.VERSION_CODE,installed==null?-1:installed.getLongVersionCode(),entry==null?0:entry.optLong("version_code"),incompatibility(entry).isEmpty());} diff --git a/android/app/src/main/java/cloud/gitwide/ampverse/PhoneMixSections.java b/android/app/src/main/java/cloud/gitwide/ampverse/PhoneMixSections.java index dd182c84..4849d7ee 100644 --- a/android/app/src/main/java/cloud/gitwide/ampverse/PhoneMixSections.java +++ b/android/app/src/main/java/cloud/gitwide/ampverse/PhoneMixSections.java @@ -5,11 +5,23 @@ /** Consumes the offline engine's portable decisions. No phone-side analysis. */ final class PhoneMixSections { - private static JSONObject fields(JSONObject p){JSONObject x=p.optJSONObject("extensions");return x==null?p:x;} - static boolean comparableProfile(JSONObject p){JSONObject x=fields(p),profile=x.optJSONObject("energy_profile");return profile!=null&&(profile.optInt("version")==2||profile.optInt("version")==1&&!x.has("perceptual_energy"));} + 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=fields(p).optJSONObject("energy_profile");double seconds=milliseconds/1000.; + 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;}} @@ -20,9 +32,9 @@ static double sectionEnergy(JSONObject p,long milliseconds){ 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 x=fields(p),plan=x.optJSONObject("auto_mix_sections"),analysis=p.optJSONObject("analysis"); + 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")||!x.optBoolean("energy_section_mixing",true)||plan==null||x.optJSONObject("energy_profile")==null||x.optJSONObject("energy_profile").optInt("version")!=2)return null; + 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; 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 65246fbb..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 double knownEnergy(Context context,MediaItem item){android.content.SharedPreferences prefs=context.getSharedPreferences("phone-track-details",0);double value;if(prefs.contains(item.mediaId+":energy"))value=prefs.getFloat(item.mediaId+":energy",Float.NaN);else value=PhoneMixSections.trackEnergy(DjEngine.preparation(item));return Double.isFinite(value)&&value>=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);} 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 5162e100..224aa26c 100644 --- a/android/app/src/main/java/cloud/gitwide/ampverse/PlaybackService.java +++ b/android/app/src/main/java/cloud/gitwide/ampverse/PlaybackService.java @@ -26,6 +26,19 @@ public final class PlaybackService extends MediaSessionService { 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 @@ -36,7 +49,7 @@ public final class PlaybackService extends MediaSessionService { &&(state==Player.STATE_READY||state==Player.STATE_BUFFERING))return; } } - super.onUpdateNotification(changed,startInForegroundRequired||notificationNeedsForeground(changed)); + super.onUpdateNotification(changed,notificationForegroundRequired||notificationNeedsForeground(changed)); } private static boolean notificationNeedsForeground(MediaSession source){ Player player=source.getPlayer();int state=player.getPlaybackState(); @@ -138,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; @@ -310,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/test/java/cloud/gitwide/ampverse/OwnedPcmMixerTest.java b/android/app/src/test/java/cloud/gitwide/ampverse/OwnedPcmMixerTest.java index b1c6c5cb..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()); } diff --git a/android/app/src/test/java/cloud/gitwide/ampverse/PhoneMixSectionsTest.java b/android/app/src/test/java/cloud/gitwide/ampverse/PhoneMixSectionsTest.java index 78c87399..4b1f8449 100644 --- a/android/app/src/test/java/cloud/gitwide/ampverse/PhoneMixSectionsTest.java +++ b/android/app/src/test/java/cloud/gitwide/ampverse/PhoneMixSectionsTest.java @@ -4,6 +4,28 @@ 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)); @@ -13,7 +35,7 @@ public class PhoneMixSectionsTest { } @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");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");} 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/app/src/test/java/cloud/gitwide/ampverse/lab/DownloadFilenameTest.java b/android/app/src/test/java/cloud/gitwide/ampverse/lab/DownloadFilenameTest.java deleted file mode 100644 index 7e0ace92..00000000 --- a/android/app/src/test/java/cloud/gitwide/ampverse/lab/DownloadFilenameTest.java +++ /dev/null @@ -1,12 +0,0 @@ -package cloud.gitwide.ampverse.lab; -import org.junit.Test; -import java.nio.charset.StandardCharsets; -import static org.junit.Assert.*; -public final class DownloadFilenameTest { - @Test public void namesRemainPortableAndLeaveRoomForUniqueSuffix(){assertEquals("_CON",UrlDownload.safeTitle("CON"));assertEquals("YouTube audio",UrlDownload.safeTitle("... "));String title=UrlDownload.safeTitle("😀".repeat(150)+"track");assertTrue(title.getBytes(StandardCharsets.UTF_8).length<=160);assertFalse(title.endsWith("."));assertEquals(-1,UrlDownload.safeTitle("bad:/\\\u0001*?\"name").indexOf('/'));assertFalse(title.endsWith("\ud83d"));} - @Test public void collidingDownloadIdentityCannotOverwriteACompletedSource()throws Exception{ - java.nio.file.Path dir=java.nio.file.Files.createTempDirectory("amp-publish-test-");java.io.File one=dir.resolve("first.pending").toFile(),two=dir.resolve("second.pending").toFile();java.util.UUID identity=java.util.UUID.randomUUID(); - try{java.nio.file.Files.write(one.toPath(),new byte[]{1,2,3});java.nio.file.Files.write(two.toPath(),new byte[]{4,5,6});java.io.File completed=UrlDownload.publish(one,dir.toFile(),"same title",identity);try{UrlDownload.publish(two,dir.toFile(),"same title",identity);fail("A completed source must never be replaced");}catch(java.nio.file.FileAlreadyExistsException expected){}assertArrayEquals(new byte[]{1,2,3},java.nio.file.Files.readAllBytes(completed.toPath()));assertArrayEquals(new byte[]{4,5,6},java.nio.file.Files.readAllBytes(two.toPath()));} - finally{try(java.util.stream.Stream paths=java.nio.file.Files.list(dir)){paths.forEach(path->{try{java.nio.file.Files.delete(path);}catch(java.io.IOException ignored){}});}java.nio.file.Files.delete(dir);} - } -} diff --git a/android/app/src/test/java/cloud/gitwide/ampverse/lab/MusicImportSourceTest.java b/android/app/src/test/java/cloud/gitwide/ampverse/lab/MusicImportSourceTest.java deleted file mode 100644 index d23e3f3f..00000000 --- a/android/app/src/test/java/cloud/gitwide/ampverse/lab/MusicImportSourceTest.java +++ /dev/null @@ -1,41 +0,0 @@ -package cloud.gitwide.ampverse.lab; - -import org.json.*; -import org.junit.Test; -import java.io.InputStream; -import java.nio.charset.StandardCharsets; -import static org.junit.Assert.*; - -public class MusicImportSourceTest { - @Test public void sharesTheDesktopProviderContract() throws Exception { - try(InputStream in=getClass().getClassLoader().getResourceAsStream("music-import-sources.json")) { - assertNotNull(in); - JSONArray cases=new JSONArray(new String(in.readAllBytes(),StandardCharsets.UTF_8)); - for(int n=0;nImportUrl.normalize(input)); - else {assertEquals(input,item.getString("url"),ImportUrl.normalize(input));assertEquals(item.getString("provider"),ImportUrl.provider(input).label);} - } - } - } - @Test public void rejectsCollectionsProtectedAudioAndSongSubstitution() throws Exception { - String url="https://artist.bandcamp.com/track/example"; - JSONObject info=new JSONObject().put("id","123").put("webpage_url",url).put("duration",180); - ImportUrl.validateInfo(url,info); - info.put("webpage_url","https://artist.bandcamp.com/track/another"); - assertThrows(IllegalArgumentException.class,()->ImportUrl.validateInfo(url,info)); - info.put("webpage_url",url).put("entries",new JSONArray()); - assertThrows(IllegalArgumentException.class,()->ImportUrl.validateInfo(url,info)); - info.remove("entries");info.put("has_drm",true); - assertThrows(IllegalArgumentException.class,()->ImportUrl.validateInfo(url,info)); - } - @Test public void rejectsUnknownDurationAndChecksYoutubeIdentity() throws Exception { - String url="https://www.youtube.com/watch?v=BaW_jenozKc"; - JSONObject info=new JSONObject().put("id","BaW_jenozKc").put("duration",180); - ImportUrl.validateInfo(url,info); - info.put("id","AAAAAAAAAAA"); - assertThrows(IllegalArgumentException.class,()->ImportUrl.validateInfo(url,info)); - info.put("id","BaW_jenozKc").put("duration",0); - assertThrows(IllegalArgumentException.class,()->ImportUrl.validateInfo(url,info)); - } -} diff --git a/android/app/src/test/java/cloud/gitwide/ampverse/lab/SunoImportTest.java b/android/app/src/test/java/cloud/gitwide/ampverse/lab/SunoImportTest.java deleted file mode 100644 index c4ffe013..00000000 --- a/android/app/src/test/java/cloud/gitwide/ampverse/lab/SunoImportTest.java +++ /dev/null @@ -1,40 +0,0 @@ -package cloud.gitwide.ampverse.lab; - -import org.json.*; -import org.junit.Test; -import static org.junit.Assert.*; - -public class SunoImportTest { - private static final String ID="0724d5a4-1344-4426-8334-55046528a845"; - private static final String PAGE="https://suno.com/song/"+ID; - private static final String AUDIO="https://cdn1.suno.ai/"+ID+".mp3"; - @Test public void hiddenProviderRoutingAcceptsShareSongAndCdnWithoutBroadeningYouTube(){ - assertEquals("https://suno.com/s/fC9zFVvfrx0temjq",ImportUrl.normalize("https://suno.com/s/fC9zFVvfrx0temjq?utm_source=app")); - assertEquals(PAGE,ImportUrl.normalize(PAGE+"?share=1"));assertEquals(AUDIO,ImportUrl.normalize(AUDIO)); - assertEquals("https://www.youtube.com/watch?v=abcdefghijk",ImportUrl.normalize("https://youtu.be/abcdefghijk")); - assertThrows(IllegalArgumentException.class,()->YouTubeUrl.normalize(PAGE)); - } - @Test public void hostileAndNonSongLinksAreRejected(){ - for(String url:new String[]{"https://suno.com.evil.test/song/"+ID,"http://suno.com/song/"+ID,"https://user@suno.com/song/"+ID,"https://suno.com:443/song/"+ID,"https://suno.com/playlist/"+ID,"https://cdn1.suno.ai/placeholder.mp3"})assertThrows(url,IllegalArgumentException.class,()->ImportUrl.normalize(url)); - assertThrows(IllegalArgumentException.class,()->SunoImport.audioUrl("https://cdn1.suno.ai/00000000-0000-0000-0000-000000000000.mp3",ID)); - } - @Test public void parsesMatchingNextRecordAndKeepsTitleAndSource()throws Exception{ - JSONObject song=new JSONObject().put("id",ID).put("status","complete").put("title","Faith & joy").put("audio_url",AUDIO).put("metadata",new JSONObject().put("duration",69.5)); - String html=""; - SunoImport.Song found=SunoImport.resolve(html,PAGE);assertEquals(AUDIO,found.audio);assertEquals("Faith & joy",found.title);assertEquals(PAGE,found.source);assertEquals(69.5,found.duration,0.01); - } - @Test public void explicitDisabledOrEncodedRecordsNeverUseAnotherAudioPath()throws Exception{ - JSONObject song=new JSONObject().put("id",ID).put("status","complete").put("audio_url",AUDIO).put("action_config",new JSONObject().put("actions",new JSONArray().put(new JSONObject().put("action_type","download").put("disabled",true)))); - String html=""; - assertThrows(IllegalArgumentException.class,()->SunoImport.resolve(html,PAGE)); - song.remove("action_config");song.remove("audio_url");song.put("media_urls",new JSONArray().put(new JSONObject().put("url",AUDIO).put("delivery","progressive").put("encoding","encrypted"))); - assertThrows(IllegalArgumentException.class,()->SunoImport.resolve("",PAGE)); - } - @Test public void legacyMetadataAndPublicProgressiveRecordsAreAccepted()throws Exception{ - SunoImport.Song legacy=SunoImport.resolve("",PAGE);assertEquals("Faith & joy",legacy.title); - JSONObject song=new JSONObject().put("id",ID).put("media_urls",new JSONArray().put(new JSONObject().put("url",AUDIO).put("delivery","progressive").put("encoding","identity"))); - assertEquals(AUDIO,SunoImport.resolve("",PAGE).audio); - assertEquals(ID,SunoImport.songId("","https://suno.com/s/abcd")); - assertThrows(IllegalArgumentException.class,()->SunoImport.resolve("no audio",PAGE)); - } -} diff --git a/android/app/src/test/java/cloud/gitwide/ampverse/lab/YouTubeUrlTest.java b/android/app/src/test/java/cloud/gitwide/ampverse/lab/YouTubeUrlTest.java deleted file mode 100644 index a26431b2..00000000 --- a/android/app/src/test/java/cloud/gitwide/ampverse/lab/YouTubeUrlTest.java +++ /dev/null @@ -1,8 +0,0 @@ -package cloud.gitwide.ampverse.lab; -import org.junit.Test; -import static org.junit.Assert.*; -public class YouTubeUrlTest { - @Test public void playlistParametersNeverSelectAPlaylist(){assertEquals("https://www.youtube.com/watch?v=BaW_jenozKc",YouTubeUrl.normalize("https://www.youtube.com/watch?v=BaW_jenozKc&list=anything&index=5"));} - @Test public void shortMobileAndLiveLinksNormalize(){for(String url:new String[]{"https://youtu.be/BaW_jenozKc?t=2","https://m.youtube.com/watch?v=BaW_jenozKc","https://youtube.com/shorts/BaW_jenozKc","https://youtube.com/live/BaW_jenozKc"})assertEquals("https://www.youtube.com/watch?v=BaW_jenozKc",YouTubeUrl.normalize(url));} - @Test public void rejectsPlaylistOnlyAndUntrustedSources(){for(String url:new String[]{"https://youtube.com/playlist?list=abc","https://youtube.com.evil.test/watch?v=BaW_jenozKc","https://youtube.com@evil.test/watch?v=BaW_jenozKc","file:///tmp/audio","https://youtube.com/watch?v=BaW_jenozKc&v=AAAAAAAAAAA","https://youtube.com/watch?v=short","http://youtube.com/watch?v=BaW_jenozKc","https://youtube.com:444/watch?v=BaW_jenozKc"}){try{YouTubeUrl.normalize(url);fail(url);}catch(IllegalArgumentException expected){assertFalse(expected.getMessage().isEmpty());}}} -} diff --git a/android/companion.gradle b/android/companion.gradle index 88c02799..436b629f 100644 --- a/android/companion.gradle +++ b/android/companion.gradle @@ -43,7 +43,6 @@ dependencies { implementation 'com.squareup.okhttp3:okhttp:4.12.0' if(ampModule == 'lab') { implementation 'dev.ffmpegkit-maintained:ffmpeg-kit-audio:8.1.9' - implementation 'io.github.junkfood02.youtubedl-android:library:0.18.1' } if(ampModule == 'cast') implementation 'com.google.android.gms:play-services-cast-framework:22.3.0' } diff --git a/android/features/cast/java/cloud/gitwide/ampverse/FullPhoneMp3Encoder.java b/android/features/cast/java/cloud/gitwide/ampverse/FullPhoneMp3Encoder.java index 8c4b9b62..2b8e7c2d 100644 --- a/android/features/cast/java/cloud/gitwide/ampverse/FullPhoneMp3Encoder.java +++ b/android/features/cast/java/cloud/gitwide/ampverse/FullPhoneMp3Encoder.java @@ -164,9 +164,13 @@ 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) { diff --git a/android/features/lab/assets/licenses/youtubedl-android/LICENSE b/android/features/lab/assets/licenses/youtubedl-android/LICENSE deleted file mode 100644 index f288702d..00000000 --- a/android/features/lab/assets/licenses/youtubedl-android/LICENSE +++ /dev/null @@ -1,674 +0,0 @@ - GNU GENERAL PUBLIC LICENSE - Version 3, 29 June 2007 - - Copyright (C) 2007 Free Software Foundation, Inc. - Everyone is permitted to copy and distribute verbatim copies - of this license document, but changing it is not allowed. - - Preamble - - The GNU General Public License is a free, copyleft license for -software and other kinds of works. - - The licenses for most software and other practical works are designed -to take away your freedom to share and change the works. By contrast, -the GNU General Public License is intended to guarantee your freedom to -share and change all versions of a program--to make sure it remains free -software for all its users. We, the Free Software Foundation, use the -GNU General Public License for most of our software; it applies also to -any other work released this way by its authors. You can apply it to -your programs, too. - - When we speak of free software, we are referring to freedom, not -price. Our General Public Licenses are designed to make sure that you -have the freedom to distribute copies of free software (and charge for -them if you wish), that you receive source code or can get it if you -want it, that you can change the software or use pieces of it in new -free programs, and that you know you can do these things. - - To protect your rights, we need to prevent others from denying you -these rights or asking you to surrender the rights. Therefore, you have -certain responsibilities if you distribute copies of the software, or if -you modify it: responsibilities to respect the freedom of others. - - For example, if you distribute copies of such a program, whether -gratis or for a fee, you must pass on to the recipients the same -freedoms that you received. You must make sure that they, too, receive -or can get the source code. And you must show them these terms so they -know their rights. - - Developers that use the GNU GPL protect your rights with two steps: -(1) assert copyright on the software, and (2) offer you this License -giving you legal permission to copy, distribute and/or modify it. - - For the developers' and authors' protection, the GPL clearly explains -that there is no warranty for this free software. For both users' and -authors' sake, the GPL requires that modified versions be marked as -changed, so that their problems will not be attributed erroneously to -authors of previous versions. - - Some devices are designed to deny users access to install or run -modified versions of the software inside them, although the manufacturer -can do so. This is fundamentally incompatible with the aim of -protecting users' freedom to change the software. The systematic -pattern of such abuse occurs in the area of products for individuals to -use, which is precisely where it is most unacceptable. Therefore, we -have designed this version of the GPL to prohibit the practice for those -products. If such problems arise substantially in other domains, we -stand ready to extend this provision to those domains in future versions -of the GPL, as needed to protect the freedom of users. - - Finally, every program is threatened constantly by software patents. -States should not allow patents to restrict development and use of -software on general-purpose computers, but in those that do, we wish to -avoid the special danger that patents applied to a free program could -make it effectively proprietary. To prevent this, the GPL assures that -patents cannot be used to render the program non-free. - - The precise terms and conditions for copying, distribution and -modification follow. - - TERMS AND CONDITIONS - - 0. Definitions. - - "This License" refers to version 3 of the GNU General Public License. - - "Copyright" also means copyright-like laws that apply to other kinds of -works, such as semiconductor masks. - - "The Program" refers to any copyrightable work licensed under this -License. Each licensee is addressed as "you". "Licensees" and -"recipients" may be individuals or organizations. - - To "modify" a work means to copy from or adapt all or part of the work -in a fashion requiring copyright permission, other than the making of an -exact copy. The resulting work is called a "modified version" of the -earlier work or a work "based on" the earlier work. - - A "covered work" means either the unmodified Program or a work based -on the Program. - - To "propagate" a work means to do anything with it that, without -permission, would make you directly or secondarily liable for -infringement under applicable copyright law, except executing it on a -computer or modifying a private copy. Propagation includes copying, -distribution (with or without modification), making available to the -public, and in some countries other activities as well. - - To "convey" a work means any kind of propagation that enables other -parties to make or receive copies. Mere interaction with a user through -a computer network, with no transfer of a copy, is not conveying. - - An interactive user interface displays "Appropriate Legal Notices" -to the extent that it includes a convenient and prominently visible -feature that (1) displays an appropriate copyright notice, and (2) -tells the user that there is no warranty for the work (except to the -extent that warranties are provided), that licensees may convey the -work under this License, and how to view a copy of this License. If -the interface presents a list of user commands or options, such as a -menu, a prominent item in the list meets this criterion. - - 1. Source Code. - - The "source code" for a work means the preferred form of the work -for making modifications to it. "Object code" means any non-source -form of a work. - - A "Standard Interface" means an interface that either is an official -standard defined by a recognized standards body, or, in the case of -interfaces specified for a particular programming language, one that -is widely used among developers working in that language. - - The "System Libraries" of an executable work include anything, other -than the work as a whole, that (a) is included in the normal form of -packaging a Major Component, but which is not part of that Major -Component, and (b) serves only to enable use of the work with that -Major Component, or to implement a Standard Interface for which an -implementation is available to the public in source code form. A -"Major Component", in this context, means a major essential component -(kernel, window system, and so on) of the specific operating system -(if any) on which the executable work runs, or a compiler used to -produce the work, or an object code interpreter used to run it. - - The "Corresponding Source" for a work in object code form means all -the source code needed to generate, install, and (for an executable -work) run the object code and to modify the work, including scripts to -control those activities. However, it does not include the work's -System Libraries, or general-purpose tools or generally available free -programs which are used unmodified in performing those activities but -which are not part of the work. For example, Corresponding Source -includes interface definition files associated with source files for -the work, and the source code for shared libraries and dynamically -linked subprograms that the work is specifically designed to require, -such as by intimate data communication or control flow between those -subprograms and other parts of the work. - - The Corresponding Source need not include anything that users -can regenerate automatically from other parts of the Corresponding -Source. - - The Corresponding Source for a work in source code form is that -same work. - - 2. Basic Permissions. - - All rights granted under this License are granted for the term of -copyright on the Program, and are irrevocable provided the stated -conditions are met. This License explicitly affirms your unlimited -permission to run the unmodified Program. The output from running a -covered work is covered by this License only if the output, given its -content, constitutes a covered work. This License acknowledges your -rights of fair use or other equivalent, as provided by copyright law. - - You may make, run and propagate covered works that you do not -convey, without conditions so long as your license otherwise remains -in force. You may convey covered works to others for the sole purpose -of having them make modifications exclusively for you, or provide you -with facilities for running those works, provided that you comply with -the terms of this License in conveying all material for which you do -not control copyright. Those thus making or running the covered works -for you must do so exclusively on your behalf, under your direction -and control, on terms that prohibit them from making any copies of -your copyrighted material outside their relationship with you. - - Conveying under any other circumstances is permitted solely under -the conditions stated below. Sublicensing is not allowed; section 10 -makes it unnecessary. - - 3. Protecting Users' Legal Rights From Anti-Circumvention Law. - - No covered work shall be deemed part of an effective technological -measure under any applicable law fulfilling obligations under article -11 of the WIPO copyright treaty adopted on 20 December 1996, or -similar laws prohibiting or restricting circumvention of such -measures. - - When you convey a covered work, you waive any legal power to forbid -circumvention of technological measures to the extent such circumvention -is effected by exercising rights under this License with respect to -the covered work, and you disclaim any intention to limit operation or -modification of the work as a means of enforcing, against the work's -users, your or third parties' legal rights to forbid circumvention of -technological measures. - - 4. Conveying Verbatim Copies. - - You may convey verbatim copies of the Program's source code as you -receive it, in any medium, provided that you conspicuously and -appropriately publish on each copy an appropriate copyright notice; -keep intact all notices stating that this License and any -non-permissive terms added in accord with section 7 apply to the code; -keep intact all notices of the absence of any warranty; and give all -recipients a copy of this License along with the Program. - - You may charge any price or no price for each copy that you convey, -and you may offer support or warranty protection for a fee. - - 5. Conveying Modified Source Versions. - - You may convey a work based on the Program, or the modifications to -produce it from the Program, in the form of source code under the -terms of section 4, provided that you also meet all of these conditions: - - a) The work must carry prominent notices stating that you modified - it, and giving a relevant date. - - b) The work must carry prominent notices stating that it is - released under this License and any conditions added under section - 7. This requirement modifies the requirement in section 4 to - "keep intact all notices". - - c) You must license the entire work, as a whole, under this - License to anyone who comes into possession of a copy. This - License will therefore apply, along with any applicable section 7 - additional terms, to the whole of the work, and all its parts, - regardless of how they are packaged. This License gives no - permission to license the work in any other way, but it does not - invalidate such permission if you have separately received it. - - d) If the work has interactive user interfaces, each must display - Appropriate Legal Notices; however, if the Program has interactive - interfaces that do not display Appropriate Legal Notices, your - work need not make them do so. - - A compilation of a covered work with other separate and independent -works, which are not by their nature extensions of the covered work, -and which are not combined with it such as to form a larger program, -in or on a volume of a storage or distribution medium, is called an -"aggregate" if the compilation and its resulting copyright are not -used to limit the access or legal rights of the compilation's users -beyond what the individual works permit. Inclusion of a covered work -in an aggregate does not cause this License to apply to the other -parts of the aggregate. - - 6. Conveying Non-Source Forms. - - You may convey a covered work in object code form under the terms -of sections 4 and 5, provided that you also convey the -machine-readable Corresponding Source under the terms of this License, -in one of these ways: - - a) Convey the object code in, or embodied in, a physical product - (including a physical distribution medium), accompanied by the - Corresponding Source fixed on a durable physical medium - customarily used for software interchange. - - b) Convey the object code in, or embodied in, a physical product - (including a physical distribution medium), accompanied by a - written offer, valid for at least three years and valid for as - long as you offer spare parts or customer support for that product - model, to give anyone who possesses the object code either (1) a - copy of the Corresponding Source for all the software in the - product that is covered by this License, on a durable physical - medium customarily used for software interchange, for a price no - more than your reasonable cost of physically performing this - conveying of source, or (2) access to copy the - Corresponding Source from a network server at no charge. - - c) Convey individual copies of the object code with a copy of the - written offer to provide the Corresponding Source. This - alternative is allowed only occasionally and noncommercially, and - only if you received the object code with such an offer, in accord - with subsection 6b. - - d) Convey the object code by offering access from a designated - place (gratis or for a charge), and offer equivalent access to the - Corresponding Source in the same way through the same place at no - further charge. You need not require recipients to copy the - Corresponding Source along with the object code. If the place to - copy the object code is a network server, the Corresponding Source - may be on a different server (operated by you or a third party) - that supports equivalent copying facilities, provided you maintain - clear directions next to the object code saying where to find the - Corresponding Source. Regardless of what server hosts the - Corresponding Source, you remain obligated to ensure that it is - available for as long as needed to satisfy these requirements. - - e) Convey the object code using peer-to-peer transmission, provided - you inform other peers where the object code and Corresponding - Source of the work are being offered to the general public at no - charge under subsection 6d. - - A separable portion of the object code, whose source code is excluded -from the Corresponding Source as a System Library, need not be -included in conveying the object code work. - - A "User Product" is either (1) a "consumer product", which means any -tangible personal property which is normally used for personal, family, -or household purposes, or (2) anything designed or sold for incorporation -into a dwelling. In determining whether a product is a consumer product, -doubtful cases shall be resolved in favor of coverage. For a particular -product received by a particular user, "normally used" refers to a -typical or common use of that class of product, regardless of the status -of the particular user or of the way in which the particular user -actually uses, or expects or is expected to use, the product. A product -is a consumer product regardless of whether the product has substantial -commercial, industrial or non-consumer uses, unless such uses represent -the only significant mode of use of the product. - - "Installation Information" for a User Product means any methods, -procedures, authorization keys, or other information required to install -and execute modified versions of a covered work in that User Product from -a modified version of its Corresponding Source. The information must -suffice to ensure that the continued functioning of the modified object -code is in no case prevented or interfered with solely because -modification has been made. - - If you convey an object code work under this section in, or with, or -specifically for use in, a User Product, and the conveying occurs as -part of a transaction in which the right of possession and use of the -User Product is transferred to the recipient in perpetuity or for a -fixed term (regardless of how the transaction is characterized), the -Corresponding Source conveyed under this section must be accompanied -by the Installation Information. But this requirement does not apply -if neither you nor any third party retains the ability to install -modified object code on the User Product (for example, the work has -been installed in ROM). - - The requirement to provide Installation Information does not include a -requirement to continue to provide support service, warranty, or updates -for a work that has been modified or installed by the recipient, or for -the User Product in which it has been modified or installed. Access to a -network may be denied when the modification itself materially and -adversely affects the operation of the network or violates the rules and -protocols for communication across the network. - - Corresponding Source conveyed, and Installation Information provided, -in accord with this section must be in a format that is publicly -documented (and with an implementation available to the public in -source code form), and must require no special password or key for -unpacking, reading or copying. - - 7. Additional Terms. - - "Additional permissions" are terms that supplement the terms of this -License by making exceptions from one or more of its conditions. -Additional permissions that are applicable to the entire Program shall -be treated as though they were included in this License, to the extent -that they are valid under applicable law. If additional permissions -apply only to part of the Program, that part may be used separately -under those permissions, but the entire Program remains governed by -this License without regard to the additional permissions. - - When you convey a copy of a covered work, you may at your option -remove any additional permissions from that copy, or from any part of -it. (Additional permissions may be written to require their own -removal in certain cases when you modify the work.) You may place -additional permissions on material, added by you to a covered work, -for which you have or can give appropriate copyright permission. - - Notwithstanding any other provision of this License, for material you -add to a covered work, you may (if authorized by the copyright holders of -that material) supplement the terms of this License with terms: - - a) Disclaiming warranty or limiting liability differently from the - terms of sections 15 and 16 of this License; or - - b) Requiring preservation of specified reasonable legal notices or - author attributions in that material or in the Appropriate Legal - Notices displayed by works containing it; or - - c) Prohibiting misrepresentation of the origin of that material, or - requiring that modified versions of such material be marked in - reasonable ways as different from the original version; or - - d) Limiting the use for publicity purposes of names of licensors or - authors of the material; or - - e) Declining to grant rights under trademark law for use of some - trade names, trademarks, or service marks; or - - f) Requiring indemnification of licensors and authors of that - material by anyone who conveys the material (or modified versions of - it) with contractual assumptions of liability to the recipient, for - any liability that these contractual assumptions directly impose on - those licensors and authors. - - All other non-permissive additional terms are considered "further -restrictions" within the meaning of section 10. If the Program as you -received it, or any part of it, contains a notice stating that it is -governed by this License along with a term that is a further -restriction, you may remove that term. If a license document contains -a further restriction but permits relicensing or conveying under this -License, you may add to a covered work material governed by the terms -of that license document, provided that the further restriction does -not survive such relicensing or conveying. - - If you add terms to a covered work in accord with this section, you -must place, in the relevant source files, a statement of the -additional terms that apply to those files, or a notice indicating -where to find the applicable terms. - - Additional terms, permissive or non-permissive, may be stated in the -form of a separately written license, or stated as exceptions; -the above requirements apply either way. - - 8. Termination. - - You may not propagate or modify a covered work except as expressly -provided under this License. Any attempt otherwise to propagate or -modify it is void, and will automatically terminate your rights under -this License (including any patent licenses granted under the third -paragraph of section 11). - - However, if you cease all violation of this License, then your -license from a particular copyright holder is reinstated (a) -provisionally, unless and until the copyright holder explicitly and -finally terminates your license, and (b) permanently, if the copyright -holder fails to notify you of the violation by some reasonable means -prior to 60 days after the cessation. - - Moreover, your license from a particular copyright holder is -reinstated permanently if the copyright holder notifies you of the -violation by some reasonable means, this is the first time you have -received notice of violation of this License (for any work) from that -copyright holder, and you cure the violation prior to 30 days after -your receipt of the notice. - - Termination of your rights under this section does not terminate the -licenses of parties who have received copies or rights from you under -this License. If your rights have been terminated and not permanently -reinstated, you do not qualify to receive new licenses for the same -material under section 10. - - 9. Acceptance Not Required for Having Copies. - - You are not required to accept this License in order to receive or -run a copy of the Program. Ancillary propagation of a covered work -occurring solely as a consequence of using peer-to-peer transmission -to receive a copy likewise does not require acceptance. However, -nothing other than this License grants you permission to propagate or -modify any covered work. These actions infringe copyright if you do -not accept this License. Therefore, by modifying or propagating a -covered work, you indicate your acceptance of this License to do so. - - 10. Automatic Licensing of Downstream Recipients. - - Each time you convey a covered work, the recipient automatically -receives a license from the original licensors, to run, modify and -propagate that work, subject to this License. You are not responsible -for enforcing compliance by third parties with this License. - - An "entity transaction" is a transaction transferring control of an -organization, or substantially all assets of one, or subdividing an -organization, or merging organizations. If propagation of a covered -work results from an entity transaction, each party to that -transaction who receives a copy of the work also receives whatever -licenses to the work the party's predecessor in interest had or could -give under the previous paragraph, plus a right to possession of the -Corresponding Source of the work from the predecessor in interest, if -the predecessor has it or can get it with reasonable efforts. - - You may not impose any further restrictions on the exercise of the -rights granted or affirmed under this License. For example, you may -not impose a license fee, royalty, or other charge for exercise of -rights granted under this License, and you may not initiate litigation -(including a cross-claim or counterclaim in a lawsuit) alleging that -any patent claim is infringed by making, using, selling, offering for -sale, or importing the Program or any portion of it. - - 11. Patents. - - A "contributor" is a copyright holder who authorizes use under this -License of the Program or a work on which the Program is based. The -work thus licensed is called the contributor's "contributor version". - - A contributor's "essential patent claims" are all patent claims -owned or controlled by the contributor, whether already acquired or -hereafter acquired, that would be infringed by some manner, permitted -by this License, of making, using, or selling its contributor version, -but do not include claims that would be infringed only as a -consequence of further modification of the contributor version. For -purposes of this definition, "control" includes the right to grant -patent sublicenses in a manner consistent with the requirements of -this License. - - Each contributor grants you a non-exclusive, worldwide, royalty-free -patent license under the contributor's essential patent claims, to -make, use, sell, offer for sale, import and otherwise run, modify and -propagate the contents of its contributor version. - - In the following three paragraphs, a "patent license" is any express -agreement or commitment, however denominated, not to enforce a patent -(such as an express permission to practice a patent or covenant not to -sue for patent infringement). To "grant" such a patent license to a -party means to make such an agreement or commitment not to enforce a -patent against the party. - - If you convey a covered work, knowingly relying on a patent license, -and the Corresponding Source of the work is not available for anyone -to copy, free of charge and under the terms of this License, through a -publicly available network server or other readily accessible means, -then you must either (1) cause the Corresponding Source to be so -available, or (2) arrange to deprive yourself of the benefit of the -patent license for this particular work, or (3) arrange, in a manner -consistent with the requirements of this License, to extend the patent -license to downstream recipients. "Knowingly relying" means you have -actual knowledge that, but for the patent license, your conveying the -covered work in a country, or your recipient's use of the covered work -in a country, would infringe one or more identifiable patents in that -country that you have reason to believe are valid. - - If, pursuant to or in connection with a single transaction or -arrangement, you convey, or propagate by procuring conveyance of, a -covered work, and grant a patent license to some of the parties -receiving the covered work authorizing them to use, propagate, modify -or convey a specific copy of the covered work, then the patent license -you grant is automatically extended to all recipients of the covered -work and works based on it. - - A patent license is "discriminatory" if it does not include within -the scope of its coverage, prohibits the exercise of, or is -conditioned on the non-exercise of one or more of the rights that are -specifically granted under this License. You may not convey a covered -work if you are a party to an arrangement with a third party that is -in the business of distributing software, under which you make payment -to the third party based on the extent of your activity of conveying -the work, and under which the third party grants, to any of the -parties who would receive the covered work from you, a discriminatory -patent license (a) in connection with copies of the covered work -conveyed by you (or copies made from those copies), or (b) primarily -for and in connection with specific products or compilations that -contain the covered work, unless you entered into that arrangement, -or that patent license was granted, prior to 28 March 2007. - - Nothing in this License shall be construed as excluding or limiting -any implied license or other defenses to infringement that may -otherwise be available to you under applicable patent law. - - 12. No Surrender of Others' Freedom. - - If conditions are imposed on you (whether by court order, agreement or -otherwise) that contradict the conditions of this License, they do not -excuse you from the conditions of this License. If you cannot convey a -covered work so as to satisfy simultaneously your obligations under this -License and any other pertinent obligations, then as a consequence you may -not convey it at all. For example, if you agree to terms that obligate you -to collect a royalty for further conveying from those to whom you convey -the Program, the only way you could satisfy both those terms and this -License would be to refrain entirely from conveying the Program. - - 13. Use with the GNU Affero General Public License. - - Notwithstanding any other provision of this License, you have -permission to link or combine any covered work with a work licensed -under version 3 of the GNU Affero General Public License into a single -combined work, and to convey the resulting work. The terms of this -License will continue to apply to the part which is the covered work, -but the special requirements of the GNU Affero General Public License, -section 13, concerning interaction through a network will apply to the -combination as such. - - 14. Revised Versions of this License. - - The Free Software Foundation may publish revised and/or new versions of -the GNU General Public License from time to time. Such new versions will -be similar in spirit to the present version, but may differ in detail to -address new problems or concerns. - - Each version is given a distinguishing version number. If the -Program specifies that a certain numbered version of the GNU General -Public License "or any later version" applies to it, you have the -option of following the terms and conditions either of that numbered -version or of any later version published by the Free Software -Foundation. If the Program does not specify a version number of the -GNU General Public License, you may choose any version ever published -by the Free Software Foundation. - - If the Program specifies that a proxy can decide which future -versions of the GNU General Public License can be used, that proxy's -public statement of acceptance of a version permanently authorizes you -to choose that version for the Program. - - Later license versions may give you additional or different -permissions. However, no additional obligations are imposed on any -author or copyright holder as a result of your choosing to follow a -later version. - - 15. Disclaimer of Warranty. - - THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY -APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT -HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY -OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, -THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR -PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM -IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF -ALL NECESSARY SERVICING, REPAIR OR CORRECTION. - - 16. Limitation of Liability. - - IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING -WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS -THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY -GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE -USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF -DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD -PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), -EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF -SUCH DAMAGES. - - 17. Interpretation of Sections 15 and 16. - - If the disclaimer of warranty and limitation of liability provided -above cannot be given local legal effect according to their terms, -reviewing courts shall apply local law that most closely approximates -an absolute waiver of all civil liability in connection with the -Program, unless a warranty or assumption of liability accompanies a -copy of the Program in return for a fee. - - END OF TERMS AND CONDITIONS - - How to Apply These Terms to Your New Programs - - If you develop a new program, and you want it to be of the greatest -possible use to the public, the best way to achieve this is to make it -free software which everyone can redistribute and change under these terms. - - To do so, attach the following notices to the program. It is safest -to attach them to the start of each source file to most effectively -state the exclusion of warranty; and each file should have at least -the "copyright" line and a pointer to where the full notice is found. - - - Copyright (C) - - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program. If not, see . - -Also add information on how to contact you by electronic and paper mail. - - If the program does terminal interaction, make it output a short -notice like this when it starts in an interactive mode: - - Copyright (C) - This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. - This is free software, and you are welcome to redistribute it - under certain conditions; type `show c' for details. - -The hypothetical commands `show w' and `show c' should show the appropriate -parts of the General Public License. Of course, your program's commands -might be different; for a GUI interface, you would use an "about box". - - You should also get your employer (if you work as a programmer) or school, -if any, to sign a "copyright disclaimer" for the program, if necessary. -For more information on this, and how to apply and follow the GNU GPL, see -. - - The GNU General Public License does not permit incorporating your program -into proprietary programs. If your program is a subroutine library, you -may consider it more useful to permit linking proprietary applications with -the library. If this is what you want to do, use the GNU Lesser General -Public License instead of this License. But first, please read -. diff --git a/android/features/lab/assets/licenses/youtubedl-android/SOURCE.txt b/android/features/lab/assets/licenses/youtubedl-android/SOURCE.txt deleted file mode 100644 index e2b2d0fb..00000000 --- a/android/features/lab/assets/licenses/youtubedl-android/SOURCE.txt +++ /dev/null @@ -1,28 +0,0 @@ -AMP Lab Android URL import dependencies - -youtubedl-android 0.18.1, GPL-3.0 -https://github.com/yausername/youtubedl-android/tree/0.18.1 -Corresponding source and native dependency build scripts: -https://github.com/yausername/youtubedl-android/archive/refs/tags/0.18.1.tar.gz - -This module packages the upstream Android Python/yt-dlp runtime and QuickJS. -The application does not download arbitrary executable add-ons. Runtime -updates are distributed in signed AMP Lab / AMP Verse Full APKs. - -yt-dlp and EJS: -https://github.com/yt-dlp/yt-dlp -https://github.com/yt-dlp/ejs -JavaScript-runtime setup: -https://github.com/yt-dlp/yt-dlp/wiki/EJS - -MP3 conversion uses the existing ffmpeg-kit-audio 8.1.9 dependency, whose -licenses and corresponding-source information are included alongside this -notice. The downloader wrapper's separate FFmpeg binary is not included. - -AMP Verse Full and AMP Lab binaries containing the GPL dependency are -distributed under the GNU GPL version 3. Original source notices and the -licenses of other components remain in force. AMP Verse Lite, DJ, Cast, -Podcasts and Remote do not link this downloader dependency. - -The exact AMP source and build instructions accompany the matching public -GitHub release at https://github.com/gitwide-cloud/amp-verse . diff --git a/android/features/lab/java/cloud/gitwide/ampverse/lab/ImportUrl.java b/android/features/lab/java/cloud/gitwide/ampverse/lab/ImportUrl.java deleted file mode 100644 index 69380476..00000000 --- a/android/features/lab/java/cloud/gitwide/ampverse/lab/ImportUrl.java +++ /dev/null @@ -1,53 +0,0 @@ -package cloud.gitwide.ampverse.lab; - -import java.net.URI; -import java.util.Locale; -import org.json.JSONObject; - -/** One explicit source per import; unsupported services never reach a generic extractor. */ -public final class ImportUrl { - private ImportUrl() {} - public enum Provider { - YOUTUBE("YouTube", "Youtube"), SUNO("Suno", ""), - SOUNDCLOUD("SoundCloud", "Soundcloud"), BANDCAMP("Bandcamp", "Bandcamp"); - public final String label, extractor; - Provider(String label, String extractor) { this.label=label;this.extractor=extractor; } - } - public static Provider provider(String input) { - URI uri; - try { uri=URI.create(input.trim()); } - catch(Exception error) { throw new IllegalArgumentException("Paste a complete music link."); } - if (!"https".equalsIgnoreCase(uri.getScheme()) || uri.getUserInfo()!=null || uri.getPort()!=-1) - throw new IllegalArgumentException("Use a secure music link without a username or custom port."); - String host=uri.getHost()==null?"":uri.getHost().toLowerCase(Locale.ROOT); - if(SunoImport.recognizes(input)) return Provider.SUNO; - switch(host) { - case "youtu.be":case "youtube.com":case "www.youtube.com":case "m.youtube.com":case "music.youtube.com":return Provider.YOUTUBE; - case "soundcloud.com":case "www.soundcloud.com":case "m.soundcloud.com":return Provider.SOUNDCLOUD; - case "pandora.com":case "www.pandora.com":throw new IllegalArgumentException("Pandora offline music stays in Pandora. It cannot be imported as an MP3 into AMP Verse."); - default: - if(host.matches("[a-z0-9-]+\\.bandcamp\\.com")&&!host.startsWith("www."))return Provider.BANDCAMP; - throw new IllegalArgumentException("This source is not supported. Use a YouTube, Suno, SoundCloud or Bandcamp song link, or open a downloaded audio file."); - } - } - public static String normalize(String input) { - Provider source=provider(input); - if(source==Provider.SUNO)return SunoImport.normalize(input); - if(source==Provider.YOUTUBE)return YouTubeUrl.normalize(input); - URI uri=URI.create(input.trim());String path=uri.getPath().replaceAll("/+$", ""); - if(!path.matches("/[A-Za-z0-9_-]+/[A-Za-z0-9_-]+"))throw new IllegalArgumentException("Choose one song, not a profile, album or playlist."); - String first=path.split("/")[1]; - if(source==Provider.BANDCAMP&&!first.equals("track")||source==Provider.SOUNDCLOUD&&java.util.Arrays.asList("discover","charts","search","you","sets","stations").contains(first))throw new IllegalArgumentException("Choose one song, not a profile, album or playlist."); - return "https://"+(source==Provider.SOUNDCLOUD?"soundcloud.com":uri.getHost().toLowerCase(Locale.ROOT))+path; - } - static void validateInfo(String input, JSONObject info) { - Provider source=provider(input); - if(info.has("entries")||info.optBoolean("is_live")||info.optBoolean("has_drm")||java.util.Arrays.asList("is_live","is_upcoming").contains(info.optString("live_status")))throw new IllegalArgumentException("Choose one completed, downloadable song; playlists, live broadcasts and protected audio are not imported."); - double duration=info.optDouble("duration",0); - if(!Double.isFinite(duration)||duration<=0||duration>14400)throw new IllegalArgumentException("Choose audio up to four hours long with a known duration."); - boolean same; - if(source==Provider.YOUTUBE)same=normalize(input).equals("https://www.youtube.com/watch?v="+info.optString("id")); - else try{same=normalize(input).equals(normalize(info.optString("webpage_url")));}catch(Exception error){same=false;} - if(!same)throw new IllegalArgumentException("The source returned a different song. No audio was imported."); - } -} diff --git a/android/features/lab/java/cloud/gitwide/ampverse/lab/MainActivity.java b/android/features/lab/java/cloud/gitwide/ampverse/lab/MainActivity.java index 705bc85a..3f2a4ac1 100644 --- a/android/features/lab/java/cloud/gitwide/ampverse/lab/MainActivity.java +++ b/android/features/lab/java/cloud/gitwide/ampverse/lab/MainActivity.java @@ -62,14 +62,8 @@ View navigation(){ volatile boolean foreground; private android.media.AudioManager focusManager; private android.media.AudioFocusRequest previewFocus; - private Uri completedDownload; - private final Runnable openCompletedDownload=new Runnable(){public void run(){if(isDestroyed()||!foreground||completedDownload==null)return;if(busy){handler.postDelayed(this,150);return;}Uri source=completedDownload;completedDownload=null;openSource(source);}}; boolean focusPreview(){if(!foreground)return false;if(focusManager==null)focusManager=(android.media.AudioManager)getSystemService(AUDIO_SERVICE);if(previewFocus==null)previewFocus=new android.media.AudioFocusRequest.Builder(android.media.AudioManager.AUDIOFOCUS_GAIN_TRANSIENT).setAudioAttributes(new android.media.AudioAttributes.Builder().setUsage(android.media.AudioAttributes.USAGE_MEDIA).setContentType(android.media.AudioAttributes.CONTENT_TYPE_MUSIC).build()).setOnAudioFocusChangeListener(change->{if(change<0)stop();},handler).build();return focusManager.requestAudioFocus(previewFocus)==android.media.AudioManager.AUDIOFOCUS_REQUEST_GRANTED;} void releasePreviewFocus(){if(focusManager!=null&&previewFocus!=null)focusManager.abandonAudioFocusRequest(previewFocus);} - UrlDownload urlDownload; - TextView urlStatus; - Button downloadButton, cancelDownload, openDownload; - File downloadedSource; MobileTimeline timeline; void timelineSection(){if(timeline==null)timeline=new MobileTimeline(this);timeline.attach();} String lastExportedEdit=""; @@ -77,57 +71,26 @@ View navigation(){ String editSignature(){return input==null?"":input.getName()+"|"+start+"|"+end+"|"+fadeIn+"|"+fadeOut+"|"+gainDb+"|"+(normalize!=null&&normalize.isChecked());} boolean hasEdits(){return input!=null&&(start>.001||Math.abs(end-duration)>.001||fadeIn>0||fadeOut>0||Math.abs(gainDb)>.001||(normalize!=null&&normalize.isChecked()))&&!editSignature().equals(lastExportedEdit);} void openSource(Uri uri){ - if(busy||urlDownload!=null)return; + if(busy)return; if(hasEdits())new android.app.AlertDialog.Builder(this).setTitle("Keep your current edit?") - .setMessage("Export it before opening another source. The downloaded original will stay in AMP Lab downloads.") + .setMessage("Export it before opening another source. Your original audio stays unchanged.") .setPositiveButton("Export edit",(d,w)->{pendingSource=uri;save();}) .setNeutralButton("Discard edits and open",(d,w)->{pendingSource=null;load(uri);}).setNegativeButton("Keep editing",(d,w)->pendingSource=null).show(); else load(uri); } - void urlSection(){ - LinearLayout form=column(),linkForm=column(),localForm=column(); - LinearLayout tabs=new LinearLayout(this);Button linkTab=new Button(this),localTab=new Button(this);linkTab.setText("Music link");localTab.setText("Local file");Retro.button(linkTab);Retro.button(localTab);linkTab.setSelected(true);linkTab.setTextColor(Retro.CYAN);tabs.addView(linkTab,new LinearLayout.LayoutParams(0,-2,1));tabs.addView(localTab,new LinearLayout.LayoutParams(0,-2,1));add(form,tabs);add(form,linkForm);add(form,localForm);localForm.setVisibility(View.GONE); - button(localForm,"Open local audio",v->pick());add(localForm,label("Choose audio from this phone or a connected drive. Your original stays unchanged.",14,Retro.appearance.muted)); - linkTab.setOnClickListener(v->{linkForm.setVisibility(View.VISIBLE);localForm.setVisibility(View.GONE);linkTab.setSelected(true);localTab.setSelected(false);linkTab.setTextColor(Retro.CYAN);localTab.setTextColor(Retro.appearance.muted);}); - localTab.setOnClickListener(v->{linkForm.setVisibility(View.GONE);localForm.setVisibility(View.VISIBLE);localTab.setSelected(true);linkTab.setSelected(false);localTab.setTextColor(Retro.CYAN);linkTab.setTextColor(Retro.appearance.muted);}); - EditText url=new EditText(this);url.setSingleLine(true);url.setHint("Paste a music link");url.setInputType(android.text.InputType.TYPE_CLASS_TEXT|android.text.InputType.TYPE_TEXT_VARIATION_URI);url.setTextColor(Retro.appearance.text);url.setHintTextColor(Retro.appearance.muted);url.setContentDescription("Music URL");url.setMinHeight(dp(48));LinearLayout entry=new LinearLayout(this);entry.addView(url,new LinearLayout.LayoutParams(0,-2,1));add(linkForm,entry); - LinearLayout urlActions=new LinearLayout(this);Button paste=new Button(this),inspect=new Button(this);paste.setText("Paste");inspect.setText("Inspect link");Retro.button(paste);Retro.button(inspect);entry.addView(paste,new LinearLayout.LayoutParams(-2,-2));urlActions.addView(inspect,new LinearLayout.LayoutParams(0,-2,1));add(linkForm,urlActions); - url.addTextChangedListener(new android.text.TextWatcher(){ - public void beforeTextChanged(CharSequence s,int start,int count,int after){} - public void onTextChanged(CharSequence text,int start,int before,int count){String source="Music";try{source=ImportUrl.provider(text.toString()).label;}catch(Exception ignored){}linkTab.setText(source+" link");url.setContentDescription(source+" song URL");} - public void afterTextChanged(android.text.Editable text){} + void localSourceSection(){ + LinearLayout form=column(); + button(form,"Open local audio",v->pick()); + add(form,label("Choose audio from this phone or a connected drive. Your original stays unchanged.",14,Retro.appearance.muted)); + button(form,"Previously imported audio",v->{ + File[] files=new File(getFilesDir(),"AMP Lab/downloads").listFiles((folder,name)->name.endsWith(".mp3")); + if(files==null||files.length==0){report("No previously imported audio.");return;} + java.util.Arrays.sort(files,(a,b)->Long.compare(b.lastModified(),a.lastModified())); + String[] names=new String[files.length];for(int i=0;iopenSource(Uri.fromFile(files[n]))).setNegativeButton("Close",null).show(); }); - paste.setOnClickListener(v->{android.content.ClipboardManager clipboard=(android.content.ClipboardManager)getSystemService(CLIPBOARD_SERVICE);if(clipboard.hasPrimaryClip()&&clipboard.getPrimaryClip().getItemCount()>0)url.setText(clipboard.getPrimaryClip().getItemAt(0).coerceToText(this));}); - inspect.setOnClickListener(v->{if(busy||urlDownload!=null)return;final String link;try{link=ImportUrl.normalize(url.getText().toString());}catch(Exception error){urlStatus.setText(error.getMessage());return;}inspectUrl(link);}); - - downloadButton=button(linkForm,"Download MP3",v->{ - if(busy||urlDownload!=null)return; - final String link;try{link=ImportUrl.normalize(url.getText().toString());}catch(Exception error){urlStatus.setText(error.getMessage());return;} - new android.app.AlertDialog.Builder(this).setTitle("Download into AMP Lab?") - .setMessage("Only download audio you own or have permission to use. One song will be downloaded, then opened for editing. The original MP3 is kept separately.") - .setPositiveButton("Download",(dialog,which)->beginDownload(link)).setNegativeButton("Cancel",null).show(); - }); - linkForm.removeView(downloadButton);urlActions.addView(downloadButton,new LinearLayout.LayoutParams(0,-2,1));add(form,label("MP3 · 256 kbps · One song per link. Conversion does not improve source quality.",14,Retro.appearance.muted)); - urlStatus=label("YouTube, downloadable Suno audio, SoundCloud or Bandcamp. One song per link.",13,Retro.appearance.muted);add(form,urlStatus); - cancelDownload=button(form,"Cancel download",v->{if(urlDownload!=null){urlStatus.setText("Cancelling…");urlDownload.cancel();}});cancelDownload.setVisibility(View.GONE); - openDownload=button(form,"Open downloaded MP3",v->{if(downloadedSource!=null)openSource(Uri.fromFile(downloadedSource));});openDownload.setVisibility(View.GONE); - button(form,"Downloaded audio",v->{File[] files=new File(getFilesDir(),"AMP Lab/downloads").listFiles((folder,name)->name.endsWith(".mp3"));if(files==null||files.length==0){urlStatus.setText("No completed downloads yet.");return;}java.util.Arrays.sort(files,(a,b)->Long.compare(b.lastModified(),a.lastModified()));String[] names=new String[files.length];for(int i=0;iopenSource(Uri.fromFile(files[n]))).setNegativeButton("Close",null).show();}); - Retro.primary(downloadButton,Retro.CYAN);addSection("IMPORT AUDIO",form); - } - void beginDownload(String link){ - downloadButton.setEnabled(false);cancelDownload.setVisibility(View.VISIBLE);openDownload.setVisibility(View.GONE); - urlDownload=new UrlDownload(this,new UrlDownload.Listener(){ - public void progress(String value){handler.post(()->{if(!isDestroyed())urlStatus.setText(value);});} - public void ready(File source){UrlDownload finished=urlDownload;handler.post(()->{urlDownload=null;if(isDestroyed())return;downloadedSource=source;downloadButton.setEnabled(true);cancelDownload.setVisibility(View.GONE);openDownload.setVisibility(View.VISIBLE);urlStatus.setText("Saved original MP3: "+source.getName());if(finished!=null&&finished.cancelled()){urlStatus.setText("Cancelled. The completed MP3 was kept in Downloaded audio.");return;}completedDownload=Uri.fromFile(source);handler.post(openCompletedDownload);});} - public void failed(String message){handler.post(()->{urlDownload=null;if(isDestroyed())return;downloadButton.setText("Retry download");downloadButton.setEnabled(true);cancelDownload.setVisibility(View.GONE);urlStatus.setText(message);});} - });urlDownload.start(link); + addSection("IMPORT AUDIO",form); } - void inspectUrl(String link){downloadButton.setEnabled(false);cancelDownload.setVisibility(View.VISIBLE);urlDownload=new UrlDownload(this,new UrlDownload.Listener(){ - public void progress(String value){handler.post(()->{if(!isDestroyed())urlStatus.setText(value);});} - public void ready(File file){} - public void failed(String message){handler.post(()->{urlDownload=null;if(isDestroyed())return;downloadButton.setEnabled(true);cancelDownload.setVisibility(View.GONE);urlStatus.setText(message);});} - public void inspected(org.json.JSONObject info){handler.post(()->{urlDownload=null;if(isDestroyed())return;downloadButton.setEnabled(true);cancelDownload.setVisibility(View.GONE);urlStatus.setText(info.optString("title","Audio")+(info.optDouble("duration",0)>0?" · "+time(info.optDouble("duration")):"")+"\nOne song · MP3 256 kbps · ready to download");});} - });urlDownload.inspect(link);} volatile int previewGeneration; Retro.Wave waveformView; float[] waveform=new float[0]; @@ -220,7 +183,7 @@ void licenses(String path){ }catch(IOException ex){report("Cannot open license: "+ex.getMessage());} } void pick(){ - if(busy||urlDownload!=null)return; + if(busy)return; Intent i=new Intent(Intent.ACTION_OPEN_DOCUMENT); i.addCategory(Intent.CATEGORY_OPENABLE);i.setType("audio/*");startActivityForResult(i,PICK); } @@ -374,7 +337,7 @@ void rebuildRestoredWaveform(File source){ try{org.json.JSONObject saved=SessionStore.snapshot(this);if(saved!=null)state.putString("editingSession",saved.toString());}catch(Exception ignored){} super.onSaveInstanceState(state); } - @Override protected void onDestroy(){handler.removeCallbacks(checkpoint);handler.removeCallbacks(openCompletedDownload);if(urlDownload!=null)urlDownload.cancel();if(timeline!=null)timeline.close();stop();super.onDestroy();} - @Override protected void onResume(){super.onResume();foreground=true;String next=getSharedPreferences("settings",MODE_PRIVATE).getString("theme","classic");if(!next.equals(themeId)){String snapshot=null;try{org.json.JSONObject saved=SessionStore.snapshot(this);if(saved!=null)snapshot=saved.toString();}catch(Exception ignored){}themeId=next;Retro.configure(this);RetroLayout.create(this);if(snapshot!=null)SessionStore.restore(this,snapshot);}handler.post(playbackTick);handler.post(openCompletedDownload);} - @Override protected void onPause(){foreground=false;handler.removeCallbacks(playbackTick);handler.removeCallbacks(checkpoint);handler.removeCallbacks(openCompletedDownload);SessionStore.save(this);stop();super.onPause();} + @Override protected void onDestroy(){handler.removeCallbacks(checkpoint);if(timeline!=null)timeline.close();stop();super.onDestroy();} + @Override protected void onResume(){super.onResume();foreground=true;String next=getSharedPreferences("settings",MODE_PRIVATE).getString("theme","classic");if(!next.equals(themeId)){String snapshot=null;try{org.json.JSONObject saved=SessionStore.snapshot(this);if(saved!=null)snapshot=saved.toString();}catch(Exception ignored){}themeId=next;Retro.configure(this);RetroLayout.create(this);if(snapshot!=null)SessionStore.restore(this,snapshot);}handler.post(playbackTick);} + @Override protected void onPause(){foreground=false;handler.removeCallbacks(playbackTick);handler.removeCallbacks(checkpoint);SessionStore.save(this);stop();super.onPause();} } diff --git a/android/features/lab/java/cloud/gitwide/ampverse/lab/RetroLayout.java b/android/features/lab/java/cloud/gitwide/ampverse/lab/RetroLayout.java index 402172a0..07a8b510 100644 --- a/android/features/lab/java/cloud/gitwide/ampverse/lab/RetroLayout.java +++ b/android/features/lab/java/cloud/gitwide/ampverse/lab/RetroLayout.java @@ -25,7 +25,7 @@ static void create(MainActivity a){ item.setOnClickListener(v->{if(which==0)a.pick();else if(which==1)editMenu(a); else if(which==2)tools(a);else about(a);}); }a.add(shell,menu); - a.urlSection(); + a.localSourceSection(); LinearLayout display=a.column();display.setPadding(a.dp(10),a.dp(5),a.dp(10),a.dp(5));display.setBackgroundColor(Retro.INK); a.clock=a.label("0:00.000 / 0:00.000",23,Retro.LED);a.clock.setTypeface(Typeface.MONOSPACE); a.filename=a.label("No audio loaded",18,Retro.appearance.text);a.add(display,a.filename);a.add(display,a.clock); diff --git a/android/features/lab/java/cloud/gitwide/ampverse/lab/SunoImport.java b/android/features/lab/java/cloud/gitwide/ampverse/lab/SunoImport.java deleted file mode 100644 index aaf71eb5..00000000 --- a/android/features/lab/java/cloud/gitwide/ampverse/lab/SunoImport.java +++ /dev/null @@ -1,106 +0,0 @@ -package cloud.gitwide.ampverse.lab; - -import java.io.*; -import java.net.URI; -import java.nio.charset.StandardCharsets; -import java.util.*; -import java.util.concurrent.TimeUnit; -import java.util.regex.*; -import okhttp3.*; -import org.json.*; - -/** Public single-song imports. Never guesses a CDN address or reads account credentials. */ -final class SunoImport { - static final String UNAVAILABLE="Suno has not provided a downloadable audio file for this link. Export it in Suno, then open the exported file in Lab."; - private static final String ID="[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12}"; - private static boolean pageHost(String host){return Arrays.asList("suno.com","www.suno.com","suno.ai","www.suno.ai").contains(host);} - private static boolean audioHost(String host){return host!=null&&(host.matches("cdn[0-9]+\\.suno\\.ai")||host.equals("d2lwuy8qc234o3.cloudfront.net"));} - static boolean recognizes(String input){try{String h=URI.create(input.trim()).getHost();return pageHost(h)||audioHost(h);}catch(Exception e){return false;}} - private static URI secure(String value){ - URI u=URI.create(value.trim()); - if(!"https".equalsIgnoreCase(u.getScheme())||u.getUserInfo()!=null||u.getPort()!=-1)throw new IllegalArgumentException("Use a secure Suno song link."); - return u; - } - static String normalize(String input){ - URI u=secure(input);String path=u.getPath().replaceAll("/+$",""); - if(audioHost(u.getHost())){String id=audioId(u);return audioUrl(u.toString(),id);} - if(!pageHost(u.getHost())||!(path.matches("/song/"+ID)||path.matches("/s/[A-Za-z0-9_-]{4,100}")))throw new IllegalArgumentException("Choose one Suno song or share link, not a profile or playlist."); - return "https://suno.com"+(path.startsWith("/song/")?path.toLowerCase(Locale.ROOT):path); - } - private static String audioId(URI u){String file=u.getPath().substring(u.getPath().lastIndexOf('/')+1);if(!file.matches(ID+"\\.(mp3|m4a|wav)"))throw new IllegalArgumentException(UNAVAILABLE);return file.substring(0,36);} - static String audioUrl(String input,String id){ - URI u=secure(input); - if(!audioHost(u.getHost())||!audioId(u).equalsIgnoreCase(id))throw new IllegalArgumentException(UNAVAILABLE); - return u.toString(); - } - static final class Song { - final String audio,title,source; final double duration; - Song(String audio,String title,String source,double duration){this.audio=audio;this.title=title;this.source=source;this.duration=duration;} - JSONObject info()throws JSONException{return new JSONObject().put("title",title).put("duration",duration).put("webpage_url",source);} - } - private static JSONObject record(Object value,String id,int depth){ - if(depth>64)return null; - if(value instanceof JSONObject){JSONObject o=(JSONObject)value;if(id.equalsIgnoreCase(o.optString("id"))&&(o.has("audio_url")||o.has("media_urls")))return o; - Iterator keys=o.keys();while(keys.hasNext()){JSONObject found=record(o.opt(keys.next()),id,depth+1);if(found!=null)return found;}} - else if(value instanceof JSONArray){JSONArray a=(JSONArray)value;for(int i=0;i").replace("&","&");} - private static String meta(String html,String property){ - Matcher tags=Pattern.compile("]{0,8192}>",Pattern.CASE_INSENSITIVE).matcher(html); - Pattern attrs=Pattern.compile("([\\w:-]+)\\s*=\\s*([\"'])(.*?)\\2",Pattern.DOTALL); - while(tags.find()){Map a=new HashMap<>();Matcher m=attrs.matcher(tags.group());while(m.find())a.put(m.group(1).toLowerCase(Locale.ROOT),entity(m.group(3)));if(property.equals(a.get("property")))return a.get("content");}return null; - } - static String songId(String html,String page){ - URI p=secure(page);if(p.getPath().matches("/song/"+ID))return p.getPath().substring(6); - String canonical=meta(html,"og:url");if(canonical!=null){URI u=secure(normalize(canonical));if(u.getPath().matches("/song/"+ID))return u.getPath().substring(6);} - throw new IllegalArgumentException("This Suno share link did not identify a song. Copy its full song link instead."); - } - static Song resolve(String html,String page){ - String id=songId(html,page),source="https://suno.com/song/"+id;List chunks=new ArrayList<>();chunks.add(html); - String marker="self.__next_f.push(";int pos=0;while((pos=html.indexOf(marker,pos))>=0){pos+=marker.length();try{Object v=new JSONTokener(html.substring(pos)).nextValue();if(v instanceof JSONArray){JSONArray a=(JSONArray)v;for(int i=0;i candidates=new ArrayList<>();if(chunk==html){Matcher scripts=Pattern.compile("]*>(.*?)",Pattern.DOTALL|Pattern.CASE_INSENSITIVE).matcher(html);while(scripts.find())candidates.add(scripts.group(1));}else candidates.addAll(Arrays.asList(chunk.split("\n"))); - for(String line:candidates){int colon=line.indexOf(':');String[] options=colon>=0?new String[]{line,line.substring(colon+1)}:new String[]{line};for(String text:options){Object value;try{value=new JSONTokener(text).nextValue();}catch(JSONException e){continue;}JSONObject r=record(value,id,0);if(r!=null){String title=r.optString("title",meta(html,"og:title"));JSONObject md=r.optJSONObject("metadata");return new Song(recordAudio(r,id),title==null?"Suno "+id:title,source,md==null?0:md.optDouble("duration",0));}}}} - String audio=meta(html,"og:audio"),title=meta(html,"og:title");if(audio!=null)return new Song(audioUrl(audio,id),title==null?"Suno "+id:title,source,0); - throw new IllegalArgumentException(UNAVAILABLE); - } - interface Progress {void update(String value);} - private final OkHttpClient client; - SunoImport(){this(new OkHttpClient.Builder().followRedirects(false).followSslRedirects(false).connectTimeout(10,TimeUnit.SECONDS).readTimeout(10,TimeUnit.SECONDS).callTimeout(120,TimeUnit.SECONDS).build());} - SunoImport(OkHttpClient client){this.client=client;} - private volatile Call active;private volatile boolean cancelled; - void cancel(){cancelled=true;Call call=active;if(call!=null)call.cancel();} - private void check()throws IOException{if(cancelled)throw new IOException("Download cancelled.");} - private Response get(String target)throws IOException{check();Call call=client.newCall(new Request.Builder().url(target).header("User-Agent","AMPVerse/1.1").build());active=call;if(cancelled)call.cancel();return call.execute();} - Song inspect(String input)throws Exception{ - String target=normalize(input);URI direct=URI.create(target);if(audioHost(direct.getHost()))return new Song(target,"Suno "+audioId(direct),"https://suno.com/song/"+audioId(direct),0); - for(int n=0;n<6;n++)try(Response r=get(target)){ - if(r.isRedirect()){String location=r.header("Location");if(location==null)throw new IOException(UNAVAILABLE);target=normalize(URI.create(target).resolve(location).toString());continue;} - if(!r.isSuccessful()||r.body()==null)throw new IOException(UNAVAILABLE); - ByteArrayOutputStream out=new ByteArrayOutputStream();copy(r.body(),out,4*1024*1024,null);String html=out.toString(StandardCharsets.UTF_8.name()); - if(URI.create(target).getPath().startsWith("/s/")){target="https://suno.com/song/"+songId(html,target);continue;} - return resolve(html,target); - }throw new IOException("The Suno link redirected too many times."); - } - void download(Song song,File target,Progress progress)throws Exception{ - String url=song.audio,id=URI.create(song.source).getPath().substring(6); - for(int n=0;n<6;n++)try(Response r=get(audioUrl(url,id))){ - if(r.isRedirect()){String location=r.header("Location");if(location==null)throw new IOException(UNAVAILABLE);url=audioUrl(URI.create(url).resolve(location).toString(),id);continue;} - if(!r.isSuccessful()||r.body()==null)throw new IOException(UNAVAILABLE); - try(OutputStream out=new FileOutputStream(target)){copy(r.body(),out,256L*1024*1024,progress);}if(target.length()==0)throw new IOException("Suno returned an empty audio file.");return; - }throw new IOException("Suno audio redirected too many times."); - } - private void copy(ResponseBody body,OutputStream out,long limit,Progress progress)throws IOException{ - if(body.contentLength()>limit)throw new IOException("Suno response exceeds the import size limit.");long count=0,last=0;byte[] buffer=new byte[65536];try(InputStream in=body.byteStream()){int n;while((n=in.read(buffer))!=-1){check();count+=n;if(count>limit)throw new IOException("Suno response exceeds the import size limit.");out.write(buffer,0,n);if(progress!=null&&count-last>=1024*1024){progress.update("Downloading Suno audio… "+count/(1024*1024)+" MB");last=count;}}}check(); - } -} diff --git a/android/features/lab/java/cloud/gitwide/ampverse/lab/UrlDownload.java b/android/features/lab/java/cloud/gitwide/ampverse/lab/UrlDownload.java deleted file mode 100644 index 9604b718..00000000 --- a/android/features/lab/java/cloud/gitwide/ampverse/lab/UrlDownload.java +++ /dev/null @@ -1,148 +0,0 @@ -package cloud.gitwide.ampverse.lab; - -import android.content.Context; -import android.media.MediaMetadataRetriever; -import android.system.Os; -import android.system.OsConstants; -import com.arthenica.ffmpegkit.FFmpegKit; -import com.arthenica.ffmpegkit.FFmpegSession; -import com.arthenica.ffmpegkit.ReturnCode; -import com.yausername.youtubedl_android.YoutubeDL; -import org.json.JSONObject; -import java.io.*; -import java.nio.charset.StandardCharsets; -import java.nio.file.Files; -import java.util.*; -import java.util.concurrent.*; - -/** Lab-only importer. Each worker has an isolated process group and temporary directory. */ -final class UrlDownload { - private static File bundledExtractor; - private static synchronized File extractor(Context context)throws Exception{ - if(bundledExtractor!=null&&bundledExtractor.isFile())return bundledExtractor; - File directory=new File(context.getNoBackupFilesDir(),"amp-lab-tools");if(!directory.isDirectory()&&!directory.mkdirs())throw new IOException("Cannot prepare the bundled download tools"); - File temporary=File.createTempFile("extractor-",".pending",directory); - try{java.security.MessageDigest digest=java.security.MessageDigest.getInstance("SHA-256"); - try(InputStream in=context.getResources().openRawResource(com.yausername.youtubedl_android.R.raw.ytdlp);FileOutputStream out=new FileOutputStream(temporary)){byte[] buffer=new byte[65536];int n;long count=0;while((n=in.read(buffer))!=-1){count+=n;if(count>32*1024*1024)throw new IOException("Bundled extractor exceeds its size limit");digest.update(buffer,0,n);out.write(buffer,0,n);}out.getFD().sync();} - StringBuilder hash=new StringBuilder();for(byte b:digest.digest())hash.append(String.format(Locale.ROOT,"%02x",b)); - File target=new File(directory,"yt-dlp-"+hash+".pyz"); - // Versioned immutable paths also avoid changing code under an active job. - Files.move(temporary.toPath(),target.toPath(),java.nio.file.StandardCopyOption.ATOMIC_MOVE,java.nio.file.StandardCopyOption.REPLACE_EXISTING); - bundledExtractor=target;return target; - }finally{temporary.delete();} - } - interface Listener { void progress(String value); void ready(File source); void failed(String message); default void inspected(JSONObject info){} } - private final Context context; - private final Listener listener; - private volatile boolean cancelled; - private volatile Process process; - private volatile File pidFile; - private volatile long conversion = -1; - private final SunoImport suno; - UrlDownload(Context context, Listener listener) { this(context,listener,new SunoImport()); } - UrlDownload(Context context, Listener listener,SunoImport suno) { this.context=context.getApplicationContext();this.listener=listener;this.suno=suno; } - void start(String url) { new Thread(()->run(url,false), "AMP Lab URL import").start(); } - void inspect(String url) { new Thread(()->run(url,true), "AMP Lab URL inspection").start(); } - void cancel() { - cancelled=true; - suno.cancel(); - if(conversion>=0) FFmpegKit.cancel(conversion); - killGroup(); - } - boolean cancelled(){return cancelled;} - static synchronized File publish(File source,File directory,String title,UUID identity)throws IOException{ - File completed=new File(directory,safeTitle(title)+"-"+identity+".mp3"); - try(RandomAccessFile durable=new RandomAccessFile(source,"rw")){durable.getFD().sync();} - // Both names live on the same private downloads filesystem. Android permits - // rename but SELinux denies hard links here. Serialize our import workers; - // move without REPLACE_EXISTING preserves any already completed download. - Files.move(source.toPath(),completed.toPath());return completed; - } - private synchronized void killGroup() { - File pid=pidFile; - if(pid!=null) try { - String value=new String(Files.readAllBytes(pid.toPath()),StandardCharsets.US_ASCII).trim(); - if(value.matches("[0-9]{1,10}")) { int group=Integer.parseInt(value);if(group>1)Os.kill(-group,OsConstants.SIGKILL); } - } catch(Exception ignored) { } - Process active=process;if(active!=null)active.destroyForcibly(); - } - private void check() throws IOException { if(cancelled)throw new IOException("Cancelled"); } - private String execute(File work,List options,boolean metadata)throws Exception { - check(); - File base=new File(context.getNoBackupFilesDir(),"youtubedl-android"); - File pythonHome=new File(base,"packages/python/usr"); - File bin=new File(context.getApplicationInfo().nativeLibraryDir); - File python=new File(bin,"libpython.so"),quickjs=new File(bin,"libqjs.so"),extractor=extractor(context); - if(!python.isFile()||!quickjs.isFile()||!extractor.isFile())throw new IOException("Download tools are missing. Update AMP Lab in Add-ons and retry."); - pidFile=new File(work,"worker.pid");Files.deleteIfExists(pidFile.toPath()); - // Own the process group instead of the wrapper's shell-based cancellation. - String entry="import os,sys,runpy; os.setsid(); open(sys.argv[1],'w').write(str(os.getpid())); sys.argv=sys.argv[2:]; runpy.run_path(sys.argv[0],run_name='__main__')"; - List args=new ArrayList<>(Arrays.asList(python.toString(),"-c",entry,pidFile.toString(),extractor.toString(),"--ignore-config","--no-playlist","--no-warnings","--socket-timeout","20","--retries","2","--no-cache-dir","--js-runtimes","quickjs:"+quickjs)); - args.addAll(options); - ProcessBuilder builder=new ProcessBuilder(args).directory(work).redirectErrorStream(true); - Map env=builder.environment();env.put("PYTHONHOME",pythonHome.toString());env.put("HOME",pythonHome.toString());env.put("LD_LIBRARY_PATH",new File(pythonHome,"lib").toString());env.put("SSL_CERT_FILE",new File(pythonHome,"etc/tls/cert.pem").toString());env.put("TMPDIR",work.toString());env.put("PATH",System.getenv("PATH")+":"+bin); - process=builder.start(); - // Cancellation can race startup before the PID file is written. - ScheduledExecutorService watchdog=Executors.newSingleThreadScheduledExecutor(); - long deadline=System.nanoTime()+TimeUnit.MINUTES.toNanos(metadata?2:60); - watchdog.scheduleAtFixedRate(()->{if(cancelled||System.nanoTime()>deadline){cancelled=true;killGroup();}},100,100,TimeUnit.MILLISECONDS); - StringBuilder output=new StringBuilder(); - try(BufferedReader reader=new BufferedReader(new InputStreamReader(process.getInputStream(),StandardCharsets.UTF_8))){ - String line;while((line=reader.readLine())!=null){ - check(); - if(metadata){if(output.length()+line.length()>2*1024*1024)throw new IOException("Video information is too large");output.append(line).append('\n');} - else {if(line.startsWith("[download]"))listener.progress(line.replace("[download]", "Downloading").trim());if(output.length()>8192)output.delete(0,4096);output.append(line).append('\n');} - } - int result=process.waitFor();check(); - if(result!=0)throw new IOException(readable(output.toString())); - return output.toString(); - }finally {killGroup();watchdog.shutdownNow();process=null;} - } - private static String readable(String error) { - String text=error.toLowerCase(Locale.ROOT); - if(text.contains("private")||text.contains("sign in")||text.contains("members-only")||text.contains("age-restricted"))return "This video requires access or sign-in. AMP Lab cannot download it."; - if(text.contains("unavailable")||text.contains("removed"))return "This video is unavailable."; - if(text.contains("space")||text.contains("permission denied"))return "Cannot write the download. Check storage space and retry."; - if(text.contains("timed out")||text.contains("network")||text.contains("resolve"))return "Network connection failed. Check your connection and retry."; - return "Music download failed. Update AMP Lab and retry. "+error.substring(Math.max(0,error.length()-400)).trim(); - } - static String safeTitle(String input){String title=input.replaceAll("[\\\\/:*?\"<>|\\p{Cntrl}]","_").trim();if(title.codePointCount(0,title.length())>100)title=title.substring(0,title.offsetByCodePoints(0,100));while(title.getBytes(StandardCharsets.UTF_8).length>160)title=title.substring(0,title.offsetByCodePoints(title.length(),-1));title=title.replaceAll("[. ]+$","");if(title.isEmpty())title="YouTube audio";if(title.matches("(?i)(CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])(?:\\..*)?"))title="_"+title;return title;} - private void run(String url,boolean inspectionOnly) { - File work=null; - try { - String video=ImportUrl.normalize(url);boolean isSuno=SunoImport.recognizes(video);check(); - File downloads=new File(context.getFilesDir(),"AMP Lab/downloads"); - if(!downloads.isDirectory()&&!downloads.mkdirs())throw new IOException("Cannot create AMP Lab downloads folder"); - work=Files.createTempDirectory(downloads.toPath(),".pending-").toFile(); - JSONObject info;SunoImport.Song song=null; - if(isSuno){listener.progress("Reading Suno song…");song=suno.inspect(video);info=song.info();} - else{listener.progress("Preparing download tools…");YoutubeDL.INSTANCE.init(context);check();listener.progress("Reading "+ImportUrl.provider(video).label+" song…");info=new JSONObject(execute(work,Arrays.asList("--use-extractors",ImportUrl.provider(video).extractor,"--dump-single-json","--skip-download","--",video),true));} - if(!isSuno)ImportUrl.validateInfo(video,info); - if(info.optBoolean("is_live")||info.has("entries"))throw new IOException("Choose one completed video, not a live stream or playlist."); - double duration=info.optDouble("duration",0);if(!Double.isFinite(duration)||(!isSuno&&duration<=0)||duration>14400)throw new IOException("Choose audio up to four hours long."); - if(inspectionOnly){check();listener.inspected(info);return;} - check();listener.progress("Downloading audio…"); - if(isSuno)suno.download(song,new File(work,"source.audio"),listener::progress); - else execute(work,Arrays.asList("--use-extractors",ImportUrl.provider(video).extractor,"-f","bestaudio/best","--newline","--no-overwrites","--max-filesize","256M","-o",new File(work,"source.%(ext)s").toString(),"--",video),false); - check();File[] sources=work.listFiles((dir,name)->name.startsWith("source.")&&!name.endsWith(".part")&&!name.endsWith(".ytdl")); - if(sources!=null&&sources.length==1&&sources[0].length()>256L*1024*1024)throw new IOException("Downloaded audio exceeds the 256 MB import limit."); - if(sources==null||sources.length!=1||sources[0].length()==0)throw new IOException("No complete audio file was downloaded"); - File mp3=new File(work,"converted.mp3");listener.progress("Converting to MP3 · 256 kbps…"); - List convert=new ArrayList<>(Arrays.asList("-nostdin","-v","error","-i",sources[0].toString(),"-vn","-map","0:a:0","-c:a","libmp3lame","-b:a","256k","-metadata","title="+info.optString("title","Audio"))); - for(String key:new String[]{"artist","album","release_date","webpage_url"}){String value=info.optString(key,"");if(!value.isEmpty())convert.addAll(Arrays.asList("-metadata",(key.equals("webpage_url")?"comment":key.equals("release_date")?"date":key)+"="+value));} - if(isSuno)convert.addAll(Arrays.asList("-metadata","comment=Suno source: "+song.source,"-metadata","source_service=Suno")); - convert.add(mp3.toString());CountDownLatch converted=new CountDownLatch(1);FFmpegSession session=FFmpegKit.executeWithArgumentsAsync(convert.toArray(new String[0]),finished->converted.countDown()); - conversion=session.getSessionId(); - if(cancelled)FFmpegKit.cancel(conversion); - // FFmpegKit completes on its own executor; waiting never blocks the UI. - converted.await(); - check();if(!ReturnCode.isSuccess(session.getReturnCode()))throw new IOException("MP3 conversion failed. The original edit was retained."); - MediaMetadataRetriever verify=new MediaMetadataRetriever();try{verify.setDataSource(mp3.toString());String length=verify.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION);if(length==null||Long.parseLong(length)<=0)throw new IOException("Converted audio could not be verified");}finally{verify.release();} - check();File completed=publish(mp3,downloads,info.optString("title","YouTube audio"),UUID.randomUUID()); - if(cancelled){listener.failed("Download cancelled; the completed MP3 was kept in Downloaded audio.");return;} - listener.ready(completed); - }catch(Exception error){String message=error.getMessage()==null?error.toString():error.getMessage();listener.failed(cancelled?"Download cancelled. Your edit and completed downloads were kept.":SunoImport.recognizes(url)?message:readable(message));} - finally{conversion=-1;killGroup();if(work!=null)cleanup(work);} - } - private static void cleanup(File directory){File[] entries=directory.listFiles();if(entries!=null)for(File file:entries){if(file.isDirectory())cleanup(file);else file.delete();}directory.delete();} -} diff --git a/android/features/lab/java/cloud/gitwide/ampverse/lab/YouTubeUrl.java b/android/features/lab/java/cloud/gitwide/ampverse/lab/YouTubeUrl.java deleted file mode 100644 index 176b7940..00000000 --- a/android/features/lab/java/cloud/gitwide/ampverse/lab/YouTubeUrl.java +++ /dev/null @@ -1,36 +0,0 @@ -package cloud.gitwide.ampverse.lab; - -import java.net.URI; -import java.net.URLDecoder; -import java.nio.charset.StandardCharsets; -import java.util.Locale; - -/** Deliberately accepts one public YouTube video, never an arbitrary extractor URL. */ -public final class YouTubeUrl { - private YouTubeUrl() {} - public static String normalize(String value) { - try { - URI uri = new URI(value.trim()); - String host = uri.getHost() == null ? "" : uri.getHost().toLowerCase(Locale.ROOT); - if (!"https".equalsIgnoreCase(uri.getScheme()) || uri.getUserInfo() != null || uri.getPort() != -1) - throw new IllegalArgumentException("Paste a secure YouTube video URL."); - String id = null, path = uri.getPath(); - if (host.equals("youtu.be")) id = path.substring(1); - else if (host.equals("youtube.com") || host.equals("www.youtube.com") || host.equals("m.youtube.com") || host.equals("music.youtube.com")) { - if (path.equals("/watch")) { - for (String part : (uri.getRawQuery() == null ? "" : uri.getRawQuery()).split("&")) { - String[] pair = part.split("=", 2); - if (pair.length == 2 && pair[0].equals("v")) { - if (id != null) throw new IllegalArgumentException("Use a URL for one video."); - id = URLDecoder.decode(pair[1], StandardCharsets.UTF_8.name()); - } - } - } else if (path.startsWith("/shorts/") || path.startsWith("/live/")) id = path.substring(path.lastIndexOf('/') + 1); - else if (path.equals("/playlist")) throw new IllegalArgumentException("Choose a video in the playlist, then paste its video URL."); - } - if (id == null || !id.matches("[A-Za-z0-9_-]{11}")) throw new IllegalArgumentException("Paste a YouTube video link, not a channel or playlist-only link."); - return "https://www.youtube.com/watch?v=" + id; - } catch (IllegalArgumentException error) { throw error; } - catch (Exception error) { throw new IllegalArgumentException("That YouTube URL is not valid."); } - } -} 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 ec0a251f..da4bfe89 100644 --- a/apps/amp-cast/src/radio.rs +++ b/apps/amp-cast/src/radio.rs @@ -853,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/lab.rs b/apps/amp-player/src/lab.rs index eda40533..31411770 100644 --- a/apps/amp-player/src/lab.rs +++ b/apps/amp-player/src/lab.rs @@ -14,7 +14,6 @@ pub struct Arrangement { timeline: timeline::Timeline, editor: crate::lab_editor::Editor, recorder: recorder::Recorder, - youtube: crate::lab_youtube::Panel, tab: usize, demo_loaded: bool, status: String, @@ -54,12 +53,6 @@ impl Arrangement { self.tab = 0; self.editor.load_path(path); } - if let Some(path) = self.youtube.poll(ui.ctx()) { - self.tab = 0; - self.timeline.stop(); - let loaded = self.editor.load_path(path); - self.youtube.opened(loaded); - } let previous = self.tab; let wide = ui.available_width() > 900.; ui.horizontal_top(|ui| { @@ -119,7 +112,6 @@ impl Arrangement { self.editor.load_path(path); self.demo_loaded = true; } - self.youtube.show(ui); egui::ScrollArea::vertical() .id_salt("lab-workspace") .max_height(ui.available_height()) diff --git a/apps/amp-player/src/lab_editor.rs b/apps/amp-player/src/lab_editor.rs index ebb51df2..93a0f373 100644 --- a/apps/amp-player/src/lab_editor.rs +++ b/apps/amp-player/src/lab_editor.rs @@ -353,7 +353,33 @@ impl Editor { } } fn command(name: &str) -> Command { - crate::lab_youtube::audio_command(name) + // Retain existing explicit codec locations after removing the downloader UI. + let configured = crate::theme::settings_path() + .and_then(|p| std::fs::read_to_string(p.with_file_name("lab-tools-directory.txt")).ok()) + .map(|p| PathBuf::from(p.trim())); + let environment = std::env::var_os("AMP_LAB_TOOLS").map(PathBuf::from); + let executable = if cfg!(windows) { + format!("{name}.exe") + } else { + name.to_owned() + }; + if let Some(path) = configured + .into_iter() + .chain(environment) + .map(|dir| dir.join(&executable)) + .find(|path| path.is_file()) + { + #[cfg(windows)] + { + use std::os::windows::process::CommandExt; + let mut command = Command::new(path); + command.creation_flags(0x08000000); + return command; + } + #[cfg(not(windows))] + return Command::new(path); + } + amp_core::command(name) } pub(super) fn duration(p: &Path) -> Result { let o = command("ffprobe") @@ -886,7 +912,7 @@ mod tests { } #[test] #[ignore = "requires AMP_LAB_LOADED_MP3 and FFmpeg; real Lab open pipeline"] - fn downloaded_mp3_loads_waveform_and_keeps_source() { + fn local_mp3_loads_waveform_and_keeps_source() { let path = PathBuf::from(std::env::var_os("AMP_LAB_LOADED_MP3").unwrap()); let bytes = std::fs::read(&path).unwrap(); let mut editor = Editor::default(); diff --git a/apps/amp-player/src/lab_music_source.rs b/apps/amp-player/src/lab_music_source.rs deleted file mode 100644 index 29f6ab0c..00000000 --- a/apps/amp-player/src/lab_music_source.rs +++ /dev/null @@ -1,157 +0,0 @@ -//! Explicit provider selection for the Lab download engine. No generic extractor fallback. -use serde_json::Value; - -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub(super) enum Provider { - YouTube, - Suno, - SoundCloud, - Bandcamp, -} -impl Provider { - pub(super) fn label(self) -> &'static str { - match self { - Self::YouTube => "YouTube", - Self::Suno => "Suno", - Self::SoundCloud => "SoundCloud", - Self::Bandcamp => "Bandcamp", - } - } - pub(super) fn extractor(self) -> &'static str { - match self { - Self::YouTube => "Youtube", - Self::SoundCloud => "Soundcloud", - Self::Bandcamp => "Bandcamp", - Self::Suno => "", - } - } -} -pub(super) fn provider(input: &str) -> Result { - let u = url::Url::parse(input.trim()).map_err(|_| "Paste a complete music link.")?; - if u.scheme() != "https" - || !u.username().is_empty() - || u.password().is_some() - || u.port().is_some() - { - return Err("Use a secure music link without a username or custom port.".into()); - } - let host = u.host_str().unwrap_or(""); - if super::suno::recognizes(input) { - return Ok(Provider::Suno); - } - match host { - "youtu.be" | "youtube.com" | "www.youtube.com" | "m.youtube.com" | "music.youtube.com" => Ok(Provider::YouTube), - "soundcloud.com" | "www.soundcloud.com" | "m.soundcloud.com" => Ok(Provider::SoundCloud), - "pandora.com" | "www.pandora.com" => Err("Pandora offline music stays in Pandora. It cannot be imported as an MP3 into AMP Verse.".into()), - _ if host.ends_with(".bandcamp.com") && host.split('.').count() == 3 && !host.starts_with("www.") => Ok(Provider::Bandcamp), - _ => Err("This source is not supported. Use a YouTube, Suno, SoundCloud or Bandcamp song link, or open a downloaded audio file.".into()), - } -} -pub(super) fn normalize(input: &str) -> Result { - let source = provider(input)?; - match source { - Provider::YouTube => super::video_url(input), - Provider::Suno => super::suno::canonical_url(input), - Provider::SoundCloud | Provider::Bandcamp => { - let u = url::Url::parse(input.trim()).map_err(|_| "Invalid music link.")?; - let path = u.path().trim_end_matches('/'); - let parts: Vec<_> = path.trim_start_matches('/').split('/').collect(); - if parts.len() != 2 - || parts.iter().any(|p| { - p.is_empty() - || !p - .bytes() - .all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_') - }) - { - return Err("Choose one song, not a profile, album or playlist.".into()); - } - if source == Provider::Bandcamp && parts[0] != "track" - || source == Provider::SoundCloud - && ["discover", "charts", "search", "you", "sets", "stations"] - .contains(&parts[0]) - { - return Err("Choose one song, not a profile, album or playlist.".into()); - } - let host = if source == Provider::SoundCloud { - "soundcloud.com" - } else { - u.host_str().unwrap_or("") - }; - Ok(format!("https://{host}{path}")) - } - } -} -pub(super) fn validate_info(input: &str, info: &Value) -> Result<(), String> { - let source = provider(input)?; - if info.get("entries").is_some() - || info["is_live"] == true - || info["has_drm"] == true - || matches!( - info["live_status"].as_str(), - Some("is_live" | "is_upcoming") - ) - { - return Err("Choose one completed, downloadable song; playlists, live broadcasts and protected audio are not imported.".into()); - } - let duration = info["duration"] - .as_f64() - .filter(|n| n.is_finite() && *n > 0. && *n <= 14400.); - if duration.is_none() { - return Err("Choose audio up to four hours long with a known duration.".into()); - } - let identity_matches = if source == Provider::YouTube { - info["id"] - .as_str() - .is_some_and(|id| input.ends_with(&format!("v={id}"))) - } else { - info["webpage_url"] - .as_str() - .and_then(|s| normalize(s).ok()) - .as_deref() - == Some(input) - }; - if !identity_matches { - return Err("The source returned a different song. No audio was imported.".into()); - } - Ok(()) -} - -#[cfg(test)] -mod tests { - use super::*; - #[test] - fn shared_provider_contract() { - let fixtures: Value = serde_json::from_str(include_str!( - "../../../crates/amp-core/tests/fixtures/music-import-sources.json" - )) - .unwrap(); - for case in fixtures.as_array().unwrap() { - let input = case["input"].as_str().unwrap(); - match case["url"].as_str() { - Some(expected) => { - assert_eq!(normalize(input).unwrap(), expected, "{input}"); - assert_eq!( - provider(input).unwrap().label(), - case["provider"].as_str().unwrap() - ); - } - None => assert!(normalize(input).is_err(), "{input}"), - } - } - } - #[test] - fn metadata_cannot_switch_song_or_expand_a_collection() { - let url = "https://artist.bandcamp.com/track/example"; - let mut info = serde_json::json!({"id":"123", "webpage_url":url,"duration":180}); - assert!(validate_info(url, &info).is_ok()); - info["webpage_url"] = Value::String("https://artist.bandcamp.com/track/another".into()); - assert!(validate_info(url, &info).is_err()); - info["webpage_url"] = Value::String(url.into()); - info["entries"] = serde_json::json!([]); - assert!(validate_info(url, &info).is_err()); - info.as_object_mut().unwrap().remove("entries"); - info["has_drm"] = Value::Bool(true); - assert!(validate_info(url, &info).is_err()); - } -} diff --git a/apps/amp-player/src/lab_suno.rs b/apps/amp-player/src/lab_suno.rs deleted file mode 100644 index 16a278f4..00000000 --- a/apps/amp-player/src/lab_suno.rs +++ /dev/null @@ -1,652 +0,0 @@ -//! Public Suno song imports. No cookies, guessed CDN paths, or restricted-media fallback. -use super::*; -const LIMIT: u64 = 256 * 1024 * 1024; -const UNAVAILABLE: &str = "Suno has not provided a downloadable audio file for this link. Download it through Suno's own export menu, then open that file in Lab."; - -fn audio_host(host: &str) -> bool { - host.strip_prefix("cdn") - .and_then(|s| s.strip_suffix(".suno.ai")) - .is_some_and(|n| !n.is_empty() && n.bytes().all(|b| b.is_ascii_digit())) - || host == "d2lwuy8qc234o3.cloudfront.net" -} -pub(super) fn recognizes(input: &str) -> bool { - url::Url::parse(input.trim()).ok().is_some_and(|u| { - matches!( - u.host_str(), - Some("suno.com" | "www.suno.com" | "suno.ai" | "www.suno.ai") - ) || audio_host(u.host_str().unwrap_or("")) - }) -} -fn audio_id(u: &url::Url) -> Option<&str> { - let file = u.path_segments()?.next_back()?; - [".mp3", ".m4a", ".wav"] - .iter() - .find_map(|ext| file.strip_suffix(ext).filter(|id| uuid(id))) -} -fn uuid(id: &str) -> bool { - id.len() == 36 - && id.bytes().enumerate().all(|(i, b)| { - if [8, 13, 18, 23].contains(&i) { - b == b'-' - } else { - b.is_ascii_hexdigit() - } - }) -} -pub(super) fn canonical_url(input: &str) -> Result { - let u = url::Url::parse(input.trim()).map_err(|_| "Paste a complete Suno song link.")?; - if u.scheme() != "https" - || !recognizes(input) - || !u.username().is_empty() - || u.password().is_some() - || u.port().is_some() - { - return Err("Use an ordinary https://suno.com/song/ link.".into()); - } - if audio_host(u.host_str().unwrap_or("")) { - return audio_url(u.as_str(), audio_id(&u).ok_or(UNAVAILABLE)?); - } - let path = u.path().trim_end_matches('/'); - let valid = path.strip_prefix("/song/").is_some_and(uuid) - || path.strip_prefix("/s/").is_some_and(|s| { - (4..=100).contains(&s.len()) - && s.bytes() - .all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_') - }); - if !valid { - return Err("Choose a single Suno song or share link, not a profile or playlist.".into()); - } - Ok(if let Some(id) = path.strip_prefix("/song/") { - format!("https://suno.com/song/{}", id.to_ascii_lowercase()) - } else { - format!("https://suno.com{path}") - }) -} -pub(super) fn song_page(input: &str) -> Option { - let canonical = canonical_url(input).ok()?; - let parsed = url::Url::parse(&canonical).ok()?; - Some(if let Some(id) = audio_id(&parsed) { - format!("https://suno.com/song/{id}") - } else { - canonical - }) -} -fn agent() -> ureq::Agent { - ureq::Agent::config_builder() - .timeout_connect(Some(Duration::from_secs(10))) - .timeout_per_read(Some(Duration::from_secs(5))) - .timeout_recv_response(Some(Duration::from_secs(20))) - .timeout_global(Some(Duration::from_secs(120))) - .max_redirects(0) - .http_status_as_error(false) - .build() - .into() -} -fn get(agent: &ureq::Agent, target: &str) -> Result, String> { - agent - .get(target) - .header("User-Agent", "AMPVerse/1.1") - .call() - .map_err(|e| format!("Could not read the Suno link: {e}")) -} -fn meta(html: &str, property: &str) -> Option { - for fragment in html.split('<').filter(|s| s.starts_with("meta ")) { - let tag = fragment.split('>').next()?.trim_end_matches('/'); - let xml = format!("<{tag}/>"); - if let Ok(doc) = roxmltree::Document::parse(&xml) { - let node = doc.root_element(); - if node.attribute("property") == Some(property) { - return node.attribute("content").map(str::to_owned); - } - } - } - None -} -fn json_strings(text: &str, key: &str) -> Vec { - let needle = format!("\"{key}\":"); - text.split(&needle) - .skip(1) - .filter_map(|part| { - serde_json::Deserializer::from_str(part.trim_start()) - .into_iter::() - .next()? - .ok() - }) - .collect() -} -fn audio_url(input: &str, id: &str) -> Result { - let u = url::Url::parse(input).map_err(|_| UNAVAILABLE)?; - let host = u.host_str().unwrap_or(""); - let known = audio_host(host); - let file = u - .path_segments() - .and_then(|mut p| p.next_back()) - .unwrap_or(""); - if u.scheme() != "https" - || !known - || !u.username().is_empty() - || u.password().is_some() - || u.port().is_some() - || ![ - format!("{id}.mp3"), - format!("{id}.m4a"), - format!("{id}.wav"), - ] - .contains(&file.to_owned()) - { - return Err(UNAVAILABLE.into()); - } - Ok(u.into()) -} -fn song_record<'a>(value: &'a serde_json::Value, id: &str) -> Option<&'a serde_json::Value> { - match value { - serde_json::Value::Object(fields) => { - if fields.get("id").and_then(|v| v.as_str()) == Some(id) - && (fields.contains_key("audio_url") || fields.contains_key("media_urls")) - { - return Some(value); - } - fields.values().find_map(|v| song_record(v, id)) - } - serde_json::Value::Array(values) => values.iter().find_map(|v| song_record(v, id)), - _ => None, - } -} -fn record_audio(record: &serde_json::Value, id: &str) -> Result { - if record["drm"] == true || record["is_encrypted"] == true { - return Err(UNAVAILABLE.into()); - } - if record["status"].as_str().is_some_and(|s| s != "complete") { - return Err("This Suno song is not ready to download yet.".into()); - } - if record["action_config"]["actions"] - .as_array() - .is_some_and(|actions| { - actions.iter().any(|action| { - matches!( - action["action_type"].as_str(), - Some("download" | "download_audio" | "download_song") - ) && (action["disabled"] == true || action["visible"] == false) - }) - }) - { - return Err(UNAVAILABLE.into()); - } - if let Some(url) = record["audio_url"] - .as_str() - .and_then(|s| audio_url(s, id).ok()) - { - return Ok(url); - } - // Modern public pages publish progressive audio here; never guess a URL from the song ID. - record["media_urls"] - .as_array() - .into_iter() - .flatten() - .filter(|media| { - media["delivery"] == "progressive" - && media["encoding"] - .as_str() - .is_none_or(|encoding| matches!(encoding, "identity" | "none" | "plain")) - && media["drm"] != true - && media["is_encrypted"] != true - }) - .find_map(|media| media["url"].as_str().and_then(|s| audio_url(s, id).ok())) - .ok_or_else(|| UNAVAILABLE.into()) -} -fn resolve(html: &str, id: &str) -> Result<(String, String), String> { - let mut chunks = vec![html.to_owned()]; - for fragment in html.split("self.__next_f.push(").skip(1) { - if let Some(Ok(serde_json::Value::Array(values))) = - serde_json::Deserializer::from_str(fragment) - .into_iter() - .next() - { - chunks.extend( - values - .into_iter() - .filter_map(|v| v.as_str().map(str::to_owned)), - ); - } - } - for text in &chunks { - for line in text.lines() { - let payload = line.split_once(':').map_or(line, |(_, body)| body); - for candidate in [line, payload] { - if let Ok(value) = serde_json::from_str(candidate) - && let Some(record) = song_record(&value, id) - { - let audio = record_audio(record, id)?; - let title = record["title"] - .as_str() - .map(str::to_owned) - .or_else(|| meta(html, "og:title")) - .unwrap_or_else(|| format!("Suno {id}")); - return Ok((audio, safe_name(&title))); - } - } - } - } - let mut urls: Vec = chunks - .iter() - .flat_map(|text| json_strings(text, "audio_url")) - .collect(); - if urls.is_empty() - && let Some(og) = meta(html, "og:audio") - { - urls.push(og); - } - let audio = urls - .iter() - .find_map(|s| audio_url(s, id).ok()) - .ok_or(UNAVAILABLE)?; - let title = meta(html, "og:title").unwrap_or_else(|| format!("Suno {id}")); - Ok((audio, safe_name(&title))) -} -fn read_page( - agent: &ureq::Agent, - initial: &str, - cancel: &AtomicBool, -) -> Result<(String, String), String> { - let mut target = canonical_url(initial)?; - for _ in 0..6 { - cancelled(cancel)?; - let mut response = get(agent, &target)?; - if response.status().is_redirection() { - let location = response - .headers() - .get("location") - .and_then(|v| v.to_str().ok()) - .ok_or(UNAVAILABLE)?; - let next = url::Url::parse(&target) - .unwrap() - .join(location) - .map_err(|_| UNAVAILABLE)?; - target = canonical_url(next.as_str())?; - continue; - } - if !response.status().is_success() { - return Err(UNAVAILABLE.into()); - } - let mut bytes = Vec::new(); - response - .body_mut() - .as_reader() - .take(4 * 1024 * 1024 + 1) - .read_to_end(&mut bytes) - .map_err(|e| e.to_string())?; - if bytes.len() > 4 * 1024 * 1024 { - return Err("Suno returned an oversized page.".into()); - } - let html = - String::from_utf8(bytes).map_err(|_| "Suno returned invalid song information.")?; - if url::Url::parse(&target).unwrap().path().starts_with("/s/") { - let next = meta(&html, "og:url").ok_or( - "This Suno share link did not identify a song. Copy its full song link instead.", - )?; - target = canonical_url(&next)?; - continue; - } - return Ok((target, html)); - } - Err("The Suno link redirected too many times. Copy the full song link instead.".into()) -} -fn copy_audio( - mut input: impl Read, - output: &mut impl Write, - cancel: &AtomicBool, - tx: &mpsc::SyncSender, - total: Option, -) -> Result<(), String> { - if total.is_some_and(|n| n > LIMIT) { - return Err("Suno audio exceeds the 256 MB import limit.".into()); - } - let mut count = 0u64; - let mut buffer = [0; 65536]; - loop { - cancelled(cancel)?; - let n = input.read(&mut buffer).map_err(|e| e.to_string())?; - if n == 0 { - break; - } - count += n as u64; - if count > LIMIT { - return Err("Suno audio exceeds the 256 MB import limit.".into()); - } - output.write_all(&buffer[..n]).map_err(|e| e.to_string())?; - progress( - tx, - "Downloading Suno audio...", - total - .filter(|n| *n > 0) - .map(|n| (count as f32 / n as f32).min(1.)), - ); - } - if count == 0 { - return Err("Suno returned an empty audio file.".into()); - } - Ok(()) -} -fn audio_response( - agent: &ureq::Agent, - initial: &str, - id: &str, - cancel: &AtomicBool, -) -> Result, String> { - let mut target = audio_url(initial, id)?; - for _ in 0..6 { - cancelled(cancel)?; - let response = get(agent, &target)?; - if response.status().is_redirection() { - let next = response - .headers() - .get("location") - .and_then(|v| v.to_str().ok()) - .ok_or(UNAVAILABLE)?; - let next = url::Url::parse(&target) - .unwrap() - .join(next) - .map_err(|_| UNAVAILABLE)?; - target = audio_url(next.as_str(), id)?; - } else if response.status().is_success() { - return Ok(response); - } else { - return Err(UNAVAILABLE.into()); - } - } - Err("Suno audio redirected too many times.".into()) -} -fn plain_audio_header(bytes: &[u8]) -> bool { - bytes.starts_with(b"ID3") - || bytes.starts_with(b"OggS") - || bytes.starts_with(b"fLaC") - || (bytes.len() >= 2 && bytes[0] == 0xff && bytes[1] & 0xe0 == 0xe0) - || (bytes.len() >= 12 && bytes.starts_with(b"RIFF") && &bytes[8..12] == b"WAVE") - || (bytes.len() >= 8 && &bytes[4..8] == b"ftyp") -} -pub(super) fn download( - input: &str, - dir: &Path, - tools: &Tools, - cancel: &AtomicBool, - tx: &mpsc::SyncSender, -) -> Result { - let agent = agent(); - progress(tx, "Reading Suno song...", None); - let initial = canonical_url(input)?; - let initial_url = url::Url::parse(&initial).unwrap(); - let (canonical, audio, title, id) = if audio_host(initial_url.host_str().unwrap_or("")) { - let id = audio_id(&initial_url).ok_or(UNAVAILABLE)?.to_owned(); - ( - format!("https://suno.com/song/{id}"), - initial.clone(), - format!("Suno {id}"), - id, - ) - } else { - let (canonical, html) = read_page(&agent, &initial, cancel)?; - let parsed = url::Url::parse(&canonical).unwrap(); - let id = parsed - .path() - .strip_prefix("/song/") - .ok_or(UNAVAILABLE)? - .to_owned(); - let (audio, title) = resolve(&html, &id)?; - (canonical, audio, title, id) - }; - let mut response = audio_response(&agent, &audio, &id, cancel)?; - let content = response - .headers() - .get("content-type") - .and_then(|v| v.to_str().ok()) - .unwrap_or(""); - if !content.starts_with("audio/") && !content.starts_with("application/octet-stream") { - return Err("Suno did not return a downloadable audio file.".into()); - } - let total = response - .headers() - .get("content-length") - .and_then(|v| v.to_str().ok()) - .and_then(|s| s.parse().ok()); - fs::create_dir_all(dir).map_err(|e| e.to_string())?; - let work = tempfile::Builder::new() - .prefix(".amp-lab-suno-") - .tempdir_in(dir) - .map_err(|e| e.to_string())?; - let source = work.path().join("source.audio"); - copy_audio( - response.body_mut().as_reader(), - &mut fs::File::create(&source).map_err(|e| e.to_string())?, - cancel, - tx, - total, - )?; - let mut header = [0u8; 12]; - let read = fs::File::open(&source) - .map_err(|e| e.to_string())? - .read(&mut header) - .map_err(|e| e.to_string())?; - if !plain_audio_header(&header[..read]) { - return Err("Suno returned encoded playback data rather than a standard audio file. Use Suno's export menu and open the exported audio in Lab.".into()); - } - convert_publish( - &source, - dir, - tools, - cancel, - tx, - ImportLabel { - name: &title, - id: &id, - suno_source: Some(&canonical), - metadata: None, - }, - ) -} -#[cfg(test)] -mod tests { - use super::*; - const ID: &str = "ab39a04d-b2e6-463b-9b8e-ddea725422f5"; - #[test] - #[ignore = "live Suno availability; requires AMP_SUNO_TEST_URL and real FFmpeg"] - fn live_public_suno_import() { - let input = std::env::var("AMP_SUNO_TEST_URL").expect("Set an accessible Suno song URL"); - let dir = tempfile::tempdir().unwrap(); - let tools = Tools::audio_only().unwrap(); - let (tx, _rx) = mpsc::sync_channel(64); - let result = download(&input, dir.path(), &tools, &AtomicBool::new(false), &tx).unwrap(); - let duration = crate::lab_editor::duration(&result).unwrap(); - assert!(duration > 30., "Downloaded only a placeholder: {duration}"); - let mut editor = crate::lab_editor::Editor::default(); - assert!(editor.load_path(result)); - println!("Suno public audio downloaded, converted and decoded: {duration:.1} seconds"); - } - #[test] - #[ignore = "requires real FFmpeg/ffprobe; no Suno account or network"] - fn local_codec_import_opens_in_lab_and_preserves_source() { - let tools = Tools::audio_only().unwrap(); - let dir = tempfile::tempdir().unwrap(); - let input = dir.path().join("source.wav"); - let (tx, _rx) = mpsc::sync_channel(64); - let cancel = AtomicBool::new(false); - let mut generate = Command::new(&tools.ffmpeg); - generate - .args([ - "-n", - "-hide_banner", - "-loglevel", - "error", - "-f", - "lavfi", - "-i", - "sine=frequency=440:duration=0.5", - ]) - .arg(&input); - run(generate, &cancel, &tx, Duration::from_secs(15)).unwrap(); - let original = fs::read(&input).unwrap(); - let destination = dir.path().join("downloads"); - fs::create_dir(&destination).unwrap(); - let saved = convert_publish( - &input, - &destination, - &tools, - &cancel, - &tx, - ImportLabel { - name: "Suno codec fixture", - id: ID, - suno_source: Some("https://suno.com/song/ab39a04d-b2e6-463b-9b8e-ddea725422f5"), - metadata: None, - }, - ) - .unwrap(); - assert!(crate::lab_editor::duration(&saved).unwrap() > 0.); - let mut probe = Command::new(&tools.probe); - probe - .args([ - "-v", - "quiet", - "-show_entries", - "format_tags=title,comment", - "-of", - "json", - ]) - .arg(&saved); - let info: serde_json::Value = - serde_json::from_str(&run(probe, &cancel, &tx, Duration::from_secs(10)).unwrap()) - .unwrap(); - assert_eq!(info["format"]["tags"]["title"], "Suno codec fixture"); - assert!( - info["format"]["tags"]["comment"] - .as_str() - .unwrap() - .contains("Suno source: https://suno.com/song/") - ); - let mut editor = crate::lab_editor::Editor::default(); - assert!(editor.load_path(saved.clone())); - let prep = amp_core::preparation::load(&saved).unwrap(); - assert!(amp_core::music_annotations::marked( - &prep, - amp_core::music_annotations::Category::AiGenerated - )); - assert_eq!(prep.extensions["source_service"], "suno"); - assert_eq!( - prep.extensions["source_url"], - "https://suno.com/song/ab39a04d-b2e6-463b-9b8e-ddea725422f5" - ); - assert_eq!(fs::read(&input).unwrap(), original); - assert_eq!( - fs::read_dir(&destination) - .unwrap() - .filter_map(Result::ok) - .filter(|e| e.path().extension().is_some_and(|ext| ext == "mp3")) - .count(), - 1 - ); - } - #[test] - fn validates_song_share_and_untrusted_links() { - assert_eq!( - canonical_url(&format!("https://www.suno.com/song/{ID}?utm_source=x")).unwrap(), - format!("https://suno.com/song/{ID}") - ); - assert!(canonical_url("https://suno.com/s/abcDEF123").is_ok()); - assert!(canonical_url(&format!("https://cdn1.suno.ai/{ID}.mp3")).is_ok()); - assert!(canonical_url("https://cdn1.suno.ai/silence.mp3").is_err()); - for u in [ - "https://suno.com/playlist/abc", - "https://suno.com.evil.test/song/x", - "https://suno.com@127.0.0.1/song/x", - "http://suno.com/song/x", - "https://suno.com:9876/song/x", - ] { - assert!(canonical_url(u).is_err()); - } - } - #[test] - fn selects_exact_song_not_silence_or_recommended_tracks() { - let record = format!( - r#"0:{{"audio_url":"https://cdn1.suno.ai/silence.mp3","other":{{"audio_url":"https://cdn1.suno.ai/{ID}.mp3"}}}}"# - ); - let flight = serde_json::json!([1, record]); - let html = format!( - r#""# - ); - let (audio, title) = resolve(&html, ID).unwrap(); - assert_eq!(audio, format!("https://cdn1.suno.ai/{ID}.mp3")); - assert_eq!(title, "A & B's track"); - assert!(resolve(r#"{"audio_url":"https://studio-api.prod.suno.com/api/forbidden","media_urls":[{"url":"https://cdn1.suno.ai/ignored.mp3"}]}"#,ID).is_err()); - for u in [ - format!("http://cdn1.suno.ai/{ID}.mp3"), - format!("https://127.0.0.1/{ID}.mp3"), - format!("https://cdn1.suno.ai.evil.test/{ID}.mp3"), - ] { - assert!(audio_url(&u, ID).is_err()); - } - } - #[test] - fn current_public_progressive_media_is_selected_with_matching_identity() { - let record = serde_json::json!({"id":ID,"status":"complete","title":"Current public song","audio_url":"https://studio-api.prod.suno.com/api/forbidden","media_urls":[{"url":format!("https://d2lwuy8qc234o3.cloudfront.net/1/clip/{ID}.m4a"),"delivery":"progressive","content_type":"m4a-opus"}]}); - let flight = - serde_json::json!([1, format!("7:{}", serde_json::json!(["$",{"clip":record}]))]); - let html = format!(""); - let (url, title) = resolve(&html, ID).unwrap(); - assert!(url.ends_with(&format!("{ID}.m4a"))); - assert_eq!(title, "Current public song"); - let mut denied = record.clone(); - denied["action_config"] = - serde_json::json!({"actions":[{"action_type":"download","disabled":true}]}); - assert!(record_audio(&denied, ID).is_err()); - let mut encoded = record.clone(); - encoded["media_urls"][0]["encoding"] = serde_json::json!("1.0.0"); - assert!(record_audio(&encoded, ID).is_err()); - assert!(!plain_audio_header(&[ - 0xaa, 0xd7, 0xc8, 0xa6, 0x97, 0xc9, 0xff, 0xe8, 0x57, 0xbb, 0xab, 0x5e - ])); - assert!(plain_audio_header(b"RIFF0000WAVE")); - let mut encrypted = record.clone(); - encrypted["media_urls"][0]["drm"] = serde_json::json!(true); - assert!(record_audio(&encrypted, ID).is_err()); - let mut wrong = record; - wrong["media_urls"][0]["url"] = - serde_json::json!("https://cdn1.suno.ai/00000000-0000-0000-0000-000000000000.mp3"); - assert!(record_audio(&wrong, ID).is_err()); - } - #[test] - fn bounded_copy_cancels_without_publishing() { - let (tx, _rx) = mpsc::sync_channel(64); - let mut output = Vec::new(); - assert!( - copy_audio( - &b"audio"[..], - &mut output, - &AtomicBool::new(true), - &tx, - None - ) - .is_err() - ); - assert!(output.is_empty()); - assert!( - copy_audio( - &b"audio"[..], - &mut output, - &AtomicBool::new(false), - &tx, - Some(LIMIT + 1) - ) - .is_err() - ); - assert!(output.is_empty()); - assert!(copy_audio(&b""[..], &mut output, &AtomicBool::new(false), &tx, None).is_err()); - copy_audio( - &b"audio"[..], - &mut output, - &AtomicBool::new(false), - &tx, - Some(5), - ) - .unwrap(); - assert_eq!(output, b"audio"); - } -} diff --git a/apps/amp-player/src/lab_youtube.rs b/apps/amp-player/src/lab_youtube.rs deleted file mode 100644 index f232dfc0..00000000 --- a/apps/amp-player/src/lab_youtube.rs +++ /dev/null @@ -1,1459 +0,0 @@ -//! AMP Lab-only URL import. No shell, cookies, user yt-dlp config, or hidden playlist expansion. -#[path = "lab_music_source.rs"] -mod music_source; -#[path = "lab_suno.rs"] -mod suno; -use eframe::egui; -use process_wrap::std::*; -use std::{ - fs, - io::{self, BufRead, Read, Write}, - path::{Path, PathBuf}, - process::{Command, Stdio}, - sync::{ - Arc, - atomic::{AtomicBool, Ordering}, - mpsc, - }, - thread, - time::{Duration, Instant}, -}; - -pub fn video_url(input: &str) -> Result { - let url = url::Url::parse(input.trim()) - .map_err(|_| "Paste a complete YouTube video URL.".to_owned())?; - if !matches!(url.scheme(), "https" | "http") - || !url.username().is_empty() - || url.password().is_some() - || url.port().is_some() - { - return Err("Use an ordinary https:// YouTube video URL.".into()); - } - let host = url.host_str().unwrap_or(""); - let id = match host { - "youtu.be" => url - .path() - .strip_prefix('/') - .filter(|s| !s.contains('/')) - .map(str::to_owned), - "youtube.com" | "www.youtube.com" | "m.youtube.com" | "music.youtube.com" => { - if url.path() == "/watch" { - url.query_pairs() - .find(|(k, _)| k == "v") - .map(|(_, v)| v.into_owned()) - } else { - url.path() - .strip_prefix("/shorts/") - .or_else(|| url.path().strip_prefix("/live/")) - .or_else(|| url.path().strip_prefix("/embed/")) - .map(str::to_owned) - } - } - _ => return Err("Only YouTube video URLs are supported.".into()), - } - .ok_or("Choose one video, not a playlist or channel URL.")?; - if id.len() != 11 - || !id - .bytes() - .all(|b| b.is_ascii_alphanumeric() || b == b'_' || b == b'-') - { - return Err("That URL does not contain a valid YouTube video ID.".into()); - } - Ok(format!("https://www.youtube.com/watch?v={id}")) -} - -fn playlist_url(input: &str) -> Result { - let u = url::Url::parse(input.trim()).map_err(|_| "Paste a complete YouTube playlist URL.")?; - if !matches!(u.scheme(), "http" | "https") - || !u.username().is_empty() - || u.password().is_some() - || u.port().is_some() - || !matches!( - u.host_str(), - Some("youtube.com" | "www.youtube.com" | "m.youtube.com" | "music.youtube.com") - ) - || !matches!(u.path(), "/playlist" | "/watch") - { - return Err("Use a YouTube playlist or video-with-playlist URL.".into()); - } - let id = u - .query_pairs() - .find(|(k, _)| k == "list") - .map(|(_, v)| v.into_owned()) - .ok_or("This URL has no playlist ID.")?; - if !(2..=150).contains(&id.len()) - || !id - .bytes() - .all(|b| b.is_ascii_alphanumeric() || b == b'_' || b == b'-') - { - return Err("Invalid playlist ID.".into()); - } - Ok(format!("https://www.youtube.com/playlist?list={id}")) -} -fn playlist_entries(info: &serde_json::Value) -> Result, String> { - let entries = info["entries"] - .as_array() - .ok_or("No playlist entries returned.")?; - if entries.is_empty() || entries.len() > 500 { - return Err("Choose a playlist containing 1–500 videos.".into()); - } - let mut urls = Vec::new(); - for entry in entries { - if let Some(id) = entry["id"].as_str() - && let Ok(url) = video_url(&format!("https://www.youtube.com/watch?v={id}")) - && !urls.contains(&url) - { - urls.push(url); - } - } - if urls.is_empty() { - return Err("No available video IDs in this playlist.".into()); - } - Ok(urls) -} -fn save_download_playlist(paths: &[PathBuf], dir: &Path, name: &str) -> Result { - let mut file = tempfile::NamedTempFile::new_in(dir).map_err(|e| e.to_string())?; - writeln!(file, "#EXTM3U").map_err(|e| e.to_string())?; - for path in paths { - let relative = path - .strip_prefix(dir) - .map_err(|_| "Unexpected playlist file location")?; - writeln!(file, "{}", relative.to_string_lossy()).map_err(|e| e.to_string())?; - } - file.as_file().sync_all().map_err(|e| e.to_string())?; - let name = safe_name(name); - for i in 0..10000 { - let path = dir.join(if i == 0 { - format!("{name}.m3u8") - } else { - format!("{name} ({i}).m3u8") - }); - match file.persist_noclobber(&path) { - Ok(_) => return Ok(path), - Err(e) if e.error.kind() == io::ErrorKind::AlreadyExists => file = e.file, - Err(e) => return Err(e.error.to_string()), - } - } - Err("Too many playlists with this name".into()) -} - -fn playlist_download( - url: &str, - dir: &Path, - tools: &Tools, - cancel: &AtomicBool, - tx: &mpsc::SyncSender, -) -> Result<(Vec, String), String> { - let mut cmd = tools.yt_command(); - cmd.args([ - "--yes-playlist", - "--flat-playlist", - "--playlist-end", - "501", - "--dump-single-json", - "--skip-download", - "--", - ]) - .arg(url); - progress(tx, "Reading playlist…", None); - let raw = run(cmd, cancel, tx, Duration::from_secs(180))?; - let info: serde_json::Value = - serde_json::from_str(&raw).map_err(|_| "Invalid playlist information")?; - let urls = playlist_entries(&info)?; - let mut saved = Vec::new(); - let mut errors = Vec::new(); - for (i, url) in urls.iter().enumerate() { - if cancel.load(Ordering::SeqCst) { - break; - } - progress( - tx, - &format!("Playlist item {} / {}", i + 1, urls.len()), - None, - ); - match download(url, dir, tools, cancel, tx) { - Ok(path) => { - let _ = tx.send(Event::Saved(path.clone())); - saved.push(path); - } - Err(e) => { - if cancel.load(Ordering::SeqCst) { - break; - } - errors.push(format!("Item {}: {e}", i + 1)); - } - } - } - let state = if cancel.load(Ordering::SeqCst) { - "Cancelled" - } else { - "Finished" - }; - let message = format!( - "{state}: {} MP3s saved, {} failed. Completed files are kept.{}", - saved.len(), - errors.len(), - errors.first().map(|e| format!("\n{e}")).unwrap_or_default() - ); - let playlist = if saved.is_empty() { - String::new() - } else { - match save_download_playlist( - &saved, - dir, - info["title"].as_str().unwrap_or("YouTube playlist"), - ) { - Ok(path) => format!("\nPlaylist saved: {}", path.display()), - Err(e) => format!("\nMP3s kept, but could not save the playlist: {e}"), - } - }; - Ok((saved, format!("{message}{playlist}"))) -} - -fn downloads() -> Result { - let base = if cfg!(windows) { - std::env::var_os("LOCALAPPDATA").map(PathBuf::from) - } else { - std::env::var_os("XDG_DATA_HOME") - .filter(|p| !p.is_empty()) - .map(PathBuf::from) - .or_else(|| std::env::var_os("HOME").map(|p| PathBuf::from(p).join(".local/share"))) - }; - base.map(|p| { - p.join(if cfg!(windows) { - "AMPVerse/AMP Lab/downloads" - } else { - "amp-verse/lab/downloads" - }) - }) - .ok_or("Your local downloads directory is unavailable.".into()) -} - -#[derive(Clone)] -struct Tools { - yt: PathBuf, - deno: PathBuf, - ffmpeg: PathBuf, - probe: PathBuf, -} -pub(super) fn audio_command(name: &str) -> Command { - match locate(name) { - Ok(path) => { - #[cfg(windows)] - { - use std::os::windows::process::CommandExt; - let mut command = Command::new(path); - command.creation_flags(0x08000000); - command - } - #[cfg(not(windows))] - { - Command::new(path) - } - } - Err(_) => amp_core::command(name), - } -} -fn locate(name: &str) -> Result { - let file = if cfg!(windows) { - format!("{name}.exe") - } else { - name.into() - }; - let mut dirs = Vec::new(); - if let Some(dir) = crate::theme::settings_path() - .and_then(|p| fs::read_to_string(p.with_file_name("lab-tools-directory.txt")).ok()) - { - dirs.push(PathBuf::from(dir.trim())); - } - if let Some(dir) = std::env::var_os("AMP_LAB_TOOLS") { - dirs.push(dir.into()); - } - if let Some(dir) = std::env::current_exe() - .ok() - .and_then(|p| p.parent().map(Path::to_path_buf)) - { - dirs.push(dir.join("tools/lab-youtube")); - dirs.push(dir); - } - if let Some(path) = std::env::var_os("PATH") { - dirs.extend(std::env::split_paths(&path)); - } - dirs.into_iter() - .map(|p| p.join(&file)) - .find(|p| p.is_file()) - .ok_or_else(|| format!("Missing {name}. Use Locate tools or Setup instructions below.")) -} -impl Tools { - fn discover() -> Result { - Ok(Self { - yt: locate("yt-dlp")?, - deno: locate("deno")?, - ffmpeg: locate("ffmpeg")?, - probe: locate("ffprobe")?, - }) - } - fn for_provider(provider: music_source::Provider) -> Result { - if provider == music_source::Provider::YouTube { - return Self::discover(); - } - Ok(Self { - yt: locate("yt-dlp")?, - deno: PathBuf::new(), - ffmpeg: locate("ffmpeg")?, - probe: locate("ffprobe")?, - }) - } - fn audio_only() -> Result { - Ok(Self { - yt: PathBuf::new(), - deno: PathBuf::new(), - ffmpeg: locate("ffmpeg")?, - probe: locate("ffprobe")?, - }) - } - fn yt_command(&self) -> Command { - let mut cmd = Command::new(&self.yt); - cmd.args([ - "--ignore-config", - "--no-plugin-dirs", - "--no-playlist", - "--no-update", - "--socket-timeout", - "20", - "--retries", - "2", - "--fragment-retries", - "2", - "--no-js-runtimes", - ]); - if !self.deno.as_os_str().is_empty() { - cmd.arg("--js-runtimes") - .arg(format!("deno:{}", self.deno.display())) - .args(["--remote-components", "ejs:github"]); - } - cmd - } -} - -enum Event { - Progress(String, Option), - Finished(Result), - Saved(PathBuf), - Batch(Result<(Vec, String), String>), -} -struct Job { - cancel: Arc, - rx: mpsc::Receiver, -} -impl Drop for Job { - fn drop(&mut self) { - self.cancel.store(true, Ordering::SeqCst); - } -} -#[derive(Default)] -pub struct Panel { - url: String, - playlist: bool, - completed: Vec, - status: String, - progress: Option, - job: Option, - ready: Option, - open_pending: bool, - failed: bool, -} -impl Panel { - fn start(&mut self) { - let provider = match music_source::provider(&self.url) { - Ok(provider) => provider, - Err(error) => { - self.status = error; - self.failed = true; - return; - } - }; - let is_suno = provider == music_source::Provider::Suno; - let playlist = self.playlist && provider == music_source::Provider::YouTube; - let url = match if playlist { - playlist_url(&self.url) - } else { - music_source::normalize(&self.url) - } { - Ok(url) => url, - Err(error) => { - self.status = error; - self.failed = true; - return; - } - }; - let (tx, rx) = mpsc::sync_channel(64); - let cancel = Arc::new(AtomicBool::new(false)); - self.job = Some(Job { - cancel: cancel.clone(), - rx, - }); - self.progress = None; - self.failed = false; - self.status = "Checking download tools…".into(); - thread::spawn(move || { - if playlist { - let result = Tools::discover().and_then(|tools| { - downloads().and_then(|dir| playlist_download(&url, &dir, &tools, &cancel, &tx)) - }); - let _ = tx.send(Event::Batch(result)); - return; - } - let result = if is_suno { - Tools::audio_only().and_then(|tools| { - downloads().and_then(|dir| suno::download(&url, &dir, &tools, &cancel, &tx)) - }) - } else { - Tools::for_provider(provider).and_then(|tools| { - downloads().and_then(|dir| download(&url, &dir, &tools, &cancel, &tx)) - }) - }; - let _ = tx.send(Event::Finished(result)); - }); - } - pub fn poll(&mut self, ctx: &egui::Context) -> Option { - let mut finished = None; - if let Some(job) = &self.job { - loop { - match job.rx.try_recv() { - Ok(Event::Progress(s, p)) => { - if !job.cancel.load(Ordering::SeqCst) { - self.status = s; - self.progress = p; - } - } - Ok(Event::Saved(path)) => { - self.completed.push(path); - } - Ok(Event::Batch(result)) => { - match result { - Ok((_, message)) => { - self.status = message; - self.failed = false; - } - Err(e) => { - self.status = e; - self.failed = true; - } - } - finished = Some(Err(String::new())); - break; - } - Ok(Event::Finished(result)) => { - finished = Some(result); - break; - } - Err(mpsc::TryRecvError::Empty) => break, - Err(mpsc::TryRecvError::Disconnected) => { - finished = Some(Err("Download worker interrupted. Completed MP3s were kept; Retry to start again.".into())); - break; - } - } - } - ctx.request_repaint_after(Duration::from_millis(100)); - } - if let Some(result) = finished { - self.job = None; - self.progress = None; - if !result.as_ref().is_err_and(|e| e.is_empty()) { - self.failed = result.is_err(); - } - match result { - Ok(path) => { - self.status = "MP3 saved. Opening in AMP Lab…".into(); - self.ready = Some(path); - self.open_pending = true; - } - Err(e) => { - if !e.is_empty() { - self.status = e; - } - } - } - } - if self.open_pending { - self.open_pending = false; - return self.ready.clone(); - } - None - } - pub fn opened(&mut self, loaded: bool) { - self.status = if loaded { - "MP3 saved and opened in AMP Lab." - } else { - "MP3 saved. Current edits were kept; use Open downloaded MP3 after exporting." - } - .into(); - } - pub fn show(&mut self, ui: &mut egui::Ui) { - crate::skin::panel(ui, false, |ui| { - ui.horizontal_wrapped(|ui| { - let provider = music_source::provider(&self.url).ok(); - ui.strong( - provider - .map(|p| format!("{} link", p.label())) - .unwrap_or_else(|| "Music link".into()), - ); - if provider == Some(music_source::Provider::YouTube) { - ui.add_enabled( - self.job.is_none(), - egui::Checkbox::new(&mut self.playlist, "Playlist"), - ); - } - ui.add_enabled( - self.job.is_none(), - egui::TextEdit::singleline(&mut self.url) - .id(egui::Id::unique("lab-youtube-url")) - .desired_width((ui.available_width() - 230.).max(130.)) - .hint_text("Paste a music link…"), - ); - if ui - .add_enabled(self.job.is_none(), egui::Button::new("Download MP3")) - .clicked() - { - self.start(); - } - if let Some(job) = &self.job - && ui.button("Cancel").clicked() - { - job.cancel.store(true, Ordering::SeqCst); - self.status = "Cancelling and removing incomplete files…".into(); - } - if self.job.is_none() - && !self.status.is_empty() - && ui.small_button("Retry").clicked() - { - self.start(); - } - if self.job.is_none() - && self.ready.is_some() - && ui.small_button("Open downloaded MP3").clicked() - { - self.open_pending = true; - } - }); - if !self.completed.is_empty() { - egui::CollapsingHeader::new(format!("Downloaded MP3s ({})", self.completed.len())) - .show(ui, |ui| { - egui::ScrollArea::vertical() - .max_height(140.) - .show(ui, |ui| { - for path in &self.completed { - if ui - .button( - path.file_name().unwrap_or_default().to_string_lossy(), - ) - .clicked() - { - self.ready = Some(path.clone()); - self.open_pending = true; - } - } - }); - }); - } - if !self.status.is_empty() { - ui.label(&self.status); - if self.failed && suno::recognizes(&self.url) { - ui.horizontal_wrapped(|ui| { - if let Some(link) = suno::song_page(&self.url) { - ui.hyperlink_to("Open in Suno", link); - } - ui.hyperlink_to( - "Suno download options", - "https://help.suno.com/en/articles/2409921", - ); - if ui.button("Open exported MP3...").clicked() - && let Some(path) = rfd::FileDialog::new() - .set_title("Open a Suno-exported MP3") - .add_filter("MP3 audio", &["mp3"]) - .pick_file() - { - self.ready = Some(path); - self.open_pending = true; - self.failed = false; - self.status = "Opening exported MP3 in Lab...".into(); - } - }); - } - } - if self.job.is_some() { - if let Some(p) = self.progress { - ui.add(egui::ProgressBar::new(p).show_percentage()); - } else { - ui.spinner(); - } - } - egui::CollapsingHeader::new("Downloads / tools").id_salt("lab-youtube-tools").show(ui, |ui| { - ui.weak("YouTube · Suno downloadable audio · SoundCloud · Bandcamp. MP3 256 kbps. Conversion does not improve source quality."); - if let Ok(dir) = downloads() { ui.label(format!("Original MP3s: {}", dir.display())); } - ui.horizontal_wrapped(|ui| { - if ui.button("Locate tools…").clicked() && let Some(dir) = rfd::FileDialog::new().set_title("Folder containing yt-dlp, Deno or FFmpeg tools").pick_folder() { - self.status = crate::theme::settings_path().ok_or_else(|| "Settings directory unavailable".to_owned()).and_then(|p| { - let p = p.with_file_name("lab-tools-directory.txt"); fs::create_dir_all(p.parent().unwrap()).and_then(|_| fs::write(p, dir.to_string_lossy().as_bytes())).map_err(|e| e.to_string()) - }).map(|_| "Tools folder saved. Retry the download.".into()).unwrap_or_else(|e| e); - } - ui.hyperlink_to("Setup instructions", "https://github.com/gitwide-cloud/amp-verse/blob/feature/six-deck-controls/docs/LAB_YOUTUBE.md"); - }); - }); - }); - } -} - -fn progress(tx: &mpsc::SyncSender, status: &str, value: Option) { - let _ = tx.try_send(Event::Progress(status.into(), value)); -} -fn cancelled(cancel: &AtomicBool) -> Result<(), String> { - if cancel.load(Ordering::SeqCst) { - Err("Cancelled. Completed downloads were kept; incomplete files were removed.".into()) - } else { - Ok(()) - } -} - -// Each stage owns a process tree: a Windows Job Object or a Unix process group. -// Job Object setup suspends the child until it is assigned, avoiding fork races. -fn run( - mut cmd: Command, - cancel: &AtomicBool, - tx: &mpsc::SyncSender, - limit: Duration, -) -> Result { - cancelled(cancel)?; - cmd.stdin(Stdio::null()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()); - let mut command = CommandWrap::from(cmd); - #[cfg(windows)] - { - command - .wrap(CreationFlags( - windows::Win32::System::Threading::CREATE_NO_WINDOW - | windows::Win32::System::Threading::BELOW_NORMAL_PRIORITY_CLASS, - )) - .wrap(JobObject); - } - #[cfg(unix)] - { - command.wrap(ProcessGroup::leader()); - } - let mut child = command - .spawn() - .map_err(|e| format!("Could not start download tool: {e}. Check Downloads / tools."))?; - let (lines_tx, lines_rx) = mpsc::sync_channel(64); - let pipes: Vec> = vec![ - Box::new(child.stdout().take().unwrap()), - Box::new(child.stderr().take().unwrap()), - ]; - let readers: Vec<_> = pipes - .into_iter() - .enumerate() - .map(|(index, pipe)| { - let tx = lines_tx.clone(); - thread::spawn(move || { - let mut reader = io::BufReader::new(pipe); - loop { - let mut line = Vec::new(); - match reader - .by_ref() - .take(2 * 1024 * 1024) - .read_until(b'\n', &mut line) - { - Ok(0) | Err(_) => break, - Ok(_) => { - if tx - .send((index, String::from_utf8_lossy(&line).into_owned())) - .is_err() - { - break; - } - } - } - } - }) - }) - .collect(); - drop(lines_tx); - let started = Instant::now(); - let mut stdout = String::new(); - let mut errors = String::new(); - let mut status = None; - let mut failure = None; - loop { - if cancel.load(Ordering::SeqCst) { - failure = cancelled(cancel).err(); - break; - } - if started.elapsed() > limit { - failure = Some("The download tool timed out. Check your connection and Retry.".into()); - break; - } - match lines_rx.recv_timeout(Duration::from_millis(30)) { - Ok((index, line)) => { - if let Some(p) = parse_progress(&line) { - progress(tx, "Downloading audio…", Some(p)); - } - if let Some(value) = line - .strip_prefix("out_time_us=") - .and_then(|s| s.trim().parse::().ok()) - { - progress( - tx, - &format!( - "Converting to MP3 · {:.0} seconds processed", - value / 1_000_000. - ), - None, - ); - } - if index == 0 { - if stdout.len() + line.len() > 8 * 1024 * 1024 { - failure = Some("Download tool returned too much output.".into()); - break; - } - stdout.push_str(&line); - } else { - errors.push_str(&line); - if errors.len() > 8192 { - let keep = errors.char_indices().rev().nth(4095).map_or(0, |(i, _)| i); - errors = errors[keep..].into(); - } - } - } - Err(mpsc::RecvTimeoutError::Disconnected) => match child.try_wait() { - Ok(Some(s)) => { - status = Some(s); - break; - } - Err(e) => { - failure = Some(e.to_string()); - break; - } - _ => {} - }, - Err(mpsc::RecvTimeoutError::Timeout) => {} - } - // Do not finish until both streams have been drained. - } - let _ = child.kill(); - let _ = child.wait(); - drop(lines_rx); - for reader in readers { - let _ = reader.join(); - } - if let Some(e) = failure { - return Err(e); - } - if !status.is_some_and(|s| s.success()) { - return Err(readable_error(&errors)); - } - Ok(stdout) -} -fn parse_progress(line: &str) -> Option { - line.strip_prefix("AMP_PROGRESS:")? - .trim() - .trim_end_matches('%') - .trim() - .parse::() - .ok() - .filter(|p| p.is_finite()) - .map(|p| (p / 100.).clamp(0., 1.)) -} -fn readable_error(detail: &str) -> String { - let lower = detail.to_lowercase(); - let reason = if lower.contains("private") - || lower.contains("sign in") - || lower.contains("unavailable") - || lower.contains("removed") - || lower.contains("age-restricted") - { - "Video unavailable or restricted. Choose a public, accessible video." - } else if lower.contains("no space") - || lower.contains("permission denied") - || lower.contains("disk") - { - "Cannot save audio. Check free disk space and folder permissions." - } else if lower.contains("timed out") - || lower.contains("network") - || lower.contains("resolve") - || lower.contains("http error") - { - "Network/download failed. Check the connection, then Retry." - } else if lower.contains("javascript") || lower.contains("ejs") || lower.contains("challenge") { - "YouTube extraction failed. Update yt-dlp, EJS and Deno using Setup instructions." - } else { - "Audio download or conversion failed. Retry or check the download tools." - }; - let detail: String = detail - .chars() - .filter(|c| !c.is_control() || *c == '\n') - .take(700) - .collect(); - format!("{reason}\n{}", detail.trim()) -} -fn download( - url: &str, - dir: &Path, - tools: &Tools, - cancel: &AtomicBool, - tx: &mpsc::SyncSender, -) -> Result { - let short = Duration::from_secs(45); - let provider = music_source::provider(url)?; - if provider == music_source::Provider::YouTube { - let mut deno = Command::new(&tools.deno); - deno.arg("--version"); - let version = run(deno, cancel, tx, short)?; - let version = version.split_whitespace().nth(1).unwrap_or(""); - let parts: Vec = version.split('.').filter_map(|p| p.parse().ok()).collect(); - if parts.len() < 2 || (parts[0], parts[1]) < (2, 3) { - return Err( - "Deno 2.3.0 or newer is required. Use Setup instructions to update tools.".into(), - ); - } - } - for path in [&tools.ffmpeg, &tools.probe] { - let mut cmd = Command::new(path); - cmd.arg("-version"); - run(cmd, cancel, tx, short)?; - } - fs::create_dir_all(dir) - .map_err(|e| format!("Cannot create AMP Lab downloads directory: {e}"))?; - let work = tempfile::Builder::new() - .prefix(".amp-lab-download-") - .tempdir_in(dir) - .map_err(|e| format!("Cannot write downloads directory: {e}"))?; - progress(tx, &format!("Reading {} song…", provider.label()), None); - let mut info = tools.yt_command(); - info.args(["--use-extractors", provider.extractor()]); - info.args([ - "--dump-single-json", - "--skip-download", - "--no-progress", - "--", - ]) - .arg(url); - let text = run(info, cancel, tx, Duration::from_secs(120))?; - let info: serde_json::Value = serde_json::from_str(&text) - .map_err(|_| "yt-dlp returned invalid video information".to_owned())?; - music_source::validate_info(url, &info)?; - let id = info["id"].as_str().ok_or("Song information has no ID")?; - let name = safe_name(info["title"].as_str().unwrap_or(id)); - progress(tx, "Downloading audio…", Some(0.)); - let mut cmd = tools.yt_command(); - cmd.args([ - "--use-extractors", - provider.extractor(), - "--max-filesize", - "256M", - ]); - cmd.args([ - "--no-simulate", - "-f", - "bestaudio/best", - "--newline", - "--progress", - "--progress-delta", - "0.25", - "--progress-template", - "download:AMP_PROGRESS:%(progress._percent_str)s", - "--print", - "after_move:AMP_FILE:%(filepath)j", - "-o", - ]) - .arg(work.path().join("source.%(ext)s")) - .arg("--") - .arg(url); - let output = run(cmd, cancel, tx, Duration::from_secs(6 * 60 * 60))?; - let source = output - .lines() - .find_map(|line| { - line.strip_prefix("AMP_FILE:") - .and_then(|s| serde_json::from_str::(s).ok()) - }) - .map(PathBuf::from) - .ok_or("Download finished without an audio file. Update yt-dlp and Retry.")?; - let source = source - .canonicalize() - .map_err(|e| format!("Downloaded audio missing: {e}"))?; - if !source.starts_with(work.path().canonicalize().map_err(|e| e.to_string())?) - || !source.is_file() - { - return Err("Downloader returned an unexpected file location.".into()); - } - if fs::metadata(&source).map_err(|e| e.to_string())?.len() > 256 * 1024 * 1024 { - return Err("Downloaded audio exceeds the 256 MB import limit.".into()); - } - convert_publish( - &source, - dir, - tools, - cancel, - tx, - ImportLabel { - name: &name, - id, - suno_source: None, - metadata: Some(&info), - }, - ) -} -struct ImportLabel<'a> { - name: &'a str, - id: &'a str, - suno_source: Option<&'a str>, - metadata: Option<&'a serde_json::Value>, -} -fn convert_publish( - source: &Path, - dir: &Path, - tools: &Tools, - cancel: &AtomicBool, - tx: &mpsc::SyncSender, - label: ImportLabel<'_>, -) -> Result { - let ImportLabel { - name, - id, - suno_source, - metadata, - } = label; - let work = tempfile::Builder::new() - .prefix(".amp-lab-convert-") - .tempdir_in(dir) - .map_err(|e| e.to_string())?; - cancelled(cancel)?; - progress(tx, "Converting to MP3 · 256 kbps…", None); - let converted = work.path().join("converted.mp3"); - let mut cmd = Command::new(&tools.ffmpeg); - cmd.args([ - "-hide_banner", - "-nostdin", - "-n", - "-loglevel", - "error", - "-progress", - "pipe:1", - "-nostats", - "-protocol_whitelist", - "file,pipe", - "-i", - ]) - .arg(source) - .args([ - "-map", - "0:a:0", - "-vn", - "-c:a", - "libmp3lame", - "-threads", - "2", - "-b:a", - "256k", - "-id3v2_version", - "3", - ]); - cmd.args(["-metadata", &format!("title={name}")]); - if let Some(info) = metadata { - for (field, tag) in [ - ("title", "title"), - ("artist", "artist"), - ("album", "album"), - ("release_date", "date"), - ("webpage_url", "comment"), - ] { - if let Some(value) = info[field].as_str().filter(|s| !s.is_empty()) { - cmd.args(["-metadata", &format!("{tag}={value}")]); - } - } - } - if let Some(source_url) = suno_source { - cmd.args([ - "-metadata", - &format!("title={name}"), - "-metadata", - &format!("comment=Suno source: {source_url}"), - "-metadata", - "AMPVerseCategories={\"ai_generated\":true}", - ]); - } - cmd.arg(&converted); - run(cmd, cancel, tx, Duration::from_secs(6 * 60 * 60))?; - let mut cmd = Command::new(&tools.probe); - cmd.args([ - "-v", - "error", - "-show_entries", - "format=duration", - "-of", - "default=noprint_wrappers=1:nokey=1", - ]) - .arg(&converted); - let duration = run(cmd, cancel, tx, Duration::from_secs(45))? - .trim() - .parse::() - .unwrap_or(0.); - if !duration.is_finite() || duration <= 0. { - return Err("Converted MP3 is empty or invalid; original editor audio was kept.".into()); - } - let output = publish( - &converted, - dir, - &format!("{name} [{}]", safe_name(id)), - cancel, - )?; - if let Some(source_url) = suno_source { - let mut preparation = amp_core::Preparation::default(); - amp_core::music_annotations::set( - &mut preparation, - amp_core::music_annotations::Category::AiGenerated, - true, - ); - preparation - .extensions - .insert("source_service".into(), serde_json::json!("suno")); - preparation - .extensions - .insert("source_url".into(), serde_json::json!(source_url)); - amp_core::preparation::save_if_unchanged( - dir, - Path::new(output.file_name().ok_or("Download filename missing")?), - &preparation, - None, - ) - .map_err(|e| { - format!( - "Audio saved at {}; source categories could not be saved: {e}", - output.display() - ) - })?; - } - Ok(output) -} -fn safe_name(title: &str) -> String { - let mut name = String::new(); - for c in title.chars() { - let c = if c.is_control() || "<>:\"/\\|?*".contains(c) { - '_' - } else { - c - }; - if name.len() + c.len_utf8() > 120 { - break; - } - name.push(c); - } - let name = name.trim_matches([' ', '.']); - if name.is_empty() { - "YouTube audio".into() - } else { - let stem = name.split('.').next().unwrap_or("").to_ascii_uppercase(); - let reserved = matches!( - stem.as_str(), - "CON" | "PRN" | "AUX" | "NUL" | "CONIN$" | "CONOUT$" - ) || (stem.len() == 4 - && (stem.starts_with("COM") || stem.starts_with("LPT")) - && matches!(stem.as_bytes()[3], b'1'..=b'9')); - if reserved { - format!("_{name}") - } else { - name.into() - } - } -} - -fn publish(source: &Path, dir: &Path, name: &str, cancel: &AtomicBool) -> Result { - let mut tmp = - tempfile::NamedTempFile::new_in(dir).map_err(|e| format!("Cannot save MP3: {e}"))?; - let mut input = fs::File::open(source).map_err(|e| e.to_string())?; - let mut buf = [0; 65536]; - loop { - cancelled(cancel)?; - let n = input.read(&mut buf).map_err(|e| e.to_string())?; - if n == 0 { - break; - } - tmp.write_all(&buf[..n]) - .map_err(|e| format!("Cannot save MP3: {e}"))?; - } - tmp.as_file().sync_all().map_err(|e| e.to_string())?; - for index in 0..10000 { - cancelled(cancel)?; - let target = dir.join(if index == 0 { - format!("{name}.mp3") - } else { - format!("{name} ({index}).mp3") - }); - match tmp.persist_noclobber(&target) { - Ok(_) => return Ok(target), - Err(e) if e.error.kind() == io::ErrorKind::AlreadyExists => tmp = e.file, - Err(e) => return Err(format!("Cannot publish MP3: {}", e.error)), - } - } - Err("Too many downloads with this filename; choose a different downloads folder.".into()) -} - -#[cfg(test)] -mod tests { - use super::*; - #[test] - fn url_field_accepts_paste_and_worker_disconnect_is_recoverable() { - let ctx = egui::Context::default(); - let mut panel = Panel::default(); - let raw = egui::RawInput { - screen_rect: Some(egui::Rect::from_min_size( - egui::Pos2::ZERO, - egui::vec2(900., 400.), - )), - ..Default::default() - }; - let mut output = ctx.run_ui(raw.clone(), |ui| panel.show(ui)); - output.textures_delta.clear(); - ctx.memory_mut(|m| m.request_focus(egui::Id::unique("lab-youtube-url"))); - let mut input = raw; - input - .events - .push(egui::Event::Paste("https://youtu.be/BaW_jenozKc".into())); - let mut output = ctx.run_ui(input, |ui| panel.show(ui)); - output.textures_delta.clear(); - assert_eq!(panel.url, "https://youtu.be/BaW_jenozKc"); - let (tx, rx) = mpsc::sync_channel(1); - drop(tx); - panel.job = Some(Job { - cancel: Arc::new(AtomicBool::new(false)), - rx, - }); - assert!(panel.poll(&ctx).is_none()); - assert!(panel.failed); - assert!(panel.job.is_none()); - assert!(panel.status.contains("interrupted")); - } - #[test] - fn batch_results_do_not_replace_unsaved_editor_automatically() { - let (tx, rx) = mpsc::sync_channel(4); - let mut panel = Panel { - job: Some(Job { - cancel: Arc::new(AtomicBool::new(false)), - rx, - }), - ..Default::default() - }; - tx.send(Event::Saved(PathBuf::from("saved.mp3"))).unwrap(); - tx.send(Event::Batch(Ok(( - vec![PathBuf::from("saved.mp3")], - "Finished: 1 MP3 saved, 1 failed".into(), - )))) - .unwrap(); - assert!(panel.poll(&egui::Context::default()).is_none()); - assert_eq!(panel.completed.len(), 1); - assert!(panel.status.contains("1 failed")); - assert!(panel.job.is_none()); - } - #[test] - #[ignore = "requires AMP_LAB_YOUTUBE_FIXTURE executable, Deno and real FFmpeg"] - fn local_playlist_keeps_success_when_an_item_is_private() { - let mut tools = Tools::discover().unwrap(); - tools.yt = PathBuf::from(std::env::var_os("AMP_LAB_YOUTUBE_FIXTURE").unwrap()); - let dir = tempfile::tempdir().unwrap(); - let (tx, rx) = mpsc::sync_channel(64); - let (saved, message) = playlist_download( - "https://www.youtube.com/playlist?list=PLfixture", - dir.path(), - &tools, - &AtomicBool::new(false), - &tx, - ) - .unwrap(); - assert_eq!(saved.len(), 1); - assert!(saved[0].is_file()); - assert!(message.contains("1 failed")); - assert!(crate::lab_editor::duration(&saved[0]).unwrap() > 0.); - assert!(rx.try_iter().any(|e| matches!(e, Event::Saved(_)))); - assert_eq!(fs::read_dir(dir.path()).unwrap().count(), 2); - let list = fs::read_to_string(dir.path().join("YouTube playlist.m3u8")).unwrap(); - assert!(list.starts_with("#EXTM3U\n")); - assert!(list.contains("[BaW_jenozKc].mp3")); - assert!(!list.contains("abcdefghijk")); - } - #[test] - #[ignore = "requires AMP_LAB_YOUTUBE_FIXTURE executable, Deno and real FFmpeg"] - fn local_pipeline_other_providers_select_exact_extractor_and_save_playable_mp3() { - let mut tools = Tools::discover().unwrap(); - tools.yt = PathBuf::from(std::env::var_os("AMP_LAB_YOUTUBE_FIXTURE").unwrap()); - let dir = tempfile::tempdir().unwrap(); - let (tx, _rx) = mpsc::sync_channel(64); - for url in [ - "https://soundcloud.com/fixture/example", - "https://fixture.bandcamp.com/track/example", - ] { - let saved = download(url, dir.path(), &tools, &AtomicBool::new(false), &tx).unwrap(); - assert!(saved.is_file()); - assert_eq!(saved.extension().unwrap(), "mp3"); - assert!(crate::lab_editor::duration(&saved).unwrap() > 1.5); - let output = Command::new(&tools.probe) - .args([ - "-v", - "error", - "-show_entries", - "format_tags=title,artist,album,comment", - "-of", - "json", - ]) - .arg(&saved) - .output() - .unwrap(); - assert!(output.status.success()); - let tags: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap(); - assert_eq!(tags["format"]["tags"]["title"], "Test: audio / source"); - assert_eq!(tags["format"]["tags"]["artist"], "Fixture artist"); - assert_eq!(tags["format"]["tags"]["album"], "Fixture album"); - assert_eq!(tags["format"]["tags"]["comment"], url); - } - assert_eq!(fs::read_dir(dir.path()).unwrap().count(), 2); - } - #[test] - #[ignore = "requires AMP_LAB_YOUTUBE_FIXTURE executable, Deno and real FFmpeg"] - fn local_pipeline_converts_reports_progress_cancels_tree_and_cleans_failures() { - let fixture = PathBuf::from(std::env::var_os("AMP_LAB_YOUTUBE_FIXTURE").unwrap()); - let mut tools = Tools::discover().unwrap(); - tools.yt = fixture.clone(); - let dir = tempfile::tempdir().unwrap(); - let cancel = Arc::new(AtomicBool::new(false)); - let (tx, rx) = mpsc::sync_channel(64); - let url = video_url("https://youtu.be/BaW_jenozKc?list=PLtest").unwrap(); - let first = download(&url, dir.path(), &tools, &cancel, &tx).unwrap(); - assert!(first.is_file()); - assert_eq!(first.extension().unwrap(), "mp3"); - assert!(crate::lab_editor::duration(&first).unwrap() > 0.); - let (done_tx, done_rx) = mpsc::sync_channel(4); - let mut panel = Panel { - job: Some(Job { - cancel: Arc::new(AtomicBool::new(false)), - rx: done_rx, - }), - ..Default::default() - }; - done_tx.send(Event::Finished(Ok(first.clone()))).unwrap(); - let delivered = panel.poll(&egui::Context::default()).unwrap(); - let mut editor = crate::lab_editor::Editor::default(); - assert!(editor.load_path(delivered)); - panel.opened(true); - assert!(panel.status.contains("opened")); - assert!( - panel.poll(&egui::Context::default()).is_none(), - "File opened twice" - ); - let events: Vec<_> = rx.try_iter().collect(); - assert!( - events - .iter() - .any(|e| matches!(e,Event::Progress(_,Some(p)) if *p>=0.5)) - ); - let blocked = tempfile::tempdir().unwrap(); - let file = blocked.path().join("not-a-directory"); - fs::write(&file, b"keep").unwrap(); - assert!( - download(&url, &file, &tools, &cancel, &tx) - .unwrap_err() - .contains("Cannot create") - ); - assert_eq!(fs::read(&file).unwrap(), b"keep"); - let mut missing = tools.clone(); - missing.deno = blocked.path().join("missing-deno"); - assert!( - download(&url, dir.path(), &missing, &cancel, &tx) - .unwrap_err() - .contains("Could not start") - ); - let original = fs::read(&first).unwrap(); - let second = download(&url, dir.path(), &tools, &cancel, &tx).unwrap(); - assert_ne!(first, second); - assert_eq!(original, fs::read(&first).unwrap()); - for mode in ["private", "invalid", "network"] { - tools.yt = fixture.with_file_name(if cfg!(windows) { - format!("yt-dlp-{mode}.exe") - } else { - format!("yt-dlp-{mode}") - }); - fs::copy(&fixture, &tools.yt).unwrap(); - let result = download(&url, dir.path(), &tools, &cancel, &tx); - assert!(result.is_err(), "{mode}"); - assert_eq!( - fs::read_dir(dir.path()).unwrap().count(), - 2, - "Incomplete files left after {mode}" - ); - } - tools.yt = fixture.with_file_name(if cfg!(windows) { - "yt-dlp-cancel.exe" - } else { - "yt-dlp-cancel" - }); - fs::copy(&fixture, &tools.yt).unwrap(); - let heartbeat = dir.path().join("heartbeat"); - let observer = heartbeat.clone(); - let trigger = cancel.clone(); - let canceller = thread::spawn(move || { - let start = Instant::now(); - while !observer.exists() && start.elapsed() < Duration::from_secs(15) { - thread::sleep(Duration::from_millis(20)); - } - trigger.store(true, Ordering::SeqCst); - }); - let result = download(&url, dir.path(), &tools, &cancel, &tx); - canceller.join().unwrap(); - assert!(result.unwrap_err().contains("Cancelled")); - assert!(heartbeat.exists(), "Child process did not start"); - let size = fs::metadata(&heartbeat).unwrap().len(); - thread::sleep(Duration::from_millis(200)); - assert_eq!( - size, - fs::metadata(&heartbeat).unwrap().len(), - "Grandchild survived Cancel" - ); - assert!(fs::read_dir(dir.path()).unwrap().all(|e| { - !e.unwrap() - .file_name() - .to_string_lossy() - .starts_with(".amp-lab") - })); - assert_eq!(fs::read(first).unwrap(), original); - let (tx, _rx) = mpsc::sync_channel(64); - let token = Arc::new(AtomicBool::new(false)); - let stop = token.clone(); - let canceller = thread::spawn(move || { - thread::sleep(Duration::from_millis(200)); - stop.store(true, Ordering::SeqCst); - }); - let mut cmd = Command::new(&tools.ffmpeg); - cmd.args([ - "-nostdin", - "-n", - "-loglevel", - "error", - "-progress", - "pipe:1", - "-re", - "-f", - "lavfi", - "-i", - "sine=frequency=440:duration=30", - "-c:a", - "libmp3lame", - "-b:a", - "256k", - ]) - .arg(dir.path().join("partial-conversion.mp3")); - assert!( - run(cmd, &token, &tx, Duration::from_secs(40)) - .unwrap_err() - .contains("Cancelled") - ); - canceller.join().unwrap(); - } - #[test] - #[ignore = "live YouTube access; requires yt-dlp, Deno and FFmpeg"] - fn live_public_test_video() { - let tools = Tools::discover().unwrap(); - let dir = tempfile::tempdir().unwrap(); - let (tx, _rx) = mpsc::sync_channel(64); - let url = video_url( - &std::env::var("AMP_LAB_LIVE_URL") - .unwrap_or_else(|_| "https://www.youtube.com/watch?v=aqz-KE-bpKQ".into()), - ) - .unwrap(); - let result = download(&url, dir.path(), &tools, &AtomicBool::new(false), &tx); - assert!(result.is_ok(), "Live YouTube test: {result:?}"); - } - #[test] - fn playlist_validation_bounds_and_deduplication() { - assert_eq!( - playlist_url("https://youtube.com/watch?v=BaW_jenozKc&list=PL123").unwrap(), - "https://www.youtube.com/playlist?list=PL123" - ); - for u in [ - "https://youtube.com.evil/playlist?list=PL123", - "https://user@youtube.com/playlist?list=PL123", - "https://youtube.com/channel/abc?list=PL123", - "https://youtu.be/BaW_jenozKc", - ] { - assert!(playlist_url(u).is_err()); - } - let v = serde_json::json!({"entries":[{"id":"BaW_jenozKc"},null,{"id":"bad"},{"id":"BaW_jenozKc"}]}); - assert_eq!(playlist_entries(&v).unwrap().len(), 1); - assert!(playlist_entries(&serde_json::json!({"entries":[]})).is_err()); - assert!( - playlist_entries(&serde_json::json!({"entries":vec![serde_json::Value::Null;501]})) - .is_err() - ); - } - #[test] - fn validates_video_and_strips_playlist_and_tracking() { - for url in [ - "https://youtu.be/BaW_jenozKc?list=PL123", - "https://www.youtube.com/watch?v=BaW_jenozKc&list=PL123", - "https://m.youtube.com/shorts/BaW_jenozKc", - ] { - assert_eq!( - video_url(url).unwrap(), - "https://www.youtube.com/watch?v=BaW_jenozKc" - ); - } - for url in [ - "https://youtube.com/playlist?list=PL123", - "https://youtube.com.evil/watch?v=BaW_jenozKc", - "file:///a", - "https://user@youtube.com/watch?v=BaW_jenozKc", - "--exec bad", - "https://youtu.be/../abc", - "https://youtube.com/watch?v=bad", - ] { - assert!(video_url(url).is_err(), "{url}"); - } - } - #[test] - fn dependency_start_failure_and_invalid_url_are_recoverable() { - let (tx, _rx) = mpsc::sync_channel(4); - let error = run( - Command::new("amp-lab-intentionally-missing-tool"), - &AtomicBool::new(false), - &tx, - Duration::from_secs(1), - ) - .unwrap_err(); - assert!(error.contains("Check Downloads / tools")); - let mut panel = Panel { - url: "https://youtube.com/playlist?list=PLtest".into(), - ..Default::default() - }; - panel.start(); - assert!(panel.failed); - assert!(panel.job.is_none()); - assert!(panel.status.contains("playlist")); - assert!(safe_name(&"🎵".repeat(200)).len() <= 120); - assert_eq!(safe_name("CON.track"), "_CON.track"); - assert_eq!(safe_name("lpt1"), "_lpt1"); - } - #[test] - fn progress_names_and_collision_safe_publication() { - assert_eq!(parse_progress("AMP_PROGRESS: 12.5%"), Some(0.125)); - assert_eq!(parse_progress("AMP_PROGRESS: NA"), None); - assert_eq!(safe_name("../a:b?*"), "_a_b__"); - let dir = tempfile::tempdir().unwrap(); - let source = dir.path().join("in"); - fs::write(&source, b"completed audio").unwrap(); - let cancel = AtomicBool::new(false); - let a = publish(&source, dir.path(), "name", &cancel).unwrap(); - let b = publish(&source, dir.path(), "name", &cancel).unwrap(); - assert_ne!(a, b); - assert_eq!(fs::read(a).unwrap(), b"completed audio"); - cancel.store(true, Ordering::SeqCst); - assert!(publish(&source, dir.path(), "cancelled", &cancel).is_err()); - assert!(!dir.path().join("cancelled.mp3").exists()); - } -} diff --git a/apps/amp-player/src/main.rs b/apps/amp-player/src/main.rs index 0cdaeef7..9a6161f9 100644 --- a/apps/amp-player/src/main.rs +++ b/apps/amp-player/src/main.rs @@ -35,7 +35,6 @@ mod key_lock; mod lab; mod lab_audio; mod lab_editor; -mod lab_youtube; mod library_cache; mod library_organizer; mod live_mix; diff --git a/apps/amp-player/src/performance.rs b/apps/amp-player/src/performance.rs index fe55eed8..2b6923e1 100644 --- a/apps/amp-player/src/performance.rs +++ b/apps/amp-player/src/performance.rs @@ -3096,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], @@ -3983,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(); diff --git a/apps/amp-player/src/preparer.rs b/apps/amp-player/src/preparer.rs index f214d6cb..b1d0ce73 100644 --- a/apps/amp-player/src/preparer.rs +++ b/apps/amp-player/src/preparer.rs @@ -1240,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/crates/amp-core/src/analysis.rs b/crates/amp-core/src/analysis.rs index be3d31f8..dc3a2a90 100644 --- a/crates/amp-core/src/analysis.rs +++ b/crates/amp-core/src/analysis.rs @@ -269,7 +269,9 @@ fn result_with_activity( p.schema_version = Some(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") { + 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")?; @@ -633,6 +635,32 @@ pub fn analyze(path: &Path, existing: &Preparation) -> Result Option { Some(profile) } /// Legacy RMS sections remain viewable, but cannot be compared to normalized -/// analyzed track scores. Legacy manual-only libraries retain their own scale. +/// 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 || !p.extensions.contains_key("perceptual_energy")) + read(p).filter(|profile| profile.version == 2) } #[derive(Clone, Copy, Debug, PartialEq)] pub struct AutomaticEntry { @@ -323,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} @@ -353,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} @@ -437,7 +436,7 @@ mod tests { p.extensions .insert(FIELD.into(), serde_json::to_value(sample()).unwrap()); assert!(read(&p).is_some()); - assert!(mixing_profile(&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()); diff --git a/crates/amp-core/src/hype_sections.rs b/crates/amp-core/src/hype_sections.rs index da557c80..588c5e5d 100644 --- a/crates/amp-core/src/hype_sections.rs +++ b/crates/amp-core/src/hype_sections.rs @@ -10,7 +10,10 @@ fn activity(p: &Preparation) -> Option { { return None; } - let profile = crate::energy_profile::mixing_profile(p)?; + // 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 }) { @@ -203,7 +206,7 @@ mod tests { 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, @@ -294,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/show.rs b/crates/amp-core/src/show.rs index 2ba7d50b..a175463e 100644 --- a/crates/amp-core/src/show.rs +++ b/crates/amp-core/src/show.rs @@ -690,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}] })); @@ -716,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| { @@ -774,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} ] @@ -807,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} ] }), @@ -816,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} ] }), @@ -851,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} ] @@ -864,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 7394b590..6e37d83e 100644 --- a/crates/amp-core/src/smart.rs +++ b/crates/amp-core/src/smart.rs @@ -1,11 +1,43 @@ //! 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 { @@ -74,7 +106,7 @@ pub(crate) fn cost_with_sections( ) } /// 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) } @@ -104,8 +136,106 @@ pub fn order_with_style( .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> { @@ -186,6 +316,131 @@ pub fn curate_with_soft_keys( #[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) diff --git a/docs/ANDROID_MODULES.md b/docs/ANDROID_MODULES.md index cdf48c08..4feda502 100644 --- a/docs/ANDROID_MODULES.md +++ b/docs/ANDROID_MODULES.md @@ -2,7 +2,7 @@ Lite and Full use `cloud.gitwide.ampverse`, one signing identity and one monotonically increasing version code (34 for this preview). They replace one another; they cannot be installed side by side. Installing with Android's normal update path retains the base application's private data. Never uninstall the base application as an upgrade workaround. -Full embeds DJ, Lab, Cast, Podcasts and Remote. Lite includes Player, local Library, Add-ons, and the small service-owned playback/DJ runtime needed by signed companions. Lite excludes Lab's FFmpeg/Python/yt-dlp/QuickJS payload and the Google Cast SDK. Neither edition contains desktop analysis models or stem-separation models. +Full embeds DJ, Lab, Cast, Podcasts and Remote. Lite includes Player, local Library, Add-ons, and the small service-owned playback/DJ runtime needed by signed companions. Lite excludes Lab's FFmpeg payload and the Google Cast SDK. Neither edition contains desktop analysis models or stem-separation models. ## Playback and data boundary @@ -10,14 +10,14 @@ The base `PlaybackService` remains the only phone music/DJ playback owner. Compa The provider returns paged song summaries, playlist summaries and bounded engine-state snapshots. Catalog reads and playlist preparation run off the UI/audio thread; only engine mutations run on its main thread. Offline playlist downloads run in the base application through the existing incremental `RadioOffline` publisher, preserving prepared metadata and local cue overrides. Module settings and podcast subscriptions/download records also stay in the base app. Offline edits are not automatically uploaded to a NAS. -Lab is an editor with its own preview transport. Entering it pauses the music/DJ transport. Original URL downloads and editing copies are separate. A Lab companion's private editing files are not yet automatically migrated from an embedded Full Lab session; switching editions retains those original base-app files. +Lab is an editor with its own preview transport. Entering it preserves music/DJ playback; auditioning requests temporary audio focus. Original audio and editing copies are separate. Previously imported MP3s remain accessible. A Lab companion's private editing files are not yet automatically migrated from an embedded Full Lab session; switching editions retains those original base-app files. ## Packages | Module | Companion application ID | Current implementation | | --- | --- | --- | | DJ | `cloud.gitwide.ampverse.dj` | Core-owned A/B and Cue Deck controls, song loading, saved playlist Auto Mix, crossfader, fade stepper, hot cues and saved sampler playback | -| Lab | `cloud.gitwide.ampverse.lab` | Shared native editor, source waveform/trim/fades/gain/normalize, MP3 preview/export, Lab-only YouTube URL import | +| Lab | `cloud.gitwide.ampverse.lab` | Shared native editor, source waveform/trim/fades/gain/normalize, MP3 preview/export, local audio import | | Cast | `cloud.gitwide.ampverse.cast` | LAN discovery, station controls/listening, host live-broadcast request, Google Cast picker and core-owned offline playlist sync | | Podcasts | `cloud.gitwide.ampverse.podcasts` | Shared native directory/RSS browsing, episode preview, subscriptions and core-owned offline episode downloads | | Remote | `cloud.gitwide.ampverse.remote` | Shared native desktop discovery/control/browsing UI, desktop A1–A3/B1–B3 selector and existing remote operations | @@ -32,19 +32,15 @@ Add-ons has Discover, Installed and Updates views. APK downloads require a compa Production release jobs require the existing `AMP_ANDROID_*` signing secrets and fail without them. Local previews use the existing phone-compatible development signing identity; do not substitute an unrelated CI debug key for an installed preview. -## Lab URL import +## Lab local audio -Paste or inspect one HTTPS YouTube video URL, then Download MP3. Playlist parameters on a video link are stripped; playlist-only/channel/untrusted URLs are rejected. MP3 at 256 kbps is automatic; conversion does not improve source quality. Downloads use pinned `youtubedl-android` 0.18.1 for its Android Python/yt-dlp/QuickJS runtime and the existing FFmpegKit audio library for conversion. No desktop executables, cookies/sign-in bypass, DRM handling, or runtime executable downloads are added. +Open local audio from the phone or a connected drive. Lab works from a separate editing copy; existing edited clips require an explicit replacement choice. Previously imported MP3s remain available through **Previously imported audio**, including the existing app-private `AMP Lab/downloads` directory. Removing the integrated downloader does not delete those files or editing sessions. -The downloader launches structured process arguments in its own native process group; Cancel kills that group and cancels its own FFmpeg session. Incomplete files belong to an isolated pending directory. Validated MP3s are atomically moved to unique persistent names under the app-private `AMP Lab/downloads` folder. Downloaded audio can be reopened from Lab. It enters the existing source-copy/waveform opening pipeline only after conversion and duration validation. Existing edited clips require an explicit replacement choice. +Lab retains source waveform, trim, fades, gain, normalization, preview and MP3 export using the existing FFmpegKit audio library. Built-in web extraction tools and their download-specific dependency are removed. Third-party module interfaces remain separate and unchanged. -The downloader wrapper is GPL-3.0. Full/Lab distribution must include its license and corresponding-source information, alongside existing FFmpeg/Python/component notices. See the Lab assets' `licenses/youtubedl-android` directory. Other editions/modules do not link this downloader. +## Verification -## Verified and remaining work - -Local checks have built both editions and all five signed companions, run unit URL validation, and passed Android lint. Pixel tests cover contract/signature validation, rejection of a foreign caller, the real packaged Python/QuickJS/yt-dlp entry point, cancellation against a stalled local server and playable local 256 kbps conversion with an unchanged original. Full companion-screen checks include a real engine fade-time change and restoration. Edition-switch and latest-build UI checks must be recorded separately from those results. - -Live YouTube MP3 downloading, physical Google Cast receiver playback, long screen-off/endurance operation and the full device/layout matrix have not been established by these checks. Do not call local fixtures live-download verification. +Current-source build, local audio decode/export and navigation/session checks must pass before publication. Historical downloader checks do not qualify the changed local-only surface. Physical Google Cast playback, long screen-off/endurance operation and the full device/layout matrix remain separate acceptance gates. Lab now includes an offline multitrack timeline (16 clips, eight lanes), non-destructive trim/gain/fades, waveform thumbnails, project save/relink, continuous MP3 export, and five-second clip export to revision-protected DJ sampler slots. Timeline rendering and sampler persistence/conflict protection have passed Pixel tests. Entering Lab leaves music playing; auditioning requests temporary Android audio focus. diff --git a/docs/ENGINE_UPGRADE_STATUS.md b/docs/ENGINE_UPGRADE_STATUS.md index 34e23213..625702bc 100644 --- a/docs/ENGINE_UPGRADE_STATUS.md +++ b/docs/ENGINE_UPGRADE_STATUS.md @@ -7,6 +7,11 @@ update catalogs remain RC33 until the platform and listening gates qualify. - 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; @@ -33,6 +38,13 @@ update catalogs remain RC33 until the platform and listening gates qualify. 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 @@ -49,6 +61,17 @@ update catalogs remain RC33 until the platform and listening gates qualify. 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. diff --git a/docs/LAB_YOUTUBE.md b/docs/LAB_YOUTUBE.md deleted file mode 100644 index 1a60bb7a..00000000 --- a/docs/LAB_YOUTUBE.md +++ /dev/null @@ -1,65 +0,0 @@ -# AMP Lab — music URL import - -The provider engine now handles YouTube, directly downloadable Suno audio, public SoundCloud tracks and Bandcamp track links. See [Music import engine](MUSIC_IMPORT_ENGINE.md) for supported sources, limits and verification. The existing YouTube playlist/setup instructions below remain applicable. - -In desktop **AMP Lab**, paste a YouTube video URL and press **Download MP3**. Progress covers downloading and MP3 conversion; **Cancel** stops the stage and its child processes. **Retry** appears after errors. The completed MP3 automatically enters the existing waveform editor with preview, selection, fades, gain, normalize and export. There is no format selector. - -The original download is a **256 kbps MP3**. Re-encoding does not improve the source quality. Lab exports suggest a separate `_clip.mp3` and reject existing destinations/source overwrites. If you have unexported edits, Lab asks before replacing them. Declining retains the editor and completed download; export first, then choose **Open downloaded MP3**. An active export also prevents replacement. This protection is shared by Open audio, From Library and URL imports. - -Completed originals persist in: - -- Windows: `%LOCALAPPDATA%\AMPVerse\AMP Lab\downloads` -- Linux: `$XDG_DATA_HOME/amp-verse/lab/downloads`, or `~/.local/share/amp-verse/lab/downloads`. - -Titles are sanitized and byte-bounded, video IDs identify sources, and collisions get numbered filenames. Each action uses its own temporary directory. Failures/Cancel remove incomplete files; completed files are retained. Completed MP3s are published atomically without replacing existing files. - -## Dependencies and recovery - -Windows x86_64 and Linux x86_64 packages include the official **yt-dlp 2026.10.26** standalone binary and **Deno 2.9.8** under `tools/lab-youtube`. These run as separate tools, not a plugin/add-on. The official yt-dlp standalone includes matching EJS scripts. YouTube support requires a supported JavaScript runtime (Deno >=2.3.0); see [yt-dlp's official EJS guide](https://github.com/yt-dlp/yt-dlp/wiki/EJS). The standalone includes Python; users do not need to install Python for normal downloading. yt-dlp's current Python-package minimum is 3.11; see [the pinned upstream release](https://github.com/yt-dlp/yt-dlp/releases/tag/2026.10.26). - -**FFmpeg, ffprobe and ffplay remain the existing AMP Lab audio dependencies**, located beside AMP Verse or on PATH. FFmpeg must include `libmp3lame`. This feature does not redistribute a new codec build. Linux: install your distribution's `ffmpeg` package (for example `sudo apt install ffmpeg`). Windows: use your existing AMP Verse audio tools, or obtain a Windows build linked from [FFmpeg's official download page](https://ffmpeg.org/download.html); place ffmpeg.exe, ffprobe.exe and ffplay.exe beside amp-player.exe. Retain that build's licenses and corresponding-source instructions. - -To repair or update the downloader/runtime bundle, run the included setup script with Python 3.11+: - -```text -python setup/setup_lab_youtube.py --dest tools/lab-youtube -``` - -From a source checkout: - -```text -python tools/setup_lab_youtube.py --dest target/release/tools/lab-youtube -``` - -The script fetches pinned official GitHub releases, verifies release SHA256 digests (or official checksum manifests), stages writes, and retains upstream licenses, third-party notices and project source archives. It neither invokes a shell nor installs global packages. Maintain the pinned versions in the script and ship updates through normal AMP Verse packages. Missing tools produce a readable error with **Downloads / tools → Locate tools** and **Setup instructions**. A selected tools folder is remembered locally. The `AMP_LAB_TOOLS` environment variable supports developer/managed installs. Unsupported architectures can provide their own official matching yt-dlp/EJS, Deno and audio tools; automatic packaging currently follows the project's Windows/Linux x86_64 targets. - -## Boundaries - -Accepts ordinary YouTube watch, youtu.be, Shorts, live-video permalink and embed URLs containing a single valid video ID. Canonicalization removes playlist/tracking parameters, and yt-dlp also receives `--no-playlist`. Channel URLs and ongoing livestreams are rejected. With Playlist off, video URLs still download one video and strip playlist parameters. With Playlist on, a YouTube playlist URL (or video URL with a list ID) queues up to 500 unique video IDs. Items download/convert sequentially; failed/private items are reported and skipped. A collision-safe M3U8 playlist is also saved beside the MP3s, containing only successful downloads in playlist order (including a partial playlist after Cancel). Completed MP3s remain available under Downloaded MP3s; choose a result to open through Lab’s normal unsaved-edit protection. Cancel stops the active process tree and retains completed files. Re-running a playlist currently downloads its available entries again with collision-safe names; persistent resume/deduplication is not implemented. No cookies, browser sessions, user yt-dlp configuration, user plugins, DRM bypass or access-control bypass are used. Private/unavailable videos, network failures, disk errors and conversion errors leave the existing editor/source intact. - -The UI uses bounded worker channels. Processes use structured argument arrays and isolated Windows Job Objects / Unix process groups; cancellation and timeouts terminate the whole tree. URL imports remain in Lab on desktop and Android; Player, DJ and Library do not own a second downloader. - -## Verification - -Focused tests cover URL validation and playlist stripping, progress parsing, safe Unicode filenames, atomic filename collisions, missing tools, disk-path errors, private/network/invalid-audio failures, original preservation, and declined/blocked edit replacement. A locally compiled fake downloader and **real FFmpeg/Deno** exercise the entire download/conversion/publication/automatic-delivery path, including Cancel during download and conversion and a spawned grandchild heartbeat. A real editor-open test verifies waveform decoding and source preservation. - -Live verification on Windows also succeeded against the public Big Buck Bunny test video (`aqz-KE-bpKQ`) using the official pinned yt-dlp/Deno and installed FFmpeg. The older upstream test ID `BaW_jenozKc` was unavailable and correctly reported as such; its fixtures remain deterministic local tests. Live YouTube access is intentionally excluded from routine CI, where it could fail due to video/network availability. Linux CI runs the local pipeline with real codecs and packages the official runtime bundle. - -## Hidden Suno URL support - -Paste a Suno song (`https://suno.com/song/`), short share (`/s/...`), or an explicit Suno CDN audio-download link into the existing YouTube URL field. The label changes to **Suno URL** only while a Suno link is present; no extra tab, catalog add-on or always-visible provider selector is added. The YouTube Playlist choice stays available for YouTube and is ignored/hidden for single-song Suno imports. - -Suno imports read publicly exposed downloadable audio for the exact song, reject placeholder/silence and unrelated song URLs, and retain the title and canonical source link in the MP3 metadata. They use the same 256 kbps MP3 conversion, progress, Cancel, collision-safe publication and protected editor-open flow. Conversion does not increase the source quality. Suno only requires the existing FFmpeg/ffprobe tools; it does not use yt-dlp or Deno. - -Public song pages and audio redirects are bounded and restricted to Suno's known hosts and matching song identity. Audio downloads are capped at 256 MB, page reads at 4 MB, and temporary files are removed on cancellation/failure. Unencoded public progressive-audio records are supported alongside legacy audio metadata. Some current Suno share links expose encoded playback data instead of a standard downloadable audio file; these require Suno's official export flow. Explicitly disabled downloads, encoded playback records and encrypted media are rejected, rather than saving an unusable MP3. No login cookies, credential extraction, guessed CDN URLs or access-control bypass are used. If Suno does not expose a standard downloadable file, use the contextual **Open in Suno** link and its official export menu, then **Open exported MP3...** to bring that file into Lab through the same unsaved-edit protection. Short links without a resolvable public song identity require the full song link. Suno playlists, profiles and account-only exports are not implemented. - -Verification includes Suno song/share/CDN validation, tracking removal, Next.js public metadata extraction, HTML title decoding, placeholder rejection, cancellation/size bounds, and real FFmpeg conversion/tagging and final Lab decoding on Windows and Linux. Live availability depends on Suno; fixture tests do not establish that a particular restricted link can be downloaded. - -Official export help: https://help.suno.com/en/articles/2409921 - -1.0.8 verification: local playlist fixture with a successful item and a private -item, real FFmpeg conversion, retained successful audio/M3U8 membership, result -selection without automatic editor replacement, and existing process-tree Cancel -tests passed. Live playlist downloading was not exercised in this pass. - -Android Lab uses the same hidden Suno URL routing: paste a Suno link into the existing URL field and its tab changes to Suno. Public song/share/CDN links are inspected and downloaded directly, without initializing the YouTube extractor. Downloads use the existing isolated temporary directory, cancellation, 256 kbps MP3 conversion, title/source metadata, decode verification, atomic publication and edit protection. Encoded/disabled/unavailable downloads show an explicit Suno explanation; they are never sent to YouTube or replaced with a guessed audio URL. diff --git a/docs/MUSIC_IMPORT_ENGINE.md b/docs/MUSIC_IMPORT_ENGINE.md index 05b83723..cd750e29 100644 --- a/docs/MUSIC_IMPORT_ENGINE.md +++ b/docs/MUSIC_IMPORT_ENGINE.md @@ -1,37 +1,11 @@ -# Music import engine +# Lab local audio import -Paste a song link into **Lab → Import audio**, inspect it, then download a local MP3 for editing or use in your library. Desktop retains its separate, explicit YouTube playlist mode. Android imports one song per link. +Lab opens local audio for waveform editing, trim, fades, gain, normalization, preview and export. Importing or editing does not replace the original file. -| Source | Implemented route | Important limit | -| --- | --- | --- | -| YouTube / YouTube Music | One completed video, through the bundled yt-dlp extractor | No ongoing live broadcast, sign-in or protected audio | -| Suno | Public song/share metadata with an explicit downloadable audio file | Encoded/protected media is not decrypted; use a Suno-exported file when no ordinary download is exposed | -| SoundCloud | A public `soundcloud.com/creator/song` link through its specific extractor | No profile, set, station, subscription or sign-in route; short share URLs are not expanded | -| Bandcamp | An `artist.bandcamp.com/track/song` link through its specific extractor | No album expansion, purchase account access or redemption links | -| Pandora | Recognized and explained as unsupported for MP3 import | Pandora offline downloads remain within Pandora | -| Exported local audio | Existing **Local file / Open audio** | Uses the user's downloaded file, without accessing the service account | +The integrated web downloaders were removed under owner Task 15. Bring audio from a separate application into the library or open it directly in Lab. Third-party module support is unchanged. -Technical support does not establish permission to save someone else's music. Use your own work or audio you are authorized to download. A supported extractor may still fail when a service changes or removes a track. A public preview is not a purchased master. - -## One job, one source - -The existing download worker owns inspection, transfer, MP3 conversion, validation and publication. Source selection is explicit: a failed SoundCloud request never searches YouTube for a replacement, and no generic extractor is used for these single-song requests. Unsupported providers are rejected before starting a download tool. Metadata must identify the requested song; collections, live broadcasts and protected media are rejected. - -Desktop uses `lab_music_source.rs` within the existing Lab importer. Android uses `ImportUrl` within `UrlDownload`. Both execute the same checked-in source fixtures, `music-import-sources.json`. This keeps platform routing behavior reviewable without introducing a second download queue, server dependency or unrelated service. - -Each import stages work privately, retains completed downloads, and leaves current edits unchanged on failure. Cancellation owns the active process tree and conversion. Android conversion completion arrives by callback, rather than repeatedly checking its status. There is no background server polling or search fallback in the source resolver. The pre-existing network/process timeout and extractor retry behavior is separate from source routing. - -## Output and resources - -- MP3 at 256 kbps using the existing FFmpeg tooling; conversion cannot improve source quality. -- Title and available artist, album, release date and original source link are written as metadata. Suno's existing AI-generated category is preserved. -- Known extractor duration must be positive and no more than four hours. Suno metadata may omit duration; the resulting file is checked by the existing codec pipeline. -- The extractor receives a 256 MB source-size limit, and the resulting source is checked before conversion. If a service omits the transfer size, this is not a hard streaming quota; the size check can occur after transfer. Suno's own reader enforces the bound while reading. -- Same-title downloads get collision-safe names. No original or completed download is overwritten. -- YouTube requires its bundled JavaScript runtime. SoundCloud and Bandcamp do not require Deno on desktop. +Existing clips and previously imported audio remain in place. Android exposes **Previously imported audio** for MP3s already saved under its private Lab directory. Editing sessions retain their source links. ## Verification -Shared source fixtures cover routing, canonical links, lookalike domains, unsupported services and collection rejection. Metadata tests cover changed identities, protected media and invalid duration. Desktop pipeline fixtures enforce the selected extractor and exercise real FFmpeg conversion and final-file decoding for SoundCloud and Bandcamp shapes. These generated fixtures prove the pipeline, not current live service availability. Existing cancellation, collision, Suno-codec and Android end-to-end import tests remain required. - -Current service references: [yt-dlp supported extractors](https://github.com/yt-dlp/yt-dlp/blob/master/supportedsites.md), [Pandora downloads](https://help.pandora.com/s/article/Offline-Mode-and-Downloads?language=en_US), [Suno export formats](https://help.suno.com/en/articles/13926081), [SoundCloud downloads](https://help.soundcloud.com/hc/en-us/articles/115003448787-Downloading-tracks), [Bandcamp downloads](https://get.bandcamp.help/en/articles/15263234-in-which-formats-can-i-download-my-purchases). +`tools/verify_music_import_engine.py` generates a local MP3, exercises the real editor opening/waveform path, verifies original-file preservation, checks unsaved-edit protection, and runs a codec export. It does not contact music services. The Windows/Linux workflow runs these checks; Android navigation and editing-session checks remain part of the device suite. diff --git a/docs/SUNO_DOWNLOAD_RESEARCH.md b/docs/SUNO_DOWNLOAD_RESEARCH.md deleted file mode 100644 index a4616e1e..00000000 --- a/docs/SUNO_DOWNLOAD_RESEARCH.md +++ /dev/null @@ -1,37 +0,0 @@ -# Suno download research for AMP Verse - -Checked 2026-11-30. Official public documentation only. Recommendations below are integration judgments, not confirmation of a Suno API contract. - -## What public availability permits - -Public/share links support listening and sharing on Suno; the download FAQ expressly separates unlimited on-platform playback/sharing from exporting files. A public song URL alone is not evidence that the listener can export that song. [Download FAQ](https://help.suno.com/en/articles/13614785) - -Suno's mobile app supports offline listening to users' own playlists and public playlists. Those saves remain inside Suno, rather than becoming individual audio files available to another player. AMP Verse should therefore link users to Suno for that capability. [Offline playlists, updated November 12, 2026](https://help.suno.com/en/articles/14467265) - -## Authorized exports - -The documented file export workflow starts in the user's Library or Workspace: song menu → Download → available format. Multiple selected songs can be exported together as a ZIP. This describes an official user-facing route, not a permission to automate private endpoints or export every public song. [Download instructions, updated September 9, 2026](https://help.suno.com/en/articles/2409921) - -MP3 is listed for all plans; WAV is listed for Pro/Premier on the website. Availability still depends on the song, device, feature and plan. Format availability does not itself establish download entitlement. [File types, updated September 9, 2026](https://help.suno.com/en/articles/13926081) - -The terms effective September 3, 2026 require copies to come through Suno-provided download channels and prohibit stream ripping/recording. They prohibit defeating content protections and scraping. Paid commercial use depends on a permitted download and applicable rights; remixes retain personal/noncommercial restrictions. Broad language about copying Output published in third-party applications such as Discord also appears, but does not establish a general export right for Suno public-song pages. Treat that apparent tension conservatively and seek written clarification for a broader integration. [Suno terms](https://about.suno.com/terms) - -## Documentation conflicts and limits - -- The download article appeared in this researcher's search/open snapshot as a November 13 revision saying free accounts receive zero credits with purchases available. A separate current-page check by the coordinating agent saw a November 25 revision describing seven grandfathered free downloads and occasional trials for newer free accounts. Pro receives 20 monthly and Premier 60; Studio workflows are excluded from limits. This illustrates stale search/page snapshots: use the current signed-in account as the source for entitlement. [How downloads work](https://help.suno.com/en/articles/13876865) -- The FAQ edited November 25 still says free accounts have up to seven lifetime trial downloads for personal use, while repeating 20/60 paid limits. It also calls September 2026 changes upcoming despite its November edit date. Do not hardcode free entitlements from either article; the signed-in account and actual official Download control must determine availability. [FAQ](https://help.suno.com/en/articles/13614785) -- Older rights articles may describe rights by generation-time subscription alone. The current terms and newer download FAQ add approved-download requirements. Avoid promising commercial rights solely from public visibility or subscription status. [Rights documentation index](https://help.suno.com/en/categories/550145-rights-ownership) -- No official public third-party download API or general public-song export authorization was located in the reviewed sources. This is a search limitation, not proof that partnership APIs cannot exist. - -## Practical AMP Verse options - -1. **Open in Suno:** retain a source URL and offer a browser/app handoff for playback and official download actions. A locked or unavailable download should remain unavailable. -2. **Import an authorized local file:** let the user choose MP3/WAV exported through Suno's official control, then use the existing local-library workflow. Keep source URL and optional rights/provenance notes; preserve embedded provenance metadata. -3. **Creator-provided file:** accept a file supplied by its creator with permission covering the intended use and confirmation it came through an authorized export route. Creator permission alone does not turn an unofficial stream extraction into a Suno-approved download. -4. **Request a supported integration:** obtain written Suno approval and documented API/partner terms before implementing automated account exports, public-song downloads, or in-app streaming beyond a normal external-link handoff. - -Do not infer authorization from a CDN URL, playable stream, cached mobile asset, or HTTP success. Do not implement decryption, key extraction, access-control workarounds, or rights-endpoint bypasses. - -## Current AMP Verse state - -The existing direct-file importer shipped in RC28/RC29. It accepts explicit downloadable audio and rejects records marked protected, encrypted, or download-disabled. This research does not add decryption support, change the app, or establish that any third-party downloader is authorized or reliable. diff --git a/tools/install-v1-preview.ps1 b/tools/install-v1-preview.ps1 index f3c36343..30a6f995 100644 --- a/tools/install-v1-preview.ps1 +++ b/tools/install-v1-preview.ps1 @@ -9,11 +9,20 @@ $binary = Join-Path $repo 'target/release/amp-player.exe' if (!(Test-Path -LiteralPath $binary)) { throw 'Build the V1 player first.' } New-Item -ItemType Directory -Force -Path $Destination | Out-Null # Copy runtime tools and their notices together; never alter the stable installation. -foreach ($name in @('ffmpeg.exe','ffprobe.exe','ffplay.exe','yt-dlp.exe','deno.exe','licenses','addons','tools','lab-tools','AUDIO_TOOL_NOTICES.md')) { - if ($name -in @('addons','tools','lab-tools') -and (Test-Path -LiteralPath (Join-Path $Destination $name))) { continue } +foreach ($name in @('ffmpeg.exe','ffprobe.exe','ffplay.exe','licenses','addons','AUDIO_TOOL_NOTICES.md')) { + if ($name -eq 'addons' -and (Test-Path -LiteralPath (Join-Path $Destination $name))) { continue } $source = Join-Path $previous $name if (Test-Path -LiteralPath $source) { Copy-Item -LiteralPath $source -Destination $Destination -Recurse -Force } } +foreach ($name in @('tools','lab-tools')) { + $source = Join-Path $previous $name + $target = Join-Path $Destination $name + if (!(Test-Path -LiteralPath $source -PathType Container) -or (Test-Path -LiteralPath $target)) { continue } + New-Item -ItemType Directory -Path $target | Out-Null + Get-ChildItem -LiteralPath $source | Where-Object { + $_.Name -notin @('lab-youtube','yt-dlp','yt-dlp.exe','deno','deno.exe') + } | ForEach-Object { Copy-Item -LiteralPath $_.FullName -Destination $target -Recurse } +} foreach ($name in @('amp-player.exe','amp-keylock.dll','amp-update.exe')) { Copy-Item -LiteralPath (Join-Path $repo "target/release/$name") -Destination $Destination -Force } diff --git a/tools/lab_youtube_fixture.rs b/tools/lab_youtube_fixture.rs deleted file mode 100644 index be0b5eb6..00000000 --- a/tools/lab_youtube_fixture.rs +++ /dev/null @@ -1,90 +0,0 @@ -//! Isolated fake yt-dlp for import/cancel tests. Never shipped in application packages. -use std::{ - env, fs, - io::{self, Write}, - path::PathBuf, - process::Command, - thread, - time::Duration, -}; -fn main() { - let args: Vec<_> = env::args().collect(); - if args.get(1).map(String::as_str) == Some("--heartbeat") { - let path = PathBuf::from(&args[2]); - loop { - if let Ok(mut file) = fs::OpenOptions::new().create(true).append(true).open(&path) { - let _ = file.write_all(b"beat\n"); - } - thread::sleep(Duration::from_millis(30)); - } - } - let exe = env::current_exe().unwrap(); - let name = exe.file_stem().unwrap().to_string_lossy(); - assert!(args.iter().any(|a| a == "--no-playlist")); - assert!(args.iter().any(|a| a == "--ignore-config")); - if args.iter().any(|a| a == "--flat-playlist") { - assert!(args.iter().any(|a| a == "--yes-playlist")); - println!("{{\"entries\":[{{\"id\":\"BaW_jenozKc\"}},{{\"id\":\"abcdefghijk\"}}]}}"); - return; - } - if args.last().unwrap().ends_with("v=abcdefghijk") { - eprintln!("ERROR: Private video"); - std::process::exit(1); - } - let source = args.last().unwrap(); - let (id, extractor) = match source.as_str() { - "https://www.youtube.com/watch?v=BaW_jenozKc" => ("BaW_jenozKc", "Youtube"), - "https://soundcloud.com/fixture/example" => ("sc-fixture", "Soundcloud"), - "https://fixture.bandcamp.com/track/example" => ("bc-fixture", "Bandcamp"), - _ => panic!("Unexpected fixture source {source}"), - }; - let source_arg = args - .iter() - .position(|a| a == "--use-extractors") - .expect("Explicit provider required"); - assert_eq!(args[source_arg + 1], extractor); - if name.contains("network") { - eprintln!("ERROR: network timed out"); - std::process::exit(1); - } - if name.contains("private") { - eprintln!("ERROR: Private video"); - std::process::exit(1); - } - if args.iter().any(|a| a == "--dump-single-json") { - println!( - "{{\"id\":\"{id}\",\"webpage_url\":\"{source}\",\"title\":\"Test: audio / source\",\"artist\":\"Fixture artist\",\"album\":\"Fixture album\",\"is_live\":false,\"duration\":2}}" - ); - return; - } - let index = args.iter().position(|a| a == "-o").unwrap(); - let template = PathBuf::from(&args[index + 1]); - let work = template.parent().unwrap(); - if name.contains("cancel") { - let heartbeat = work.parent().unwrap().join("heartbeat"); - let _child = Command::new(&exe) - .arg("--heartbeat") - .arg(heartbeat) - .spawn() - .unwrap(); - fs::write(work.join("source.part"), b"partial").unwrap(); - loop { - println!("AMP_PROGRESS: 5%"); - io::stdout().flush().unwrap(); - thread::sleep(Duration::from_millis(50)); - } - } - let source = work.join("source.wav"); - if name.contains("invalid") { - fs::write(&source, b"not audio").unwrap(); - } else { - fs::copy(exe.parent().unwrap().join("fixture.wav"), &source).unwrap(); - } - println!("AMP_PROGRESS: 50%"); - println!("AMP_PROGRESS: 100%"); - let quoted = source - .to_string_lossy() - .replace('\\', "\\\\") - .replace('"', "\\\""); - println!("AMP_FILE:\"{quoted}\""); -} diff --git a/tools/launch-tested-preview.ps1 b/tools/launch-tested-preview.ps1 index 9b4a5f75..eac49aa2 100644 --- a/tools/launch-tested-preview.ps1 +++ b/tools/launch-tested-preview.ps1 @@ -38,7 +38,6 @@ $values = @{ AMP_DOCUMENTS_DIR=(Join-Path $profile 'Documents'); AMP_CONTROL_BIND='127.0.0.1:8790'; AMP_CAST_ADDRESS='127.0.0.1:8787'; AMP_CAST_BIND='127.0.0.1:8787'; AMP_CAST_CONFIG_DIR=(Join-Path $profile 'settings\cast-host'); - AMP_LAB_TOOLS=(Join-Path $app 'tools\lab-youtube'); AMP_STEM_PYTHON=(Join-Path $app 'addons\stems\Scripts\python.exe') } # Some legacy preference/index readers derive AppData from USERPROFILE rather diff --git a/tools/package_android_modules.py b/tools/package_android_modules.py index 8e914aa2..354981fc 100644 --- a/tools/package_android_modules.py +++ b/tools/package_android_modules.py @@ -12,7 +12,7 @@ IDS = ("dj", "lab", "cast", "podcasts", "remote") CAPABILITIES = { "dj": ["two-deck", "cue-decks", "prepared-auto-mix", "hot-cues", "sampler-playback"], - "lab": ["trim", "fades", "gain", "normalize", "mp3-export", "youtube-url-import"], + "lab": ["trim", "fades", "gain", "normalize", "mp3-export"], "cast": ["lan-discovery", "station-listening", "google-cast", "host-live-broadcast", "offline-playlist-sync"], "podcasts": ["directory-search", "rss", "preview", "subscriptions", "offline-episodes"], "remote": ["host-discovery", "desktop-control", "desktop-library", "desktop-playlists"], diff --git a/tools/setup_lab_youtube.py b/tools/setup_lab_youtube.py deleted file mode 100644 index e8077ae1..00000000 --- a/tools/setup_lab_youtube.py +++ /dev/null @@ -1,114 +0,0 @@ -#!/usr/bin/env python3 -"""Pinned, checksum-verified official tools for AMP Lab (Windows/Linux x86_64). - -No pip, shell, global installation or access credentials. FFmpeg remains the -existing external audio dependency; see docs/LAB_YOUTUBE.md for OS setup. -""" -import argparse -import hashlib -import io -import json -import os -from pathlib import Path -import platform -import tempfile -import urllib.request -import urllib.parse -import zipfile - -YT_VERSION = "2026.10.26" -DENO_VERSION = "v2.9.8" - - -def fetch(url): - request = urllib.request.Request(url, headers={"User-Agent": "AMPVerse-Lab-Setup", "Accept": "application/vnd.github+json"}) - token = os.environ.get("GH_TOKEN") - if token and urllib.parse.urlsplit(url).hostname == "api.github.com": - request.add_header("Authorization", "Bearer " + token) - class SafeRedirect(urllib.request.HTTPRedirectHandler): - def redirect_request(self, req, fp, code, msg, headers, newurl): - redirected = super().redirect_request(req, fp, code, msg, headers, newurl) - if redirected and urllib.parse.urlsplit(newurl).hostname != urllib.parse.urlsplit(req.full_url).hostname: - redirected.remove_header("Authorization") - return redirected - with urllib.request.build_opener(SafeRedirect).open(request, timeout=120) as response: - return response.read() - - -def release(repo, tag): - return json.loads(fetch(f"https://api.github.com/repos/{repo}/releases/tags/{tag}")) - - -def verified_asset(info, name): - assets = {a["name"]: a for a in info["assets"]} - asset = assets[name] - content = fetch(asset["browser_download_url"]) - expected = asset.get("digest") or "" - if expected.startswith("sha256:"): - expected = expected.removeprefix("sha256:") - else: - expected = "" - for manifest in ("SHA2-256SUMS", name + ".sha256sum"): - if manifest not in assets: - continue - for line in fetch(assets[manifest]["browser_download_url"]).decode().splitlines(): - parts = line.split() - if len(parts) == 2 and parts[1].lstrip("*") == name: - expected = parts[0] - actual = hashlib.sha256(content).hexdigest() - if len(expected) != 64 or actual != expected: - raise RuntimeError(f"Missing or mismatched official SHA256 for {name}; nothing installed") - return content, {"url": asset["browser_download_url"], "sha256": actual} - - -def write(path, data, executable=False): - path.parent.mkdir(parents=True, exist_ok=True) - with tempfile.NamedTemporaryFile(dir=path.parent, delete=False) as temp: - temp.write(data) - temp.flush() - os.fsync(temp.fileno()) - temporary = Path(temp.name) - try: - temporary.chmod(0o755 if executable else 0o644) - os.replace(temporary, path) - finally: - temporary.unlink(missing_ok=True) - - -def main(): - parser = argparse.ArgumentParser(description=__doc__) - parser.add_argument("--dest", type=Path, required=True, help="AMP Verse/tools/lab-youtube") - args = parser.parse_args() - system = platform.system() - if system not in ("Windows", "Linux") or platform.machine().lower() not in ("amd64", "x86_64"): - raise SystemExit("Automatic setup supports Windows/Linux x86_64. Install official yt-dlp, EJS, Deno >=2.3 and FFmpeg for your platform, then Locate tools in Lab.") - windows = system == "Windows" - yt_name = "yt-dlp.exe" if windows else "yt-dlp_linux" - deno_name = "deno-x86_64-pc-windows-msvc.zip" if windows else "deno-x86_64-unknown-linux-gnu.zip" - print("Downloading verified official yt-dlp and Deno releases...", flush=True) - yt, yt_manifest = verified_asset(release("yt-dlp/yt-dlp", YT_VERSION), yt_name) - deno_zip, deno_manifest = verified_asset(release("denoland/deno", DENO_VERSION), deno_name) - binary = "deno.exe" if windows else "deno" - with zipfile.ZipFile(io.BytesIO(deno_zip)) as archive: - deno = archive.read(binary) # Never extract arbitrary archive paths. - # Collect license and corresponding project sources before publishing binaries. - notices = { - "yt-dlp-LICENSE": fetch(f"https://raw.githubusercontent.com/yt-dlp/yt-dlp/{YT_VERSION}/LICENSE"), - "yt-dlp-THIRD_PARTY_LICENSES.txt": fetch(f"https://raw.githubusercontent.com/yt-dlp/yt-dlp/{YT_VERSION}/THIRD_PARTY_LICENSES.txt"), - "deno-LICENSE.md": fetch(f"https://raw.githubusercontent.com/denoland/deno/{DENO_VERSION}/LICENSE.md"), - "deno-rusty-v8-LICENSE": fetch("https://raw.githubusercontent.com/denoland/rusty_v8/v150.4.0/LICENSE"), - "deno-v8-engine-LICENSE": fetch("https://raw.githubusercontent.com/v8/v8/15.0.245/LICENSE"), - "deno-typescript-LICENSE": fetch("https://raw.githubusercontent.com/microsoft/TypeScript/v6.0.3/LICENSE.txt"), - "yt-dlp-source.tar.gz": fetch(f"https://github.com/yt-dlp/yt-dlp/archive/refs/tags/{YT_VERSION}.tar.gz"), - "deno-source.tar.gz": fetch(f"https://github.com/denoland/deno/archive/refs/tags/{DENO_VERSION}.tar.gz"), - } - for name, content in notices.items(): - write(args.dest / "licenses" / name, content) - write(args.dest / ("yt-dlp.exe" if windows else "yt-dlp"), yt, True) - write(args.dest / binary, deno, True) - write(args.dest / "versions.json", json.dumps({"yt-dlp": {"version": YT_VERSION, **yt_manifest}, "deno": {"version": DENO_VERSION, **deno_manifest}, "ejs": "included in official yt-dlp standalone binary", "ffmpeg": "external; existing AMP audio tool lookup"}, indent=2).encode()) - print(f"Installed in {args.dest}. FFmpeg and ffprobe must be beside AMP Verse or on PATH.") - - -if __name__ == "__main__": - main() 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_setup_lab_youtube.py b/tools/test_setup_lab_youtube.py deleted file mode 100644 index 9cd9ea30..00000000 --- a/tools/test_setup_lab_youtube.py +++ /dev/null @@ -1,28 +0,0 @@ -"""No-network checks for the official-tool setup's checksum gate.""" -import hashlib -import unittest -from unittest.mock import patch -import setup_lab_youtube as setup - - -class SetupTest(unittest.TestCase): - def test_digest_verified_before_binary_is_returned(self): - blob = b"test executable" - info = {"assets": [{"name": "tool", "browser_download_url": "https://github.com/official/tool", "digest": "sha256:" + hashlib.sha256(blob).hexdigest()}]} - with patch.object(setup, "fetch", return_value=blob): - data, manifest = setup.verified_asset(info, "tool") - self.assertEqual(data, blob) - self.assertEqual(manifest["sha256"], hashlib.sha256(blob).hexdigest()) - info["assets"][0]["digest"] = "sha256:" + "0" * 64 - with self.assertRaises(RuntimeError): - setup.verified_asset(info, "tool") - - def test_no_digest_or_checksum_never_installs(self): - info = {"assets": [{"name": "tool", "browser_download_url": "https://github.com/official/tool"}]} - with patch.object(setup, "fetch", return_value=b"unverified"): - with self.assertRaises(RuntimeError): - setup.verified_asset(info, "tool") - - -if __name__ == "__main__": - unittest.main() diff --git a/tools/verify_music_import_engine.py b/tools/verify_music_import_engine.py index 2c5ca485..f5d9fd62 100644 --- a/tools/verify_music_import_engine.py +++ b/tools/verify_music_import_engine.py @@ -20,21 +20,19 @@ def main(): os.chdir(root) work = root / "test-output/music-import-engine" work.mkdir(parents=True, exist_ok=True) - fixture = work / ("yt-dlp-fixture.exe" if os.name == "nt" else "yt-dlp-fixture") - run(["rustc", "tools/lab_youtube_fixture.rs", "-o", str(fixture)]) + source = work / "fixture.mp3" run(["ffmpeg", "-n", "-hide_banner", "-loglevel", "error", "-f", "lavfi", "-i", - "sine=frequency=440:duration=2", str(work / "fixture.wav")]) - env = dict(os.environ, AMP_LAB_TOOLS=str(root / "test-output/lab-tools"), - AMP_LAB_YOUTUBE_FIXTURE=str(fixture)) + "sine=frequency=440:duration=2", "-c:a", "libmp3lame", "-b:a", "256k", str(source)]) + env = dict(os.environ, AMP_LAB_LOADED_MP3=str(source)) base = ["cargo", "test", "--locked", "-p", "amp-player", "--bin", "amp-player"] - run(base + ["lab_youtube::", "--", "--test-threads=1"], env, True) - run(base + ["lab_youtube::tests::local_", "--", "--ignored", "--test-threads=1"], env, True) - run(base + ["lab_youtube::suno::tests::local_codec_import", "--", "--ignored", "--test-threads=1"], env, True) + run(base + ["lab_editor::tests::", "--", "--test-threads=1"], env, True) + run(base + ["lab_editor::tests::local_mp3", "--", "--ignored", "--test-threads=1"], env, True) + run(base + ["lab_editor::tests::ffmpeg_export_smoke", "--", "--ignored", "--test-threads=1"], env, True) (work / "proof.json").write_text(json.dumps({ "source_commit": os.environ.get("GITHUB_SHA", "local"), "platform": sys.platform, - "source": "generated sine audio and explicit fake extractors", - "passed": ["source routing and identity", "real MP3 decode and metadata", - "cancellation and collision preservation", "Suno codec and publication"], + "source": "generated local sine audio", + "passed": ["local MP3 decode and source preservation", "waveform and trim controls", + "unsaved edit protection", "real codec export"], "live_music_services_tested": False, }, indent=2) + "\n", encoding="utf-8")