ProjectFile.cpp 89 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901
  1. #include "engine/ProjectFile.h"
  2. #include <algorithm>
  3. #include "core/Effects.h"
  4. #include "core/PluginSubstitutes.h"
  5. #include "core/ProjectSafety.h"
  6. #include "engine/Text.h"
  7. namespace lynx::ProjectFile
  8. {
  9. namespace
  10. {
  11. // cutoff/pitch envelopes: [amount, attack, hold, decay, sustain, release(, shape)]; only the active ones
  12. void writeEnvelopes (juce::DynamicObject& o, const ModEnvelope& filter, const ModEnvelope& pitch)
  13. {
  14. for (auto [name, env] : { std::pair { "filterEnv", &filter }, { "pitchEnv", &pitch } })
  15. if (env->amount != 0.0f)
  16. {
  17. juce::Array<juce::var> values { env->amount, env->attack, env->hold, env->decay, env->sustain, env->release };
  18. if (env->shape != 0)
  19. values.add (env->shape);
  20. o.setProperty (name, values);
  21. }
  22. }
  23. void readEnvelopes (const juce::var& o, ModEnvelope& filter, ModEnvelope& pitch)
  24. {
  25. for (auto [name, env, limit] : { std::tuple { "filterEnv", &filter, 10.0f }, { "pitchEnv", &pitch, 48.0f } })
  26. if (const auto& e = o[name]; e.isArray() && (e.size() == 6 || e.size() == 7))
  27. {
  28. const auto shape = e.size() == 7 ? juce::jlimit (0, 1, (int) e[6]) : 0;
  29. auto time = [&] (int i) { return juce::jlimit (0.0f, shape == 1 ? 50.0f : 20.0f, (float) (double) e[i]); };
  30. *env = { juce::jlimit (-limit, limit, (float) (double) e[0]), time (1), time (2), time (3),
  31. juce::jlimit (0.0f, 1.0f, (float) (double) e[4]), time (5), shape };
  32. }
  33. }
  34. // channel LFOs: only the active ones, [target, amount, period, synced, shape, delay, fade-in]
  35. void writeLfos (juce::DynamicObject& o, const std::array<ChannelLfo, lfoTargets>& lfo)
  36. {
  37. juce::Array<juce::var> list;
  38. for (int i = 0; i < lfoTargets; ++i)
  39. if (const auto& l = lfo[(std::size_t) i]; l.amount != 0.0f)
  40. {
  41. juce::Array<juce::var> values { i, l.amount, l.period, l.sync, l.shape, l.delay, l.attack, l.global };
  42. if (l.secondsTiming)
  43. values.add (true);
  44. list.add (values);
  45. }
  46. if (! list.isEmpty())
  47. o.setProperty ("lfo", list);
  48. }
  49. void readLfos (const juce::var& o, std::array<ChannelLfo, lfoTargets>& lfo)
  50. {
  51. if (auto* list = o["lfo"].getArray())
  52. for (const auto& e : *list)
  53. if (e.isArray() && e.size() >= 7)
  54. if (const auto i = (int) e[0]; i >= 0 && i < lfoTargets)
  55. lfo[(std::size_t) i] = { juce::jlimit (-48.0f, 48.0f, (float) (double) e[1]), juce::jlimit (0.005f, 64.0f, (float) (double) e[2]),
  56. (bool) e[3], juce::jlimit (0, 2, (int) e[4]), juce::jlimit (0.0f, 64.0f, (float) (double) e[5]),
  57. juce::jlimit (0.0f, 64.0f, (float) (double) e[6]), e.size() >= 8 && (bool) e[7],
  58. e.size() >= 9 && (bool) e[8] };
  59. }
  60. const char* instrumentId (InstrumentKind k)
  61. {
  62. switch (k)
  63. {
  64. case InstrumentKind::kick: return "kick";
  65. case InstrumentKind::snare: return "snare";
  66. case InstrumentKind::hat: return "hat";
  67. case InstrumentKind::clap: return "clap";
  68. case InstrumentKind::synth: return "synth";
  69. case InstrumentKind::sampler: return "sampler";
  70. case InstrumentKind::audioClip: return "audioClip";
  71. case InstrumentKind::plugin: return "plugin";
  72. case InstrumentKind::controller: return "controller";
  73. case InstrumentKind::sakura: return "sakura";
  74. case InstrumentKind::drumpad: return "drumpad";
  75. case InstrumentKind::boobass: return "boobass";
  76. case InstrumentKind::drumsynth: return "drumsynth";
  77. case InstrumentKind::harmless: return "harmless";
  78. case InstrumentKind::sytrus: return "sytrus";
  79. case InstrumentKind::harmor: return "harmor";
  80. case InstrumentKind::gms: return "gms";
  81. case InstrumentKind::morphine: return "morphine";
  82. case InstrumentKind::ogun: return "ogun";
  83. case InstrumentKind::minisynth: return "minisynth";
  84. case InstrumentKind::dx10: return "dx10";
  85. case InstrumentKind::kepler: return "kepler";
  86. case InstrumentKind::poizone: return "poizone";
  87. case InstrumentKind::fruitkick: return "fruitkick";
  88. case InstrumentKind::bassdrum: return "bassdrum";
  89. case InstrumentKind::toxic: return "toxic";
  90. case InstrumentKind::threeosc: return "threeosc";
  91. case InstrumentKind::autogun: return "autogun";
  92. case InstrumentKind::transistorbass: return "transistorbass";
  93. case InstrumentKind::simsynth: return "simsynth";
  94. case InstrumentKind::wasp: return "wasp";
  95. case InstrumentKind::plucked: return "plucked";
  96. case InstrumentKind::beepmap: return "beepmap";
  97. case InstrumentKind::sawer: return "sawer";
  98. case InstrumentKind::flkeys: return "flkeys";
  99. case InstrumentKind::granulizer: return "granulizer";
  100. case InstrumentKind::drumaxx: return "drumaxx";
  101. case InstrumentKind::slayer: return "slayer";
  102. case InstrumentKind::fruitydance: return "fruitydance";
  103. case InstrumentKind::directwave: return "directwave";
  104. case InstrumentKind::midiOut: return "midiOut";
  105. case InstrumentKind::patcher: return "patcher";
  106. }
  107. return "synth";
  108. }
  109. InstrumentKind instrumentFromId (const juce::String& id)
  110. {
  111. for (auto k : { InstrumentKind::kick, InstrumentKind::snare, InstrumentKind::hat, InstrumentKind::clap,
  112. InstrumentKind::synth, InstrumentKind::sampler, InstrumentKind::audioClip,
  113. InstrumentKind::plugin, InstrumentKind::controller, InstrumentKind::sakura, InstrumentKind::drumpad, InstrumentKind::boobass,
  114. InstrumentKind::drumsynth, InstrumentKind::harmless, InstrumentKind::sytrus, InstrumentKind::harmor,
  115. InstrumentKind::gms, InstrumentKind::morphine, InstrumentKind::ogun, InstrumentKind::minisynth, InstrumentKind::dx10, InstrumentKind::kepler, InstrumentKind::poizone,
  116. InstrumentKind::fruitkick, InstrumentKind::bassdrum, InstrumentKind::toxic,
  117. InstrumentKind::threeosc, InstrumentKind::autogun, InstrumentKind::transistorbass,
  118. InstrumentKind::simsynth, InstrumentKind::wasp, InstrumentKind::plucked, InstrumentKind::beepmap, InstrumentKind::sawer, InstrumentKind::flkeys,
  119. InstrumentKind::granulizer, InstrumentKind::drumaxx, InstrumentKind::slayer, InstrumentKind::fruitydance, InstrumentKind::directwave, InstrumentKind::midiOut, InstrumentKind::patcher })
  120. if (id == instrumentId (k))
  121. return k;
  122. return InstrumentKind::synth;
  123. }
  124. juce::String str (const std::string& s) { return juce::String::fromUTF8 (s.c_str()); }
  125. const char* effectId (EffectKind k)
  126. {
  127. switch (k)
  128. {
  129. case EffectKind::eq: return "eq";
  130. case EffectKind::compressor: return "compressor";
  131. case EffectKind::delay: return "delay";
  132. case EffectKind::reverb: return "reverb";
  133. case EffectKind::plugin: return "plugin";
  134. case EffectKind::limiter: return "limiter";
  135. case EffectKind::filter: return "filter";
  136. case EffectKind::distortion: return "distortion";
  137. case EffectKind::chorus: return "chorus";
  138. case EffectKind::parametricEq: return "peq";
  139. case EffectKind::utility: return "utility";
  140. case EffectKind::volumeGate: return "volumeGate";
  141. case EffectKind::peakController: return "peakController";
  142. case EffectKind::pitchShift: return "pitchShift";
  143. case EffectKind::freqShift: return "freqShift";
  144. case EffectKind::parallel: return "parallel";
  145. case EffectKind::patcher: return "patcher";
  146. case EffectKind::lofi: return "lofi";
  147. case EffectKind::effector: return "effector";
  148. case EffectKind::crossover: return "crossover";
  149. case EffectKind::rhythmGain: return "rhythmGain";
  150. case EffectKind::autoPan: return "autoPan";
  151. case EffectKind::vocoder: return "vocoder";
  152. case EffectKind::pitchCorrect: return "pitchCorrect";
  153. case EffectKind::squeeze: return "squeeze";
  154. case EffectKind::vintagePhaser: return "vintagePhaser";
  155. case EffectKind::vocodex: return "vocodex";
  156. case EffectKind::maximus: return "maximus";
  157. case EffectKind::fruityLimiter: return "fruityLimiter";
  158. case EffectKind::fruityCompressor: return "fruityCompressor";
  159. case EffectKind::fruityWaveShaper: return "fruityWaveShaper";
  160. case EffectKind::fruitySoftClipper: return "fruitySoftClipper";
  161. case EffectKind::fruityPanOMatic: return "fruityPanOMatic";
  162. case EffectKind::fruityBalance: return "fruityBalance";
  163. case EffectKind::fruityBloodOverdrive: return "fruityBloodOverdrive";
  164. case EffectKind::reeverb2: return "reeverb2";
  165. case EffectKind::reeverb1: return "reeverb1";
  166. case EffectKind::fruityDelay2: return "fruityDelay2";
  167. case EffectKind::fruityDelay3: return "fruityDelay3";
  168. case EffectKind::stereoShaper: return "stereoShaper";
  169. case EffectKind::stereoEnhancer: return "stereoEnhancer";
  170. case EffectKind::transientProcessor: return "transientProcessor";
  171. case EffectKind::spreader: return "spreader";
  172. case EffectKind::fruityChorus: return "fruityChorus";
  173. case EffectKind::hyperChorus: return "hyperChorus";
  174. case EffectKind::vintageChorus: return "vintageChorus";
  175. case EffectKind::grossBeat: return "grossBeat";
  176. case EffectKind::fruityDelayBank: return "fruityDelayBank";
  177. case EffectKind::fruityMultiband: return "fruityMultiband";
  178. case EffectKind::fruityFastDist: return "fruityFastDist";
  179. case EffectKind::fruityFlangus: return "fruityFlangus";
  180. case EffectKind::fruityFlanger: return "fruityFlanger";
  181. case EffectKind::luxeVerb: return "luxeVerb";
  182. case EffectKind::convolver: return "convolver";
  183. case EffectKind::equo: return "equo";
  184. case EffectKind::flPitchShifter: return "flPitchShifter";
  185. case EffectKind::frequencySplitter: return "frequencySplitter";
  186. case EffectKind::fruityFastLP: return "fruityFastLP";
  187. case EffectKind::fruityFreeFilter: return "fruityFreeFilter";
  188. case EffectKind::fruityFilter: return "fruityFilter";
  189. case EffectKind::hardcore: return "hardcore";
  190. case EffectKind::distructor: return "distructor";
  191. case EffectKind::multibandDelay: return "multibandDelay";
  192. case EffectKind::lovePhilter: return "lovePhilter";
  193. case EffectKind::newtone: return "newtone";
  194. case EffectKind::newtime: return "newtime";
  195. case EffectKind::facetEq: return "facetEq";
  196. case EffectKind::apexLimiter: return "apexLimiter";
  197. case EffectKind::ridgeStrip: return "ridgeStrip";
  198. case EffectKind::glowLeveler: return "glowLeveler";
  199. case EffectKind::hushDeEsser: return "hushDeEsser";
  200. case EffectKind::aether: return "aether";
  201. case EffectKind::ember: return "ember";
  202. case EffectKind::lynxTune: return "lynxTune";
  203. case EffectKind::fruityPhaser: return "fruityPhaser";
  204. case EffectKind::epochVerb: return "epochVerb";
  205. case EffectKind::atrium: return "atrium";
  206. case EffectKind::foilPlate: return "foilPlate";
  207. case EffectKind::nebula: return "nebula";
  208. case EffectKind::halo: return "halo";
  209. case EffectKind::horizon: return "horizon";
  210. case EffectKind::echoform: return "echoform";
  211. case EffectKind::spiralEcho: return "spiralEcho";
  212. case EffectKind::orbit: return "orbit";
  213. case EffectKind::latticeMod: return "latticeMod";
  214. case EffectKind::fruitySend: return "fruitySend";
  215. case EffectKind::crestCompressor: return "crestCompressor";
  216. case EffectKind::prismMultiband: return "prismMultiband";
  217. case EffectKind::sentryGate: return "sentryGate";
  218. case EffectKind::quellDenoiser: return "quellDenoiser";
  219. case EffectKind::geminiDoubler: return "geminiDoubler";
  220. case EffectKind::formulaController: return "formulaController";
  221. case EffectKind::voiceShift: return "voiceShift";
  222. }
  223. return "eq";
  224. }
  225. juce::var pluginToVar (const PluginRef& p)
  226. {
  227. auto o = std::make_unique<juce::DynamicObject>();
  228. o->setProperty ("id", str (p.id));
  229. o->setProperty ("name", str (p.name));
  230. o->setProperty ("state", str (p.state));
  231. // an .flp plugin reference not resolved here (kept by a LYNX substitute): every field, the state byte for byte
  232. if (p.foreign.format != ForeignPlugin::Format::none)
  233. o->setProperty ("foreign", str (foreignToText (p.foreign)));
  234. if (p.fixedBuffers)
  235. o->setProperty ("fixedBuffers", true);
  236. if (p.separateProcess)
  237. o->setProperty ("separateProcess", true);
  238. if (! p.threaded)
  239. o->setProperty ("threaded", false);
  240. if (p.maxSizeBuffers)
  241. o->setProperty ("maxSizeBuffers", true);
  242. if (! p.allowSmartDisable)
  243. o->setProperty ("allowSmartDisable", false);
  244. if (p.hostMaxBuffer)
  245. o->setProperty ("hostMaxBuffer", true);
  246. if (p.midiInPort >= 0)
  247. o->setProperty ("midiInPort", p.midiInPort);
  248. if (p.midiOutPort >= 0)
  249. o->setProperty ("midiOutPort", p.midiOutPort);
  250. if (! p.notifyRender)
  251. o->setProperty ("notifyRender", false);
  252. if (p.latencyOverrideMs >= 0.0f)
  253. o->setProperty ("latencyMs", p.latencyOverrideMs);
  254. return juce::var (o.release());
  255. }
  256. PluginRef pluginFromVar (const juce::var& v)
  257. {
  258. PluginRef p;
  259. p.id = v["id"].toString().toStdString();
  260. p.name = v["name"].toString().toStdString();
  261. p.state = v["state"].toString().toStdString();
  262. if (v.hasProperty ("foreign") && ! foreignFromText (v["foreign"].toString().toStdString(), p.foreign))
  263. p.foreign = {};
  264. p.fixedBuffers = (bool) v.getProperty ("fixedBuffers", false);
  265. p.separateProcess = (bool) v.getProperty ("separateProcess", false);
  266. p.threaded = (bool) v.getProperty ("threaded", true);
  267. p.maxSizeBuffers = (bool) v.getProperty ("maxSizeBuffers", false);
  268. p.allowSmartDisable = (bool) v.getProperty ("allowSmartDisable", true);
  269. p.hostMaxBuffer = (bool) v.getProperty ("hostMaxBuffer", false);
  270. p.midiInPort = juce::jlimit (-1, 255, (int) v.getProperty ("midiInPort", -1));
  271. p.midiOutPort = juce::jlimit (-1, 255, (int) v.getProperty ("midiOutPort", -1));
  272. p.notifyRender = (bool) v.getProperty ("notifyRender", true);
  273. p.latencyOverrideMs = v.hasProperty ("latencyMs") ? juce::jlimit (0.0f, 2000.0f, (float) (double) v["latencyMs"]) : -1.0f;
  274. return p;
  275. }
  276. std::optional<EffectKind> effectFromId (const juce::String& id);
  277. juce::var channelToVar (const ChannelDef& c);
  278. ChannelDef channelFromVar (const juce::var& c, const Song& song);
  279. juce::var effectToVar (const EffectSlot& slot);
  280. std::optional<EffectSlot> effectFromVar (const juce::var& e);
  281. // FL's Patcher graph (REA_rodada141): nodes (an effect or a channel each, nested Patchers too), cables, the host
  282. // nodes' places and the extra outputs' inserts
  283. juce::var patcherToVar (const PatcherDoc& doc)
  284. {
  285. auto o = std::make_unique<juce::DynamicObject>();
  286. juce::Array<juce::var> nodes;
  287. for (const auto& n : doc.nodes)
  288. {
  289. auto v = std::make_unique<juce::DynamicObject>();
  290. if (n.generator)
  291. v->setProperty ("channel", channelToVar (n.channel));
  292. else
  293. v->setProperty ("effect", effectToVar (n.effect));
  294. if (! n.label.empty())
  295. v->setProperty ("label", str (n.label));
  296. v->setProperty ("x", juce::roundToInt (n.x * 10.0f) / 10.0);
  297. v->setProperty ("y", juce::roundToInt (n.y * 10.0f) / 10.0);
  298. if (! n.busHeads.empty())
  299. {
  300. juce::Array<juce::var> heads;
  301. for (const auto& h : n.busHeads)
  302. {
  303. auto hv = std::make_unique<juce::DynamicObject>();
  304. hv->setProperty ("bus", h.bus);
  305. hv->setProperty ("gain", h.gain);
  306. if (h.head)
  307. hv->setProperty ("head", effectToVar (*h.head));
  308. heads.add (juce::var (hv.release()));
  309. }
  310. v->setProperty ("busHeads", heads);
  311. }
  312. nodes.add (juce::var (v.release()));
  313. }
  314. o->setProperty ("nodes", nodes);
  315. juce::Array<juce::var> wires;
  316. for (const auto& w : doc.wires)
  317. {
  318. // [kind (0 audio, 1 MIDI, 2 control), from, from port, to, to port, gain, on, curve…]
  319. juce::Array<juce::var> wire { (int) w.kind, w.from, w.fromPort, w.to, w.toPort, w.gain, w.enabled };
  320. for (const auto v : w.curve)
  321. wire.add (juce::roundToInt (v * 10000.0f) / 10000.0);
  322. wires.add (wire);
  323. }
  324. o->setProperty ("wires", wires);
  325. o->setProperty ("io", juce::Array<juce::var> { doc.inputX, doc.inputY, doc.outputX, doc.outputY });
  326. if (! doc.published.empty()) // [node, parameter, name, curve…] per Patcher parameter
  327. {
  328. juce::Array<juce::var> published;
  329. for (const auto& p : doc.published)
  330. {
  331. juce::Array<juce::var> entry { p.node, p.param, str (p.name) };
  332. for (const auto v : p.curve)
  333. entry.add (juce::roundToInt (v * 10000.0f) / 10000.0);
  334. published.add (entry);
  335. }
  336. o->setProperty ("published", published);
  337. }
  338. if (! doc.outputTracks.empty())
  339. {
  340. juce::Array<juce::var> tracks;
  341. for (const auto t : doc.outputTracks)
  342. tracks.add (t);
  343. o->setProperty ("outputTracks", tracks);
  344. }
  345. return juce::var (o.release());
  346. }
  347. PatcherDoc patcherFromVar (const juce::var& v, const Song& song)
  348. {
  349. PatcherDoc doc;
  350. if (auto* nodes = v["nodes"].getArray())
  351. for (const auto& n : *nodes)
  352. {
  353. PatchNode node;
  354. if (n.hasProperty ("channel"))
  355. {
  356. node.generator = true;
  357. node.channel = channelFromVar (n["channel"], song);
  358. }
  359. else if (auto fx = effectFromVar (n["effect"]))
  360. node.effect = std::move (*fx);
  361. else
  362. node.effect = makeEffectSlot (EffectKind::utility); // an effect from a future version: a pass-through
  363. node.label = n.getProperty ("label", "").toString().toStdString();
  364. node.x = (float) (double) n.getProperty ("x", 0.0);
  365. node.y = (float) (double) n.getProperty ("y", 0.0);
  366. if (auto* heads = n["busHeads"].getArray())
  367. for (const auto& h : *heads)
  368. {
  369. PatchNode::BusHead head;
  370. head.bus = juce::jlimit (1, 64, (int) h.getProperty ("bus", 1));
  371. head.gain = juce::jlimit (0.0f, 16.0f, (float) (double) h.getProperty ("gain", 1.0));
  372. if (h.hasProperty ("head"))
  373. head.head = effectFromVar (h["head"]);
  374. node.busHeads.push_back (std::move (head));
  375. }
  376. doc.nodes.push_back (std::move (node));
  377. }
  378. const auto count = (int) doc.nodes.size();
  379. if (auto* wires = v["wires"].getArray())
  380. for (const auto& w : *wires)
  381. if (w.isArray() && w.size() >= 7)
  382. {
  383. PatchWire wire;
  384. wire.kind = (PatchWire::Kind) juce::jlimit (0, 2, (int) w[0]);
  385. wire.from = juce::jlimit (patchToHost, count - 1, (int) w[1]);
  386. wire.fromPort = juce::jmax (0, (int) w[2]);
  387. wire.to = juce::jlimit (patchToHost, count - 1, (int) w[3]);
  388. wire.toPort = juce::jmax (0, (int) w[4]);
  389. wire.gain = juce::jlimit (-16.0f, 16.0f, (float) (double) w[5]);
  390. wire.enabled = (bool) w[6];
  391. for (int k = 7; k < w.size(); ++k)
  392. wire.curve.push_back (juce::jlimit (0.0f, 1.0f, (float) (double) w[k]));
  393. if (wire.from != patchToHost && wire.to != patchFromHost)
  394. doc.wires.push_back (std::move (wire));
  395. }
  396. if (const auto& io = v["io"]; io.isArray() && io.size() == 4)
  397. {
  398. doc.inputX = (float) (double) io[0];
  399. doc.inputY = (float) (double) io[1];
  400. doc.outputX = (float) (double) io[2];
  401. doc.outputY = (float) (double) io[3];
  402. }
  403. if (auto* published = v["published"].getArray())
  404. for (const auto& p : *published)
  405. if (p.isArray() && p.size() >= 3)
  406. {
  407. PatchParam param;
  408. param.node = juce::jlimit (-1, count - 1, (int) p[0]);
  409. param.param = juce::jmax (0, (int) p[1]);
  410. param.name = p[2].toString().toStdString();
  411. for (int k = 3; k < p.size(); ++k)
  412. param.curve.push_back (juce::jlimit (0.0f, 1.0f, (float) (double) p[k]));
  413. doc.published.push_back (std::move (param));
  414. }
  415. if (auto* tracks = v["outputTracks"].getArray())
  416. for (const auto& t : *tracks)
  417. doc.outputTracks.push_back (juce::jlimit (-1, maxMixerTracks - 1, (int) t));
  418. return doc;
  419. }
  420. juce::var effectToVar (const EffectSlot& slot)
  421. {
  422. auto e = std::make_unique<juce::DynamicObject>();
  423. e->setProperty ("kind", effectId (slot.kind));
  424. e->setProperty ("on", slot.enabled);
  425. juce::Array<juce::var> params;
  426. const auto used = slot.kind == EffectKind::plugin ? 0 : effectInfo (slot.kind).params.size();
  427. for (std::size_t i = 0; i < used && i < slot.params.size(); ++i)
  428. params.add (juce::roundToInt (slot.params[i] * 10000.0f) / 10000.0);
  429. e->setProperty ("params", params);
  430. if (slot.mix < 1.0f)
  431. e->setProperty ("mix", juce::roundToInt (slot.mix * 10000.0f) / 10000.0);
  432. if (! slot.smartDisable)
  433. e->setProperty ("smartDisable", false);
  434. if (slot.sidechain >= 0)
  435. e->setProperty ("sidechain", slot.sidechain);
  436. if (slot.sidechain2 >= 0)
  437. e->setProperty ("sidechain2", slot.sidechain2);
  438. if (! slot.state.empty()) // FL's raw state of an exact effect (Vocodex), base64
  439. e->setProperty ("state", juce::Base64::toBase64 (slot.state.data(), slot.state.size()));
  440. if (! slot.samplePath.empty()) // Newtone / Newtime source sample
  441. e->setProperty ("sample", str (slot.samplePath));
  442. if (! slot.presetName.empty()) // the editor's preset name and A/B compare (round 129)
  443. e->setProperty ("preset", str (slot.presetName));
  444. if (! slot.abOther.empty())
  445. {
  446. juce::Array<juce::var> other;
  447. for (const auto v : slot.abOther)
  448. other.add (juce::roundToInt (v * 10000.0f) / 10000.0);
  449. e->setProperty ("abOther", other);
  450. if (slot.abShowingB)
  451. e->setProperty ("abB", true);
  452. }
  453. if (slot.kind == EffectKind::plugin)
  454. e->setProperty ("plugin", pluginToVar (slot.plugin));
  455. else if (slot.isSubstitute()) // a LYNX substitute: the original plugin travels with it, unchanged
  456. e->setProperty ("substituteFor", pluginToVar (slot.substituteFor));
  457. if (slot.kind == EffectKind::patcher)
  458. e->setProperty ("patcher", patcherToVar (slot.patcher));
  459. if (slot.kind == EffectKind::parallel) // container branches, each with its own chain
  460. {
  461. juce::Array<juce::var> branches;
  462. for (const auto& b : slot.branches)
  463. {
  464. auto o = std::make_unique<juce::DynamicObject>();
  465. o->setProperty ("gain", b.gain);
  466. juce::Array<juce::var> chain;
  467. for (const auto& child : b.chain)
  468. chain.add (effectToVar (child));
  469. o->setProperty ("chain", chain);
  470. branches.add (juce::var (o.release()));
  471. }
  472. e->setProperty ("branches", branches);
  473. if (! slot.links.empty())
  474. {
  475. juce::Array<juce::var> links;
  476. for (const auto& link : slot.links)
  477. {
  478. auto o = std::make_unique<juce::DynamicObject>();
  479. o->setProperty ("branch", link.branch);
  480. o->setProperty ("source", link.source);
  481. o->setProperty ("target", link.target);
  482. o->setProperty ("param", link.param);
  483. juce::Array<juce::var> curve;
  484. for (auto v : link.curve)
  485. curve.add (v);
  486. o->setProperty ("curve", curve);
  487. links.add (juce::var (o.release()));
  488. }
  489. e->setProperty ("links", links);
  490. }
  491. }
  492. return juce::var (e.release());
  493. }
  494. std::optional<EffectSlot> effectFromVar (const juce::var& e)
  495. {
  496. const auto kind = effectFromId (e["kind"].toString());
  497. if (! kind)
  498. return std::nullopt;
  499. // start from the effect's defaults: parameters missing from the file (parameter added to the
  500. // effect later) stay at their default instead of 0
  501. auto slot = *kind == EffectKind::plugin ? EffectSlot {} : makeEffectSlot (*kind);
  502. slot.kind = *kind;
  503. slot.enabled = (bool) e.getProperty ("on", true);
  504. slot.mix = juce::jlimit (0.0f, 1.0f, (float) (double) e.getProperty ("mix", 1.0));
  505. slot.smartDisable = (bool) e.getProperty ("smartDisable", true);
  506. if (auto* params = e["params"].getArray())
  507. {
  508. for (int i = 0; i < params->size() && i < maxEffectParams; ++i)
  509. slot.params[(std::size_t) i] = juce::jlimit (0.0f, 1.0f, (float) (double) (*params)[i]);
  510. upgradeLoadedEffectParams (slot, (std::size_t) params->size()); // engines that changed since the file was saved
  511. }
  512. slot.plugin = pluginFromVar (e["plugin"]);
  513. if (*kind != EffectKind::plugin && e.hasProperty ("substituteFor"))
  514. slot.substituteFor = pluginFromVar (e["substituteFor"]);
  515. slot.sidechain = juce::jlimit (-1, maxMixerTracks - 1, (int) e.getProperty ("sidechain", -1));
  516. slot.sidechain2 = juce::jlimit (-1, maxMixerTracks - 1, (int) e.getProperty ("sidechain2", -1));
  517. slot.samplePath = e.getProperty ("sample", "").toString().toStdString();
  518. slot.presetName = e.getProperty ("preset", "").toString().toStdString();
  519. if (auto* other = e["abOther"].getArray())
  520. {
  521. for (int i = 0; i < other->size() && i < maxEffectParams; ++i)
  522. slot.abOther.push_back (juce::jlimit (0.0f, 1.0f, (float) (double) (*other)[i]));
  523. slot.abShowingB = (bool) e.getProperty ("abB", false);
  524. }
  525. if (e.hasProperty ("state"))
  526. {
  527. juce::MemoryOutputStream raw;
  528. if (juce::Base64::convertFromBase64 (raw, e["state"].toString()))
  529. slot.state.assign ((const std::uint8_t*) raw.getData(), (const std::uint8_t*) raw.getData() + raw.getDataSize());
  530. }
  531. if (auto* branches = e["branches"].getArray())
  532. for (const auto& b : *branches)
  533. {
  534. EffectBranch branch;
  535. branch.gain = juce::jlimit (0.0f, 4.0f, (float) (double) b.getProperty ("gain", 1.0));
  536. if (auto* chain = b["chain"].getArray())
  537. for (const auto& child : *chain)
  538. if (auto c = effectFromVar (child))
  539. branch.chain.push_back (std::move (*c)); // containers can be nested
  540. slot.branches.push_back (std::move (branch));
  541. }
  542. if (*kind == EffectKind::patcher && e.hasProperty ("patcher"))
  543. slot.patcher = patcherFromVar (e["patcher"], Song {});
  544. if (auto* links = e["links"].getArray())
  545. for (const auto& l : *links)
  546. {
  547. EffectLink link;
  548. link.branch = (int) l.getProperty ("branch", 0);
  549. link.source = (int) l.getProperty ("source", 0);
  550. link.target = (int) l.getProperty ("target", 0);
  551. link.param = juce::jlimit (0, maxEffectParams - 1, (int) l.getProperty ("param", 0));
  552. if (auto* curve = l["curve"].getArray())
  553. for (const auto& v : *curve)
  554. link.curve.push_back (juce::jlimit (0.0f, 1.0f, (float) (double) v));
  555. if (link.branch >= 0 && link.branch < (int) slot.branches.size() && link.curve.size() >= 2)
  556. slot.links.push_back (std::move (link));
  557. }
  558. return slot;
  559. }
  560. std::optional<EffectKind> effectFromId (const juce::String& id)
  561. {
  562. for (auto k : { EffectKind::eq, EffectKind::compressor, EffectKind::delay, EffectKind::reverb, EffectKind::plugin,
  563. EffectKind::limiter, EffectKind::filter, EffectKind::distortion, EffectKind::chorus, EffectKind::parametricEq, EffectKind::utility, EffectKind::volumeGate, EffectKind::peakController, EffectKind::pitchShift, EffectKind::freqShift, EffectKind::parallel, EffectKind::lofi, EffectKind::effector, EffectKind::crossover, EffectKind::rhythmGain, EffectKind::autoPan, EffectKind::vocoder, EffectKind::pitchCorrect, EffectKind::squeeze, EffectKind::vintagePhaser, EffectKind::vocodex, EffectKind::maximus, EffectKind::fruityLimiter, EffectKind::fruityCompressor, EffectKind::fruityWaveShaper, EffectKind::fruitySoftClipper, EffectKind::reeverb2, EffectKind::reeverb1, EffectKind::fruityDelay2, EffectKind::fruityDelay3,
  564. EffectKind::stereoShaper, EffectKind::stereoEnhancer, EffectKind::transientProcessor, EffectKind::spreader,
  565. EffectKind::fruityChorus, EffectKind::hyperChorus, EffectKind::vintageChorus, EffectKind::fruityPanOMatic, EffectKind::fruityBalance, EffectKind::fruityBloodOverdrive, EffectKind::grossBeat,
  566. EffectKind::fruityChorus, EffectKind::hyperChorus, EffectKind::vintageChorus,
  567. EffectKind::fruityDelayBank, EffectKind::fruityMultiband,
  568. EffectKind::fruityFastDist, EffectKind::fruityFlangus, EffectKind::fruityFlanger, EffectKind::luxeVerb, EffectKind::convolver,
  569. EffectKind::equo, EffectKind::flPitchShifter,
  570. EffectKind::frequencySplitter,
  571. EffectKind::fruityFastLP, EffectKind::fruityFreeFilter, EffectKind::fruityFilter, EffectKind::hardcore, EffectKind::distructor, EffectKind::multibandDelay,
  572. EffectKind::lovePhilter,
  573. EffectKind::newtone, EffectKind::newtime, EffectKind::facetEq, EffectKind::apexLimiter,
  574. EffectKind::ridgeStrip, EffectKind::glowLeveler, EffectKind::hushDeEsser, EffectKind::aether, EffectKind::ember, EffectKind::lynxTune, EffectKind::fruityPhaser,
  575. EffectKind::epochVerb, EffectKind::atrium, EffectKind::foilPlate, EffectKind::nebula, EffectKind::halo, EffectKind::horizon,
  576. EffectKind::echoform, EffectKind::spiralEcho, EffectKind::orbit, EffectKind::latticeMod,
  577. EffectKind::fruitySend,
  578. EffectKind::crestCompressor, EffectKind::prismMultiband, EffectKind::sentryGate,
  579. EffectKind::quellDenoiser, EffectKind::geminiDoubler, EffectKind::formulaController, EffectKind::voiceShift, EffectKind::patcher })
  580. if (id == effectId (k))
  581. return k;
  582. return std::nullopt; // effect from a future version: ignored
  583. }
  584. const char* targetKindName (AutomationTargetKind k)
  585. {
  586. switch (k)
  587. {
  588. case AutomationTargetKind::channelVolume: return "channelVolume";
  589. case AutomationTargetKind::channelPan: return "channelPan";
  590. case AutomationTargetKind::channelParam: return "channelParam";
  591. case AutomationTargetKind::mixerVolume: return "mixerVolume";
  592. case AutomationTargetKind::mixerPan: return "mixerPan";
  593. case AutomationTargetKind::effectParam: return "effectParam";
  594. case AutomationTargetKind::tempo: return "tempo";
  595. case AutomationTargetKind::effectMix: return "effectMix";
  596. case AutomationTargetKind::none: break;
  597. }
  598. return "none";
  599. }
  600. AutomationTargetKind targetKindFromName (const juce::String& name)
  601. {
  602. for (auto k : { AutomationTargetKind::channelVolume, AutomationTargetKind::channelPan, AutomationTargetKind::channelParam,
  603. AutomationTargetKind::mixerVolume, AutomationTargetKind::mixerPan, AutomationTargetKind::effectParam,
  604. AutomationTargetKind::tempo, AutomationTargetKind::effectMix })
  605. if (name == targetKindName (k))
  606. return k;
  607. return AutomationTargetKind::none;
  608. }
  609. juce::var clipsToVar (const std::vector<Clip>& list)
  610. {
  611. juce::Array<juce::var> clips;
  612. // [pattern, track, start, length, offset, kind (0 pattern, 1 audio, 2 automation), channel or automation]
  613. for (const auto& c : list)
  614. {
  615. juce::Array<juce::var> clip { c.pattern, c.track, (juce::int64) c.start, (juce::int64) c.length,
  616. (juce::int64) c.offset, (int) c.kind,
  617. c.kind == ClipKind::automation ? c.automation : c.channel };
  618. // [.., fade-in, fade-out, gain, muted, sub-tick offset] only when not default
  619. const auto fraction = juce::roundToInt (c.offsetFraction * 10000.0f) / 10000.0;
  620. if (c.fadeIn > 0 || c.fadeOut > 0 || c.gain != 1.0f || c.muted || fraction != 0.0)
  621. {
  622. clip.add ((juce::int64) c.fadeIn);
  623. clip.add ((juce::int64) c.fadeOut);
  624. clip.add (juce::roundToInt (c.gain * 1000.0f) / 1000.0);
  625. if (c.muted || fraction != 0.0)
  626. clip.add (c.muted);
  627. if (fraction != 0.0)
  628. clip.add (fraction);
  629. }
  630. clips.add (clip);
  631. }
  632. return clips;
  633. }
  634. // Needs channels, patterns and automations already loaded to validate the indices.
  635. std::vector<Clip> clipsFromVar (const juce::var& v, const Song& song)
  636. {
  637. std::vector<Clip> out;
  638. if (auto* clips = v.getArray())
  639. for (const auto& c : *clips)
  640. {
  641. if (! c.isArray() || c.size() < 5)
  642. continue;
  643. Clip clip;
  644. clip.pattern = (int) c[0];
  645. clip.track = juce::jmax (0, (int) c[1]);
  646. clip.start = juce::jmax<juce::int64> (0, (juce::int64) c[2]);
  647. clip.length = (juce::int64) c[3];
  648. clip.offset = juce::jmax<juce::int64> (0, (juce::int64) c[4]);
  649. if (c.size() >= 10)
  650. {
  651. clip.fadeIn = juce::jmax<juce::int64> (0, (juce::int64) c[7]);
  652. clip.fadeOut = juce::jmax<juce::int64> (0, (juce::int64) c[8]);
  653. clip.gain = juce::jlimit (0.0f, 4.0f, (float) (double) c[9]);
  654. clip.muted = c.size() >= 11 && (bool) c[10];
  655. clip.offsetFraction = c.size() >= 12 ? juce::jlimit (-0.5f, 0.5f, (float) (double) c[11]) : 0.0f;
  656. }
  657. if (c.size() >= 7 && (int) c[5] == 2)
  658. {
  659. clip.kind = ClipKind::automation;
  660. clip.automation = (int) c[6];
  661. if (clip.automation >= 0 && clip.automation < (int) song.automations.size() && clip.length > 0)
  662. out.push_back (clip);
  663. }
  664. else if (c.size() >= 7 && (int) c[5] == 1) // [.., kind, channel]; old files have only 5 fields
  665. {
  666. clip.kind = ClipKind::audio;
  667. clip.channel = (int) c[6];
  668. if (clip.channel >= 0 && clip.channel < (int) song.channels.size() && clip.length > 0)
  669. out.push_back (clip);
  670. }
  671. else if (clip.pattern >= 0 && clip.pattern < (int) song.patterns.size() && clip.length > 0)
  672. out.push_back (clip);
  673. }
  674. return out;
  675. }
  676. juce::var channelToVar (const ChannelDef& c)
  677. {
  678. auto o = std::make_unique<juce::DynamicObject>();
  679. o->setProperty ("name", str (c.name));
  680. o->setProperty ("instrument", instrumentId (c.instrument));
  681. o->setProperty ("volume", c.volume);
  682. o->setProperty ("pan", c.pan);
  683. o->setProperty ("muted", c.muted);
  684. if (! c.samplePath.empty())
  685. o->setProperty ("sample", str (c.samplePath));
  686. if (! c.controllerState.empty())
  687. o->setProperty ("controllerState", juce::Base64::toBase64 (c.controllerState.data(), c.controllerState.size()));
  688. if (! c.pluginState.empty())
  689. o->setProperty ("pluginState", juce::Base64::toBase64 (c.pluginState.data(), c.pluginState.size()));
  690. if (! c.modelParams.empty())
  691. {
  692. juce::StringArray values;
  693. for (auto v : c.modelParams)
  694. values.add (juce::String (v, 7));
  695. o->setProperty ("modelParams", values.joinIntoString (" "));
  696. }
  697. if (! c.zones.empty()) // [file, root, min key, max key, min velocity, max velocity, tune, gain]
  698. {
  699. juce::Array<juce::var> zones;
  700. for (const auto& z : c.zones)
  701. zones.add (juce::Array<juce::var> { str (z.path), z.rootKey, z.lowKey, z.highKey, z.lowVelocity, z.highVelocity, z.tune, z.gain,
  702. (juce::int64) z.loopStart, (juce::int64) z.loopEnd, z.loopMode });
  703. o->setProperty ("zones", zones);
  704. }
  705. o->setProperty ("mixer", c.mixerTrack);
  706. if (c.maxPolyphony > 0)
  707. o->setProperty ("maxPolyphony", c.maxPolyphony);
  708. if (c.colour != 0)
  709. o->setProperty ("colour", juce::String::toHexString ((juce::int64) (c.colour & 0xFFFFFF)).paddedLeft ('0', 6));
  710. if (c.group >= 0)
  711. o->setProperty ("group", c.group);
  712. if (c.swingMix != 1.0f)
  713. o->setProperty ("swingMix", c.swingMix);
  714. if (c.arp.enabled())
  715. {
  716. o->setProperty ("arp", juce::Array<juce::var> { c.arp.direction, c.arp.range, c.arp.stepBeats, c.arp.gate, c.arp.repeat });
  717. // FL's chord / slide / repeat (REA round 146b)
  718. juce::Array<juce::var> chord;
  719. for (auto i : c.arp.chord)
  720. chord.add (i);
  721. auto fl = std::make_unique<juce::DynamicObject>();
  722. fl->setProperty ("chord", chord);
  723. fl->setProperty ("chordSustain", c.arp.chordSustain);
  724. fl->setProperty ("slide", c.arp.slide);
  725. fl->setProperty ("octaveRepeat", c.arp.octaveRepeat);
  726. o->setProperty ("arpFl", juce::var (fl.release()));
  727. }
  728. // FL's Misc tab (REA round 146b): only what differs from the defaults
  729. if (! (c.misc == ChannelMisc {}))
  730. {
  731. const auto& m = c.misc;
  732. auto misc = std::make_unique<juce::DynamicObject>();
  733. misc->setProperty ("shift", m.shiftBeats);
  734. misc->setProperty ("gate", m.gateBeats);
  735. misc->setProperty ("fullPorta", m.fullPorta);
  736. misc->setProperty ("echo", juce::Array<juce::var> { m.echo.feedback, m.echo.pan, m.echo.pitch, m.echo.modX, m.echo.modY, m.echo.echoes,
  737. m.echo.timeBeats, m.echo.pingPong, m.echo.fat });
  738. misc->setProperty ("velocityTracking", juce::Array<juce::var> { m.velocity.mid, m.velocity.pan, m.velocity.modX, m.velocity.modY });
  739. misc->setProperty ("keyTracking", juce::Array<juce::var> { m.key.mid, m.key.pan, m.key.modX, m.key.modY });
  740. misc->setProperty ("pitchRange", m.pitchRange);
  741. misc->setProperty ("mainPitch", m.mainPitch);
  742. misc->setProperty ("rootNote", m.rootNote);
  743. misc->setProperty ("addToKey", m.addToKey);
  744. o->setProperty ("misc", juce::var (misc.release()));
  745. }
  746. if (c.cutGroup != 0 || c.cutBy != 0)
  747. o->setProperty ("cut", juce::Array<juce::var> { c.cutGroup, c.cutBy });
  748. if (! (c.synth == SynthSettings {}))
  749. {
  750. auto synth = std::make_unique<juce::DynamicObject>();
  751. juce::Array<juce::var> oscs;
  752. for (const auto& osc : c.synth.osc)
  753. oscs.add (juce::Array<juce::var> { (int) osc.wave, osc.octave, osc.detune, osc.level, osc.semitones, osc.pan });
  754. synth->setProperty ("osc", oscs);
  755. if (std::any_of (c.synth.spectrum.begin(), c.synth.spectrum.end(), [] (float a) { return a != 0.0f; }))
  756. {
  757. juce::StringArray amplitudes, phases;
  758. for (int h = 0; h < SynthSettings::spectrumSize; ++h)
  759. {
  760. amplitudes.add (juce::String (c.synth.spectrum[(std::size_t) h], 6));
  761. phases.add (juce::String (c.synth.spectrumPhase[(std::size_t) h], 6));
  762. }
  763. synth->setProperty ("spectrum", amplitudes.joinIntoString (" "));
  764. synth->setProperty ("spectrumPhase", phases.joinIntoString (" "));
  765. if (std::any_of (c.synth.spectrumDecay.begin(), c.synth.spectrumDecay.end(), [] (float t) { return t != 0.0f; }))
  766. {
  767. juce::StringArray decays;
  768. for (auto t : c.synth.spectrumDecay)
  769. decays.add (juce::String (t, 4));
  770. synth->setProperty ("spectrumDecay", decays.joinIntoString (" "));
  771. if (std::any_of (c.synth.spectrumTarget.begin(), c.synth.spectrumTarget.end(), [] (float a) { return a != 0.0f; }))
  772. {
  773. juce::StringArray targets;
  774. for (auto a : c.synth.spectrumTarget)
  775. targets.add (juce::String (a, 6));
  776. synth->setProperty ("spectrumTarget", targets.joinIntoString (" "));
  777. }
  778. }
  779. }
  780. synth->setProperty ("adsr", juce::Array<juce::var> { c.synth.attack, c.synth.decay, c.synth.sustain, c.synth.release });
  781. synth->setProperty ("filter", juce::Array<juce::var> { c.synth.cutoff, c.synth.resonance, c.synth.filterType });
  782. if (c.synth.ladder)
  783. synth->setProperty ("ladder", true);
  784. if (c.synth.chorus > 0)
  785. synth->setProperty ("chorus", c.synth.chorus);
  786. if (c.synth.stereoTremolo > 0.0f)
  787. synth->setProperty ("stereoTremolo", c.synth.stereoTremolo);
  788. if (c.synth.vibratoCents > 0.0f)
  789. synth->setProperty ("vibratoCents", c.synth.vibratoCents);
  790. if (c.synth.mono)
  791. synth->setProperty ("mono", true);
  792. if (c.synth.porta)
  793. synth->setProperty ("porta", true);
  794. if (c.synth.portaBeats != SynthSettings {}.portaBeats)
  795. synth->setProperty ("portaTime", c.synth.portaBeats);
  796. if (c.synth.am)
  797. synth->setProperty ("am", true);
  798. if (c.synth.ring)
  799. synth->setProperty ("ring", true);
  800. if (c.synth.keyTrack != 0.0f)
  801. synth->setProperty ("keyTrack", c.synth.keyTrack);
  802. if (c.synth.bandGain != std::array<float, 3> { 1.0f, 1.0f, 1.0f })
  803. synth->setProperty ("bands", juce::String (c.synth.bandGain[0]) + " " + juce::String (c.synth.bandGain[1]) + " " + juce::String (c.synth.bandGain[2]));
  804. if (c.synth.sweep > 0.0f)
  805. {
  806. synth->setProperty ("sweep", c.synth.sweep);
  807. synth->setProperty ("sweepTime", c.synth.sweepTime);
  808. }
  809. if (c.synth.fm > 0.0f)
  810. synth->setProperty ("fm", juce::Array<juce::var> { c.synth.fm, c.synth.fmDecay, c.synth.fmSustain });
  811. writeEnvelopes (*synth, c.synth.filterEnv, c.synth.pitchEnv);
  812. writeLfos (*synth, c.synth.lfo);
  813. o->setProperty ("synthSettings", juce::var (synth.release()));
  814. }
  815. if (! (c.sampler == SamplerSettings {}))
  816. {
  817. auto sampler = std::make_unique<juce::DynamicObject>();
  818. sampler->setProperty ("pitch", c.sampler.pitch);
  819. sampler->setProperty ("attack", c.sampler.attack);
  820. sampler->setProperty ("decay", c.sampler.decay);
  821. sampler->setProperty ("sustain", c.sampler.sustain);
  822. sampler->setProperty ("release", c.sampler.release);
  823. sampler->setProperty ("stretchBeats", c.sampler.stretchBeats);
  824. sampler->setProperty ("keepPitch", c.sampler.keepPitch);
  825. sampler->setProperty ("region", juce::Array<juce::var> { c.sampler.regionStart, c.sampler.regionEnd });
  826. if (! c.sampler.slices.empty())
  827. {
  828. juce::Array<juce::var> slices;
  829. for (auto v : c.sampler.slices)
  830. slices.add (juce::roundToInt (v * 100000.0f) / 100000.0);
  831. sampler->setProperty ("slices", slices);
  832. }
  833. sampler->setProperty ("reverse", c.sampler.reverse);
  834. sampler->setProperty ("cut", c.sampler.cut);
  835. if (c.sampler.porta)
  836. sampler->setProperty ("porta", true);
  837. if (c.sampler.portaBeats != SamplerSettings {}.portaBeats)
  838. sampler->setProperty ("portaTime", c.sampler.portaBeats);
  839. sampler->setProperty ("filter", juce::Array<juce::var> { c.sampler.cutoff, c.sampler.resonance, c.sampler.filterType });
  840. if (c.sampler.gainDb != 0.0f)
  841. sampler->setProperty ("gainDb", c.sampler.gainDb);
  842. if (! c.sampler.flVolumeEnvelope.empty())
  843. {
  844. juce::Array<juce::var> env;
  845. for (auto v : c.sampler.flVolumeEnvelope)
  846. env.add ((int) v);
  847. sampler->setProperty ("flVolumeEnvelope", env);
  848. }
  849. if (! c.sampler.flChannel.empty())
  850. {
  851. juce::Array<juce::var> fl;
  852. for (auto v : c.sampler.flChannel)
  853. fl.add ((int) v);
  854. sampler->setProperty ("flChannel", fl);
  855. }
  856. writeEnvelopes (*sampler, c.sampler.filterEnv, c.sampler.pitchEnv);
  857. writeLfos (*sampler, c.sampler.lfo);
  858. o->setProperty ("samplerSettings", juce::var (sampler.release()));
  859. }
  860. if (c.instrument == InstrumentKind::plugin)
  861. o->setProperty ("plugin", pluginToVar (c.plugin));
  862. if (c.instrument == InstrumentKind::patcher)
  863. o->setProperty ("patcher", patcherToVar (c.patcher));
  864. return juce::var (o.release());
  865. }
  866. ChannelDef channelFromVar (const juce::var& c, const Song& song)
  867. {
  868. ChannelDef def;
  869. def.name = c["name"].toString().toStdString();
  870. def.instrument = instrumentFromId (c["instrument"].toString());
  871. def.volume = juce::jlimit (0.0f, 1.0f, (float) c.getProperty ("volume", 0.8));
  872. def.pan = juce::jlimit (-1.0f, 1.0f, (float) c.getProperty ("pan", 0.0));
  873. def.muted = (bool) c.getProperty ("muted", false);
  874. def.samplePath = c["sample"].toString().toStdString();
  875. {
  876. const auto values = juce::StringArray::fromTokens (c.getProperty ("modelParams", "").toString(), " ", "");
  877. for (int k = 0; k < values.size() && k < 8192; ++k) // (DrumSynth Live: 4562)
  878. def.modelParams.push_back (values[k].getFloatValue());
  879. }
  880. if (const auto encoded = c["pluginState"].toString(); encoded.isNotEmpty())
  881. {
  882. juce::MemoryOutputStream decoded;
  883. if (juce::Base64::convertFromBase64 (decoded, encoded))
  884. {
  885. const auto* bytes = static_cast<const std::uint8_t*> (decoded.getData());
  886. def.pluginState.assign (bytes, bytes + decoded.getDataSize());
  887. }
  888. }
  889. if (const auto encoded = c["controllerState"].toString(); encoded.isNotEmpty())
  890. {
  891. juce::MemoryOutputStream decoded;
  892. if (juce::Base64::convertFromBase64 (decoded, encoded))
  893. {
  894. const auto* bytes = static_cast<const std::uint8_t*> (decoded.getData());
  895. def.controllerState.assign (bytes, bytes + decoded.getDataSize());
  896. }
  897. }
  898. if (auto* zones = c["zones"].getArray())
  899. for (const auto& z : *zones)
  900. if (z.isArray() && z.size() >= 8)
  901. {
  902. def.zones.push_back ({ z[0].toString().toStdString(), juce::jlimit (0, 127, (int) z[1]), juce::jlimit (0, 127, (int) z[2]),
  903. juce::jlimit (0, 127, (int) z[3]), juce::jlimit (0, 127, (int) z[4]), juce::jlimit (0, 127, (int) z[5]),
  904. juce::jlimit (-48.0f, 48.0f, (float) (double) z[6]), juce::jlimit (0.0f, 4.0f, (float) (double) z[7]) });
  905. if (z.size() >= 11) // loop
  906. {
  907. def.zones.back().loopStart = juce::jmax<juce::int64> (0, (juce::int64) z[8]);
  908. def.zones.back().loopEnd = juce::jmax<juce::int64> (0, (juce::int64) z[9]);
  909. def.zones.back().loopMode = juce::jlimit (0, 2, (int) z[10]);
  910. }
  911. }
  912. def.mixerTrack = juce::jlimit (0, maxMixerTracks - 1, (int) c.getProperty ("mixer", 0));
  913. def.maxPolyphony = juce::jlimit (0, 128, (int) c.getProperty ("maxPolyphony", 0));
  914. def.plugin = pluginFromVar (c["plugin"]);
  915. if (c.hasProperty ("colour"))
  916. def.colour = 0xFF000000u | (std::uint32_t) c["colour"].toString().getHexValue32();
  917. if (const int group = c.getProperty ("group", -1); group >= 0 && group < (int) song.channelGroups.size())
  918. def.group = group;
  919. def.swingMix = juce::jlimit (0.0f, 1.0f, (float) (double) c.getProperty ("swingMix", 1.0));
  920. if (const auto& arp = c["arp"]; arp.isArray() && arp.size() == 5)
  921. {
  922. def.arp.direction = juce::jlimit (0, 5, (int) arp[0]);
  923. def.arp.range = juce::jlimit (1, 4, (int) arp[1]);
  924. def.arp.stepBeats = juce::jlimit (1.0f / 192.0f, 4.0f, (float) (double) arp[2]);
  925. def.arp.gate = juce::jlimit (0.05f, 128.0f / 48.0f, (float) (double) arp[3]);
  926. def.arp.repeat = juce::jlimit (1, 16, (int) arp[4]);
  927. if (const auto& fl = c["arpFl"]; fl.isObject())
  928. {
  929. if (const auto* chord = fl["chord"].getArray())
  930. for (const auto& i : *chord)
  931. def.arp.chord.push_back (juce::jlimit (-48, 48, (int) i));
  932. def.arp.chordSustain = (bool) fl.getProperty ("chordSustain", true);
  933. def.arp.slide = (bool) fl.getProperty ("slide", false);
  934. def.arp.octaveRepeat = juce::jlimit (0, 16, (int) fl.getProperty ("octaveRepeat", 1));
  935. }
  936. }
  937. if (const auto& misc = c["misc"]; misc.isObject())
  938. {
  939. auto& m = def.misc;
  940. m.shiftBeats = juce::jlimit (0.0f, 1.0f, (float) (double) misc.getProperty ("shift", 0.0));
  941. m.gateBeats = juce::jlimit (0.0f, 4.0f, (float) (double) misc.getProperty ("gate", 0.0));
  942. m.fullPorta = (bool) misc.getProperty ("fullPorta", true);
  943. if (const auto& e = misc["echo"]; e.isArray() && e.size() >= 9)
  944. {
  945. m.echo.feedback = juce::jlimit (0.0f, 2.0f, (float) (double) e[0]);
  946. m.echo.pan = juce::jlimit (-1.0f, 1.0f, (float) (double) e[1]);
  947. m.echo.pitch = juce::jlimit (-4800.0f, 4800.0f, (float) (double) e[2]);
  948. m.echo.modX = juce::jlimit (-1.0f, 1.0f, (float) (double) e[3]);
  949. m.echo.modY = juce::jlimit (-1.0f, 1.0f, (float) (double) e[4]);
  950. m.echo.echoes = juce::jlimit (0, 16, (int) e[5]);
  951. m.echo.timeBeats = juce::jlimit (1.0f / 192.0f, 16.0f, (float) (double) e[6]);
  952. m.echo.pingPong = (bool) e[7];
  953. m.echo.fat = (bool) e[8];
  954. }
  955. auto tracking = [] (const juce::var& t, NoteTracking& to) {
  956. if (! t.isArray() || t.size() < 4)
  957. return;
  958. to.mid = juce::jlimit (0, 131, (int) t[0]);
  959. to.pan = juce::jlimit (-1.0f, 1.0f, (float) (double) t[1]);
  960. to.modX = juce::jlimit (-1.0f, 1.0f, (float) (double) t[2]);
  961. to.modY = juce::jlimit (-1.0f, 1.0f, (float) (double) t[3]);
  962. };
  963. tracking (misc["velocityTracking"], m.velocity);
  964. tracking (misc["keyTracking"], m.key);
  965. m.pitchRange = juce::jlimit (0, 48, (int) misc.getProperty ("pitchRange", 2));
  966. m.mainPitch = (bool) misc.getProperty ("mainPitch", true);
  967. m.rootNote = juce::jlimit (0, 127, (int) misc.getProperty ("rootNote", 60));
  968. m.addToKey = (bool) misc.getProperty ("addToKey", false);
  969. }
  970. if (const auto& cut = c["cut"]; cut.isArray() && cut.size() == 2)
  971. {
  972. def.cutGroup = (int) cut[0];
  973. def.cutBy = (int) cut[1];
  974. }
  975. if (const auto& s = c["synthSettings"]; s.isObject())
  976. {
  977. if (auto* oscs = s["osc"].getArray())
  978. for (int i = 0; i < oscs->size() && i < 3; ++i)
  979. if (const auto& o = (*oscs)[i]; o.isArray() && o.size() >= 4)
  980. {
  981. auto& osc = def.synth.osc[(std::size_t) i];
  982. osc = { (Waveform) juce::jlimit (0, 5, (int) o[0]), juce::jlimit (-3, 3, (int) o[1]),
  983. juce::jlimit (-100.0f, 100.0f, (float) (double) o[2]), juce::jlimit (0.0f, 4.0f, (float) (double) o[3]) }; // > 1: Harmor with volume above 0 dB
  984. if (o.size() >= 6) // semitones and pan (since the 3x Osc import)
  985. {
  986. osc.semitones = juce::jlimit (-11, 11, (int) o[4]);
  987. osc.pan = juce::jlimit (-1.0f, 1.0f, (float) (double) o[5]);
  988. }
  989. }
  990. if (const auto& a = s["adsr"]; a.isArray() && a.size() == 4)
  991. {
  992. def.synth.attack = juce::jlimit (0.0f, 10.0f, (float) (double) a[0]);
  993. def.synth.decay = juce::jlimit (0.0f, 10.0f, (float) (double) a[1]);
  994. def.synth.sustain = juce::jlimit (0.0f, 1.0f, (float) (double) a[2]);
  995. def.synth.release = juce::jlimit (0.0f, 10.0f, (float) (double) a[3]);
  996. }
  997. if (const auto& f = s["filter"]; f.isArray() && f.size() >= 2)
  998. {
  999. def.synth.cutoff = juce::jlimit (20.0f, 20000.0f, (float) (double) f[0]);
  1000. def.synth.resonance = juce::jlimit (0.0f, 1.0f, (float) (double) f[1]);
  1001. def.synth.filterType = f.size() >= 3 ? juce::jlimit (0, 3, (int) f[2]) : 0;
  1002. def.synth.ladder = (bool) s.getProperty ("ladder", false);
  1003. def.synth.chorus = juce::jlimit (0, 3, (int) s.getProperty ("chorus", 0));
  1004. def.synth.stereoTremolo = juce::jlimit (0.0f, 1.0f, (float) (double) s.getProperty ("stereoTremolo", 0.0));
  1005. def.synth.vibratoCents = juce::jlimit (0.0f, 100.0f, (float) (double) s.getProperty ("vibratoCents", 0.0));
  1006. }
  1007. def.synth.mono = (bool) s.getProperty ("mono", false);
  1008. def.synth.porta = (bool) s.getProperty ("porta", false);
  1009. def.synth.portaBeats = juce::jlimit (0.0f, 8.0f, (float) (double) s.getProperty ("portaTime", (double) SynthSettings {}.portaBeats));
  1010. def.synth.am = (bool) s.getProperty ("am", false);
  1011. def.synth.ring = (bool) s.getProperty ("ring", false);
  1012. for (const auto& [key, target] : { std::pair { "spectrum", &def.synth.spectrum }, std::pair { "spectrumPhase", &def.synth.spectrumPhase } })
  1013. {
  1014. const auto values = juce::StringArray::fromTokens (s.getProperty (key, "").toString(), " ", "");
  1015. for (int h = 0; h < values.size() && h < SynthSettings::spectrumSize; ++h)
  1016. (*target)[(std::size_t) h] = juce::jlimit (-16.0f, 16.0f, values[h].getFloatValue());
  1017. }
  1018. {
  1019. const auto values = juce::StringArray::fromTokens (s.getProperty ("spectrumDecay", "").toString(), " ", "");
  1020. for (int h = 0; h < values.size() && h < SynthSettings::spectrumSize; ++h)
  1021. def.synth.spectrumDecay[(std::size_t) h] = juce::jlimit (0.0f, 60.0f, values[h].getFloatValue());
  1022. const auto targets = juce::StringArray::fromTokens (s.getProperty ("spectrumTarget", "").toString(), " ", "");
  1023. for (int h = 0; h < targets.size() && h < SynthSettings::spectrumSize; ++h)
  1024. def.synth.spectrumTarget[(std::size_t) h] = juce::jlimit (0.0f, 16.0f, targets[h].getFloatValue());
  1025. }
  1026. def.synth.keyTrack = juce::jlimit (-2.0f, 2.0f, (float) (double) s.getProperty ("keyTrack", 0.0));
  1027. if (const auto bands = juce::StringArray::fromTokens (s.getProperty ("bands", "").toString(), " ", ""); bands.size() == 3)
  1028. for (int b = 0; b < 3; ++b)
  1029. def.synth.bandGain[(std::size_t) b] = juce::jlimit (0.0f, 4.0f, bands[b].getFloatValue());
  1030. def.synth.sweep = juce::jlimit (0.0f, 200.0f, (float) (double) s.getProperty ("sweep", 0.0));
  1031. def.synth.sweepTime = juce::jlimit (0.0005f, 30.0f, (float) (double) s.getProperty ("sweepTime", 0.1));
  1032. if (const auto* fm = s.getProperty ("fm", {}).getArray(); fm != nullptr && fm->size() >= 3)
  1033. {
  1034. def.synth.fm = juce::jlimit (0.0f, 16.0f, (float) (double) (*fm)[0]);
  1035. def.synth.fmDecay = juce::jlimit (0.0f, 30.0f, (float) (double) (*fm)[1]);
  1036. def.synth.fmSustain = juce::jlimit (0.0f, 1.0f, (float) (double) (*fm)[2]);
  1037. }
  1038. readEnvelopes (s, def.synth.filterEnv, def.synth.pitchEnv);
  1039. readLfos (s, def.synth.lfo);
  1040. }
  1041. if (const auto& s = c["samplerSettings"]; s.isObject())
  1042. {
  1043. def.sampler.pitch = juce::jlimit (-24.0f, 24.0f, (float) (double) s.getProperty ("pitch", 0.0));
  1044. def.sampler.attack = juce::jlimit (0.0f, 2.0f, (float) (double) s.getProperty ("attack", 0.0));
  1045. def.sampler.release = juce::jlimit (0.0f, 4.0f, (float) (double) s.getProperty ("release", 0.0));
  1046. def.sampler.decay = juce::jlimit (0.0f, 10.0f, (float) (double) s.getProperty ("decay", 0.0));
  1047. def.sampler.sustain = juce::jlimit (0.0f, 1.0f, (float) (double) s.getProperty ("sustain", 1.0));
  1048. def.sampler.stretchBeats = juce::jmax (0.0f, (float) (double) s.getProperty ("stretchBeats", 0.0));
  1049. def.sampler.keepPitch = (bool) s.getProperty ("keepPitch", false);
  1050. if (auto* slices = s["slices"].getArray())
  1051. for (const auto& v : *slices)
  1052. def.sampler.slices.push_back (juce::jlimit (0.0f, 1.0f, (float) (double) v));
  1053. if (const auto& region = s["region"]; region.isArray() && region.size() == 2)
  1054. {
  1055. def.sampler.regionStart = juce::jlimit (0.0f, 1.0f, (float) (double) region[0]);
  1056. def.sampler.regionEnd = juce::jlimit (0.0f, 1.0f, (float) (double) region[1]);
  1057. }
  1058. def.sampler.reverse = (bool) s.getProperty ("reverse", false);
  1059. def.sampler.cut = (bool) s.getProperty ("cut", false);
  1060. def.sampler.porta = (bool) s.getProperty ("porta", false);
  1061. def.sampler.portaBeats = juce::jlimit (0.0f, 8.0f, (float) (double) s.getProperty ("portaTime", (double) SamplerSettings {}.portaBeats));
  1062. def.sampler.gainDb = juce::jlimit (-24.0f, 24.0f, (float) (double) s.getProperty ("gainDb", 0.0));
  1063. if (auto* env = s["flVolumeEnvelope"].getArray(); env != nullptr && env->size() == 18)
  1064. for (const auto& v : *env)
  1065. def.sampler.flVolumeEnvelope.push_back ((std::int32_t) (int) v);
  1066. if (auto* fl = s["flChannel"].getArray(); fl != nullptr && (fl->size() == 89 || fl->size() == 90))
  1067. for (const auto& v : *fl)
  1068. def.sampler.flChannel.push_back ((std::int32_t) (int) v);
  1069. if (const auto& filter = s["filter"]; filter.isArray() && filter.size() >= 2)
  1070. {
  1071. def.sampler.cutoff = juce::jlimit (20.0f, 20000.0f, (float) (double) filter[0]);
  1072. def.sampler.resonance = juce::jlimit (0.0f, 1.0f, (float) (double) filter[1]);
  1073. def.sampler.filterType = filter.size() >= 3 ? juce::jlimit (0, 3, (int) filter[2]) : 0;
  1074. }
  1075. readEnvelopes (s, def.sampler.filterEnv, def.sampler.pitchEnv);
  1076. readLfos (s, def.sampler.lfo);
  1077. }
  1078. if (def.instrument == InstrumentKind::patcher && c.hasProperty ("patcher"))
  1079. def.patcher = patcherFromVar (c["patcher"], song);
  1080. return def;
  1081. }
  1082. } // namespace
  1083. juce::var mixerTrackToVar (const MixerTrack& t)
  1084. {
  1085. auto o = std::make_unique<juce::DynamicObject>();
  1086. o->setProperty ("name", str (t.name));
  1087. o->setProperty ("volume", t.volume);
  1088. o->setProperty ("pan", t.pan);
  1089. o->setProperty ("muted", t.muted);
  1090. o->setProperty ("solo", t.solo);
  1091. if (! t.threaded)
  1092. o->setProperty ("threaded", false);
  1093. if (t.separator)
  1094. o->setProperty ("separator", true);
  1095. if (t.dock != MixerDock::middle)
  1096. o->setProperty ("dock", t.dock == MixerDock::left ? "left" : "right");
  1097. if (! t.toMaster)
  1098. o->setProperty ("toMaster", false);
  1099. if (t.masterLevel != 1.0f)
  1100. o->setProperty ("masterLevel", juce::roundToInt (t.masterLevel * 10000.0f) / 10000.0);
  1101. if (t.colour != 0)
  1102. o->setProperty ("colour", juce::String::toHexString ((juce::int64) (t.colour & 0xFFFFFF)).paddedLeft ('0', 6));
  1103. if (t.stereo != 0.0f)
  1104. o->setProperty ("stereo", juce::roundToInt (t.stereo * 1000.0f) / 1000.0);
  1105. if (t.invertPhase)
  1106. o->setProperty ("invertPhase", true);
  1107. if (t.swapChannels)
  1108. o->setProperty ("swap", true);
  1109. if (t.inputChannel >= 0) // external audio input: device channel (0-based), stereo pair or mono
  1110. {
  1111. o->setProperty ("input", t.inputChannel);
  1112. if (! t.inputStereo)
  1113. o->setProperty ("inputMono", true);
  1114. }
  1115. if (t.monitor != InputMonitor::automatic)
  1116. o->setProperty ("monitor", (int) t.monitor);
  1117. if (! (t.eq == TrackEq {})) // [gains dB, frequencies Hz, widths 0..1] of the 3 bands
  1118. o->setProperty ("eq", juce::Array<juce::var> { t.eq.gainDb[0], t.eq.gainDb[1], t.eq.gainDb[2], t.eq.hz[0], t.eq.hz[1], t.eq.hz[2],
  1119. t.eq.width[0], t.eq.width[1], t.eq.width[2] });
  1120. if (! t.sends.empty())
  1121. {
  1122. juce::Array<juce::var> sends;
  1123. for (const auto& send : t.sends)
  1124. sends.add (juce::Array<juce::var> { send.target, juce::roundToInt (send.level * 10000.0f) / 10000.0 });
  1125. o->setProperty ("sends", sends);
  1126. }
  1127. juce::Array<juce::var> effects;
  1128. for (const auto& slot : t.effects)
  1129. effects.add (effectToVar (slot));
  1130. if (! effects.isEmpty())
  1131. o->setProperty ("effects", effects);
  1132. return juce::var (o.release());
  1133. }
  1134. MixerTrack mixerTrackFromVar (const juce::var& t)
  1135. {
  1136. MixerTrack track;
  1137. track.name = t["name"].toString().toStdString();
  1138. track.volume = juce::jlimit (0.0f, 1.0f, (float) t.getProperty ("volume", unityFader));
  1139. track.pan = juce::jlimit (-1.0f, 1.0f, (float) t.getProperty ("pan", 0.0));
  1140. track.muted = (bool) t.getProperty ("muted", false);
  1141. track.solo = (bool) t.getProperty ("solo", false);
  1142. track.threaded = (bool) t.getProperty ("threaded", true);
  1143. track.separator = (bool) t.getProperty ("separator", false);
  1144. track.dock = t["dock"].toString() == "left" ? MixerDock::left : t["dock"].toString() == "right" ? MixerDock::right : MixerDock::middle;
  1145. track.toMaster = (bool) t.getProperty ("toMaster", true);
  1146. track.masterLevel = juce::jlimit (0.0f, maxFaderGain, (float) (double) t.getProperty ("masterLevel", 1.0));
  1147. track.stereo = juce::jlimit (-1.0f, 1.0f, (float) (double) t.getProperty ("stereo", 0.0));
  1148. if (t.hasProperty ("colour"))
  1149. track.colour = 0xFF000000u | (std::uint32_t) t["colour"].toString().getHexValue32();
  1150. track.invertPhase = (bool) t.getProperty ("invertPhase", false);
  1151. track.swapChannels = (bool) t.getProperty ("swap", false);
  1152. track.inputChannel = juce::jlimit (-1, 255, (int) t.getProperty ("input", -1));
  1153. track.inputStereo = ! (bool) t.getProperty ("inputMono", false);
  1154. track.monitor = (InputMonitor) juce::jlimit (0, 3, (int) t.getProperty ("monitor", (int) InputMonitor::automatic));
  1155. if (const auto& eq = t["eq"]; eq.isArray() && eq.size() == 9)
  1156. for (std::size_t b = 0; b < 3; ++b)
  1157. {
  1158. track.eq.gainDb[b] = juce::jlimit (-18.0f, 18.0f, (float) (double) eq[(int) b]);
  1159. track.eq.hz[b] = juce::jlimit (10.0f, 16000.0f, (float) (double) eq[(int) b + 3]);
  1160. track.eq.width[b] = juce::jlimit (0.0f, 1.0f, (float) (double) eq[(int) b + 6]);
  1161. }
  1162. if (auto* sends = t["sends"].getArray())
  1163. for (const auto& send : *sends)
  1164. if (send.isArray() && send.size() == 2)
  1165. track.sends.push_back ({ (int) send[0], juce::jlimit (0.0f, maxFaderGain, (float) (double) send[1]) });
  1166. if (auto* effects = t["effects"].getArray())
  1167. for (const auto& e : *effects)
  1168. {
  1169. if ((int) track.effects.size() >= maxEffectSlots)
  1170. continue;
  1171. if (auto slot = effectFromVar (e))
  1172. track.effects.push_back (std::move (*slot));
  1173. }
  1174. return track;
  1175. }
  1176. juce::String toJson (const Song& song)
  1177. {
  1178. auto root = std::make_unique<juce::DynamicObject>();
  1179. root->setProperty ("format", "lynx-project");
  1180. root->setProperty ("version", currentVersion);
  1181. root->setProperty ("bpm", song.bpm);
  1182. root->setProperty ("beatsPerBar", song.beatsPerBar);
  1183. if (song.swing > 0.0f)
  1184. root->setProperty ("swing", juce::roundToInt (song.swing * 1000.0f) / 1000.0);
  1185. if (! song.channelGroups.empty())
  1186. {
  1187. juce::Array<juce::var> groups;
  1188. for (const auto& name : song.channelGroups)
  1189. groups.add (str (name));
  1190. root->setProperty ("channelGroups", groups);
  1191. }
  1192. if (song.masterPitch != 0.0f)
  1193. root->setProperty ("masterPitch", (double) song.masterPitch);
  1194. if (song.substitutesBypassed)
  1195. root->setProperty ("substitutesBypassed", true);
  1196. if (! song.info.empty())
  1197. {
  1198. auto info = std::make_unique<juce::DynamicObject>();
  1199. auto set = [&info] (const char* key, const std::string& value) {
  1200. if (! value.empty())
  1201. info->setProperty (key, juce::String::fromUTF8 (value.c_str()));
  1202. };
  1203. set ("title", song.info.title);
  1204. set ("author", song.info.author);
  1205. set ("genre", song.info.genre);
  1206. set ("url", song.info.url);
  1207. set ("comments", song.info.comments);
  1208. if (song.info.showOnOpen)
  1209. info->setProperty ("showOnOpen", true);
  1210. root->setProperty ("info", juce::var (info.release()));
  1211. }
  1212. root->setProperty ("currentPattern", song.currentPattern);
  1213. juce::Array<juce::var> channels;
  1214. for (const auto& c : song.channels)
  1215. channels.add (channelToVar (c));
  1216. root->setProperty ("channels", channels);
  1217. juce::Array<juce::var> patterns;
  1218. for (const auto& p : song.patterns)
  1219. {
  1220. auto o = std::make_unique<juce::DynamicObject>();
  1221. o->setProperty ("name", str (p.name));
  1222. if (p.lengthTicks > 0)
  1223. o->setProperty ("length", (juce::int64) p.lengthTicks);
  1224. if (p.colour != 0)
  1225. o->setProperty ("colour", juce::String::toHexString ((juce::int64) (p.colour & 0xFFFFFF)).paddedLeft ('0', 6));
  1226. juce::Array<juce::var> notes;
  1227. for (const auto& n : p.notes)
  1228. {
  1229. juce::Array<juce::var> note { (juce::int64) n.start, (juce::int64) n.length, n.channel, n.key,
  1230. juce::roundToInt (n.velocity * 1000.0f) / 1000.0 };
  1231. // [.., pan, fine pitch, muted] only when not default
  1232. // [.., release, mod X, mod Y (, colour)]
  1233. const auto extra = n.release != 0.5f || n.modX != 0.5f || n.modY != 0.5f || n.colour != 0;
  1234. if (n.pan != 0.0f || n.finePitch != 0.0f || n.muted || n.slide || n.porta || extra)
  1235. {
  1236. note.add (juce::roundToInt (n.pan * 1000.0f) / 1000.0);
  1237. note.add (juce::roundToInt (n.finePitch * 10.0f) / 10.0);
  1238. note.add (n.muted);
  1239. note.add (n.slide);
  1240. if (n.porta || extra)
  1241. note.add (n.porta);
  1242. if (extra)
  1243. for (auto v : { n.release, n.modX, n.modY })
  1244. note.add (juce::roundToInt (v * 1000.0f) / 1000.0);
  1245. if (n.colour != 0)
  1246. note.add (n.colour);
  1247. }
  1248. notes.add (note);
  1249. }
  1250. o->setProperty ("notes", notes);
  1251. // event editor lanes: [kind, index, slot, param] + [[tick, value], ...]
  1252. juce::Array<juce::var> lanes;
  1253. for (const auto& lane : p.events)
  1254. {
  1255. if (lane.events.empty() || lane.target.kind == AutomationTargetKind::none)
  1256. continue;
  1257. auto l = std::make_unique<juce::DynamicObject>();
  1258. l->setProperty ("target", juce::Array<juce::var> { targetKindName (lane.target.kind), lane.target.index, lane.target.slot, lane.target.param });
  1259. juce::Array<juce::var> events;
  1260. for (const auto& e : lane.events)
  1261. events.add (juce::Array<juce::var> { (juce::int64) e.tick, juce::roundToInt (e.value * 10000.0f) / 10000.0 });
  1262. l->setProperty ("events", events);
  1263. lanes.add (juce::var (l.release()));
  1264. }
  1265. if (! lanes.isEmpty())
  1266. o->setProperty ("events", lanes);
  1267. patterns.add (juce::var (o.release()));
  1268. }
  1269. root->setProperty ("patterns", patterns);
  1270. juce::Array<juce::var> automations;
  1271. for (const auto& a : song.automations)
  1272. {
  1273. auto o = std::make_unique<juce::DynamicObject>();
  1274. o->setProperty ("name", str (a.name));
  1275. o->setProperty ("target", juce::Array<juce::var> { targetKindName (a.target.kind), a.target.index, a.target.slot, a.target.param });
  1276. juce::Array<juce::var> points;
  1277. for (const auto& pt : a.points)
  1278. points.add (juce::Array<juce::var> { (juce::int64) pt.tick, juce::roundToInt (pt.value * 10000.0f) / 10000.0,
  1279. juce::roundToInt (pt.tension * 1000.0f) / 1000.0 });
  1280. o->setProperty ("points", points);
  1281. if (a.isLive())
  1282. {
  1283. o->setProperty ("source", juce::Array<juce::var> { a.source.track, a.source.slot, a.source.output, a.source.channel });
  1284. juce::Array<juce::var> curve;
  1285. for (auto v : a.curve)
  1286. curve.add (juce::roundToInt (v * 10000.0f) / 10000.0);
  1287. o->setProperty ("curve", curve);
  1288. }
  1289. automations.add (juce::var (o.release()));
  1290. }
  1291. if (! automations.isEmpty())
  1292. root->setProperty ("automations", automations);
  1293. if (! song.midiLinks.empty())
  1294. {
  1295. juce::Array<juce::var> links;
  1296. for (const auto& l : song.midiLinks)
  1297. links.add (juce::Array<juce::var> { l.cc, l.channel, targetKindName (l.target.kind), l.target.index, l.target.slot, l.target.param });
  1298. root->setProperty ("midiLinks", links);
  1299. }
  1300. if (! song.initialValues.empty()) // FL's initialized controls (REA round 146)
  1301. {
  1302. juce::Array<juce::var> values;
  1303. for (const auto& v : song.initialValues)
  1304. values.add (juce::Array<juce::var> { targetKindName (v.target.kind), v.target.index, v.target.slot, v.target.param, v.value });
  1305. root->setProperty ("initialValues", values);
  1306. }
  1307. root->setProperty ("playlist", clipsToVar (song.playlist));
  1308. {
  1309. juce::Array<juce::var> tracks;
  1310. for (std::size_t i = 0; i < song.playlistTracks.size(); ++i)
  1311. if (const auto& t = song.playlistTracks[i]; ! t.name.empty() || t.muted)
  1312. tracks.add (juce::Array<juce::var> { (int) i, str (t.name), t.muted });
  1313. if (! tracks.isEmpty())
  1314. root->setProperty ("playlistTracks", tracks);
  1315. // row heights in a separate list, so older versions still read the names and mutes
  1316. juce::Array<juce::var> heights;
  1317. for (std::size_t i = 0; i < song.playlistTracks.size(); ++i)
  1318. if (song.playlistTracks[i].height > 0)
  1319. heights.add (juce::Array<juce::var> { (int) i, song.playlistTracks[i].height });
  1320. if (! heights.isEmpty())
  1321. root->setProperty ("playlistTrackHeights", heights);
  1322. juce::Array<juce::var> colours; // [index, 0xRRGGBB]
  1323. for (std::size_t i = 0; i < song.playlistTracks.size(); ++i)
  1324. if (song.playlistTracks[i].colour != 0)
  1325. colours.add (juce::Array<juce::var> { (int) i, (int) (song.playlistTracks[i].colour & 0xFFFFFF) });
  1326. if (! colours.isEmpty())
  1327. root->setProperty ("playlistTrackColours", colours);
  1328. // track groups: [index, grouped, collapsed] for the tracks that have either (older versions ignore it)
  1329. juce::Array<juce::var> groups;
  1330. for (std::size_t i = 0; i < song.playlistTracks.size(); ++i)
  1331. if (song.playlistTracks[i].grouped || song.playlistTracks[i].collapsed)
  1332. groups.add (juce::Array<juce::var> { (int) i, song.playlistTracks[i].grouped ? 1 : 0, song.playlistTracks[i].collapsed ? 1 : 0 });
  1333. if (! groups.isEmpty())
  1334. root->setProperty ("playlistTrackGroups", groups);
  1335. // track modes (round 146a): [index, "audio" | "instrument", mixer track, channel]
  1336. juce::Array<juce::var> modes;
  1337. for (std::size_t i = 0; i < song.playlistTracks.size(); ++i)
  1338. if (const auto& t = song.playlistTracks[i]; t.mode != PlaylistTrackMode::unassigned)
  1339. modes.add (juce::Array<juce::var> { (int) i, t.mode == PlaylistTrackMode::audio ? "audio" : "instrument", t.mixerTrack, t.channel });
  1340. if (! modes.isEmpty())
  1341. root->setProperty ("playlistTrackModes", modes);
  1342. }
  1343. const auto anyMarkers = std::any_of (song.arrangements.begin(), song.arrangements.end(), [] (const Arrangement& a) { return ! a.markers.empty(); });
  1344. if (song.arrangements.size() > 1 || anyMarkers)
  1345. {
  1346. juce::Array<juce::var> arrangements;
  1347. for (std::size_t i = 0; i < song.arrangements.size(); ++i)
  1348. {
  1349. const auto& a = song.arrangements[i];
  1350. auto o = std::make_unique<juce::DynamicObject>();
  1351. o->setProperty ("name", str (a.name));
  1352. if ((int) i != song.currentArrangement) // the current one is in "playlist"
  1353. {
  1354. o->setProperty ("clips", clipsToVar (a.clips));
  1355. if (a.loopEnd > a.loopStart)
  1356. o->setProperty ("loop", juce::Array<juce::var> { (juce::int64) a.loopStart, (juce::int64) a.loopEnd });
  1357. }
  1358. // markers: [tick, name, numerator, denominator] (numerator 0 = plain marker)
  1359. if (! a.markers.empty())
  1360. {
  1361. juce::Array<juce::var> markers;
  1362. for (const auto& m : a.markers)
  1363. {
  1364. juce::Array<juce::var> one { (juce::int64) m.tick, str (m.name), m.numerator, m.denominator };
  1365. if (m.action != 0) // FL's marker action (Start / Stop recording...)
  1366. one.add (m.action);
  1367. markers.add (one);
  1368. }
  1369. o->setProperty ("markers", markers);
  1370. }
  1371. arrangements.add (juce::var (o.release()));
  1372. }
  1373. root->setProperty ("arrangements", arrangements);
  1374. root->setProperty ("currentArrangement", song.currentArrangement);
  1375. }
  1376. juce::Array<juce::var> mixer;
  1377. for (const auto& t : song.mixer)
  1378. mixer.add (mixerTrackToVar (t));
  1379. root->setProperty ("mixer", mixer);
  1380. root->setProperty ("mode", song.mode == PlayMode::song ? "song" : "pattern");
  1381. if (song.hasLoop())
  1382. root->setProperty ("loop", juce::Array<juce::var> { (juce::int64) song.loopStart, (juce::int64) song.loopEnd });
  1383. return juce::JSON::toString (juce::var (root.release()), false);
  1384. }
  1385. std::optional<Song> fromJson (const juce::String& json, juce::String& error)
  1386. {
  1387. juce::var root;
  1388. const auto parsed = juce::JSON::parse (json, root);
  1389. if (parsed.failed())
  1390. {
  1391. error = utf8 ("invalid JSON: ") + parsed.getErrorMessage();
  1392. return std::nullopt;
  1393. }
  1394. // "daw-project" = projects saved before the project was named LYNX
  1395. if (root["format"].toString() != "lynx-project" && root["format"].toString() != "daw-project")
  1396. {
  1397. error = utf8 ("not a project from this DAW");
  1398. return std::nullopt;
  1399. }
  1400. if ((int) root["version"] > currentVersion)
  1401. {
  1402. error = utf8 ("project saved by a newer version of LYNX");
  1403. return std::nullopt;
  1404. }
  1405. Song song;
  1406. song.bpm = juce::jlimit (10.0, 999.0, (double) root.getProperty ("bpm", 130.0));
  1407. song.beatsPerBar = juce::jlimit (1, 32, (int) root.getProperty ("beatsPerBar", 4));
  1408. song.swing = juce::jlimit (0.0f, 1.0f, (float) (double) root.getProperty ("swing", 0.0));
  1409. if (auto* groups = root["channelGroups"].getArray())
  1410. for (const auto& name : *groups)
  1411. song.channelGroups.push_back (name.toString().toStdString());
  1412. song.masterPitch = juce::jlimit (-1200.0f, 1200.0f, (float) (double) root.getProperty ("masterPitch", 0.0));
  1413. song.substitutesBypassed = (bool) root.getProperty ("substitutesBypassed", false);
  1414. if (const auto info = root.getProperty ("info", {}); info.isObject())
  1415. {
  1416. auto get = [&info] (const char* key) { return info.getProperty (key, {}).toString().toStdString(); };
  1417. song.info.title = get ("title");
  1418. song.info.author = get ("author");
  1419. song.info.genre = get ("genre");
  1420. song.info.url = get ("url");
  1421. song.info.comments = get ("comments");
  1422. song.info.showOnOpen = (bool) info.getProperty ("showOnOpen", false);
  1423. }
  1424. song.currentPattern = (int) root.getProperty ("currentPattern", 0);
  1425. if (auto* channels = root["channels"].getArray())
  1426. for (const auto& c : *channels)
  1427. song.channels.push_back (channelFromVar (c, song));
  1428. if (auto* patterns = root["patterns"].getArray())
  1429. for (const auto& p : *patterns)
  1430. {
  1431. Pattern pattern;
  1432. pattern.name = p["name"].toString().toStdString();
  1433. pattern.lengthTicks = (juce::int64) p.getProperty ("length", 0);
  1434. if (p.hasProperty ("colour"))
  1435. pattern.colour = 0xFF000000u | (std::uint32_t) p["colour"].toString().getHexValue32();
  1436. if (auto* notes = p["notes"].getArray())
  1437. for (const auto& n : *notes)
  1438. {
  1439. if (! n.isArray() || n.size() < 5)
  1440. continue;
  1441. Note note;
  1442. note.start = (juce::int64) n[0];
  1443. note.length = juce::jmax<juce::int64> (1, (juce::int64) n[1]);
  1444. note.channel = (int) n[2];
  1445. note.key = juce::jlimit (0, 127, (int) n[3]);
  1446. note.velocity = juce::jlimit (0.0f, 1.0f, (float) (double) n[4]);
  1447. if (n.size() >= 8)
  1448. {
  1449. note.pan = juce::jlimit (-1.0f, 1.0f, (float) (double) n[5]);
  1450. note.finePitch = juce::jlimit (-120.0f, 120.0f, (float) (double) n[6]);
  1451. note.muted = (bool) n[7];
  1452. note.slide = n.size() >= 9 && (bool) n[8];
  1453. note.porta = n.size() >= 10 && (bool) n[9];
  1454. if (n.size() >= 13)
  1455. {
  1456. note.release = juce::jlimit (0.0f, 1.0f, (float) (double) n[10]);
  1457. note.modX = juce::jlimit (0.0f, 1.0f, (float) (double) n[11]);
  1458. note.modY = juce::jlimit (0.0f, 1.0f, (float) (double) n[12]);
  1459. }
  1460. if (n.size() >= 14)
  1461. note.colour = juce::jlimit (0, noteColourCount - 1, (int) n[13]);
  1462. }
  1463. if (note.channel >= 0 && note.channel < (int) song.channels.size())
  1464. pattern.notes.push_back (note);
  1465. }
  1466. pattern.sortNotes();
  1467. if (auto* lanes = p["events"].getArray())
  1468. for (const auto& l : *lanes)
  1469. {
  1470. PatternEvents lane;
  1471. if (const auto& t = l["target"]; t.isArray() && t.size() == 4)
  1472. lane.target = { targetKindFromName (t[0].toString()), (int) t[1], (int) t[2], (int) t[3] };
  1473. if (auto* events = l["events"].getArray())
  1474. for (const auto& e : *events)
  1475. if (e.isArray() && e.size() >= 2)
  1476. lane.events.push_back ({ juce::jmax<juce::int64> (0, (juce::int64) e[0]), juce::jlimit (0.0f, 1.0f, (float) (double) e[1]) });
  1477. std::stable_sort (lane.events.begin(), lane.events.end(), [] (const PatternEvent& a, const PatternEvent& b) { return a.tick < b.tick; });
  1478. if (lane.target.kind != AutomationTargetKind::none && ! lane.events.empty())
  1479. pattern.events.push_back (std::move (lane));
  1480. }
  1481. song.patterns.push_back (std::move (pattern));
  1482. }
  1483. if (song.patterns.empty())
  1484. song.patterns.emplace_back().name = "Pattern 1";
  1485. if (auto* automations = root["automations"].getArray())
  1486. for (const auto& a : *automations)
  1487. {
  1488. Automation automation;
  1489. automation.name = a["name"].toString().toStdString();
  1490. if (const auto& t = a["target"]; t.isArray() && t.size() == 4)
  1491. automation.target = { targetKindFromName (t[0].toString()), (int) t[1], (int) t[2], (int) t[3] };
  1492. if (auto* points = a["points"].getArray())
  1493. for (const auto& pt : *points)
  1494. if (pt.isArray() && pt.size() >= 2)
  1495. automation.points.push_back ({ juce::jmax<juce::int64> (0, (juce::int64) pt[0]),
  1496. juce::jlimit (0.0f, 1.0f, (float) (double) pt[1]),
  1497. pt.size() >= 3 ? juce::jlimit (-1.0f, 1.0f, (float) (double) pt[2]) : 0.0f });
  1498. if (const auto& source = a["source"]; source.isArray() && source.size() >= 3)
  1499. automation.source = { (int) source[0], (int) source[1], (int) source[2], source.size() >= 4 ? (int) source[3] : -1 };
  1500. if (auto* curve = a["curve"].getArray())
  1501. for (const auto& v : *curve)
  1502. automation.curve.push_back (juce::jlimit (0.0f, 1.0f, (float) (double) v));
  1503. std::stable_sort (automation.points.begin(), automation.points.end(),
  1504. [] (const AutomationPoint& x, const AutomationPoint& y) { return x.tick < y.tick; });
  1505. song.automations.push_back (std::move (automation));
  1506. }
  1507. song.playlist = clipsFromVar (root["playlist"], song);
  1508. if (auto* links = root["midiLinks"].getArray())
  1509. for (const auto& l : *links)
  1510. if (l.isArray() && l.size() == 6)
  1511. song.midiLinks.push_back ({ juce::jlimit (0, 127, (int) l[0]), juce::jlimit (-1, 15, (int) l[1]),
  1512. { targetKindFromName (l[2].toString()), (int) l[3], (int) l[4], (int) l[5] } });
  1513. if (auto* values = root["initialValues"].getArray())
  1514. for (const auto& v : *values)
  1515. if (v.isArray() && v.size() == 5)
  1516. song.setInitialValue ({ targetKindFromName (v[0].toString()), (int) v[1], (int) v[2], (int) v[3] }, (float) (double) v[4]);
  1517. if (auto* tracks = root["playlistTracks"].getArray())
  1518. for (const auto& t : *tracks)
  1519. if (t.isArray() && t.size() == 3 && (int) t[0] >= 0 && (int) t[0] < 500)
  1520. {
  1521. const auto index = (std::size_t) (int) t[0];
  1522. if (song.playlistTracks.size() <= index)
  1523. song.playlistTracks.resize (index + 1);
  1524. song.playlistTracks[index] = { t[1].toString().toStdString(), (bool) t[2] };
  1525. }
  1526. if (auto* heights = root["playlistTrackHeights"].getArray())
  1527. for (const auto& t : *heights)
  1528. if (t.isArray() && t.size() == 2 && (int) t[0] >= 0 && (int) t[0] < 500)
  1529. {
  1530. const auto index = (std::size_t) (int) t[0];
  1531. if (song.playlistTracks.size() <= index)
  1532. song.playlistTracks.resize (index + 1);
  1533. song.playlistTracks[index].height = juce::jlimit (0, 400, (int) t[1]);
  1534. }
  1535. if (auto* colours = root["playlistTrackColours"].getArray())
  1536. for (const auto& t : *colours)
  1537. if (t.isArray() && t.size() == 2 && (int) t[0] >= 0 && (int) t[0] < 500)
  1538. {
  1539. const auto index = (std::size_t) (int) t[0];
  1540. if (song.playlistTracks.size() <= index)
  1541. song.playlistTracks.resize (index + 1);
  1542. song.playlistTracks[index].colour = 0xFF000000u | ((std::uint32_t) (int) t[1] & 0xFFFFFFu);
  1543. }
  1544. if (auto* groups = root["playlistTrackGroups"].getArray())
  1545. for (const auto& t : *groups)
  1546. if (t.isArray() && t.size() == 3 && (int) t[0] >= 0 && (int) t[0] < 500)
  1547. {
  1548. const auto index = (std::size_t) (int) t[0];
  1549. if (song.playlistTracks.size() <= index)
  1550. song.playlistTracks.resize (index + 1);
  1551. song.playlistTracks[index].grouped = index > 0 && (int) t[1] != 0;
  1552. song.playlistTracks[index].collapsed = (int) t[2] != 0;
  1553. }
  1554. if (auto* modes = root["playlistTrackModes"].getArray())
  1555. for (const auto& t : *modes)
  1556. if (t.isArray() && t.size() == 4 && (int) t[0] >= 0 && (int) t[0] < 500)
  1557. {
  1558. const auto index = (std::size_t) (int) t[0];
  1559. const auto mixer = (int) t[2], channel = (int) t[3];
  1560. const auto audio = t[1].toString() == "audio";
  1561. if (audio ? (mixer <= 0 || mixer >= (int) song.mixer.size()) : (channel < 0 || channel >= (int) song.channels.size()))
  1562. continue;
  1563. if (song.playlistTracks.size() <= index)
  1564. song.playlistTracks.resize (index + 1);
  1565. auto& track = song.playlistTracks[index];
  1566. track.mode = audio ? PlaylistTrackMode::audio : PlaylistTrackMode::instrument;
  1567. track.mixerTrack = mixer > 0 && mixer < (int) song.mixer.size() ? mixer : -1;
  1568. track.channel = audio ? -1 : channel;
  1569. }
  1570. if (auto* arrangements = root["arrangements"].getArray(); arrangements != nullptr && ! arrangements->isEmpty())
  1571. {
  1572. song.arrangements.clear();
  1573. for (const auto& a : *arrangements)
  1574. {
  1575. Arrangement arrangement;
  1576. arrangement.name = a["name"].toString().toStdString();
  1577. arrangement.clips = clipsFromVar (a["clips"], song);
  1578. if (const auto& loop = a["loop"]; loop.isArray() && loop.size() == 2)
  1579. {
  1580. arrangement.loopStart = juce::jmax<juce::int64> (0, (juce::int64) loop[0]);
  1581. arrangement.loopEnd = juce::jmax<juce::int64> (arrangement.loopStart, (juce::int64) loop[1]);
  1582. }
  1583. if (auto* markers = a["markers"].getArray())
  1584. for (const auto& m : *markers)
  1585. if (m.isArray() && (m.size() == 4 || m.size() == 5))
  1586. arrangement.markers.push_back ({ juce::jmax<juce::int64> (0, (juce::int64) m[0]), m[1].toString().toStdString(),
  1587. juce::jlimit (0, 32, (int) m[2]), juce::jlimit (1, 32, (int) m[3]),
  1588. m.size() == 5 ? juce::jlimit (0, 255, (int) m[4]) : 0 });
  1589. std::stable_sort (arrangement.markers.begin(), arrangement.markers.end(), [] (const Marker& x, const Marker& y) { return x.tick < y.tick; });
  1590. song.arrangements.push_back (std::move (arrangement));
  1591. }
  1592. song.currentArrangement = juce::jlimit (0, (int) song.arrangements.size() - 1, (int) root.getProperty ("currentArrangement", 0));
  1593. song.arrangements[(std::size_t) song.currentArrangement].clips.clear();
  1594. }
  1595. song.mode = root["mode"].toString() == "song" ? PlayMode::song : PlayMode::pattern;
  1596. if (const auto& loop = root["loop"]; loop.isArray() && loop.size() == 2)
  1597. {
  1598. song.loopStart = juce::jmax<juce::int64> (0, (juce::int64) loop[0]);
  1599. song.loopEnd = juce::jmax<juce::int64> (song.loopStart, (juce::int64) loop[1]);
  1600. }
  1601. if (auto* mixer = root["mixer"].getArray())
  1602. for (const auto& t : *mixer)
  1603. {
  1604. if ((int) song.mixer.size() >= maxMixerTracks)
  1605. break;
  1606. auto track = mixerTrackFromVar (t);
  1607. song.mixer.push_back (std::move (track));
  1608. }
  1609. if (song.mixer.empty()) // projects from before the mixer existed
  1610. song.mixer = Song::defaultMixer();
  1611. // sends to tracks that don't exist are discarded
  1612. for (auto& t : song.mixer)
  1613. t.sends.erase (std::remove_if (t.sends.begin(), t.sends.end(),
  1614. [n = (int) song.mixer.size()] (const MixerSend& s) { return s.target <= 0 || s.target >= n; }),
  1615. t.sends.end());
  1616. song.currentPattern = juce::jlimit (0, (int) song.patterns.size() - 1, song.currentPattern);
  1617. return song;
  1618. }
  1619. bool save (const Song& song, const juce::File& file, juce::String& error)
  1620. {
  1621. // Write to a temp file and swap, so a mid-write error doesn't destroy the previous project.
  1622. juce::TemporaryFile temp (file);
  1623. if (! temp.getFile().replaceWithText (toJson (song)) || ! temp.overwriteTargetFileWithTemporary())
  1624. {
  1625. error = utf8 ("could not write ") + file.getFullPathName();
  1626. return false;
  1627. }
  1628. return true;
  1629. }
  1630. std::optional<Song> load (const juce::File& file, juce::String& error)
  1631. {
  1632. if (! file.existsAsFile())
  1633. {
  1634. error = utf8 ("file not found");
  1635. return std::nullopt;
  1636. }
  1637. auto song = fromJson (file.loadFileAsString(), error);
  1638. // samples saved relative to the project (a package) or moved along with it are found next to it (REA round 118)
  1639. if (song)
  1640. safety::resolveProjectSamples (*song, file.getParentDirectory().getFullPathName().toStdString(), [] (const std::string& path) {
  1641. return juce::File::isAbsolutePath (juce::String::fromUTF8 (path.c_str())) && juce::File (juce::String::fromUTF8 (path.c_str())).existsAsFile();
  1642. });
  1643. return song;
  1644. }
  1645. juce::String mixerTrackStateToJson (const MixerTrack& track)
  1646. {
  1647. // the track's own settings and effects; routing, audio input, mute and solo belong to the project
  1648. auto state = track;
  1649. state.sends.clear();
  1650. state.toMaster = true;
  1651. state.masterLevel = 1.0f;
  1652. state.inputChannel = -1;
  1653. state.monitor = InputMonitor::automatic;
  1654. state.muted = state.solo = false;
  1655. auto root = std::make_unique<juce::DynamicObject>();
  1656. root->setProperty ("format", "lynx-mixer-track");
  1657. root->setProperty ("version", 1);
  1658. root->setProperty ("track", mixerTrackToVar (state));
  1659. return juce::JSON::toString (juce::var (root.release()));
  1660. }
  1661. std::optional<MixerTrack> mixerTrackStateFromJson (const juce::String& json, juce::String& error)
  1662. {
  1663. const auto root = juce::JSON::parse (json);
  1664. if (root["format"].toString() != "lynx-mixer-track" || ! root["track"].isObject())
  1665. {
  1666. error = utf8 ("not a LYNX mixer track state");
  1667. return std::nullopt;
  1668. }
  1669. return mixerTrackFromVar (root["track"]);
  1670. }
  1671. void applyMixerTrackState (MixerTrack& target, const MixerTrack& state, bool takeName)
  1672. {
  1673. // FL's "Open mixer track state": the effects and the track's settings; the routing stays
  1674. if (takeName && ! state.name.empty())
  1675. target.name = state.name;
  1676. if (takeName || state.colour != 0)
  1677. target.colour = state.colour;
  1678. target.volume = state.volume;
  1679. target.pan = state.pan;
  1680. target.stereo = state.stereo;
  1681. target.invertPhase = state.invertPhase;
  1682. target.swapChannels = state.swapChannels;
  1683. target.eq = state.eq;
  1684. target.threaded = state.threaded;
  1685. target.effects = state.effects;
  1686. }
  1687. } // namespace lynx::ProjectFile