Просмотр исходного кода

Edison: Tools > Analysis > Convert to score and dump to piano roll, as FL (the selected channel's notes in the current pattern)

Ka1-S 1 месяц назад
Родитель
Сommit
92eade3270

+ 6 - 0
resources/i18n/de.txt

@@ -6032,3 +6032,9 @@ countries: de at ch li lu
 "Deverb..." = "Deverb..."
 "Choose a profile that best matches the source material" = "Wähle das Profil, das am besten zum Ausgangsmaterial passt"
 "Processed" = "Bearbeitet"
+"Analysis" = "Analyse"
+"Convert to score and dump to piano roll" = "In Noten umwandeln und in die Piano Roll übertragen"
+"Detecting score..." = "Noten werden erkannt..."
+"Dumping score..." = "Noten werden übertragen..."
+"No notes found in the sample" = "Keine Noten im Sample gefunden"
+"{0} notes put in the Piano roll of the selected channel" = "{0} Noten in die Piano Roll des gewählten Kanals gesetzt"

+ 6 - 0
resources/i18n/es.txt

@@ -6032,3 +6032,9 @@ countries: es mx ar co cl pe ve
 "Deverb..." = "Deverb..."
 "Choose a profile that best matches the source material" = "Elige el perfil que mejor se ajuste al material de origen"
 "Processed" = "Procesado"
+"Analysis" = "Análisis"
+"Convert to score and dump to piano roll" = "Convertir en partitura y volcar al piano roll"
+"Detecting score..." = "Detectando la partitura..."
+"Dumping score..." = "Volcando la partitura..."
+"No notes found in the sample" = "No se encontraron notas en el sample"
+"{0} notes put in the Piano roll of the selected channel" = "{0} notas puestas en el Piano roll del canal seleccionado"

+ 6 - 0
resources/i18n/fr.txt

@@ -6032,3 +6032,9 @@ countries: fr be ch ca lu
 "Deverb..." = "Deverb..."
 "Choose a profile that best matches the source material" = "Choisissez le profil qui correspond le mieux au matériau source"
 "Processed" = "Traité"
+"Analysis" = "Analyse"
+"Convert to score and dump to piano roll" = "Convertir en partition et envoyer au piano roll"
+"Detecting score..." = "Détection de la partition..."
+"Dumping score..." = "Envoi de la partition..."
+"No notes found in the sample" = "Aucune note trouvée dans l'échantillon"
+"{0} notes put in the Piano roll of the selected channel" = "{0} notes placées dans le Piano roll du canal sélectionné"

+ 6 - 0
resources/i18n/id.txt

@@ -6032,3 +6032,9 @@ countries: id
 "Deverb..." = "Deverb..."
 "Choose a profile that best matches the source material" = "Pilih profil yang paling cocok dengan materi sumber"
 "Processed" = "Diproses"
+"Analysis" = "Analisis"
+"Convert to score and dump to piano roll" = "Ubah menjadi notasi dan kirim ke piano roll"
+"Detecting score..." = "Mendeteksi notasi..."
+"Dumping score..." = "Mengirim notasi..."
+"No notes found in the sample" = "Tidak ada not dalam sampel"
+"{0} notes put in the Piano roll of the selected channel" = "{0} not dimasukkan ke Piano roll channel terpilih"

+ 6 - 0
resources/i18n/it.txt

@@ -6032,3 +6032,9 @@ countries: it ch sm
 "Deverb..." = "Deverb..."
 "Choose a profile that best matches the source material" = "Scegli il profilo più adatto al materiale di partenza"
 "Processed" = "Elaborato"
+"Analysis" = "Analisi"
+"Convert to score and dump to piano roll" = "Converti in partitura e invia al piano roll"
+"Detecting score..." = "Rilevamento della partitura..."
+"Dumping score..." = "Invio della partitura..."
+"No notes found in the sample" = "Nessuna nota trovata nel campione"
+"{0} notes put in the Piano roll of the selected channel" = "{0} note inserite nel Piano roll del canale selezionato"

+ 6 - 0
resources/i18n/ja.txt

@@ -6032,3 +6032,9 @@ countries: jp
 "Deverb..." = "Deverb..."
 "Choose a profile that best matches the source material" = "素材に最も合うプロファイルを選んでください"
 "Processed" = "処理後"
+"Analysis" = "解析"
+"Convert to score and dump to piano roll" = "スコアに変換してピアノロールへ書き出す"
+"Detecting score..." = "スコアを検出中..."
+"Dumping score..." = "スコアを書き出し中..."
+"No notes found in the sample" = "サンプルにノートが見つかりません"
+"{0} notes put in the Piano roll of the selected channel" = "選択チャンネルのピアノロールに {0} 個のノートを入れました"

+ 6 - 0
resources/i18n/ko.txt

@@ -6032,3 +6032,9 @@ countries: kr
 "Deverb..." = "Deverb..."
 "Choose a profile that best matches the source material" = "원본 소재에 가장 잘 맞는 프로필을 고르세요"
 "Processed" = "처리됨"
+"Analysis" = "분석"
+"Convert to score and dump to piano roll" = "악보로 변환해 피아노 롤로 보내기"
+"Detecting score..." = "악보 감지 중..."
+"Dumping score..." = "악보 보내는 중..."
+"No notes found in the sample" = "샘플에서 노트를 찾지 못했습니다"
+"{0} notes put in the Piano roll of the selected channel" = "선택한 채널의 피아노 롤에 노트 {0}개를 넣었습니다"

+ 6 - 0
resources/i18n/nl.txt

@@ -6032,3 +6032,9 @@ countries: nl be
 "Deverb..." = "Deverb..."
 "Choose a profile that best matches the source material" = "Kies het profiel dat het best bij het bronmateriaal past"
 "Processed" = "Bewerkt"
+"Analysis" = "Analyse"
+"Convert to score and dump to piano roll" = "Omzetten naar noten en naar de pianorol sturen"
+"Detecting score..." = "Noten worden herkend..."
+"Dumping score..." = "Noten worden overgezet..."
+"No notes found in the sample" = "Geen noten gevonden in de sample"
+"{0} notes put in the Piano roll of the selected channel" = "{0} noten in de pianorol van het gekozen kanaal gezet"

+ 6 - 0
resources/i18n/pl.txt

@@ -6032,3 +6032,9 @@ countries: pl
 "Deverb..." = "Deverb..."
 "Choose a profile that best matches the source material" = "Wybierz profil najlepiej pasujący do materiału źródłowego"
 "Processed" = "Przetworzony"
+"Analysis" = "Analiza"
+"Convert to score and dump to piano roll" = "Zamień na nuty i przenieś do piano rolla"
+"Detecting score..." = "Wykrywanie nut..."
+"Dumping score..." = "Przenoszenie nut..."
+"No notes found in the sample" = "Nie znaleziono nut w samplu"
+"{0} notes put in the Piano roll of the selected channel" = "{0} nut wstawiono do piano rolla wybranego kanału"

+ 6 - 0
resources/i18n/pt-BR.txt

@@ -6189,3 +6189,9 @@ countries: br
 "Deverb..." = "Deverb..."
 "Choose a profile that best matches the source material" = "Escolha o perfil que melhor combina com o material de origem"
 "Processed" = "Processado"
+"Analysis" = "Análise"
+"Convert to score and dump to piano roll" = "Converter em partitura e enviar ao piano roll"
+"Detecting score..." = "Detectando a partitura..."
+"Dumping score..." = "Enviando a partitura..."
+"No notes found in the sample" = "Nenhuma nota encontrada no sample"
+"{0} notes put in the Piano roll of the selected channel" = "{0} notas colocadas no Piano roll do canal selecionado"

+ 6 - 0
resources/i18n/ru.txt

@@ -6032,3 +6032,9 @@ countries: ru by kz
 "Deverb..." = "Deverb..."
 "Choose a profile that best matches the source material" = "Выберите профиль, лучше всего подходящий к исходному материалу"
 "Processed" = "Обработанный"
+"Analysis" = "Анализ"
+"Convert to score and dump to piano roll" = "Преобразовать в ноты и выгрузить в Piano roll"
+"Detecting score..." = "Распознавание нот..."
+"Dumping score..." = "Выгрузка нот..."
+"No notes found in the sample" = "В сэмпле не найдено нот"
+"{0} notes put in the Piano roll of the selected channel" = "{0} нот добавлено в Piano roll выбранного канала"

+ 6 - 0
resources/i18n/tr.txt

@@ -6032,3 +6032,9 @@ countries: tr
 "Deverb..." = "Deverb..."
 "Choose a profile that best matches the source material" = "Kaynak malzemeye en uygun profili seçin"
 "Processed" = "İşlenmiş"
+"Analysis" = "Analiz"
+"Convert to score and dump to piano roll" = "Notaya dönüştür ve piano roll'a aktar"
+"Detecting score..." = "Notalar algılanıyor..."
+"Dumping score..." = "Notalar aktarılıyor..."
+"No notes found in the sample" = "Örnekte nota bulunamadı"
+"{0} notes put in the Piano roll of the selected channel" = "Seçili kanalın Piano roll'una {0} nota kondu"

+ 6 - 0
resources/i18n/zh-Hans.txt

@@ -6032,3 +6032,9 @@ countries: cn sg
 "Deverb..." = "Deverb..."
 "Choose a profile that best matches the source material" = "选择最符合源素材的配置"
 "Processed" = "处理后"
+"Analysis" = "分析"
+"Convert to score and dump to piano roll" = "转换为乐谱并导入钢琴卷帘"
+"Detecting score..." = "正在检测乐谱..."
+"Dumping score..." = "正在导入乐谱..."
+"No notes found in the sample" = "采样中未找到音符"
+"{0} notes put in the Piano roll of the selected channel" = "已将 {0} 个音符放入所选通道的钢琴卷帘"

+ 6 - 0
resources/i18n/zh-Hant.txt

@@ -6032,3 +6032,9 @@ countries: tw hk mo
 "Deverb..." = "Deverb..."
 "Choose a profile that best matches the source material" = "選擇最符合來源素材的設定檔"
 "Processed" = "處理後"
+"Analysis" = "分析"
+"Convert to score and dump to piano roll" = "轉換為樂譜並匯入鋼琴捲簾"
+"Detecting score..." = "正在偵測樂譜..."
+"Dumping score..." = "正在匯入樂譜..."
+"No notes found in the sample" = "取樣中未找到音符"
+"{0} notes put in the Piano roll of the selected channel" = "已將 {0} 個音符放入所選通道的鋼琴捲簾"

+ 83 - 0
src/core/NewtoneFx.cpp

@@ -965,6 +965,89 @@ std::vector<ScoreNote> score (const Track& track, double sampleRate)
     return out;
 }
 
+std::vector<DetectedNote> detectScore (const SampleData& source, double* detune)
+{
+    std::vector<DetectedNote> out;
+    const auto track = analyseNotes (source);
+    if (track.pitches.empty())
+    {
+        if (detune != nullptr)
+            *detune = 0.0;
+        return out;
+    }
+    // the overall detune: how far the notes sit from their semitones, weighted by their length
+    double sum = 0.0, weight = 0.0;
+    for (const auto& p : track.pitches)
+    {
+        const auto w = (double) (p.origEnd - p.origStart);
+        sum += w * (p.origPitch - std::round (p.origPitch));
+        weight += w;
+    }
+    const auto offset = weight > 0.0 ? sum / weight : 0.0;
+    if (detune != nullptr)
+        *detune = offset;
+    // each note's level (RMS of the channels' mean)
+    std::vector<double> rms;
+    double loudest = 0.0;
+    for (const auto& p : track.pitches)
+    {
+        double e = 0.0;
+        for (auto i = p.origStart; i < p.origEnd; ++i)
+        {
+            const auto x = 0.5 * ((double) source.leftData()[i] + (double) source.rightData()[i]);
+            e += x * x;
+        }
+        rms.push_back (std::sqrt (e / (double) std::max<std::int64_t> (1, p.origEnd - p.origStart)));
+        loudest = std::max (loudest, rms.back());
+    }
+    for (std::size_t k = 0; k < track.pitches.size(); ++k)
+    {
+        const auto& p = track.pitches[k];
+        const auto key = (int) std::lround (p.origPitch - offset);
+        if (key < 0 || key > 127)
+            continue;
+        DetectedNote n;
+        n.start = p.origStart;
+        n.end = p.origEnd;
+        n.key = key;
+        n.velocity = (float) (0.5 + 0.5 * (loudest > 0.0 ? rms[k] / loudest : 1.0));
+        out.push_back (n);
+    }
+    return out;
+}
+
+int dumpScore (Song& song, int channel, const std::vector<DetectedNote>& notes, double sampleRate)
+{
+    if (sampleRate <= 0.0 || channel < 0)
+        return 0;
+    if (song.patterns.empty())
+        song.patterns.emplace_back();
+    song.currentPattern = std::clamp (song.currentPattern, 0, (int) song.patterns.size() - 1);
+    auto& pattern = song.patterns[(std::size_t) song.currentPattern];
+    pattern.notes.erase (std::remove_if (pattern.notes.begin(), pattern.notes.end(), [channel] (const lynx::Note& n) { return n.channel == channel; }),
+                         pattern.notes.end());
+    const auto ticksPerFrame = song.bpm / 60.0 * ppq / sampleRate;
+    const std::int64_t shortest = 3 * ppq / 96;
+    int count = 0;
+    for (const auto& d : notes)
+    {
+        const auto start = std::max<std::int64_t> (0, std::llround ((double) d.start * ticksPerFrame));
+        const auto end = std::max<std::int64_t> (0, std::llround ((double) d.end * ticksPerFrame));
+        if (end - start <= shortest)
+            continue;
+        lynx::Note n;
+        n.start = start;
+        n.length = end - start;
+        n.channel = channel;
+        n.key = d.key;
+        n.velocity = std::clamp (d.velocity, 0.0f, 1.0f);
+        pattern.notes.push_back (n);
+        ++count;
+    }
+    pattern.sortNotes();
+    return count;
+}
+
 std::vector<std::uint8_t> writeNative (const Track& track)
 {
     std::vector<std::uint8_t> out { 'L', 'X', 'N', 'T' };

+ 18 - 0
src/core/NewtoneFx.h

@@ -141,6 +141,24 @@ struct ScoreNote
 };
 std::vector<ScoreNote> score (const Track& track, double sampleRate);
 
+// Edison's "Convert to score and dump to piano roll" (round 167c, REA_rodada167c.md §4): FL runs its pitch analyser
+// (the one Newtone uses) on the whole sample and takes each note it finds: key = round(pitch - the sample's overall
+// detune), only keys 0..127; volume = 0.5 + 0.5 x the note's level. LYNX: analyseNotes(), the detune = the notes'
+// length-weighted mean offset from their semitones, the level = the note's RMS over the loudest note's (0..1).
+// Times in source frames, [start, end).
+struct DetectedNote
+{
+    std::int64_t start = 0, end = 0;
+    int key = 60;
+    float velocity = 1.0f;
+};
+std::vector<DetectedNote> detectScore (const SampleData& source, double* detune = nullptr);
+// FL hands them to the Piano roll of the selected channel in the current pattern, replacing that channel's notes
+// there (the plugin SDK's note list: piano roll, flags "empty first" + "use selection", pattern -1, channel -1):
+// position = frames / rate x tempo / 60 x PPQ (rounded), notes of 3 ticks or less at FL's PPQ 96 (LYNX: 30 ticks)
+// are left out. Returns how many notes went in.
+int dumpScore (Song& song, int channel, const std::vector<DetectedNote>& notes, double sampleRate);
+
 // Newtone: the track's notes. "LXNT" + version + frames + global formant + the notes.
 std::vector<std::uint8_t> writeNative (const Track& track);
 std::optional<Track> parseNative (const std::vector<std::uint8_t>& state);

+ 43 - 0
src/ui/AudioEditor.cpp

@@ -15,6 +15,8 @@
 #include "core/AudioCapture.h"
 #include "core/AudioEditTools.h"
 #include "core/EdisonScript.h"
+#include "core/Instruments.h"
+#include "core/NewtoneFx.h"
 #include "core/WaveAnalysis.h"
 #include "core/ValueMath.h"
 #include "engine/SampleLibrary.h"
@@ -1878,6 +1880,44 @@ private:
         commit (tr ("Set loop"));
     }
 
+    // --- Tools › Analysis › Convert to score and dump to piano roll (REA_rodada167c.md §4): the whole sample's notes
+    // into the selected channel's notes of the current pattern (replacing them), as FL's Edison
+    void convertToScore()
+    {
+        if (doc.audio.empty() || scoreBusy)
+            return;
+        stopPlayback();
+        auto data = std::make_shared<SampleData>();
+        data->sampleRate = doc.audio.sampleRate;
+        data->left = doc.audio.channels[0];
+        if (doc.audio.numChannels() > 1)
+            data->right = doc.audio.channels[1];
+        scoreBusy = true;
+        setStatus (tr ("Detecting score..."), false);
+        juce::Component::SafePointer<AudioEditor> self (this);
+        std::thread ([self, data] {
+            auto notes = std::make_shared<std::vector<newtonefx::DetectedNote>> (newtonefx::detectScore (*data));
+            juce::MessageManager::callAsync ([self, notes, rate = data->sampleRate] {
+                if (self == nullptr)
+                    return;
+                self->scoreBusy = false;
+                if (notes->empty())
+                {
+                    self->setStatus (tr ("No notes found in the sample"), false);
+                    return;
+                }
+                self->setStatus (tr ("Dumping score..."), false);
+                const auto channel = self->engine.getSelectedChannel();
+                int count = 0;
+                self->engine.editSong ([&] (Song& s) {
+                    if (channel >= 0 && channel < (int) s.channels.size())
+                        count = newtonefx::dumpScore (s, channel, *notes, rate);
+                });
+                self->setStatus (tr ("{0} notes put in the Piano roll of the selected channel", { juce::String (count) }), false);
+            });
+        }).detach();
+    }
+
     // --- scripts (Tools › Scripting: Run script / Edit last script; REA_rodada167c.md §2) -----------------------------
     struct ScriptRef
     {
@@ -3279,6 +3319,7 @@ private:
     bool playing = false, loopPlay = false;
     ScriptRef lastScript;         // Edit last script
     bool scriptBusy = false;      // a script is running (its form may be open)
+    bool scoreBusy = false;       // Convert to score is analysing
     std::uint64_t previewTicket = 0;
     std::int64_t playFrom = 0, playhead = -1;
     double playStartedMs = 0.0;
@@ -3524,6 +3565,8 @@ juce::PopupMenu AudioEditor::mainMenu()
     tools.addItem (tr ("Declick out all regions"), has, false, [this] { regionsTool (tr ("Declick out all regions"), [] (ae::Document& d) { return ae::declickRegions (d, false, true); }); });
     tools.addItem (tr ("Perfect all regions"), has, false, [this] { regionsTool (tr ("Perfect all regions"), [] (ae::Document& d) { return ae::perfectRegions (d); }); });
     tools.addItem (tr ("Tune loop..."), has, false, [this] { openEdisonTool (T::loopTuner); });
+    tools.addSectionHeader (tr ("Analysis"));
+    tools.addItem (tr ("Convert to score and dump to piano roll"), has && ! scoreBusy, false, [this] { convertToScore(); });
 
     juce::PopupMenu regions;
     regions.addItem (tr ("Add marker") + "\tM", has, false, [this] { addMarkerAtCursor(); });

+ 72 - 0
tests/Score167Tests.inc

@@ -0,0 +1,72 @@
+// --- Edison's Convert to score and dump to piano roll (core/NewtoneFx.h detectScore / dumpScore) - round 167c (§4)
+
+#include "core/NewtoneFx.h"
+
+TEST (score167_detects_the_melody)
+{
+    using namespace lynx;
+    // C4, E4, G4 (0.5 s each, 0.1 s apart), all sung 0.2 semitone sharp; E4 at half the level
+    const double rate = 44100.0, sharp = 0.2;
+    SampleData s;
+    s.sampleRate = rate;
+    s.left.assign ((std::size_t) (rate * 2.0), 0.0f);
+    const int keys[] = { 60, 64, 67 };
+    const float amps[] = { 0.5f, 0.25f, 0.5f };
+    for (int k = 0; k < 3; ++k)
+    {
+        const auto from = (std::size_t) (rate * (0.1 + 0.6 * k)), to = from + (std::size_t) (rate * 0.5);
+        const auto hz = 440.0 * std::pow (2.0, (keys[k] + sharp - 69) / 12.0);
+        for (auto i = from; i < to; ++i)
+        {
+            // a few harmonics, like a voice
+            const auto t = (double) (i - from) / rate;
+            double x = 0.0;
+            for (int h = 1; h <= 4; ++h)
+                x += std::sin (2.0 * 3.141592653589793 * hz * h * t) / h;
+            s.left[i] = (float) (amps[k] * 0.6 * x);
+        }
+    }
+    double detune = 0.0;
+    const auto notes = newtonefx::detectScore (s, &detune);
+    CHECK (notes.size() == 3u);
+    CHECK (std::abs (detune - sharp) < 0.05);
+    if (notes.size() == 3u)
+    {
+        for (int k = 0; k < 3; ++k)
+        {
+            CHECK (notes[(std::size_t) k].key == keys[k]); // the detune is taken out: the written keys
+            CHECK (std::abs ((double) notes[(std::size_t) k].start / rate - (0.1 + 0.6 * k)) < 0.03);
+            CHECK (std::abs ((double) notes[(std::size_t) k].end / rate - (0.6 + 0.6 * k)) < 0.03);
+        }
+        // volume = 0.5 + 0.5 x level: the loudest notes full, the quieter one about 0.75
+        CHECK (notes[0].velocity > 0.95f && notes[2].velocity > 0.95f && std::abs (notes[1].velocity - 0.75f) < 0.05f);
+    }
+
+    // into the current pattern, the selected channel's notes replaced, the other channels' kept
+    Song song;
+    song.bpm = 120.0;
+    song.patterns.resize (2);
+    song.currentPattern = 1;
+    Note old;
+    old.channel = 2;
+    old.key = 30;
+    song.patterns[1].notes.push_back (old);
+    old.channel = 0;
+    song.patterns[1].notes.push_back (old);
+    auto withShort = notes;
+    newtonefx::DetectedNote tiny;
+    tiny.start = 0;
+    tiny.end = (std::int64_t) (rate * 0.01); // 0.01 s at 120 BPM = 19 ticks: left out (3 ticks at FL's PPQ 96)
+    withShort.push_back (tiny);
+    const auto count = newtonefx::dumpScore (song, 2, withShort, rate);
+    CHECK (count == (int) notes.size());
+    int ofTwo = 0, ofZero = 0;
+    for (const auto& n : song.patterns[1].notes)
+        (n.channel == 2 ? ofTwo : ofZero) += 1;
+    CHECK (ofTwo == (int) notes.size() && ofZero == 1 && song.patterns[0].notes.empty());
+    if (! notes.empty())
+    {
+        const auto& first = song.patterns[1].notes[0].channel == 2 ? song.patterns[1].notes[0] : song.patterns[1].notes[1];
+        CHECK (first.start == std::llround ((double) notes[0].start / rate * 2.0 * ppq) && first.key == 60);
+    }
+}

+ 1 - 0
tests/tests.cpp

@@ -16542,3 +16542,4 @@ TEST (fl_low_lifter_matches_fl_engine)
 #include "Dvs167Tests.inc"
 #include "EdisonScript167Tests.inc"
 #include "Deverb167Tests.inc"
+#include "Score167Tests.inc"