From 96d4bbf3108f946bed3957d6aa83c16b291e671e Mon Sep 17 00:00:00 2001 From: Xiantaidu Date: Thu, 12 Nov 2026 16:34:34 +0800 Subject: [PATCH] Import CopyVocal files (.cvf) as editable projects CopyVocal exports a correction job as a versioned document; OpenTune imports it as a project that can still be edited, rather than as a flat rendered wav. The student reference audio, the notes, the student's original F0, CopyVocal's corrected target F0 mapped back to source time, and the source->output time grid all enter the editing model. The format is CopyVocal's: identifier "copyvocal.file", extension .cvf. This repository carries only the reader and a user-facing import guide; the format definition lives in CopyVocal's own docs/. There is no compatibility path for the earlier experimental spelling -- the format had no external users. - Source/Utils/CopyVocalBundle.* parses and validates the JSON, decodes the base64 F0 arrays, and builds the editable domain types (Note / PitchCurve / TimeGridSnapshot). It is deliberately free of the audio engine, project session and UI so it can be tested on its own. - ProjectSession::prepareCopyVocalBundle runs on a worker: it fits the student media to the bundle's declared duration, injects both F0 layers (no extraction is started) and proposes an .otproj path next to the bundle. - The editor accepts files by menu and by drag-and-drop; the chooser, the drag test and the loader all read the extension from CopyVocalBundle::kFileExtension instead of spelling it out at each call site. Two TimeGrid points the importer depends on: - buildTimeGrid emits word granularity. A region spans one word, so its student/teacher start and end are the anchors worth exposing; the region's teacher_anchors/student_anchors arrays are sub-word phoneme splits, and silence/mute regions have a zero-length student span and map nothing. Expanding the phoneme arrays put 38 handles on a 17-word sentence with gaps down to 30 ms -- a wall of handles nobody edits by hand. - TimeGridSnapshot::validate exempts pairs touching a High-confidence anchor from the 150 ms minimum source spacing. That limit is an editing-UX constraint, not a DSP invariant, and an externally imported analysis is entitled to place anchors closer than a human would. Without the exemption a dense grid fails validation and buildTimeGrid silently falls back to identity, so the import succeeds with the time mapping gone. docs/copyvocal-import.md is the user-facing walkthrough and is whitelisted in .gitignore, which ignores docs/ wholesale. The whitelist uses docs/* rather than docs/ -- a trailing slash excludes the directory itself, and Git then never descends to apply the ! exception. Tests: CopyVocalBundleTests parses a synthetic bundle and rejects a future formatVersion and a duration mismatch (it also takes a real export as argv[1] for a round-trip); CopyVocalImportTests drives the full prepare path including the trim case where corrected output is shorter than the student media. --- .gitignore | 6 +- CMakeLists.txt | 63 ++ Source/Standalone/PluginEditor.cpp | 115 ++- Source/Standalone/PluginEditor.h | 6 + Source/Standalone/UI/MenuBarComponent.cpp | 5 + Source/Standalone/UI/MenuBarComponent.h | 2 + Source/Utils/CopyVocalBundle.cpp | 941 ++++++++++++++++++++++ Source/Utils/CopyVocalBundle.h | 169 ++++ Source/Utils/LocalizationManager.h | 6 + Source/Utils/ProjectSession.cpp | 184 ++++- Source/Utils/ProjectSession.h | 13 + Source/Utils/TimeGrid.cpp | 8 +- Source/Utils/TimeGrid.h | 1 + Tests/CopyVocalBundleTests.cpp | 293 +++++++ Tests/CopyVocalImportTests.cpp | 218 +++++ docs/copyvocal-import.md | 107 +++ 16 files changed, 2121 insertions(+), 16 deletions(-) create mode 100644 Source/Utils/CopyVocalBundle.cpp create mode 100644 Source/Utils/CopyVocalBundle.h create mode 100644 Tests/CopyVocalBundleTests.cpp create mode 100644 Tests/CopyVocalImportTests.cpp create mode 100644 docs/copyvocal-import.md diff --git a/.gitignore b/.gitignore index 12125f8f..6c3db9f6 100644 --- a/.gitignore +++ b/.gitignore @@ -17,7 +17,11 @@ install_manifest.txt !cmake/*.cmake models/* pc_nsf_hifigan_44.1k_ONNX/ -docs/ +# Ignore docs/ except the CopyVocal import guide, which documents the reader in this +# repository. The bundle format itself is defined by CopyVocal. +# Use `docs/*` rather than `docs/` so Git still traverses docs/ for the `!` exception below. +docs/* +!docs/copyvocal-import.md docs/UserGuide.html .*/ # .*/ 会忽略点开头的目录;Actions 工作流必须入库 diff --git a/CMakeLists.txt b/CMakeLists.txt index b1aaf269..0e37ff4c 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -917,6 +917,8 @@ set(OPENTUNE_STANDALONE_SOURCES Source/Utils/ProjectPersistence.h Source/Utils/ProjectSession.cpp Source/Utils/ProjectSession.h + Source/Utils/CopyVocalBundle.cpp + Source/Utils/CopyVocalBundle.h Source/Utils/PlacementActions.cpp Source/Utils/PlacementActions.h @@ -2026,6 +2028,28 @@ if(OPENTUNE_BUILD_TESTS) endif() add_test(NAME VisibleTrackCountTests COMMAND OpenTuneVisibleTrackCountTests) + # CopyVocal .cvf parser + editable-domain builders (JUCE core only). + add_executable(OpenTuneCopyVocalBundleTests + Tests/CopyVocalBundleTests.cpp + Source/Utils/CopyVocalBundle.cpp + Source/Utils/PitchCurve.cpp + Source/Utils/TimeGrid.cpp + Source/Utils/ProjectModel.cpp + Source/Utils/AppLogger.cpp + ) + target_include_directories(OpenTuneCopyVocalBundleTests + PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/Source) + target_link_libraries(OpenTuneCopyVocalBundleTests PRIVATE + juce::juce_audio_basics + juce::juce_core + juce::juce_graphics + ) + if(MSVC) + target_compile_options(OpenTuneCopyVocalBundleTests PRIVATE /utf-8 /EHsc) + endif() + add_test(NAME CopyVocalBundleTests COMMAND OpenTuneCopyVocalBundleTests) + + # Demo-tour load gate: a not-yet-started open is not a failed open. add_executable(OpenTuneDemoTourGateTests Tests/DemoTourGateTests.cpp @@ -2178,6 +2202,45 @@ if(OPENTUNE_BUILD_TESTS) endif() add_test(NAME StandaloneArrangementMoveTests COMMAND OpenTuneStandaloneArrangementMoveTests) + # CopyVocal .cvf -> PreparedOpen (audio fit, F0 injection, snapshot wiring). + # Links the real Standalone shared code; no inference is started. + add_executable(OpenTuneCopyVocalImportTests + Tests/CopyVocalImportTests.cpp + ) + target_include_directories(OpenTuneCopyVocalImportTests + PRIVATE + ${CMAKE_CURRENT_SOURCE_DIR}/Source + ${ONNXRUNTIME_INCLUDE_DIR} + ${ONNXRUNTIME_DML_GENERATED_INCLUDE_DIR} + ${ARA_SDK_PATH}) + target_compile_definitions(OpenTuneCopyVocalImportTests PRIVATE + JucePlugin_Build_Standalone=1) + target_link_libraries(OpenTuneCopyVocalImportTests PRIVATE + OpenTuneStandalone + OpenTuneResources + juce::juce_audio_basics + juce::juce_audio_formats + juce::juce_core + juce::juce_events + ) + if(MSVC) + target_compile_options(OpenTuneCopyVocalImportTests PRIVATE /utf-8 /EHsc) + endif() + # The Standalone shared code delay-loads ONNX Runtime; the test executable + # needs the same runtime DLLs next to it as the app does. + if(WIN32) + add_custom_command(TARGET OpenTuneCopyVocalImportTests POST_BUILD + COMMAND ${CMAKE_COMMAND} -E copy_if_different + "${ONNXRUNTIME_DLL}" + "$/${OPENTUNE_ORT_DLL_NAME}" + COMMAND ${CMAKE_COMMAND} -E copy_if_different + "${DIRECTML_DLL}" + "$/DirectML.dll" + COMMENT "Copying inference runtime DLLs to OpenTuneCopyVocalImportTests..." + VERBATIM) + endif() + add_test(NAME CopyVocalImportTests COMMAND OpenTuneCopyVocalImportTests) + # Render/ARA contract tests use the production objects and their real worker # threads. They intentionally link the application target instead of # providing test doubles for the render backends. diff --git a/Source/Standalone/PluginEditor.cpp b/Source/Standalone/PluginEditor.cpp index b5673185..8c96556e 100644 --- a/Source/Standalone/PluginEditor.cpp +++ b/Source/Standalone/PluginEditor.cpp @@ -19,6 +19,7 @@ #include "Audio/AsyncAudioLoader.h" #include "StandaloneArrangementHelpers.h" #include "Utils/ProjectSession.h" +#include "Utils/CopyVocalBundle.h" #include "Utils/PlatformFileDialogs.h" #include "Utils/DemoProject.h" #include "Utils/DemoTourGate.h" @@ -1507,7 +1508,8 @@ bool OpenTuneAudioProcessorEditor::isInterestedInFileDrag(const juce::StringArra for (const auto& path : files) { const juce::File f(path); - if (f.hasFileExtension(kImportExtensionSpec)) + if (f.hasFileExtension(CopyVocalBundle::kFileExtension) + || f.hasFileExtension(kImportExtensionSpec)) return true; } return false; @@ -1539,6 +1541,13 @@ void OpenTuneAudioProcessorEditor::filesDropped(const juce::StringArray& files, if (!file.existsAsFile()) return; + if (file.hasFileExtension(CopyVocalBundle::kFileExtension)) + { + clearImportDropPreview(); + importCopyVocalBundleFile(file); + return; + } + static const juce::String kImportExtensionSpec = getImportExtensionSpec(); if (!file.hasFileExtension(kImportExtensionSpec)) { @@ -2508,6 +2517,110 @@ void OpenTuneAudioProcessorEditor::saveAndReturnRequested() app->quit(); } +void OpenTuneAudioProcessorEditor::importCopyVocalBundleRequested() +{ + if (externalEditActive_) + return; + if (rejectProjectOperationIfBusy()) + return; + + if (projectSession_.isDirty()) + { + juce::Component::SafePointer safeThis(this); + ConfirmDialogContent::launch( + new ConfirmDialogContent( + LOC_RAW("Current project has unsaved changes"), + LOC_RAW("Importing a CopyVocal bundle replaces the current project. Save changes first?"), + { { LOC_RAW("Save"), [safeThis] { + if (safeThis == nullptr) return; + if (!safeThis->projectSession_.hasProjectPath()) { + safeThis->saveProjectAsThenOpenProject(); + return; + } + safeThis->saveProject(juce::File(), true); + }, true }, + { LOC_RAW("Do Not Save"), [safeThis] { + if (safeThis == nullptr) return; + safeThis->launchImportCopyVocalBundleChooser(); + }, false }, + { LOC(kCancel), nullptr, false } }), + &contentRoot_); + return; + } + + launchImportCopyVocalBundleChooser(); +} + +void OpenTuneAudioProcessorEditor::launchImportCopyVocalBundleChooser() +{ + juce::Component::SafePointer safeThis(this); + const juce::String wildcard = "*.cvf"; + PlatformFileDialogs::chooseFilesToOpen( + LOC(kImportCopyVocalDialog), juce::File(), wildcard, false, false, &contentRoot_, + [safeThis](const juce::Array& files) { + if (safeThis == nullptr) return; + safeThis->importCopyVocalBundleFile(files.getFirst()); + }); +} + +void OpenTuneAudioProcessorEditor::importCopyVocalBundleFile(const juce::File& file) +{ + if (rejectProjectOperationIfBusy()) + return; + + projectOperationBusy_ = true; + startImportCopyVocalBundle(file); +} + +void OpenTuneAudioProcessorEditor::startImportCopyVocalBundle(const juce::File& file) +{ + const auto safeThis = juce::Component::SafePointer(this); + const auto openLanguage = LocalizationManager::getInstance().resolveLanguage(); + projectWorkerPool_.addJob( + [this, safeThis, file, openLanguage]() { + auto preparedResult = std::make_shared>( + projectSession_.prepareCopyVocalBundle(file, openLanguage)); + juce::MessageManager::callAsync([safeThis, preparedResult]() mutable { + if (safeThis == nullptr) + return; + + if (!preparedResult->ok()) { + ConfirmDialogContent::launch( + new ConfirmDialogContent( + LOC(kImportCopyVocalFailed), + projectErrorMessage(preparedResult->error()), + { { LOC(kOK), nullptr, true } }), + &safeThis->contentRoot_); + safeThis->projectOperationBusy_ = false; + return; + } + + auto commitResult = safeThis->projectSession_.commitPreparedOpen( + std::move(*preparedResult).value()); + if (!commitResult.ok()) { + ConfirmDialogContent::launch( + new ConfirmDialogContent( + LOC(kImportCopyVocalFailed), + projectErrorMessage(commitResult.error()), + { { LOC(kOK), nullptr, true } }), + &safeThis->contentRoot_); + safeThis->projectOperationBusy_ = false; + return; + } + + // The bundle is a starting point, not a saved project: opening it + // must not look like an already-persisted .otproj. + safeThis->projectSession_.markDirty(); + safeThis->syncRecentProjectsToMenu(); + safeThis->updateTitleWithProjectPath(); + safeThis->refreshAllUIFromProject(); + safeThis->projectOperationBusy_ = false; + safeThis->maybeStartOnboarding(); + safeThis->updateDemoTour(); + }); + }); +} + void OpenTuneAudioProcessorEditor::importAudioRequested() { if (externalEditActive_) diff --git a/Source/Standalone/PluginEditor.h b/Source/Standalone/PluginEditor.h index 458a0c93..17fdd760 100644 --- a/Source/Standalone/PluginEditor.h +++ b/Source/Standalone/PluginEditor.h @@ -103,6 +103,7 @@ class OpenTuneAudioProcessorEditor : public juce::AudioProcessorEditor, // MenuBarComponent::Listener void importAudioRequested() override; // 新版本:不再需要trackId参数 + void importCopyVocalBundleRequested() override; void exportAudioRequested(MenuBarComponent::ExportType exportType) override; // 使用ExportType枚举 void openProjectRequested() override; void saveProjectRequested() override; @@ -235,6 +236,11 @@ class OpenTuneAudioProcessorEditor : public juce::AudioProcessorEditor, void openProjectFile(const juce::File& file); void startOpenProject(const juce::File& file); + /// CopyVocal .cvf: replace the current project with an editable view of the bundle. + void launchImportCopyVocalBundleChooser(); + void importCopyVocalBundleFile(const juce::File& file); + void startImportCopyVocalBundle(const juce::File& file); + OpenTuneAudioProcessor& processorRef_; AppPreferences& appPreferences_; std::unique_ptr preferencesDialog_; diff --git a/Source/Standalone/UI/MenuBarComponent.cpp b/Source/Standalone/UI/MenuBarComponent.cpp index b425c789..f8ac22a9 100644 --- a/Source/Standalone/UI/MenuBarComponent.cpp +++ b/Source/Standalone/UI/MenuBarComponent.cpp @@ -101,6 +101,7 @@ juce::PopupMenu MenuBarComponent::getMenuForIndex(int topLevelMenuIndex, const j { if (profile_ == Profile::Standalone) { menu.addItem(ImportAudio, LOC(kImportAudio)); + menu.addItem(ImportCopyVocalBundle, LOC(kImportCopyVocalBundle)); juce::PopupMenu exportMenu; exportMenu.addItem(ExportSelectedClip, LOC(kExportSelectedClip)); @@ -222,6 +223,10 @@ void MenuBarComponent::menuItemSelected(int menuItemID, int topLevelMenuIndex) listeners_.call([](Listener& l) { l.importAudioRequested(); }); break; + case ImportCopyVocalBundle: + listeners_.call([](Listener& l) { l.importCopyVocalBundleRequested(); }); + break; + // 导出选项 - 使用ExportType枚举 case ExportSelectedClip: listeners_.call([](Listener& l) { l.exportAudioRequested(ExportType::SelectedClip); }); diff --git a/Source/Standalone/UI/MenuBarComponent.h b/Source/Standalone/UI/MenuBarComponent.h index 5759a33f..8f6c4edf 100644 --- a/Source/Standalone/UI/MenuBarComponent.h +++ b/Source/Standalone/UI/MenuBarComponent.h @@ -46,6 +46,7 @@ class MenuBarComponent : public juce::Component, public: virtual ~Listener() = default; virtual void importAudioRequested() = 0; + virtual void importCopyVocalBundleRequested() {} virtual void exportAudioRequested(ExportType exportType) = 0; virtual void openProjectRequested() = 0; virtual void saveProjectRequested() = 0; @@ -114,6 +115,7 @@ class MenuBarComponent : public juce::Component, enum MenuItemIDs { ImportAudio = 1, + ImportCopyVocalBundle, ExportSelectedClip, ExportTrack, ExportBus, diff --git a/Source/Utils/CopyVocalBundle.cpp b/Source/Utils/CopyVocalBundle.cpp new file mode 100644 index 00000000..75463f5a --- /dev/null +++ b/Source/Utils/CopyVocalBundle.cpp @@ -0,0 +1,941 @@ +#include "CopyVocalBundle.h" +#include "ContentAnalysisState.h" +#include "../Services/ImportedClipF0Extraction.h" + +#include +#include +#include +#include + +namespace OpenTune::CopyVocalBundle { + +namespace { + +using Var = juce::var; + +Result fail(const juce::String& message) +{ + return Result::failure( + Error(ErrorCode::InvalidParameter, message.toStdString(), "CopyVocal bundle")); +} + +bool isFiniteNumber(const Var& value) +{ + return value.isInt() || value.isInt64() || value.isDouble(); +} + +bool readNumber(const Var& object, const juce::Identifier& name, double& out, + bool required, const juce::String& context, juce::String& error) +{ + const auto value = object.getProperty(name, {}); + if (value.isVoid() || value.isUndefined()) + { + if (required) + { + error = context + ": missing required number '" + name.toString() + "'"; + return false; + } + return true; + } + if (!isFiniteNumber(value)) + { + error = context + ": '" + name.toString() + "' must be a number"; + return false; + } + out = static_cast(value); + if (!std::isfinite(out)) + { + error = context + ": '" + name.toString() + "' must be finite"; + return false; + } + return true; +} + +bool readInt(const Var& object, const juce::Identifier& name, int& out, + bool required, const juce::String& context, juce::String& error) +{ + double number = 0.0; + if (!readNumber(object, name, number, required, context, error)) + return false; + if (object.getProperty(name, {}).isVoid()) + return true; + if (number < static_cast(std::numeric_limits::min()) + || number > static_cast(std::numeric_limits::max())) + { + error = context + ": '" + name.toString() + "' is out of range"; + return false; + } + out = static_cast(std::llround(number)); + return true; +} + +bool readInt64(const Var& object, const juce::Identifier& name, int64_t& out, + bool required, const juce::String& context, juce::String& error) +{ + double number = 0.0; + if (!readNumber(object, name, number, required, context, error)) + return false; + if (object.getProperty(name, {}).isVoid()) + return true; + out = static_cast(std::llround(number)); + return true; +} + +bool readBool(const Var& object, const juce::Identifier& name, bool& out, + bool required, const juce::String& context, juce::String& error) +{ + const auto value = object.getProperty(name, {}); + if (value.isVoid() || value.isUndefined()) + { + if (required) + { + error = context + ": missing required bool '" + name.toString() + "'"; + return false; + } + return true; + } + if (!value.isBool()) + { + error = context + ": '" + name.toString() + "' must be a bool"; + return false; + } + out = static_cast(value); + return true; +} + +bool readString(const Var& object, const juce::Identifier& name, juce::String& out, + bool required, const juce::String& context, juce::String& error) +{ + const auto value = object.getProperty(name, {}); + if (value.isVoid() || value.isUndefined()) + { + if (required) + { + error = context + ": missing required string '" + name.toString() + "'"; + return false; + } + return true; + } + if (!value.isString()) + { + error = context + ": '" + name.toString() + "' must be a string"; + return false; + } + out = value.toString(); + return true; +} + +bool readNumberArray(const Var& object, const juce::Identifier& name, + std::vector& out, bool required, + const juce::String& context, juce::String& error) +{ + const auto value = object.getProperty(name, {}); + if (value.isVoid() || value.isUndefined()) + { + if (required) + { + error = context + ": missing required array '" + name.toString() + "'"; + return false; + } + return true; + } + auto* array = value.getArray(); + if (array == nullptr) + { + error = context + ": '" + name.toString() + "' must be an array"; + return false; + } + out.clear(); + out.reserve(static_cast(array->size())); + for (const auto& item : *array) + { + if (!isFiniteNumber(item)) + { + error = context + ": '" + name.toString() + "' contains a non-number"; + return false; + } + const double number = static_cast(item); + if (!std::isfinite(number)) + { + error = context + ": '" + name.toString() + "' contains a non-finite value"; + return false; + } + out.push_back(number); + } + return true; +} + +bool decodeBase64(const juce::String& encoded, juce::MemoryBlock& out) +{ + out.reset(); + if (encoded.isEmpty()) + return false; + juce::MemoryOutputStream stream; + if (!juce::Base64::convertFromBase64(stream, encoded)) + return false; + out = stream.getMemoryBlock(); + return !out.isEmpty(); +} + +bool parsePitchTrack(const Var& object, PitchTrack& out, const juce::String& context, + juce::String& error) +{ + if (!object.isObject()) + { + error = context + ": must be an object"; + return false; + } + if (!readInt(object, "hopSize", out.hopSize, true, context, error)) + return false; + if (!readNumber(object, "sampleRate", out.sampleRate, true, context, error)) + return false; + if (!readInt(object, "frameCount", out.frameCount, true, context, error)) + return false; + if (out.hopSize != kF0HopSize || std::abs(out.sampleRate - kF0SampleRate) > 1e-6) + { + error = context + ": only hopSize=160 / sampleRate=16000 is supported by format v1"; + return false; + } + if (out.frameCount <= 1 || out.frameCount > 20'000'000) + { + error = context + ": frameCount is out of range"; + return false; + } + + return true; +} + +bool parsePitchChannel(const Var& channelObject, PitchTrack& track, const juce::String& context, + juce::String& error) +{ + if (!channelObject.isObject()) + { + error = context + ": F0 channel must be an object"; + return false; + } + juce::String encoding; + if (!readString(channelObject, "encoding", encoding, true, context, error)) + return false; + if (encoding != "base64-f32le") + { + error = context + ": unsupported F0 encoding '" + encoding + "'"; + return false; + } + juce::String valuesBase64; + juce::String voicedBase64; + if (!readString(channelObject, "values", valuesBase64, true, context, error)) + return false; + if (!readString(channelObject, "voiced", voicedBase64, true, context, error)) + return false; + + juce::MemoryBlock valuesBlock; + juce::MemoryBlock voicedBlock; + if (!decodeBase64(valuesBase64, valuesBlock)) + { + error = context + ": 'values' is not valid base64"; + return false; + } + if (!decodeBase64(voicedBase64, voicedBlock)) + { + error = context + ": 'voiced' is not valid base64"; + return false; + } + const auto expectedValueBytes = static_cast(track.frameCount) * sizeof(float); + if (valuesBlock.getSize() != expectedValueBytes) + { + error = context + ": 'values' byte count " + juce::String(valuesBlock.getSize()) + + " does not match frameCount*4=" + juce::String(expectedValueBytes); + return false; + } + if (voicedBlock.getSize() != static_cast(track.frameCount)) + { + error = context + ": 'voiced' byte count " + juce::String(voicedBlock.getSize()) + + " does not match frameCount=" + juce::String(track.frameCount); + return false; + } + + track.f0Hz.resize(static_cast(track.frameCount)); + std::memcpy(track.f0Hz.data(), valuesBlock.getData(), expectedValueBytes); + track.voiced.assign(voicedBlock.getSize(), 0); + std::memcpy(track.voiced.data(), voicedBlock.getData(), voicedBlock.getSize()); + + for (int frame = 0; frame < track.frameCount; ++frame) + { + if (!std::isfinite(track.f0Hz[static_cast(frame)]) + || track.f0Hz[static_cast(frame)] < 0.0f) + { + error = context + ": F0 value at frame " + juce::String(frame) + " is invalid"; + return false; + } + track.voiced[static_cast(frame)] = + (track.voiced[static_cast(frame)] != 0 + && track.f0Hz[static_cast(frame)] > 0.0f) ? 1 : 0; + } + return true; +} + +bool parseMedia(const Var& object, const juce::File& bundleDirectory, MediaRef& out, + bool required, const juce::String& context, juce::String& error) +{ + if (object.isVoid() || object.isUndefined()) + { + if (required) + { + error = context + ": missing required object"; + return false; + } + return true; + } + if (!object.isObject()) + { + error = context + ": must be an object"; + return false; + } + juce::String path; + if (!readString(object, "path", path, true, context, error)) + return false; + out.file = juce::File::isAbsolutePath(path) + ? juce::File(path) + : bundleDirectory.getChildFile(path); + if (!out.file.existsAsFile()) + { + error = context + ": media file does not exist: " + out.file.getFullPathName(); + return false; + } + if (!readInt(object, "sampleRate", out.sampleRate, true, context, error)) + return false; + if (!readInt(object, "channels", out.channels, true, context, error)) + return false; + if (!readInt64(object, "sampleCount", out.sampleCount, true, context, error)) + return false; + if (!readNumber(object, "durationSeconds", out.durationSeconds, true, context, error)) + return false; + if (out.sampleRate <= 0 || out.channels <= 0 || out.channels > 2 || out.sampleCount <= 0) + { + error = context + ": invalid media shape (sampleRate/channels/sampleCount)"; + return false; + } + if (!readString(object, "sha256", out.sha256, false, context, error)) + return false; + return true; +} + +bool parseNotes(const Var& object, std::vector& out, const juce::String& context, + juce::String& error) +{ + const auto value = object.getProperty("notes", {}); + if (value.isVoid() || value.isUndefined()) + return true; + auto* array = value.getArray(); + if (array == nullptr) + { + error = context + ": 'notes' must be an array"; + return false; + } + out.clear(); + out.reserve(static_cast(array->size())); + int index = 0; + for (const auto& item : *array) + { + const auto itemContext = context + " note[" + juce::String(index++) + "]"; + if (!item.isObject()) + { + error = itemContext + ": must be an object"; + return false; + } + NoteEvent note; + double pitchHz = 0.0; + double midi = 0.0; + double confidence = 0.0; + if (!readNumber(item, "start", note.startSeconds, true, itemContext, error) + || !readNumber(item, "end", note.endSeconds, true, itemContext, error) + || !readNumber(item, "pitchHz", pitchHz, true, itemContext, error) + || !readNumber(item, "midi", midi, false, itemContext, error) + || !readNumber(item, "confidence", confidence, false, itemContext, error) + || !readString(item, "lyric", note.lyric, false, itemContext, error) + || !readString(item, "source", note.source, false, itemContext, error)) + { + return false; + } + note.pitchHz = static_cast(pitchHz); + note.midi = static_cast(midi); + note.confidence = static_cast(confidence); + if (note.endSeconds <= note.startSeconds || note.pitchHz <= 0.0f) + continue; + out.push_back(std::move(note)); + } + std::sort(out.begin(), out.end(), [](const NoteEvent& a, const NoteEvent& b) { + return a.startSeconds < b.startSeconds + || (a.startSeconds == b.startSeconds && a.endSeconds < b.endSeconds); + }); + return true; +} + +bool parseRegions(const Var& object, std::vector& out, const juce::String& context, + juce::String& error) +{ + const auto value = object.getProperty("regions", {}); + if (value.isVoid() || value.isUndefined()) + return true; + auto* array = value.getArray(); + if (array == nullptr) + { + error = context + ": 'regions' must be an array"; + return false; + } + out.clear(); + out.reserve(static_cast(array->size())); + int index = 0; + for (const auto& item : *array) + { + const auto itemContext = context + " region[" + juce::String(index++) + "]"; + if (!item.isObject()) + { + error = itemContext + ": must be an object"; + return false; + } + Region region; + if (!readNumber(item, "teacherStart", region.teacherStart, true, itemContext, error) + || !readNumber(item, "teacherEnd", region.teacherEnd, true, itemContext, error) + || !readNumber(item, "studentStart", region.studentStart, true, itemContext, error) + || !readNumber(item, "studentEnd", region.studentEnd, true, itemContext, error) + || !readNumber(item, "quality", region.quality, false, itemContext, error) + || !readBool(item, "unsupported", region.unsupported, false, itemContext, error) + || !readString(item, "status", region.status, false, itemContext, error) + || !readString(item, "mode", region.mode, false, itemContext, error) + || !readString(item, "reason", region.reason, false, itemContext, error) + || !readNumberArray(item, "teacherAnchors", region.teacherAnchors, false, itemContext, error) + || !readNumberArray(item, "studentAnchors", region.studentAnchors, false, itemContext, error)) + { + return false; + } + double stretchRatio = 0.0; + if (item.getProperty("stretchRatio", {}).isVoid() == false) + { + if (!readNumber(item, "stretchRatio", stretchRatio, false, itemContext, error)) + return false; + region.hasStretchRatio = true; + region.stretchRatio = stretchRatio; + } + if (region.teacherEnd < region.teacherStart) + std::swap(region.teacherStart, region.teacherEnd); + if (region.studentEnd < region.studentStart) + std::swap(region.studentStart, region.studentEnd); + if (region.teacherAnchors.size() != region.studentAnchors.size() + || region.teacherAnchors.size() < 2) + { + region.teacherAnchors.clear(); + region.studentAnchors.clear(); + } + else + { + bool valid = true; + for (size_t anchor = 0; anchor < region.teacherAnchors.size(); ++anchor) + { + const double previousTeacher = anchor == 0 ? -1.0 : region.teacherAnchors[anchor - 1]; + const double previousStudent = anchor == 0 ? -1.0 : region.studentAnchors[anchor - 1]; + if (region.teacherAnchors[anchor] <= previousTeacher + || region.studentAnchors[anchor] <= previousStudent) + { + valid = false; + break; + } + } + if (!valid) + { + region.teacherAnchors.clear(); + region.studentAnchors.clear(); + } + } + out.push_back(std::move(region)); + } + return true; +} + +bool parseTimeGrid(const Var& object, std::vector& out, const juce::String& context, + juce::String& error) +{ + const auto grid = object.getProperty("timeGrid", {}); + if (!grid.isObject()) + { + error = context + ": missing 'timeGrid' object"; + return false; + } + const auto handlesValue = grid.getProperty("handles", {}); + auto* handles = handlesValue.getArray(); + if (handles == nullptr || handles->size() < 2) + { + error = context + ": 'timeGrid.handles' must contain at least two handles"; + return false; + } + out.clear(); + out.reserve(static_cast(handles->size())); + int index = 0; + for (const auto& item : *handles) + { + const auto itemContext = context + " timeGrid.handle[" + juce::String(index++) + "]"; + if (!item.isObject()) + { + error = itemContext + ": must be an object"; + return false; + } + TimeHandleSpec handle; + if (!readNumber(item, "sourceSeconds", handle.sourceSeconds, true, itemContext, error) + || !readNumber(item, "outputSeconds", handle.outputSeconds, true, itemContext, error) + || !readString(item, "kind", handle.kind, true, itemContext, error) + || !readString(item, "confidence", handle.confidence, true, itemContext, error)) + { + return false; + } + out.push_back(std::move(handle)); + } + return true; +} + +juce::var childObject(const Var& parent, const juce::Identifier& name) +{ + return parent.getProperty(name, {}); +} + +} // namespace + +int expectedF0FrameCount(int64_t sampleCount, int hopSize, double f0SampleRate) noexcept +{ + if (sampleCount <= 0 || hopSize <= 0 || f0SampleRate <= 0.0) + return 1; + const auto f0Samples = static_cast( + std::llround(static_cast(sampleCount) * f0SampleRate / 44100.0)); + return static_cast(f0Samples / hopSize + 1); +} + +Result Bundle::loadFromFile(const juce::File& file) +{ + if (!file.existsAsFile()) + return fail("bundle file does not exist: " + file.getFullPathName()); + + const auto root = juce::JSON::parse(file); + if (root.isVoid() || !root.isObject()) + return fail("bundle is not valid JSON object: " + file.getFullPathName()); + + const juce::String context = "CopyVocal bundle"; + juce::String error; + Bundle bundle; + + juce::String format; + if (!readString(root, "format", format, true, context, error)) + return fail(error); + if (format != kFormatName) + return fail("unsupported bundle format '" + format + "' (expected " + kFormatName + ")"); + if (!readInt(root, "formatVersion", bundle.formatVersion, true, context, error)) + return fail(error); + if (bundle.formatVersion <= 0 || bundle.formatVersion > kFormatVersion) + { + return fail("unsupported bundle formatVersion " + + juce::String(bundle.formatVersion) + " (this OpenTune supports up to " + + juce::String(kFormatVersion) + ")"); + } + + const auto project = childObject(root, "project"); + if (!project.isObject()) + return fail("missing 'project' object"); + if (!readString(project, "name", bundle.projectName, true, "project", error) + || !readString(project, "language", bundle.language, false, "project", error)) + return fail(error); + + const auto clocks = childObject(root, "clocks"); + if (!clocks.isObject()) + return fail("missing 'clocks' object"); + if (!readNumber(clocks, "studentSeconds", bundle.studentSeconds, true, "clocks", error) + || !readNumber(clocks, "teacherSeconds", bundle.teacherSeconds, true, "clocks", error) + || !readNumber(clocks, "outputSeconds", bundle.outputSeconds, true, "clocks", error) + || !readNumber(clocks, "projectSourceSeconds", bundle.projectSourceSeconds, true, "clocks", error) + || !readBool(clocks, "timingChanged", bundle.timingChanged, true, "clocks", error) + || !readString(clocks, "outputClock", bundle.outputClock, true, "clocks", error) + || !readString(clocks, "pitchPolicy", bundle.pitchPolicy, false, "clocks", error) + || !readNumber(clocks, "registerOffsetCents", bundle.registerOffsetCents, false, "clocks", error)) + return fail(error); + + if (bundle.outputSeconds <= 0.0 || bundle.projectSourceSeconds <= 0.0) + return fail("clocks: output/projectSource duration must be positive"); + if (std::abs(bundle.outputSeconds - bundle.projectSourceSeconds) > 1e-6) + return fail("clocks: projectSourceSeconds must equal outputSeconds"); + if (bundle.outputClock != "teacher" && bundle.outputClock != "student") + return fail("clocks: outputClock must be 'teacher' or 'student'"); + + const auto media = childObject(root, "media"); + if (!media.isObject()) + return fail("missing 'media' object"); + if (!parseMedia(childObject(media, "student"), file.getParentDirectory(), + bundle.studentMedia, true, "media.student", error)) + return fail(error); + bundle.hasTeacherMedia = !childObject(media, "teacher").isVoid(); + if (bundle.hasTeacherMedia + && !parseMedia(childObject(media, "teacher"), file.getParentDirectory(), + bundle.teacherMedia, false, "media.teacher", error)) + return fail(error); + bundle.hasCorrectedMedia = !childObject(media, "corrected").isVoid(); + if (bundle.hasCorrectedMedia + && !parseMedia(childObject(media, "corrected"), file.getParentDirectory(), + bundle.correctedMedia, false, "media.corrected", error)) + return fail(error); + + const auto f0 = childObject(root, "f0"); + if (!f0.isObject()) + return fail("missing 'f0' object"); + if (!parsePitchTrack(f0, bundle.originalF0, "f0", error) + || !parsePitchChannel(childObject(f0, "original"), bundle.originalF0, "f0.original", error)) + return fail(error); + bundle.targetF0.hopSize = bundle.originalF0.hopSize; + bundle.targetF0.sampleRate = bundle.originalF0.sampleRate; + bundle.targetF0.frameCount = bundle.originalF0.frameCount; + if (!parsePitchChannel(childObject(f0, "target"), bundle.targetF0, "f0.target", error)) + return fail(error); + + const auto expectedFrames = static_cast(std::llround(bundle.outputSeconds / kF0FrameStepSeconds)) + 1; + if (std::abs(bundle.originalF0.frameCount - expectedFrames) > 2) + { + return fail("f0: frameCount " + juce::String(bundle.originalF0.frameCount) + + " does not match project duration " + juce::String(bundle.outputSeconds, 9) + + "s (expected about " + juce::String(expectedFrames) + ")"); + } + + if (!parseNotes(root, bundle.notes, "bundle", error) + || !parseRegions(root, bundle.regions, "bundle", error) + || !parseTimeGrid(root, bundle.timeGrid, "bundle", error)) + return fail(error); + + const auto diagnostics = childObject(root, "diagnostics"); + if (diagnostics.isObject()) + { + const auto warnings = diagnostics.getProperty("warnings", {}); + if (auto* array = warnings.getArray()) + for (const auto& warning : *array) + if (warning.isString()) + bundle.warnings.add(warning.toString()); + if (!readInt(diagnostics, "unresolvedRegionCount", bundle.unresolvedRegionCount, + false, "diagnostics", error) + || !readNumber(diagnostics, "unsupportedDurationSeconds", + bundle.unsupportedDurationSeconds, false, "diagnostics", error)) + return fail(error); + } + + // Notes may be slightly outside the padded/trimmed project window; clamp + // them instead of rejecting an otherwise usable bundle. + for (auto& note : bundle.notes) + { + note.startSeconds = juce::jlimit(0.0, bundle.projectSourceSeconds, note.startSeconds); + note.endSeconds = juce::jlimit(0.0, bundle.projectSourceSeconds, note.endSeconds); + } + bundle.notes.erase( + std::remove_if(bundle.notes.begin(), bundle.notes.end(), + [](const NoteEvent& note) { return note.endSeconds <= note.startSeconds; }), + bundle.notes.end()); + + return Result::success(std::move(bundle)); +} + +Result> buildPitchCurve(const Bundle& bundle, int expectedFrames) +{ + const int frames = expectedFrames > 0 ? expectedFrames : bundle.originalF0.frameCount; + if (frames <= 0) + return Result>::failure( + Error(ErrorCode::InvalidParameter, "invalid F0 frame count", "CopyVocal bundle")); + + std::vector original(static_cast(frames), 0.0f); + std::vector target(static_cast(frames), 0.0f); + const int copyFrames = std::min(frames, bundle.originalF0.frameCount); + if (copyFrames > 0) + { + std::copy_n(bundle.originalF0.f0Hz.begin(), copyFrames, original.begin()); + std::copy_n(bundle.targetF0.f0Hz.begin(), copyFrames, target.begin()); + } + + auto curve = std::make_shared(); + curve->setHopSize(kF0HopSize); + curve->setSampleRate(kF0SampleRate); + curve->setOriginalF0(original); + + std::vector segments; + int frame = 0; + while (frame < frames) + { + const bool voiced = target[static_cast(frame)] > 0.0f + && original[static_cast(frame)] > 0.0f; + if (!voiced) + { + ++frame; + continue; + } + const int start = frame; + while (frame < frames + && target[static_cast(frame)] > 0.0f + && original[static_cast(frame)] > 0.0f) + ++frame; + const int end = frame; + PitchCorrectionSegment segment; + segment.startFrame = start; + segment.endFrame = end; + segment.f0Data.assign(target.begin() + start, target.begin() + end); + segment.baseF0Data = segment.f0Data; + segment.source = PitchCorrectionSegment::Source::HandDraw; + segment.parameterSnapshot = {}; + segments.push_back(std::move(segment)); + } + if (!segments.empty()) + curve->replaceCorrectionSegments(segments); + return Result>::success(std::move(curve)); +} + +std::vector buildNotes(const Bundle& bundle) +{ + std::vector notes; + notes.reserve(bundle.notes.size()); + for (const auto& event : bundle.notes) + { + Note note; + note.startTime = juce::jlimit(0.0, bundle.projectSourceSeconds, event.startSeconds); + note.endTime = juce::jlimit(0.0, bundle.projectSourceSeconds, event.endSeconds); + if (note.endTime - note.startTime < 0.020) + continue; + note.pitch = event.pitchHz; + const int frame = static_cast(std::llround(note.startTime / kF0FrameStepSeconds)); + if (frame >= 0 && frame < bundle.originalF0.frameCount) + { + const float original = bundle.originalF0.f0Hz[static_cast(frame)]; + note.originalPitch = original > 0.0f ? original : event.pitchHz; + } + else + { + note.originalPitch = event.pitchHz; + } + note.pitchOffset = 0.0f; + note.isVoiced = true; + note.dirty = true; + notes.push_back(note); + } + return normalizeStoredNotes(notes); +} + +namespace { + +HandleKind handleKindFromString(const juce::String& value) +{ + if (value == "clipStart") return HandleKind::ClipStart; + if (value == "clipEnd") return HandleKind::ClipEnd; + if (value == "onsetVoiced") return HandleKind::OnsetVoiced; + if (value == "onsetSibilant") return HandleKind::OnsetSibilant; + if (value == "onsetSilence") return HandleKind::OnsetSilence; + if (value == "userAdded") return HandleKind::UserAdded; + return HandleKind::InternalOnset; +} + +} // namespace + +std::shared_ptr buildTimeGrid(const Bundle& bundle) +{ + if (!bundle.timingChanged || bundle.outputClock != "teacher") + return TimeGridSnapshot::makeIdentity(bundle.projectSourceSeconds); + + if (bundle.timeGrid.size() < 2) + return TimeGridSnapshot::makeIdentity(bundle.projectSourceSeconds); + + std::vector handles; + handles.reserve(bundle.timeGrid.size()); + uint64_t id = 1; + for (const auto& spec : bundle.timeGrid) + { + TimeHandle handle; + handle.id = id++; + handle.kind = handleKindFromString(spec.kind); + handle.source_seconds = spec.sourceSeconds; + handle.output_seconds = spec.outputSeconds; + handle.confidence = spec.confidence == "high" ? Confidence::High : Confidence::Default; + if (handle.kind == HandleKind::ClipStart || handle.kind == HandleKind::ClipEnd) + handle.confidence = Confidence::Default; + handles.push_back(handle); + } + + auto snapshot = TimeGridSnapshot::makeFromHandles(std::move(handles)); + if (snapshot == nullptr + || std::abs(snapshot->totalDurationSeconds() - bundle.projectSourceSeconds) > 1e-6) + { + return TimeGridSnapshot::makeIdentity(bundle.projectSourceSeconds); + } + if (snapshot->isIdentity()) + return TimeGridSnapshot::makeIdentity(bundle.projectSourceSeconds); + return snapshot; +} + +bool hasEditablePitch(const Bundle& bundle) noexcept +{ + for (const auto value : bundle.targetF0.f0Hz) + if (value > 0.0f) + return true; + return false; +} + +Result buildProject(const Bundle& bundle, + int64_t storedSamples, + int numChannels, + double sampleRate, + const std::vector& silentGaps, + int projectFormatVersion, + const juce::String& appVersion, + const float* sourcePCM) +{ + if (storedSamples <= 0 || numChannels <= 0 || numChannels > 2 || sampleRate <= 0.0) + { + return Result::failure( + Error(ErrorCode::InvalidAudioInput, + "invalid stored audio shape for CopyVocal bundle", + "CopyVocal bundle")); + } + if (std::abs(sampleRate - 44100.0) > 1e-6) + { + return Result::failure( + Error(ErrorCode::InvalidAudioInput, + "CopyVocal student media must be imported at 44100 Hz", + "CopyVocal bundle")); + } + + const double durationSeconds = static_cast(storedSamples) / sampleRate; + if (std::abs(durationSeconds - bundle.projectSourceSeconds) > 0.002) + { + return Result::failure( + Error(ErrorCode::InvalidParameter, + "stored audio duration does not match the bundle's projectSourceSeconds", + "CopyVocal bundle")); + } + + const int expectedFrames = expectedF0FrameCount(storedSamples); + auto curveResult = buildPitchCurve(bundle, expectedFrames); + if (!curveResult.ok()) + return Result::failure(curveResult.error()); + auto pitchCurve = std::move(curveResult).value(); + + if (sourcePCM != nullptr) + { + // OpenDyne draws note blobs from per-frame original energy. Native + // imports get this from F0 extraction; a bundle import must compute it + // from the same student PCM or the roller shows no note blocks. + const auto originalSnapshot = pitchCurve->getSnapshot(); + auto energy = computeFrameEnergy( + sourcePCM, + static_cast(storedSamples), + static_cast(std::llround(sampleRate)), + originalSnapshot->getOriginalF0(), + static_cast(kF0SampleRate), + kF0HopSize); + pitchCurve->setOriginalEnergy(energy); + } + + auto notes = buildNotes(bundle); + for (auto& note : notes) + { + note.startTime = juce::jlimit(0.0, durationSeconds, note.startTime); + note.endTime = juce::jlimit(0.0, durationSeconds, note.endTime); + } + notes = normalizeStoredNotes(notes); + + auto timeGrid = buildTimeGrid(bundle); + if (timeGrid == nullptr + || std::abs(timeGrid->totalDurationSeconds() - durationSeconds) > 1e-6) + timeGrid = TimeGridSnapshot::makeIdentity(durationSeconds); + if (timeGrid == nullptr) + { + return Result::failure( + Error(ErrorCode::InvalidParameter, + "cannot build a time grid for the CopyVocal bundle", + "CopyVocal bundle")); + } + + const ContentKey contentKey{DomainKind::StandaloneClip, 1, 0}; + + PreparedProject prepared; + prepared.contentKey = contentKey; + prepared.pitchCurve = std::move(pitchCurve); + prepared.expectedF0Frames = expectedFrames; + prepared.projectDurationSeconds = durationSeconds; + + auto& snapshot = prepared.snapshot; + snapshot.header.projectFormatVersion = projectFormatVersion; + snapshot.header.appVersion = appVersion; + snapshot.header.projectName = bundle.projectName.isNotEmpty() + ? bundle.projectName + : juce::String("CopyVocal"); + snapshot.header.projectId = ProjectSnapshot::generateProjectId(); + snapshot.header.createdAt = ProjectSnapshot::generateTimestamp(); + + snapshot.settings.bpm = 120.0; + snapshot.settings.sampleRate = sampleRate; + snapshot.settings.timeSignatureNumerator = 4; + snapshot.settings.timeSignatureDenominator = 4; + snapshot.settings.selectedTrackId = 0; + snapshot.settings.selectedPlacementId = 1; + snapshot.settings.visibleTrackCount = 1; + snapshot.settings.activeTrackId = 0; + + ProjectSourceEntry sourceEntry; + sourceEntry.sourceId = 1; + sourceEntry.displayName = "CopyVocal Student"; + sourceEntry.originalImportPath = bundle.studentMedia.file.getFullPathName(); + sourceEntry.sampleRate = sampleRate; + sourceEntry.numChannels = numChannels; + sourceEntry.lengthSamples = storedSamples; + sourceEntry.lengthSeconds = durationSeconds; + sourceEntry.contentHash = bundle.studentMedia.sha256; + sourceEntry.fileSizeBytes = bundle.studentMedia.file.getSize(); + snapshot.sources.push_back(std::move(sourceEntry)); + + ProjectContentEntry contentEntry; + contentEntry.contentKey = contentKey; + contentEntry.sourceId = 1; + contentEntry.sourceWindow.sourceId = 1; + contentEntry.sourceWindow.sourceStartSeconds = 0.0; + contentEntry.sourceWindow.sourceEndSeconds = durationSeconds; + contentEntry.notes = notes; + contentEntry.noteTopologyInitialized = true; + contentEntry.originalF0State = static_cast(OriginalF0State::Ready); + contentEntry.timeGrid.handles.reserve(timeGrid->handles().size()); + for (const auto& handle : timeGrid->handles()) + { + ProjectContentEntry::TimeGridEntry::HandleEntry entry; + entry.id = handle.id; + entry.kind = static_cast(handle.kind); + entry.sourceSeconds = handle.source_seconds; + entry.outputSeconds = handle.output_seconds; + entry.confidence = static_cast(handle.confidence); + contentEntry.timeGrid.handles.push_back(entry); + } + contentEntry.silentGaps.reserve(silentGaps.size()); + for (const auto& gap : silentGaps) + { + ProjectContentEntry::SilentGapEntry entry; + entry.startSample = gap.startSample; + entry.endSampleExclusive = gap.endSampleExclusive; + entry.minLevel_dB = gap.minLevel_dB; + contentEntry.silentGaps.push_back(entry); + } + snapshot.contents.push_back(std::move(contentEntry)); + + ProjectTrackEntry trackEntry; + trackEntry.trackId = 0; + trackEntry.name = "Vocal"; + trackEntry.gain = 1.0f; + trackEntry.mute = false; + trackEntry.solo = false; + trackEntry.colour = juce::Colour(0xff4a90d9); + ProjectPlacementEntry placement; + placement.placementId = 1; + placement.contentKey = contentKey; + placement.timelineStartSeconds = 0.0; + placement.timelineDurationSeconds = durationSeconds; + placement.clipGain = 1.0f; + placement.name = snapshot.header.projectName; + trackEntry.placements.push_back(std::move(placement)); + snapshot.tracks.push_back(std::move(trackEntry)); + + return Result::success(std::move(prepared)); +} + +} // namespace OpenTune::CopyVocalBundle diff --git a/Source/Utils/CopyVocalBundle.h b/Source/Utils/CopyVocalBundle.h new file mode 100644 index 00000000..3a96db0a --- /dev/null +++ b/Source/Utils/CopyVocalBundle.h @@ -0,0 +1,169 @@ +#pragma once + +#include + +#include "Error.h" +#include "Note.h" +#include "PitchCurve.h" +#include "ProjectModel.h" +#include "SilentGapDetector.h" +#include "TimeGrid.h" + +#include +#include +#include + +namespace OpenTune::CopyVocalBundle { + +inline constexpr const char* kFormatName = "copyvocal.file"; +inline constexpr int kFormatVersion = 1; + +/** Canonical file extension, without the dot. */ +inline constexpr const char* kFileExtension = "cvf"; + +inline constexpr int kF0HopSize = 160; +inline constexpr double kF0SampleRate = 16000.0; +inline constexpr double kF0FrameStepSeconds = 0.01; + +struct MediaRef +{ + juce::File file; + int sampleRate{0}; + int channels{0}; + int64_t sampleCount{0}; + double durationSeconds{0.0}; + juce::String sha256; + + bool isValid() const noexcept + { + return file != juce::File() && sampleRate > 0 && channels > 0 && sampleCount > 0; + } +}; + +struct PitchTrack +{ + int hopSize{kF0HopSize}; + double sampleRate{kF0SampleRate}; + int frameCount{0}; + std::vector f0Hz; + std::vector voiced; + + double timeAtFrame(int frame) const noexcept + { + return sampleRate > 0.0 + ? static_cast(frame) * static_cast(hopSize) / sampleRate + : 0.0; + } +}; + +struct NoteEvent +{ + double startSeconds{0.0}; + double endSeconds{0.0}; + float pitchHz{0.0f}; + float midi{0.0f}; + float confidence{0.0f}; + juce::String lyric; + juce::String source; +}; + +struct Region +{ + double teacherStart{0.0}; + double teacherEnd{0.0}; + double studentStart{0.0}; + double studentEnd{0.0}; + double quality{0.0}; + bool unsupported{false}; + juce::String status; + juce::String mode; + juce::String reason; + std::vector teacherAnchors; + std::vector studentAnchors; + bool hasStretchRatio{false}; + double stretchRatio{0.0}; +}; + +struct TimeHandleSpec +{ + double sourceSeconds{0.0}; + double outputSeconds{0.0}; + juce::String kind; + juce::String confidence; +}; + +struct Bundle +{ + int formatVersion{0}; + + juce::String projectName; + juce::String language; + + double studentSeconds{0.0}; + double teacherSeconds{0.0}; + double outputSeconds{0.0}; + double projectSourceSeconds{0.0}; + bool timingChanged{false}; + juce::String outputClock; + juce::String pitchPolicy; + double registerOffsetCents{0.0}; + + MediaRef studentMedia; + MediaRef teacherMedia; + MediaRef correctedMedia; + bool hasTeacherMedia{false}; + bool hasCorrectedMedia{false}; + + PitchTrack originalF0; + PitchTrack targetF0; + + std::vector notes; + std::vector regions; + std::vector timeGrid; + + juce::StringArray warnings; + int unresolvedRegionCount{0}; + double unsupportedDurationSeconds{0.0}; + + /** Reads, validates and decodes a .cvf file. */ + static Result loadFromFile(const juce::File& file); +}; + +/** Number of 10 ms F0 frames OpenTune expects for a canonical clip length. */ +int expectedF0FrameCount(int64_t sampleCount, int hopSize = kF0HopSize, + double f0SampleRate = kF0SampleRate) noexcept; + +/// Maps original F0 to the original layer and voiced-original target F0 to HandDraw segments; +/// clips or zero-pads minor (<=2) frame-count differences to match `expectedFrames`. +Result> buildPitchCurve(const Bundle& bundle, int expectedFrames); + +/** Builds normalized, non-overlapping OpenTune notes in project source seconds. */ +std::vector buildNotes(const Bundle& bundle); + +/// Builds the source->output time grid, falling back to an identity grid when +/// outputClock is "student", no internal anchors exist, or validation fails. +std::shared_ptr buildTimeGrid(const Bundle& bundle); + +bool hasEditablePitch(const Bundle& bundle) noexcept; + +/// Materializes a bundle into a ProjectSnapshot without a processor (`storedSamples` at 44.1 kHz +/// post-fit). Optional mono `sourcePCM` computes per-frame energy required to display note blobs. +struct PreparedProject +{ + ProjectSnapshot snapshot; + ContentKey contentKey; + std::shared_ptr pitchCurve; + int expectedF0Frames{0}; + double projectDurationSeconds{0.0}; +}; + +Result buildProject(const Bundle& bundle, + int64_t storedSamples, + int numChannels, + double sampleRate, + const std::vector& silentGaps, + int projectFormatVersion, + const juce::String& appVersion, + const float* sourcePCM = nullptr); + +} // namespace OpenTune::CopyVocalBundle diff --git a/Source/Utils/LocalizationManager.h b/Source/Utils/LocalizationManager.h index b5181d76..3c52726a 100644 --- a/Source/Utils/LocalizationManager.h +++ b/Source/Utils/LocalizationManager.h @@ -177,6 +177,9 @@ constexpr const char* kEdit = "Edit"; constexpr const char* kView = "View"; constexpr const char* kImportAudio = "Import Audio..."; +constexpr const char* kImportCopyVocalBundle = "Import CopyVocal Bundle..."; +constexpr const char* kImportCopyVocalDialog = "Import CopyVocal Bundle"; +constexpr const char* kImportCopyVocalFailed = "CopyVocal import failed"; constexpr const char* kExportAudio = "Export Audio"; constexpr const char* kExportSelectedClip = "Export Selected Clip"; constexpr const char* kExportTrack = "Export Track"; @@ -528,6 +531,9 @@ inline juce::String get(Language lang, const char* key) { Keys::kView, "View", "视图", "表示", "Вид", "Ver" }, { Keys::kImportAudio, "Import Audio...", "导入音频...", "オーディオをインポート...", "Импорт аудио...", "Importar audio..." }, + { Keys::kImportCopyVocalBundle, "Import CopyVocal Bundle...", "导入 CopyVocal 工程包...", "CopyVocal バンドルをインポート...", "Импорт пакета CopyVocal...", "Importar paquete CopyVocal..." }, + { Keys::kImportCopyVocalDialog, "Import CopyVocal Bundle", "导入 CopyVocal 工程包", "CopyVocal バンドルのインポート", "Импорт пакета CopyVocal", "Importar paquete CopyVocal" }, + { Keys::kImportCopyVocalFailed, "CopyVocal import failed", "CopyVocal 导入失败", "CopyVocal のインポートに失敗しました", "Ошибка импорта CopyVocal", "Error al importar CopyVocal" }, { Keys::kExportAudio, "Export Audio", "导出音频", "オーディオをエクスポート", "Экспорт аудио", "Exportar audio" }, { Keys::kExportSelectedClip, "Export Selected Clip", "导出选中的片段", "選択したクリップをエクスポート", "Экспорт клипа", "Exportar clip seleccionado" }, { Keys::kExportTrack, "Export Track", "导出轨道", "トラックをエクスポート", "Экспорт дорожки", "Exportar pista" }, diff --git a/Source/Utils/ProjectSession.cpp b/Source/Utils/ProjectSession.cpp index 4f867700..49a97f71 100644 --- a/Source/Utils/ProjectSession.cpp +++ b/Source/Utils/ProjectSession.cpp @@ -8,10 +8,12 @@ #include "../Standalone/StandaloneArrangementHelpers.h" #include "AppLogger.h" #include "AppPreferences.h" +#include "CopyVocalBundle.h" #include "ProjectPersistence.h" #include "LocalizationManager.h" #include "TimeCoordinate.h" #include "VisibleTrackCount.h" +#include #include namespace OpenTune { @@ -371,6 +373,133 @@ Result ProjectSession::prepareOpen(const juce::Fil return Result::success(std::move(preparedOpen)); } +namespace { + +std::shared_ptr> fitAudioBufferToDuration( + const std::shared_ptr>& source, + double sourceSampleRate, + double targetDurationSeconds) +{ + if (source == nullptr || sourceSampleRate <= 0.0 || targetDurationSeconds <= 0.0) + return nullptr; + const auto targetSamples64 = static_cast( + std::llround(targetDurationSeconds * sourceSampleRate)); + if (targetSamples64 <= 0 || targetSamples64 > std::numeric_limits::max() - 1) + return nullptr; + const int targetSamples = static_cast(targetSamples64); + if (source->getNumSamples() == targetSamples) + return source; + + auto fitted = std::make_shared>( + source->getNumChannels(), targetSamples); + fitted->clear(); + const int copySamples = std::min(source->getNumSamples(), targetSamples); + if (copySamples > 0) + { + for (int channel = 0; channel < source->getNumChannels(); ++channel) + fitted->copyFrom(channel, 0, *source, channel, 0, copySamples); + } + return fitted; +} + +} // namespace + +Result ProjectSession::prepareCopyVocalBundle( + const juce::File& file, Language language) +{ + using namespace CopyVocalBundle; + + const auto bundleResult = Bundle::loadFromFile(file); + if (!bundleResult.ok()) + return Result::failure(bundleResult.error()); + const auto& bundle = bundleResult.value(); + + double loadedSampleRate = 0.0; + auto audioBuffer = loadAudioFile(bundle.studentMedia.file, loadedSampleRate); + if (audioBuffer == nullptr || audioBuffer->getNumSamples() <= 0) + { + return Result::failure( + Error(ErrorCode::InvalidAudioInput, + "Cannot decode CopyVocal student media: " + + bundle.studentMedia.file.getFullPathName().toStdString(), + "CopyVocal bundle")); + } + if (audioBuffer->getNumChannels() <= 0 || audioBuffer->getNumChannels() > 2) + { + return Result::failure( + Error(ErrorCode::InvalidAudioInput, + "CopyVocal student media must be mono or stereo", + "CopyVocal bundle")); + } + + auto fittedBuffer = fitAudioBufferToDuration( + audioBuffer, loadedSampleRate, bundle.projectSourceSeconds); + if (fittedBuffer == nullptr) + { + return Result::failure( + Error(ErrorCode::InvalidParameter, + "Cannot fit CopyVocal student media to the bundle duration", + "CopyVocal bundle")); + } + + OpenTuneAudioProcessor::PreparedImport preparedImport; + if (!processorRef_.prepareImport( + juce::AudioBuffer(*fittedBuffer), + loadedSampleRate, + bundle.projectName.isNotEmpty() ? bundle.projectName : juce::String("CopyVocal"), + bundle.studentMedia.file.getFullPathName(), + preparedImport, + "copyvocal-file")) + { + return Result::failure( + Error(ErrorCode::InvalidAudioInput, + "OpenTune rejected the CopyVocal student media", + "CopyVocal bundle")); + } + + const int64_t storedSamples = preparedImport.storedAudioBuffer.getNumSamples(); + const auto projectResult = buildProject( + bundle, + storedSamples, + preparedImport.storedAudioBuffer.getNumChannels(), + TimeCoordinate::kRenderSampleRate, + preparedImport.silentGaps, + ProjectPersistence::kCurrentProjectFormatVersion, + "1.8.2", + preparedImport.storedAudioBuffer.getReadPointer(0)); + if (!projectResult.ok()) + return Result::failure(projectResult.error()); + auto prepared = std::move(projectResult).value(); + + // A provisional .otproj path lets Ctrl+S save next to the bundle without + // silently overwriting an existing project. If the name is taken, leave the + // path empty so Save routes through Save As. + const auto legalBase = juce::File::createLegalFileName(prepared.snapshot.header.projectName); + const auto parentDirectory = file.getParentDirectory(); + auto proposedProject = parentDirectory.getChildFile(legalBase + ".otproj"); + if (proposedProject.existsAsFile()) + proposedProject = juce::File(); + if (proposedProject == juce::File() && legalBase.isNotEmpty()) + { + auto alternative = parentDirectory.getChildFile(legalBase + " (CopyVocal).otproj"); + if (!alternative.existsAsFile()) + proposedProject = alternative; + } + + PreparedOpen preparedOpen; + preparedOpen.snapshot = std::move(prepared.snapshot); + preparedOpen.projectFile = proposedProject; + preparedOpen.language = language; + + PreparedProjectSource preparedSource; + preparedSource.sourceId = 1; + preparedSource.preparedImport = std::move(preparedImport); + preparedOpen.sources.push_back(std::move(preparedSource)); + preparedOpen.providedF0.push_back({prepared.contentKey, std::move(prepared.pitchCurve)}); + + return Result::success(std::move(preparedOpen)); +} + Result ProjectSession::commitPreparedOpen(PreparedOpen&& preparedOpen) { const auto& snapshot = preparedOpen.snapshot; @@ -402,6 +531,12 @@ Result ProjectSession::commitPreparedOpen(PreparedOpen&& preparedOpen) if (auto* crs = processorRef_.getContentRenderService()) crs->clearAll(); + std::map> providedCurves; + for (const auto& provided : preparedOpen.providedF0) + if (provided.pitchCurve != nullptr) + providedCurves[provided.contentKey] = provided.pitchCurve; + std::set providedKeys; + // 1. 重建 Sources for (auto& preparedSource : preparedOpen.sources) { auto& prepared = preparedSource.preparedImport; @@ -508,6 +643,18 @@ Result ProjectSession::commitPreparedOpen(PreparedOpen&& preparedOpen) } clip->applyPitchCurve(pitchCurve); + const auto providedIt = providedCurves.find(contentEntry.contentKey); + const bool hasProvidedF0 = providedIt != providedCurves.end() + && providedIt->second != nullptr; + if (hasProvidedF0) + { + // Importer-supplied analysis: install the whole curve and mark F0 + // Ready. The normal project path deliberately re-extracts F0, but a + // CopyVocal bundle already carries the student's RMVPE curve. + clip->applyOriginalF0(providedIt->second); + providedKeys.insert(contentEntry.contentKey); + } + // 恢复 TimeGrid if (!contentEntry.timeGrid.handles.empty()) { std::vector handles; @@ -552,13 +699,16 @@ Result ProjectSession::commitPreparedOpen(PreparedOpen&& preparedOpen) } } - // 恢复 Original F0 state — Ready 和 Extracting 都归一化为 NotRequested, - // 让 F0 提取流程重新分析。 - auto restoredF0State = static_cast(contentEntry.originalF0State); - if (restoredF0State == OriginalF0State::Ready - || restoredF0State == OriginalF0State::Extracting) - restoredF0State = OriginalF0State::NotRequested; - clip->applyOriginalF0State(restoredF0State); + // Normalize Ready/Extracting to NotRequested so F0 is re-extracted, except for + // importer-provided F0 which was already installed as Ready above. + if (!hasProvidedF0) + { + auto restoredF0State = static_cast(contentEntry.originalF0State); + if (restoredF0State == OriginalF0State::Ready + || restoredF0State == OriginalF0State::Extracting) + restoredF0State = OriginalF0State::NotRequested; + clip->applyOriginalF0State(restoredF0State); + } // 恢复 Pitch shift settings PitchShiftSettings pitchShift; @@ -680,10 +830,19 @@ Result ProjectSession::commitPreparedOpen(PreparedOpen&& preparedOpen) if (uniqueKeys.insert(key).second) { - OpenTuneAudioProcessor::ContentRefreshRequest refreshRequest; - refreshRequest.contentKey = key; - refreshRequest.preserveCorrectionsOutsideChangedRange = true; - processorRef_.requestContentRefresh(refreshRequest); + if (providedKeys.count(key) > 0) + { + // The curve is already complete; skip F0 inference and go + // straight to the Stage 1 render. + processorRef_.requestFullContentRender(key); + } + else + { + OpenTuneAudioProcessor::ContentRefreshRequest refreshRequest; + refreshRequest.contentKey = key; + refreshRequest.preserveCorrectionsOutsideChangedRange = true; + processorRef_.requestContentRefresh(refreshRequest); + } } } } @@ -692,7 +851,8 @@ Result ProjectSession::commitPreparedOpen(PreparedOpen&& preparedOpen) cachedProjectId_ = snapshot.header.projectId; cachedCreatedAt_ = snapshot.header.createdAt; clearDirty(); - pushRecentProject(preparedOpen.projectFile); + if (preparedOpen.projectFile.existsAsFile()) + pushRecentProject(preparedOpen.projectFile); return Result::success(); } diff --git a/Source/Utils/ProjectSession.h b/Source/Utils/ProjectSession.h index 87d76958..e6af23b5 100644 --- a/Source/Utils/ProjectSession.h +++ b/Source/Utils/ProjectSession.h @@ -25,6 +25,7 @@ #include "ProjectModel.h" #include "Error.h" #include "LocalizationManager.h" +#include "PitchCurve.h" namespace OpenTune { @@ -108,16 +109,28 @@ class ProjectSession { OpenTuneAudioProcessor::PreparedImport preparedImport; }; + /// Analysis provided by an importer instead of OpenTune's F0 extractor; + /// commitPreparedOpen installs it as Ready and skips initial F0 re-analysis. + struct ProvidedContentF0 { + ContentKey contentKey; + std::shared_ptr pitchCurve; + }; + struct PreparedOpen { ProjectSnapshot snapshot; juce::File projectFile; std::vector sources; + std::vector providedF0; Language language = Language::Chinese; }; /** 在后台线程读取工程媒体并执行 canonical import 预处理。 */ Result prepareOpen(const juce::File& file, Language language); + /// Load a CopyVocal .cvf on a worker thread, fitting student audio to + /// projectSourceSeconds and injecting original/target F0 without extraction. + Result prepareCopyVocalBundle(const juce::File& file, Language language); + /** 在消息线程一次性提交已预处理的工程数据。 */ Result commitPreparedOpen(PreparedOpen&& preparedOpen); diff --git a/Source/Utils/TimeGrid.cpp b/Source/Utils/TimeGrid.cpp index 19fe9cc2..162723ae 100644 --- a/Source/Utils/TimeGrid.cpp +++ b/Source/Utils/TimeGrid.cpp @@ -110,8 +110,12 @@ bool TimeGridSnapshot::validate(const std::vector& handles, juce::St + ", curr=" + juce::String(curr.output_seconds, 9) + ")"; return false; } - // Internal handle spacing: require 150 ms minimum source-time spacing - if (!isEndpointOnly && !hasMinimumSourceSpacing(prev.source_seconds, curr.source_seconds)) { + // Require 150 ms source spacing for editing UX; dense anchors are allowed + // when either handle is a High-confidence externally imported fact. + const bool denseImportedPair = prev.confidence == Confidence::High + || curr.confidence == Confidence::High; + if (!isEndpointOnly && !denseImportedPair + && !hasMinimumSourceSpacing(prev.source_seconds, curr.source_seconds)) { const double srcGapMs = (curr.source_seconds - prev.source_seconds) * 1000.0; outError = "Handles must have source_seconds spacing >= " + juce::String(static_cast(kMinSourceSpacingSeconds * 1000.0)) diff --git a/Source/Utils/TimeGrid.h b/Source/Utils/TimeGrid.h index ba28f3ce..60df9385 100644 --- a/Source/Utils/TimeGrid.h +++ b/Source/Utils/TimeGrid.h @@ -76,6 +76,7 @@ class TimeGridSnapshot { TimeGridSnapshot() = default; static constexpr double kMinOutputSpacingSeconds = 0.030; + // Editing-UX minimum; bypassed for pairs involving a High-confidence imported anchor. static constexpr double kMinSourceSpacingSeconds = 0.150; static bool hasMinimumSourceSpacing(double previousSourceSeconds, diff --git a/Tests/CopyVocalBundleTests.cpp b/Tests/CopyVocalBundleTests.cpp new file mode 100644 index 00000000..394f0cae --- /dev/null +++ b/Tests/CopyVocalBundleTests.cpp @@ -0,0 +1,293 @@ +#include "Utils/CopyVocalBundle.h" +#include "Utils/ContentAnalysisState.h" + +#include + +#include +#include +#include + +namespace { + +int failures = 0; + +void check(bool condition, const char* message) +{ + if (!condition) + { + std::printf("FAIL: %s\n", message); + ++failures; + } +} + +juce::String base64F32(const std::vector& values) +{ + return juce::Base64::toBase64(values.data(), values.size() * sizeof(float)); +} + +juce::String base64U8(const std::vector& values) +{ + return juce::Base64::toBase64(values.data(), values.size()); +} + +juce::String makeBundleJson(const juce::String& mediaPath, const juce::String& originalBase64, + const juce::String& originalMask, const juce::String& targetBase64, + const juce::String& targetMask) +{ + juce::String json = R"JSON({ + "format": "copyvocal.file", + "formatVersion": 1, + "producer": { "name": "CopyVocal", "version": "test", "createdAt": "2026-11-10T00:00:00Z", "jobStatus": "completed" }, + "project": { "name": "unit-test", "language": "zh", "sampleRate": 44100 }, + "clocks": { + "studentSeconds": 0.05, + "teacherSeconds": 0.03, + "outputSeconds": 0.03, + "projectSourceSeconds": 0.03, + "outputClock": "teacher", + "timingChanged": true, + "pitchPolicy": "teacher_contour_student_register", + "registerOffsetCents": 0.0 + }, + "media": { + "student": { + "role": "student", + "path": "__MEDIA__", + "sampleRate": 44100, + "channels": 1, + "sampleCount": 1323, + "durationSeconds": 0.03 + } + }, + "f0": { + "hopSize": 160, + "sampleRate": 16000, + "frameStepSeconds": 0.01, + "frameCount": 3, + "original": { "encoding": "base64-f32le", "values": "__ORIG__", "voiced": "__ORIGMASK__" }, + "target": { "encoding": "base64-f32le", "values": "__TARGET__", "voiced": "__TARGETMASK__" } + }, + "notes": [ + { "start": 0.0, "end": 0.02, "pitchHz": 120.0, "midi": 46.7, "lyric": "a", "source": "teacher" } + ], + "regions": [ + { "teacherStart": 0.0, "teacherEnd": 0.03, "studentStart": 0.0, "studentEnd": 0.03, + "status": "matched", "mode": "synthesize", "quality": 1.0, "unsupported": false, + "teacherAnchors": [0.0, 0.03], "studentAnchors": [0.0, 0.03] } + ], + "timeGrid": { + "totalDurationSeconds": 0.03, + "handles": [ + { "sourceSeconds": 0.0, "outputSeconds": 0.0, "kind": "clipStart", "confidence": "default" }, + { "sourceSeconds": 0.01, "outputSeconds": 0.005, "kind": "internalOnset", "confidence": "high" }, + { "sourceSeconds": 0.02, "outputSeconds": 0.025, "kind": "internalOnset", "confidence": "high" }, + { "sourceSeconds": 0.03, "outputSeconds": 0.03, "kind": "clipEnd", "confidence": "default" } + ] + }, + "diagnostics": { "warnings": ["unit"], "unresolvedRegionCount": 0, "unsupportedDurationSeconds": 0.0 } +})JSON"; + json = json.replace("__MEDIA__", mediaPath.replace("\\", "\\\\")); + json = json.replace("__ORIG__", originalBase64); + json = json.replace("__ORIGMASK__", originalMask); + json = json.replace("__TARGET__", targetBase64); + json = json.replace("__TARGETMASK__", targetMask); + return json; +} + +} // namespace + +int main(int argc, char** argv) +{ + const auto temp = juce::File::getSpecialLocation(juce::File::tempDirectory) + .getNonexistentChildFile("copyvocal-cvf-test", ".wav"); + temp.replaceWithText("RIFF"); + const auto mediaPath = temp.getFullPathName(); + + const std::vector original{100.0f, 0.0f, 200.0f}; + const std::vector originalMask{1, 0, 1}; + const std::vector target{110.0f, 120.0f, 0.0f}; + const std::vector targetMask{1, 1, 0}; + + auto json = makeBundleJson(mediaPath, base64F32(original), base64U8(originalMask), + base64F32(target), base64U8(targetMask)); + const auto bundleFile = juce::File::getSpecialLocation(juce::File::tempDirectory) + .getNonexistentChildFile("copyvocal-cvf-test", ".cvf"); + bundleFile.replaceWithText(json); + + const auto parsed = OpenTune::CopyVocalBundle::Bundle::loadFromFile(bundleFile); + check(parsed.ok(), "valid bundle parses"); + if (parsed.ok()) + { + const auto& bundle = parsed.value(); + check(bundle.formatVersion == 1, "format version"); + check(bundle.originalF0.f0Hz.size() == 3, "original F0 size"); + check(std::abs(bundle.originalF0.f0Hz[0] - 100.0f) < 1e-4f, "original F0 value"); + check(bundle.targetF0.f0Hz[2] == 0.0f, "target F0 zero"); + check(bundle.notes.size() == 1, "note parsed"); + check(bundle.timeGrid.size() == 4, "time grid parsed"); + + const int expectedFrames = OpenTune::CopyVocalBundle::expectedF0FrameCount( + static_cast(std::llround(bundle.projectSourceSeconds * 44100.0))); + check(expectedFrames == 4 || expectedFrames == 3, "expected frame count is sane"); + + const auto curveResult = OpenTune::CopyVocalBundle::buildPitchCurve(bundle, 3); + check(curveResult.ok(), "pitch curve builds"); + if (curveResult.ok()) + { + const auto curve = curveResult.value(); + const auto snapshot = curve->getSnapshot(); + check(snapshot->getOriginalF0().size() == 3, "curve original size"); + check(std::abs(snapshot->getOriginalF0()[2] - 200.0f) < 1e-4f, "curve original value"); + check(snapshot->getCorrectionSegments().size() == 1, "one voiced correction run"); + if (!snapshot->getCorrectionSegments().empty()) + { + const auto& segment = snapshot->getCorrectionSegments().front(); + check(segment.startFrame == 0 && segment.endFrame == 1, "correction clips unvoiced frame"); + check(std::abs(segment.f0Data[0] - 110.0f) < 1e-4f, "correction target value"); + } + } + + const auto notes = OpenTune::CopyVocalBundle::buildNotes(bundle); + check(notes.size() == 1, "note builder keeps valid note"); + if (!notes.empty()) + { + check(std::abs(notes.front().pitch - 120.0f) < 1e-4f, "note pitch"); + check(std::abs(notes.front().originalPitch - 100.0f) < 1e-4f, "note original pitch"); + } + + const auto grid = OpenTune::CopyVocalBundle::buildTimeGrid(bundle); + check(grid != nullptr, "time grid builds"); + if (grid != nullptr) + { + check(std::abs(grid->totalDurationSeconds() - 0.03) < 1e-9, "time grid duration"); + check(grid->handles().size() == 4, "dense high-confidence handles accepted"); + check(std::abs(grid->tauForward(0.01) - 0.005) < 1e-9, "time grid mapping"); + check(!grid->isIdentity(), "time grid is non-identity"); + } + + const int64_t storedSamples = static_cast(std::llround( + bundle.projectSourceSeconds * 44100.0)); + std::vector pcm(static_cast(storedSamples), 0.25f); + const auto project = OpenTune::CopyVocalBundle::buildProject( + bundle, storedSamples, 1, 44100.0, {}, 7, "test", pcm.data()); + check(project.ok(), "project snapshot builds"); + if (project.ok()) + { + const auto& prepared = project.value(); + check(prepared.snapshot.sources.size() == 1, "one source"); + check(prepared.snapshot.contents.size() == 1, "one content"); + check(prepared.snapshot.tracks.size() == 1, "one track"); + check(prepared.snapshot.tracks.front().placements.size() == 1, "one placement"); + check(prepared.contentKey.isValid(), "content key valid"); + check(prepared.snapshot.tracks.front().placements.front().contentKey + == prepared.contentKey, "placement binds the content key"); + check(prepared.snapshot.contents.front().contentKey == prepared.contentKey, + "content entry binds the content key"); + check(prepared.snapshot.contents.front().sourceId == 1, "content uses the source"); + check(std::abs(prepared.snapshot.contents.front().sourceWindow.sourceEndSeconds - 0.03) + < 1e-6, "source window spans the project duration"); + check(prepared.snapshot.contents.front().originalF0State + == static_cast(OpenTune::OriginalF0State::Ready), + "original F0 marked ready"); + check(prepared.snapshot.contents.front().noteTopologyInitialized, + "note topology initialized"); + check(prepared.snapshot.contents.front().timeGrid.handles.size() == 4, + "project persists the imported grid"); + check(prepared.pitchCurve != nullptr, "project carries the provided curve"); + if (prepared.pitchCurve != nullptr) + { + const auto curve = prepared.pitchCurve->getSnapshot(); + check(static_cast(curve->getOriginalEnergy().size()) + == prepared.expectedF0Frames, + "provided curve carries per-frame energy"); + check(!curve->getOriginalEnergy().empty() + && curve->getOriginalEnergy().front() > 0.0f, + "voiced frames get non-zero energy"); + } + } + + const auto wrongLength = OpenTune::CopyVocalBundle::buildProject( + bundle, storedSamples + 4410, 1, 44100.0, {}, 7, "test"); + check(!wrongLength.ok(), "duration mismatch is rejected"); + } + + auto badJson = json.replace("\"formatVersion\": 1", "\"formatVersion\": 99"); + const auto badFile = juce::File::getSpecialLocation(juce::File::tempDirectory) + .getNonexistentChildFile("copyvocal-cvf-bad", ".cvf"); + badFile.replaceWithText(badJson); + const auto bad = OpenTune::CopyVocalBundle::Bundle::loadFromFile(badFile); + check(!bad.ok(), "future format version rejected"); + + // Optional round-trip against a real CopyVocal export: + // OpenTuneCopyVocalBundleTests.exe path\to\opentune.cvf + if (argc > 1) + { + const juce::File realFile(juce::String::fromUTF8(argv[1])); + const auto real = OpenTune::CopyVocalBundle::Bundle::loadFromFile(realFile); + check(real.ok(), "real CopyVocal bundle parses"); + if (real.ok()) + { + const auto& bundle = real.value(); + std::printf("real bundle: notes=%d handles=%d frames=%d timingChanged=%d\n", + static_cast(bundle.notes.size()), + static_cast(bundle.timeGrid.size()), + bundle.originalF0.frameCount, + bundle.timingChanged ? 1 : 0); + const auto expected = OpenTune::CopyVocalBundle::expectedF0FrameCount( + static_cast(std::llround(bundle.projectSourceSeconds * 44100.0))); + const auto curve = OpenTune::CopyVocalBundle::buildPitchCurve(bundle, expected); + check(curve.ok(), "real bundle pitch curve builds"); + if (curve.ok()) + { + const auto snapshot = curve.value()->getSnapshot(); + check(!snapshot->getOriginalF0().empty(), "real bundle has original F0"); + check(snapshot->getHopSize() == 160, "real bundle hop size"); + int correctionFrames = 0; + for (const auto& segment : snapshot->getCorrectionSegments()) + correctionFrames += segment.endFrame - segment.startFrame; + std::printf("real bundle: correction frames=%d\n", correctionFrames); + check(correctionFrames > 0, "real bundle target F0 becomes corrections"); + } + const auto grid = OpenTune::CopyVocalBundle::buildTimeGrid(bundle); + check(grid != nullptr, "real bundle time grid builds"); + if (grid != nullptr) + std::printf("real bundle: grid handles=%d identity=%d\n", + static_cast(grid->handles().size()), + grid->isIdentity() ? 1 : 0); + const auto realNotes = OpenTune::CopyVocalBundle::buildNotes(bundle); + check(realNotes.size() == bundle.notes.size(), "real bundle notes survive normalization"); + + // The real file is the one users import: make sure materializing it + // keeps the notes in the project snapshot (the piano roll reads + // notes from there, not from the parsed bundle). + const int64_t realSamples = static_cast(std::llround( + bundle.projectSourceSeconds * 44100.0)); + std::vector silence(static_cast(realSamples), 0.0f); + const auto realProject = OpenTune::CopyVocalBundle::buildProject( + bundle, realSamples, 1, 44100.0, {}, 7, "test", silence.data()); + check(realProject.ok(), "real bundle project builds"); + if (realProject.ok()) + { + const auto& content = realProject.value().snapshot.contents.front(); + check(content.notes.size() == realNotes.size(), + "real bundle notes reach the project snapshot"); + check(realProject.value().pitchCurve != nullptr + && !realProject.value().pitchCurve->getSnapshot() + ->getOriginalEnergy().empty(), + "real bundle project carries energy"); + } + } + } + + badFile.deleteFile(); + bundleFile.deleteFile(); + temp.deleteFile(); + + if (failures != 0) + { + std::printf("CopyVocalBundle tests failed: %d\n", failures); + return 1; + } + std::puts("CopyVocalBundle tests passed."); + return 0; +} diff --git a/Tests/CopyVocalImportTests.cpp b/Tests/CopyVocalImportTests.cpp new file mode 100644 index 00000000..0aa5f2ec --- /dev/null +++ b/Tests/CopyVocalImportTests.cpp @@ -0,0 +1,218 @@ +#include "../Source/Utils/ProjectSession.h" +#include "../Source/Utils/CopyVocalBundle.h" +#include "../Source/PluginProcessor.h" + +#include +#include + +#include +#include +#include + +namespace OpenTune { +// The test links the Standalone shared code but not the UI. createEditor() is +// never exercised here, so a null factory satisfies the linker without pulling +// the whole editor into the test binary. +juce::AudioProcessorEditor* createOpenTuneEditor(OpenTuneAudioProcessor&) +{ + return nullptr; +} +} // namespace OpenTune + +namespace { + +int failures = 0; + +void check(bool condition, const char* message) +{ + if (!condition) + { + std::printf("FAIL: %s\n", message); + ++failures; + } +} + +juce::File writeWav(const juce::File& file, double seconds, double sampleRate, int channels) +{ + file.deleteFile(); + auto stream = std::unique_ptr(file.createOutputStream()); + if (stream == nullptr) + return {}; + juce::WavAudioFormat format; + auto writer = std::unique_ptr( + format.createWriterFor(stream.get(), sampleRate, + static_cast(channels), 24, {}, 0)); + if (writer == nullptr) + return {}; + stream.release(); + const int samples = static_cast(std::llround(seconds * sampleRate)); + juce::AudioBuffer buffer(channels, samples); + buffer.clear(); + for (int channel = 0; channel < channels; ++channel) + { + auto* data = buffer.getWritePointer(channel); + for (int index = 0; index < samples; ++index) + data[index] = 0.25f * std::sin(2.0f * juce::MathConstants::pi + * 220.0f * static_cast(index) / static_cast(sampleRate)); + } + writer->writeFromAudioSampleBuffer(buffer, 0, samples); + writer.reset(); + return file; +} + +juce::String base64F32(const std::vector& values) +{ + return juce::Base64::toBase64(values.data(), values.size() * sizeof(float)); +} + +juce::String base64U8(const std::vector& values) +{ + return juce::Base64::toBase64(values.data(), values.size()); +} + +juce::String makeBundle(const juce::File& media, double outputSeconds) +{ + const int frames = static_cast(std::llround(outputSeconds / 0.01)) + 1; + std::vector original(static_cast(frames), 0.0f); + std::vector target(static_cast(frames), 0.0f); + std::vector originalMask(static_cast(frames), 0); + std::vector targetMask(static_cast(frames), 0); + for (int frame = 5; frame < frames; ++frame) + { + original[static_cast(frame)] = 200.0f; + target[static_cast(frame)] = 220.0f; + originalMask[static_cast(frame)] = 1; + targetMask[static_cast(frame)] = 1; + } + + const double middle = outputSeconds * 0.5; + const auto escapedPath = media.getFullPathName().replace("\\", "\\\\"); + juce::String json = R"JSON({ + "format": "copyvocal.file", + "formatVersion": 1, + "producer": { "name": "CopyVocal", "version": "test", "createdAt": "2026-11-10T00:00:00Z", "jobStatus": "completed" }, + "project": { "name": "integration", "language": "en", "sampleRate": 44100 }, + "clocks": { + "studentSeconds": 1.0, "teacherSeconds": __OUT__, + "outputSeconds": __OUT__, "projectSourceSeconds": __OUT__, + "outputClock": "teacher", "timingChanged": true, + "pitchPolicy": "teacher_contour_student_register", "registerOffsetCents": 0.0 + }, + "media": { "student": { "role": "student", "path": "__MEDIA__", + "sampleRate": 44100, "channels": 1, "sampleCount": 44100, "durationSeconds": 1.0 } }, + "f0": { + "hopSize": 160, "sampleRate": 16000, "frameStepSeconds": 0.01, "frameCount": __FRAMES__, + "original": { "encoding": "base64-f32le", "values": "__ORIG__", "voiced": "__ORIGMASK__" }, + "target": { "encoding": "base64-f32le", "values": "__TARGET__", "voiced": "__TARGETMASK__" } + }, + "notes": [ { "start": 0.05, "end": 0.2, "pitchHz": 220.0, "midi": 57.0, "source": "teacher" } ], + "regions": [ { "teacherStart": 0.05, "teacherEnd": 0.2, "studentStart": 0.05, "studentEnd": 0.2, + "status": "matched", "mode": "synthesize", "quality": 1.0, "unsupported": false, + "teacherAnchors": [0.05, 0.2], "studentAnchors": [0.05, 0.2] } ], + "timeGrid": { "totalDurationSeconds": __OUT__, "handles": [ + { "sourceSeconds": 0.0, "outputSeconds": 0.0, "kind": "clipStart", "confidence": "default" }, + { "sourceSeconds": 0.05, "outputSeconds": 0.05, "kind": "onsetVoiced", "confidence": "high" }, + { "sourceSeconds": 0.2, "outputSeconds": 0.2, "kind": "internalOnset", "confidence": "high" }, + { "sourceSeconds": __OUT__, "outputSeconds": __OUT__, "kind": "clipEnd", "confidence": "default" } ] }, + "diagnostics": { "warnings": [], "unresolvedRegionCount": 0, "unsupportedDurationSeconds": 0.0 } +})JSON"; + json = json.replace("__MEDIA__", escapedPath); + json = json.replace("__OUT__", juce::String(outputSeconds, 9)); + json = json.replace("__FRAMES__", juce::String(frames)); + json = json.replace("__ORIG__", base64F32(original)); + json = json.replace("__ORIGMASK__", base64U8(originalMask)); + json = json.replace("__TARGET__", base64F32(target)); + json = json.replace("__TARGETMASK__", base64U8(targetMask)); + return json; +} + +} // namespace + +int main() +{ + juce::ScopedJuceInitialiser_GUI juceInitialiser; + + const auto root = juce::File::getSpecialLocation(juce::File::tempDirectory) + .getNonexistentChildFile("copyvocal-cvf-import", {}); + root.createDirectory(); + + // Student media is 1.0 s but the corrected output is 0.6 s: the importer + // must trim, and the F0 grid must follow the trimmed duration. + auto audio = writeWav(root.getChildFile("student.wav"), 1.0, 44100.0, 1); + check(audio.existsAsFile(), "test wav written"); + + const auto bundleFile = root.getChildFile("bundle.cvf"); + bundleFile.replaceWithText(makeBundle(audio, 0.6)); + + OpenTune::AppPreferences::StorageOptions options; + options.applicationName = "OpenTuneCopyVocalImportTest"; + options.settingsDirectory = root.getChildFile("settings"); + OpenTune::AppPreferences preferences(options); + preferences.load(); + + OpenTune::OpenTuneAudioProcessor processor; + OpenTune::ProjectSession session(processor, preferences); + + const auto prepared = session.prepareCopyVocalBundle(bundleFile, OpenTune::Language::English); + check(prepared.ok(), "bundle prepares an OpenTune project"); + if (prepared.ok()) + { + const auto& value = prepared.value(); + check(value.sources.size() == 1, "one prepared source"); + check(value.providedF0.size() == 1, "one provided F0 curve"); + check(value.snapshot.sources.size() == 1, "snapshot has one source"); + check(value.snapshot.contents.size() == 1, "snapshot has one content"); + check(value.snapshot.tracks.size() == 1, "snapshot has one track"); + check(std::abs(value.snapshot.sources.front().lengthSeconds - 0.6) < 0.001, + "source trimmed to the bundle duration"); + check(std::abs(value.snapshot.contents.front().sourceWindow.sourceEndSeconds - 0.6) < 0.001, + "content window matches the bundle duration"); + if (!value.sources.empty()) + { + const int stored = value.sources.front().preparedImport.storedAudioBuffer.getNumSamples(); + check(std::abs(static_cast(stored) / 44100.0 - 0.6) < 0.001, + "stored audio has the bundle duration"); + } + if (!value.providedF0.empty() && value.providedF0.front().pitchCurve != nullptr) + { + const auto curve = value.providedF0.front().pitchCurve; + const auto snapshot = curve->getSnapshot(); + const int expected = OpenTune::CopyVocalBundle::expectedF0FrameCount( + static_cast(std::llround(0.6 * 44100.0))); + check(static_cast(snapshot->getOriginalF0().size()) == expected, + "provided original F0 matches the clip frame count"); + check(static_cast(snapshot->getOriginalEnergy().size()) == expected, + "provided curve carries OpenDyne energy"); + bool hasEnergy = false; + for (const float value : snapshot->getOriginalEnergy()) + hasEnergy = hasEnergy || value > 0.0f; + check(hasEnergy, "imported audio produces non-zero note energy"); + check(!snapshot->getCorrectionSegments().empty(), + "provided target F0 becomes a correction segment"); + if (!snapshot->getCorrectionSegments().empty()) + { + const auto& segment = snapshot->getCorrectionSegments().front(); + check(std::abs(segment.f0Data.front() - 220.0f) < 1e-3f, + "correction carries the bundle target pitch"); + } + } + check(!value.snapshot.contents.front().notes.empty(), "bundle notes survive import"); + if (!value.snapshot.contents.front().notes.empty()) + { + const auto& note = value.snapshot.contents.front().notes.front(); + check(std::abs(note.pitch - 220.0f) < 1e-3f, "note target pitch"); + } + check(std::abs(value.snapshot.tracks.front().placements.front().timelineDurationSeconds - 0.6) + < 0.001, "placement duration"); + } + + root.deleteRecursively(); + + if (failures != 0) + { + std::printf("CopyVocal import tests failed: %d\n", failures); + return 1; + } + std::puts("CopyVocal import tests passed."); + return 0; +} diff --git a/docs/copyvocal-import.md b/docs/copyvocal-import.md new file mode 100644 index 00000000..ab2ac64c --- /dev/null +++ b/docs/copyvocal-import.md @@ -0,0 +1,107 @@ +# 在 OpenTune 中导入 CopyVocal 结果(`.cvf`) + +本页是面向使用者的快速上手说明。`.cvf` 格式本身由 CopyVocal 定义,权威文档见 +CopyVocal 仓库的 `docs/copyvocal-bundle-v1.md`。 + +OpenTune 导入 `.cvf` 后得到的是一个**可继续编辑的工程**:学生原始音频、音符、 +原始 F0、CopyVocal 的目标 F0(作为音高修正段)以及教师对齐得到的时间网格都会 +进入 OpenTune 的编辑模型。它不是把 `student.corrected.wav` 当成普通音频导入。 + +--- + +## 1. 在 CopyVocal 侧生成 `.cvf` + +### 方法 A:运行任务时顺便导出 + +```powershell +.\run.bat --teacher ".\Teacher.wav" --student ".\Student.wav" ` + --output ".\outputs\short" --export-cvf +``` + +产物:`.\outputs\short\copyvocal.cvf`。导出结果也会写入 `job.json` 的 +`stages.opentune_bundle`,包含 note / handle / frame 数量。 + +### 方法 B:为已有输出补导出(不重新推理) + +```powershell +D:\miniconda3\envs\vocal2midi\python.exe -m application.opentune_bundle ".\outputs\short" +``` + +输出目录需要已经包含 `job.json`、`student.analysis.json`、`alignment.json` 和 +`target_pitch.npz`。默认写到 `\copyvocal.cvf`,可用 `-o` 指定路径。 + +> `.cvf` 里记录的是学生参考音频的**绝对路径**,请保持 CopyVocal 输出目录不动, +> 或把整个输出目录一起迁移。 + +### 方法 C:在 CopyVocal GUI 中导出 + +- 运行前在 **设置 → 运行选项** 打开 **同时导出 CopyVocal 文件 (.cvf)**,任务完成后 + 会随输出一起写出 `copyvocal.cvf`; +- 对已经完成的输出,在 **结果** 页点击 **导出 CopyVocal 文件** 即可补导出。 + +--- + +## 2. 在 OpenTune 侧导入 + +两种方式等价: + +- 菜单 **File → Import CopyVocal Bundle...**,选择 `.cvf` 文件; +- 直接把 `.cvf` 拖进 OpenTune 窗口。 + +如果当前工程有未保存修改,OpenTune 会先询问保存 / 不保存 / 取消,与打开普通 +工程的行为一致。导入在后台完成,完成后自动切到新工程。 + +导入后应能看到: + +| 内容 | 来源 | +| --- | --- | +| 音符(音高、起止) | 教师 GAME notes(失败时回退学生 notes),音高取目标 F0 中位数 | +| 原始 F0 曲线 | `f0.original`,已标记为 Ready,不会重新推理 | +| 音高修正段(手绘) | `f0.target`,仅在原始 F0 有声的连续区间生成 | +| 时间网格 | `timeGrid.handles`,教师对齐锚点,可继续编辑 | +| 工程源音频 | 学生参考音频补零/裁剪到 CopyVocal 输出时长 | + +--- + +## 3. 关于时间与音频长度 + +CopyVocal 完整修正后的输出长度等于教师长度,通常不等于学生录音长度;而 OpenTune +要求 clip 的源时长与输出时长一致。因此导入时会: + +1. 把学生参考音频补零或裁剪到 `clocks.projectSourceSeconds`(= 输出时长); +2. 补零区间的 F0 保持为 0,不产生虚假音符或修正; +3. `timeGrid` 保持 CopyVocal 的映射,导入后可继续拖动编辑。 + +这些操作只影响 OpenTune 内存中的工程媒体,不修改 CopyVocal 的任何原始文件。 + +--- + +## 4. 保存工程后的行为 + +导入后可以像普通工程一样保存为 `.otproj`、编辑音符和音高、导出渲染。 + +- 原始 F0 与目标修正段会随工程持久化;重新打开工程不需要 CopyVocal。 +- v1 的 `words` / `phonemes` 只被解析,不在界面显示(OpenTune 当前没有歌词模型)。 +- 如果之后在 OpenTune 里对同一段音频重新提取 F0,原始 F0 会被重算,但目标修正段 + 仍保留在工程中。 + +--- + +## 5. 常见问题 + +| 现象 | 原因 / 处理 | +| --- | --- | +| 提示 `unsupported format version` | `.cvf` 的 `formatVersion` 高于当前 OpenTune 支持的版本,升级 OpenTune | +| 提示无法解码学生媒体 | `media.student.path` 指向的 WAV 被移动或删除;保持 CopyVocal 输出目录完整 | +| 提示时长不一致 | 学生参考音频与 `projectSourceSeconds` 偏差超过容差;重新导出 `.cvf` | +| 导入后没有音符 | CopyVocal 运行时加了 `--no-game` 且学生分析也没有可用音符;重新运行并保留音符提取 | +| 音高修正段为空 | 目标 F0 在原始 F0 有声区间内全为 0,通常是该段没有可修正内容 | + +--- + +## 6. 时间映射的实现 + +导入的工程通常带非恒等 `timeGrid`。OpenTune 把该映射烘焙进 Stage 1 的 conditioning +与 F0,由声码器一次合成输出时间轴的音频,不做波形时间伸缩。实现细节与取舍见 +[`time-grid-conditioning-warp.md`](time-grid-conditioning-warp.md)。 +