From 4b2d2652405410106f93c284e752881447c868c9 Mon Sep 17 00:00:00 2001 From: Jean Pierre Cimalando Date: Tue, 19 May 2020 19:45:32 +0200 Subject: [PATCH] Add the Surge tuning library --- src/external/tunings/LICENSE.md | 9 + src/external/tunings/README.txt | 2 + src/external/tunings/include/Tunings.h | 251 ++++++++++++ src/external/tunings/src/Tunings.cpp | 540 +++++++++++++++++++++++++ 4 files changed, 802 insertions(+) create mode 100644 src/external/tunings/LICENSE.md create mode 100644 src/external/tunings/README.txt create mode 100644 src/external/tunings/include/Tunings.h create mode 100644 src/external/tunings/src/Tunings.cpp diff --git a/src/external/tunings/LICENSE.md b/src/external/tunings/LICENSE.md new file mode 100644 index 00000000..64d1d077 --- /dev/null +++ b/src/external/tunings/LICENSE.md @@ -0,0 +1,9 @@ +Copyright 2019-2020, Paul Walker + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + diff --git a/src/external/tunings/README.txt b/src/external/tunings/README.txt new file mode 100644 index 00000000..4a6507b1 --- /dev/null +++ b/src/external/tunings/README.txt @@ -0,0 +1,2 @@ +Based on the Surge tuning library, revision a5f2879, with small modifications +https://github.com/surge-synthesizer/tuning-library diff --git a/src/external/tunings/include/Tunings.h b/src/external/tunings/include/Tunings.h new file mode 100644 index 00000000..dfd39dfa --- /dev/null +++ b/src/external/tunings/include/Tunings.h @@ -0,0 +1,251 @@ +// -*-c++-*- + +/** + * Tunings.h + * Copyright Paul Walker, 2019-2020 + * Released under the MIT License. See LICENSE.md + * + * Tunings.h contains the public API required to determine full keyboard frequency maps + * for a scala SCL and KBM file in standalone, tested, open licensed C++ header only library. + * + * An example of using the API is + * + * ``` + * auto s = Tunings::readSCLFile( "./my-scale.scl" ); + * auto k = Tunings::readKBMFile( "./my-mapping.kbm" ); + * + * Tunings::Tuning t( s, k ); + * + * std::cout << "The frequency of C4 and A4 are " + * << t.frequencyForMidiNote( 60 ) << " and " + * << t.frequencyForMidiNote( 69 ) << std::endl; + * ``` + * + * The API provides several other points, such as access to the structure of the SCL and KBM, + * the ability to create several prototype SCL and KBM files wthout SCL or KBM content, + * a frequency measure which is normalized by the frequency of standard tuning midi note 0 + * and the logarithmic frequency scale, with a doubling per frequency doubling. + * + * Documentation is in the class header below; tests are in `tests/all_tests.cpp` and + * a variety of command line tools accompany the header. + */ + +#pragma once +#include +#include +#include +#include + +namespace Tunings +{ + const double MIDI_0_FREQ=8.17579891564371; // or 440.0 * pow( 2.0, - (69.0/12.0 ) ) + + /** + * A Tone is a single entry in an SCL file. It is expressed either in cents or in + * a ratio, as described in the SCL documentation. + * + * In most normal use, you will not use this class, and it will be internal to a Scale + */ + struct Tone + { + typedef enum Type + { + kToneCents, // An SCL representation like "133.0" + kToneRatio // An SCL representation like "3/7" + } Type; + + Type type = kToneRatio; + double cents = 0; + int ratio_d = 1, ratio_n = 1; + std::string stringRep = "1/1"; + double floatValue = 1.0; // cents / 1200 + 1. + }; + + /** + * Given an SCL string like "100.231" or "3/7" set up a Tone + */ + Tone toneFromString(const std::string &t, int lineno=-1); + + /** + * The Scale is the representation of the SCL file. It contains several key + * features. Most importantly it has a count and a vector of Tones. + * + * In most normal use, you will simply pass around instances of this class + * to a Tunings::Tuning instance, but in some cases you may want to create + * or inspect this class yourself. Especially if you are displaying this + * class to your end users, you may want to use the rawText or count methods. + */ + struct Scale + { + //std::string name = "empty scale"; // The name in the SCL file. Informational only + std::string description; // The description in the SCL file. Informational only + std::string rawText; // The raw text of the SCL file used to create this Scale + int count = 0; // The number of tones. + std::vector tones; // The tones + }; + + /** + * The KeyboardMapping class represents a KBM file. In most cases, the salient + * features are the tuningConstantNote and tuningFrequency, which allow you to + * pick a fixed note in the midi keyboard when retuning. The KBM file can also + * remap individual keys to individual points in a scale, which kere is done with the + * keys vector. + * + * Just as with Scale, the rawText member contains the text of the KBM file used. + */ + + struct KeyboardMapping + { + int count = 0; + int firstMidi = 0, lastMidi = 127; + int middleNote = 60; + int tuningConstantNote = 60; + double tuningFrequency = MIDI_0_FREQ * 32.0, tuningPitch = 32.0; // pitch = frequency / MIDI_0_FREQ + int octaveDegrees = 12; + std::vector keys; // rather than an 'x' we use a '-1' for skipped keys + + std::string rawText; + //std::string name; + }; + + /** + * In some failure states, the tuning library will throw an exception of + * type TuningError with a descriptive message. + */ + class TuningError : public std::exception { + public: + explicit TuningError(std::string m) : whatv(std::move(m)) { } + virtual const char* what() const noexcept override { return whatv.c_str(); } + private: + std::string whatv; + }; + + /** + * readSCLStream returns a Scale from the SCL input stream + */ + Scale readSCLStream(std::istream &inf); + + /** + * readSCLFile returns a Scale from the SCL File in fname + */ + Scale readSCLFile(std::string fname); + + /** + * parseSCLData returns a scale from the SCL file contents in memory + */ + Scale parseSCLData(const std::string &sclContents); + + /** + * evenTemperament12NoteScale provides a utility scale which is + * the "standard tuning" scale + */ + Scale evenTemperament12NoteScale(); + + /** + * evenDivisionOfSpanByM provides a scale referd to as "ED2-17" or + * "ED3-24" by dividing the Span into M points. eventDivisionOfSpanByM(2,12) + * should be the evenTemperament12NoteScale + */ + Scale evenDivisionOfSpanByM( int Span, int M ); + + /** + * readKBMStream returns a KeyboardMapping from a KBM input stream + */ + KeyboardMapping readKBMStream(std::istream &inf); + + /** + * readKBMFile returns a KeyboardMapping from a KBM file name + */ + KeyboardMapping readKBMFile(std::string fname); + + /** + * parseKBMData returns a KeyboardMapping from a KBM data in memory + */ + KeyboardMapping parseKBMData(const std::string &kbmContents); + + /** + * tuneA69To creates a KeyboardMapping which keeps the midi note 69 (A4) set + * to a constant frequency, given + */ + KeyboardMapping tuneA69To(double freq); + + /** + * tuneNoteTo creates a KeyboardMapping which keeps the midi note given is set + * to a constant frequency, given + */ + KeyboardMapping tuneNoteTo(int midiNote, double freq); + + /** + * startScaleOnAndTuneNoteTo generates a KBM where scaleStart is the note 0 + * of the scale, where midiNote is the tuned note, and where feq is the frequency + */ + KeyboardMapping startScaleOnAndTuneNoteTo(int scaleStart, int midiNote, double freq); + + /** + * The Tuning class is the primary place where you will interact with this library. + * It is constructed for a scale and mapping and then gives you the ability to + * determine frequencies across and beyond the midi keyboard. Since modulation + * can force key number well outside the [0,127] range in some of our synths we + * support a midi note range from -256 to + 256 spanning more than the entire frequency + * space reasonable. + * + * To use this class, you construct a fresh instance every time you want to use a + * different Scale and Keyboard. If you want to tune to a different scale or mapping, + * just construct a new instance. + */ + class Tuning { + public: + // The number of notes we pre-compute + constexpr static int N = 512; + + // Construct a tuning with even temperament and standard mapping + Tuning(); + + /** + * Construct a tuning for a particular scale, mapping, or for both. + */ + explicit Tuning( const Scale &s ); + explicit Tuning( const KeyboardMapping &k ); + Tuning( const Scale &s, const KeyboardMapping &k ); + + /** + * These three related functions provide you the information you + * need to use this tuning. + * + * frequencyForMidiNote returns the Frequency in HZ for a given midi + * note. In standard tuning, FrequencyForMidiNote(69) will be 440 + * and frequencyForMidiNote(60) will be 261.62 - the standard frequencies + * for A and middle C. + * + * frequencyForMidiNoteScaledByMidi0 returns the frequency but with the + * standard frequency of midi note 0 divided out. So in standard tuning + * frequencyForMidiNoteScaledByMidi0(0) = 1 and frequencyForMidiNoteScaledByMidi0(60) = 32 + * + * Finally logScaledFrequencyForMidiNote returns the log base 2 of the scaled frequency. + * So logScaledFrequencyForMidiNote(0) = 0 and logScaledFrequencyForMidiNote(60) = 5. + * + * Both the frequency measures have the feature of doubling when frequency doubles + * (or when a standard octave is spanned), whereas the log one increase by 1 per frequency double. + * + * Depending on your internal pitch model, one of these three methods should allow you + * to calibrate your oscillators to the appropriate frequency based on the midi note + * at hand. + * + * The scalePositionForMidiNote returns the space in the logical scale. Note 0 is the root. + * It has a maxiumum value of count-1. Note that SCL files omit the root internally and so + * this logical scale position is off by 1 from the index in the tones array of the Scale data. + */ + double frequencyForMidiNote( int mn ) const; + double frequencyForMidiNoteScaledByMidi0( int mn ) const; + double logScaledFrequencyForMidiNote( int mn ) const; + int scalePositionForMidiNote( int mn ) const; + + // For convenience, the scale and mapping used to construct this are kept as public copies + Scale scale; + KeyboardMapping keyboardMapping; + private: + std::array ptable, lptable; + std::array scalepositiontable; + }; + +} // namespace Tunings diff --git a/src/external/tunings/src/Tunings.cpp b/src/external/tunings/src/Tunings.cpp new file mode 100644 index 00000000..a516e6f5 --- /dev/null +++ b/src/external/tunings/src/Tunings.cpp @@ -0,0 +1,540 @@ +// -*-c++-*- +/** + * TuningsImpl.h + * Copyright 2019-2020 Paul Walker + * Released under the MIT License. See LICENSE.md + * + * This contains the nasty nitty gritty implementation of the api in Tunings.h. You probably + * don't need to read it unless you have found and are fixing a bug, are curious, or want + * to add a feature to the API. For usages of this library, the documentation in Tunings.h and + * the usages in tests/all_tests.cpp should provide you more than enough guidance. + */ + +#include "Tunings.h" +#include +#include +#include +#include +#include +#include +#include + +namespace Tunings +{ + static double locale_atof(const char* s) + { + double result = 0; + std::istringstream istr(s); + istr.imbue(std::locale("C")); + istr >> result; + return result; + } + + Tone toneFromString(const std::string &line, int lineno) + { + Tone t; + t.stringRep = line; + if (line.find(".") != std::string::npos) + { + t.type = Tone::kToneCents; + t.cents = locale_atof(line.c_str()); + } + else + { + t.type = Tone::kToneRatio; + auto slashPos = line.find("/"); + if (slashPos == std::string::npos) + { + t.ratio_n = atoi(line.c_str()); + t.ratio_d = 1; + } + else + { + t.ratio_n = atoi(line.substr(0, slashPos).c_str()); + t.ratio_d = atoi(line.substr(slashPos + 1).c_str()); + } + + if( t.ratio_n == 0 || t.ratio_d == 0 ) + { + std::string s = "Invalid Tone in SCL file."; + if( lineno >= 0 ) + s += "Line " + std::to_string(lineno) + "."; + s += " Line is '" + line + "'."; + throw TuningError(s); + } + // 2^(cents/1200) = n/d + // cents = 1200 * log2(n/d) + + t.cents = 1200 * log2(1.0 * t.ratio_n/t.ratio_d); + } + t.floatValue = t.cents / 1200.0 + 1.0; + return t; + } + + Scale readSCLStream(std::istream &inf) + { + std::string line; + const int read_header = 0, read_count = 1, read_note = 2, trailing = 3; + int state = read_header; + + Scale res; + std::ostringstream rawOSS; + int lineno = 0; + while (std::getline(inf, line)) + { + rawOSS << line << "\n"; + lineno ++; + + if (line.empty() || line[0] == '!') + { + continue; + } + switch (state) + { + case read_header: + res.description = line; + state = read_count; + break; + case read_count: + res.count = atoi(line.c_str()); + state = read_note; + break; + case read_note: + auto t = toneFromString(line, lineno); + res.tones.push_back(t); + if( (int)res.tones.size() == res.count ) + state = trailing; + + break; + } + } + + if( ! ( state == read_note || state == trailing ) ) + { + throw TuningError( "Incomplete SCL file. Found no notes section in the file" ); + } + + if( (int)res.tones.size() != res.count ) + { + std::string s = "Read fewer notes than count in file. Count=" + std::to_string( res.count ) + + " notes array size=" + std::to_string( res.tones.size() ); + throw TuningError(s); + + } + res.rawText = rawOSS.str(); + return res; + } + + Scale readSCLFile(std::string fname) + { + std::ifstream inf; + inf.open(fname); + if (!inf.is_open()) + { + std::string s = "Unable to open file '" + fname + "'"; + throw TuningError(s); + } + + auto res = readSCLStream(inf); + //res.name = std::move(fname); + return res; + } + + Scale parseSCLData(const std::string &d) + { + std::istringstream iss(d); + auto res = readSCLStream(iss); + //res.name = "Scale from Patch"; + return res; + } + + Scale evenTemperament12NoteScale() + { + std::string data = R"SCL(! even.scl +! +12 note even temperament + 12 +! + 100.0 + 200.0 + 300.0 + 400.0 + 500.0 + 600.0 + 700.0 + 800.0 + 900.0 + 1000.0 + 1100.0 + 2/1 +)SCL"; + return parseSCLData(data); + } + + Scale evenDivisionOfSpanByM( int Span, int M ) + { + if( Span <= 0 ) + throw Tunings::TuningError( "Span should be a positive number. You entered " + std::to_string( Span ) ); + if( M <= 0 ) + throw Tunings::TuningError( "You must divide the period into at least one step. You entered " + std::to_string( M ) ); + + std::ostringstream oss; + oss.imbue( std::locale( "C" ) ); + oss << "! Automatically generated ED" << Span << "-" << M << " scale\n"; + oss << "Automatically generated ED" << Span << "-" << M << " scale\n"; + oss << M << "\n"; + oss << "!\n"; + + + double topCents = 1200.0 * log2(1.0 * Span); + double dCents = topCents / M; + for( int i=1; i 0; + char badChar = '\0'; + while( validLine && *lc != '\0' ) + { + if( ! ( *lc == ' ' || std::isdigit( *lc ) || *lc == '.' || *lc == (char)13 || *lc == '\n' ) ) + { + validLine = false; + badChar = *lc; + } + lc ++; + } + if( ! validLine ) + { + throw TuningError( "Invalid line " + std::to_string( lineno ) + ". line='" + line + "'. Bad char is '" + + badChar + "/" + std::to_string( (int)badChar ) + "'" ); + } + } + + int i = std::atoi(line.c_str()); + double v = locale_atof(line.c_str()); + + switch (state) + { + case map_size: + res.count = i; + break; + case first_midi: + res.firstMidi = i; + break; + case last_midi: + res.lastMidi = i; + break; + case middle: + res.middleNote = i; + break; + case reference: + res.tuningConstantNote = i; + break; + case freq: + res.tuningFrequency = v; + res.tuningPitch = res.tuningFrequency / 8.17579891564371; + break; + case degree: + res.octaveDegrees = i; + break; + case keys: + res.keys.push_back(i); + if( (int)res.keys.size() == res.count ) state = trailing; + break; + case trailing: + break; + } + if( ! ( state == keys || state == trailing ) ) state = (parsePosition)(state + 1); + if( state == keys && res.count == 0 ) state = trailing; + + } + + if( ! ( state == keys || state == trailing ) ) + { + throw TuningError( "Incomplete KBM file. Ubable to get to keys section of file" ); + } + + if( (int)res.keys.size() != res.count ) + { + throw TuningError( "Different number of keys than mapping file indicates. Count is " + + std::to_string( res.count ) + " and we parsed " + std::to_string( res.keys.size() ) + " keys." ); + } + + res.rawText = rawOSS.str(); + return res; + } + + KeyboardMapping readKBMFile(std::string fname) + { + std::ifstream inf; + inf.open(fname); + if (!inf.is_open()) + { + std::string s = "Unable to open file '" + fname + "'"; + throw TuningError(s); + } + + auto res = readKBMStream(inf); + //res.name = std::move(fname); + return res; + } + + KeyboardMapping parseKBMData(const std::string &d) + { + std::istringstream iss(d); + auto res = readKBMStream(iss); + //res.name = "Mapping from Patch"; + return res; + } + + Tuning::Tuning() : Tuning( evenTemperament12NoteScale(), KeyboardMapping() ) { } + Tuning::Tuning(const Scale &s ) : Tuning( s, KeyboardMapping() ) {} + Tuning::Tuning(const KeyboardMapping &k ) : Tuning( evenTemperament12NoteScale(), k ) {} + + Tuning::Tuning(const Scale& s, const KeyboardMapping &k) + { + scale = s; + keyboardMapping = k; + + if( s.count <= 0 ) + throw TuningError( "Unable to tune to a scale with no notes. Your scale provided " + std::to_string( s.count ) + " notes." ); + + + double pitches[N]; + + int posPitch0 = 256 + k.tuningConstantNote; + int posScale0 = 256 + k.middleNote; + + double pitchMod = log2(k.tuningPitch) - 1; + + int scalePositionOfTuningNote = k.tuningConstantNote - k.middleNote; + if( k.count > 0 ) + scalePositionOfTuningNote = k.keys[scalePositionOfTuningNote]; + + double tuningCenterPitchOffset; + if( scalePositionOfTuningNote == 0 ) + tuningCenterPitchOffset = 0; + else + { + double tshift = 0; + double dt = s.tones[s.count -1].floatValue - 1.0; + while( scalePositionOfTuningNote < 0 ) + { + scalePositionOfTuningNote += s.count; + tshift += dt; + } + while( scalePositionOfTuningNote > s.count ) + { + scalePositionOfTuningNote -= s.count; + tshift -= dt; + } + + if( scalePositionOfTuningNote == 0 ) + tuningCenterPitchOffset = -tshift; + else + tuningCenterPitchOffset = s.tones[scalePositionOfTuningNote-1].floatValue - 1.0 - tshift; + } + + for (int i=0; i