AudioEditor.cpp 178 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067
  1. #include "ui/AudioEditor.h"
  2. #include "ui/AudioEditorTools.h"
  3. #include "ui/BrowserComponent.h"
  4. #include "ui/EditorTools.h"
  5. #include <algorithm>
  6. #include <cmath>
  7. #include <functional>
  8. #include <map>
  9. #include <optional>
  10. #include <thread>
  11. #include <juce_audio_formats/juce_audio_formats.h>
  12. #include "core/AudioCapture.h"
  13. #include "core/AudioEditTools.h"
  14. #include "core/AutoWarp.h"
  15. #include "core/EdisonScript.h"
  16. #include "core/Instruments.h"
  17. #include "core/NewtoneFx.h"
  18. #include "core/WaveAnalysis.h"
  19. #include "core/ValueMath.h"
  20. #include "core/WarpEdit.h"
  21. #include "engine/SampleLibrary.h"
  22. #include "engine/Text.h"
  23. #include "platform/Paths.h"
  24. #include "ui/AudioClipboard.h"
  25. #include "ui/FileChoosers.h"
  26. #include "ui/HintBar.h"
  27. #include "ui/ValueControl.h"
  28. #include "ui/I18n.h"
  29. #include "ui/Icons.h"
  30. #include "ui/Theme.h"
  31. #include "ui/ToolWindow.h"
  32. namespace lynx
  33. {
  34. namespace
  35. {
  36. namespace ae = audioedit;
  37. // one clipboard for every editor window (copy in one, paste in another); Tools › Clipboard saves it (round 181b)
  38. ae::Audio& clipboard()
  39. {
  40. return audioclipboard::editor();
  41. }
  42. // an audio file read on a worker thread (an audio script's Sample.LoadFromFile)
  43. bool readAudioFile (const juce::File& file, ae::Audio& out)
  44. {
  45. juce::AudioFormatManager formats;
  46. formats.registerBasicFormats();
  47. std::unique_ptr<juce::AudioFormatReader> reader (formats.createReaderFor (file));
  48. if (reader == nullptr || reader->lengthInSamples <= 0 || reader->lengthInSamples > (juce::int64) 1 << 31 || reader->numChannels == 0)
  49. return false;
  50. const auto channels = (int) juce::jmin (2u, reader->numChannels);
  51. juce::AudioBuffer<float> buffer (channels, (int) reader->lengthInSamples);
  52. if (! reader->read (&buffer, 0, buffer.getNumSamples(), 0, true, channels > 1))
  53. return false;
  54. out = ae::silence (channels, reader->sampleRate, buffer.getNumSamples());
  55. for (int c = 0; c < channels; ++c)
  56. std::copy (buffer.getReadPointer (c), buffer.getReadPointer (c) + buffer.getNumSamples(), out.channels[(std::size_t) c].begin());
  57. return true;
  58. }
  59. // the clean clip look (docs/analise/UI_STUDY_playlist_clips.md): one light filled shape in a tint of the audio colour
  60. juce::Colour waveColour() { return theme::colour::audioClip.interpolatedWith (juce::Colours::white, 0.7f); }
  61. enum class TimeFormat
  62. {
  63. automatic,
  64. samples,
  65. seconds,
  66. bars
  67. };
  68. enum class RecordMode
  69. {
  70. now, // starts at once
  71. onInput, // starts when the input goes above the threshold
  72. onPlay // starts with the song playback, stops with it
  73. };
  74. constexpr float inputThreshold = 0.01f; // -40 dBFS
  75. juce::String formatSeconds (double s)
  76. {
  77. const auto negative = s < 0.0;
  78. s = std::abs (s);
  79. const auto minutes = (int) (s / 60.0);
  80. const auto rest = s - minutes * 60.0;
  81. return juce::String (negative ? "-" : "") + juce::String (minutes) + ":" + juce::String (rest, 3).paddedLeft ('0', 6);
  82. }
  83. // Spectrogram colours (LYNX's own map): the canvas, a deep red, the accent, amber, then white for the loudest.
  84. juce::Colour spectrumColour (float db)
  85. {
  86. const auto t = juce::jlimit (0.0f, 1.0f, (db + 96.0f) / 96.0f);
  87. static const juce::Colour stops[] = { theme::colour::bg0, juce::Colour (0xff3a1016), theme::colour::accent, theme::colour::warning,
  88. juce::Colour (0xfffff4dc) };
  89. static const float at[] = { 0.0f, 0.35f, 0.62f, 0.85f, 1.0f };
  90. for (int i = 1; i < 5; ++i)
  91. if (t <= at[i])
  92. return stops[i - 1].interpolatedWith (stops[i], (t - at[i - 1]) / (at[i] - at[i - 1]));
  93. return stops[4];
  94. }
  95. // --- a small parameter window for the tools (sliders + an optional choice; Preview / Accept / Cancel) ------------
  96. class ToolPanel final : public juce::Component
  97. {
  98. public:
  99. struct Param
  100. {
  101. juce::String name;
  102. double min = 0.0, max = 1.0, value = 0.0, step = 0.0;
  103. juce::String suffix;
  104. };
  105. using Action = std::function<void (const std::vector<double>&, int)>;
  106. ToolPanel (std::vector<Param> ps, juce::StringArray choices, const juce::String& choiceName, int choice, Action applyAction, Action previewAction)
  107. : params (std::move (ps)), apply (std::move (applyAction)), preview (std::move (previewAction))
  108. {
  109. for (const auto& p : params)
  110. {
  111. auto* label = labels.add (new juce::Label ({}, p.name));
  112. label->setFont (theme::font (theme::type::body));
  113. label->setColour (juce::Label::textColourId, theme::colour::textSecondary);
  114. addAndMakeVisible (label);
  115. auto* s = sliders.add (new juce::Slider (juce::Slider::LinearHorizontal, juce::Slider::TextBoxRight));
  116. s->setRange (p.min, p.max, p.step);
  117. s->setValue (p.value, juce::dontSendNotification);
  118. s->setDoubleClickReturnValue (true, p.value);
  119. s->setTextValueSuffix (p.suffix);
  120. s->setTextBoxStyle (juce::Slider::TextBoxRight, false, 84, 22);
  121. addAndMakeVisible (s);
  122. }
  123. if (! choices.isEmpty())
  124. {
  125. choiceLabel.setText (choiceName, juce::dontSendNotification);
  126. choiceLabel.setFont (theme::font (theme::type::body));
  127. choiceLabel.setColour (juce::Label::textColourId, theme::colour::textSecondary);
  128. addAndMakeVisible (choiceLabel);
  129. choiceBox.addItemList (choices, 1);
  130. choiceBox.setSelectedItemIndex (choice, juce::dontSendNotification);
  131. addAndMakeVisible (choiceBox);
  132. }
  133. previewButton.setButtonText (tr ("Preview"));
  134. acceptButton.setButtonText (tr ("Accept"));
  135. cancelButton.setButtonText (tr ("Cancel"));
  136. acceptButton.setColour (juce::TextButton::buttonColourId, theme::colour::accent);
  137. previewButton.onClick = [this] {
  138. if (preview)
  139. preview (values(), choiceBox.getSelectedItemIndex());
  140. };
  141. acceptButton.onClick = [this] {
  142. if (apply)
  143. apply (values(), choiceBox.getSelectedItemIndex());
  144. closeToolWindowOf (*this);
  145. };
  146. cancelButton.onClick = [this] { closeToolWindowOf (*this); };
  147. previewButton.setVisible (preview != nullptr);
  148. for (auto* b : { &previewButton, &acceptButton, &cancelButton })
  149. addAndMakeVisible (*b);
  150. setSize (420, 24 + (int) params.size() * 36 + (choices.isEmpty() ? 0 : 36) + 52);
  151. }
  152. void paint (juce::Graphics& g) override { g.fillAll (theme::colour::bg2); }
  153. void resized() override
  154. {
  155. auto area = getLocalBounds().reduced (theme::space::lg);
  156. if (choiceBox.getNumItems() > 0)
  157. {
  158. auto row = area.removeFromTop (28);
  159. choiceLabel.setBounds (row.removeFromLeft (120));
  160. choiceBox.setBounds (row);
  161. area.removeFromTop (8);
  162. }
  163. for (int i = 0; i < sliders.size(); ++i)
  164. {
  165. auto row = area.removeFromTop (28);
  166. labels[i]->setBounds (row.removeFromLeft (120));
  167. sliders[i]->setBounds (row);
  168. area.removeFromTop (8);
  169. }
  170. auto buttons = area.removeFromBottom (30);
  171. cancelButton.setBounds (buttons.removeFromRight (90));
  172. buttons.removeFromRight (8);
  173. acceptButton.setBounds (buttons.removeFromRight (90));
  174. buttons.removeFromRight (8);
  175. previewButton.setBounds (buttons.removeFromRight (90));
  176. }
  177. private:
  178. std::vector<double> values() const
  179. {
  180. std::vector<double> v;
  181. for (auto* s : sliders)
  182. v.push_back (s->getValue());
  183. return v;
  184. }
  185. std::vector<Param> params;
  186. juce::OwnedArray<juce::Label> labels;
  187. juce::OwnedArray<juce::Slider> sliders;
  188. juce::Label choiceLabel;
  189. juce::ComboBox choiceBox;
  190. juce::TextButton previewButton, acceptButton, cancelButton;
  191. Action apply, preview;
  192. };
  193. // --- Edison's script form ("Configure script", REA_rodada167c.md §2): the controls a script's ScriptDialog asks for;
  194. // Preview (automatic, when a control changes) / Regenerate / Reset / Edit script / Run / Cancel ------------------------
  195. class ScriptPanel final : public juce::Component,
  196. private juce::Timer
  197. {
  198. public:
  199. using Answer = std::function<void (const ae::script::Form&)>;
  200. ScriptPanel (ae::script::Form f, Answer runAction, Answer previewAction, std::function<void()> editAction)
  201. : form (std::move (f)), defaults (form), run (std::move (runAction)), preview (std::move (previewAction)), edit (std::move (editAction))
  202. {
  203. header.setText (juce::String::fromUTF8 (form.title.c_str()), juce::dontSendNotification);
  204. header.setFont (theme::font (theme::type::title));
  205. header.setColour (juce::Label::textColourId, theme::colour::textPrimary);
  206. addAndMakeVisible (header);
  207. description.setText (juce::String::fromUTF8 (form.description.c_str()), juce::dontSendNotification);
  208. description.setFont (theme::font (theme::type::body));
  209. description.setColour (juce::Label::textColourId, theme::colour::textSecondary);
  210. description.setJustificationType (juce::Justification::topLeft);
  211. description.setVisible (! form.description.empty());
  212. addChildComponent (description);
  213. using T = ae::script::Control::Type;
  214. for (std::size_t i = 0; i < form.controls.size(); ++i)
  215. {
  216. const auto& c = form.controls[i];
  217. auto* label = labels.add (new juce::Label ({}, juce::String::fromUTF8 (c.name.c_str())));
  218. label->setFont (theme::font (theme::type::body));
  219. label->setColour (juce::Label::textColourId, theme::colour::textSecondary);
  220. label->setTooltip (juce::String::fromUTF8 (c.hint.c_str()));
  221. addAndMakeVisible (label);
  222. std::unique_ptr<juce::Component> editor;
  223. switch (c.type)
  224. {
  225. case T::value:
  226. case T::knob:
  227. case T::knobInt:
  228. {
  229. auto s = std::make_unique<juce::Slider> (juce::Slider::LinearHorizontal, juce::Slider::TextBoxRight);
  230. const auto lo = std::min (c.minimum, c.maximum), hi = std::max (c.minimum, c.maximum);
  231. s->setRange (lo, hi > lo ? hi : lo + 1.0, c.type == T::knobInt ? 1.0 : 0.0);
  232. s->setNumDecimalPlacesToDisplay (c.type == T::knobInt ? 0 : 3);
  233. s->setValue (c.value, juce::dontSendNotification);
  234. s->setTextBoxStyle (juce::Slider::TextBoxRight, false, 84, 22);
  235. s->onValueChange = [this, i, p = s.get()] {
  236. form.controls[i].value = p->getValue();
  237. changed();
  238. };
  239. editor = std::move (s);
  240. break;
  241. }
  242. case T::combo:
  243. {
  244. auto b = std::make_unique<juce::ComboBox>();
  245. for (std::size_t o = 0; o < c.options.size(); ++o)
  246. b->addItem (juce::String::fromUTF8 (c.options[o].c_str()), (int) o + 1);
  247. b->setSelectedItemIndex ((int) c.value, juce::dontSendNotification);
  248. b->onChange = [this, i, p = b.get()] {
  249. form.controls[i].value = juce::jmax (0, p->getSelectedItemIndex());
  250. changed();
  251. };
  252. editor = std::move (b);
  253. break;
  254. }
  255. case T::checkbox:
  256. {
  257. auto b = std::make_unique<juce::ToggleButton>();
  258. b->setToggleState (c.value != 0.0, juce::dontSendNotification);
  259. b->onClick = [this, i, p = b.get()] {
  260. form.controls[i].value = p->getToggleState() ? 1.0 : 0.0;
  261. changed();
  262. };
  263. editor = std::move (b);
  264. break;
  265. }
  266. case T::text:
  267. {
  268. auto t = std::make_unique<juce::TextEditor>();
  269. t->setText (juce::String::fromUTF8 (c.text.c_str()), false);
  270. t->onTextChange = [this, i, p = t.get()] {
  271. form.controls[i].text = p->getText().toStdString();
  272. changed();
  273. };
  274. editor = std::move (t);
  275. break;
  276. }
  277. case T::surface:
  278. {
  279. auto l = std::make_unique<juce::Label> (juce::String {}, tr ("(Control Surface presets are not available in LYNX SHARE)"));
  280. l->setFont (theme::font (theme::type::caption));
  281. l->setColour (juce::Label::textColourId, theme::colour::textDisabled);
  282. editor = std::move (l);
  283. break;
  284. }
  285. }
  286. addAndMakeVisible (*editor);
  287. editors.push_back (std::move (editor));
  288. }
  289. previewToggle.setButtonText (tr ("Preview"));
  290. previewToggle.setTooltip (tr ("Automatic preview when controls are modified"));
  291. previewToggle.onClick = [this] {
  292. if (previewToggle.getToggleState())
  293. startTimer (1);
  294. else
  295. stopTimer();
  296. };
  297. regenerateButton.setButtonText (tr ("Regenerate"));
  298. regenerateButton.onClick = [this] { startTimer (1); };
  299. resetButton.setButtonText (tr ("Reset"));
  300. resetButton.onClick = [this] { reset(); };
  301. editButton.setButtonText (tr ("Edit script"));
  302. editButton.onClick = [this] {
  303. if (edit)
  304. edit();
  305. };
  306. runButton.setButtonText (tr ("Run"));
  307. runButton.setColour (juce::TextButton::buttonColourId, theme::colour::accent);
  308. runButton.onClick = [this] {
  309. stopTimer();
  310. const auto f = form;
  311. auto action = run;
  312. closeToolWindowOf (*this); // (deletes this)
  313. if (action)
  314. action (f);
  315. };
  316. cancelButton.setButtonText (tr ("Cancel"));
  317. cancelButton.onClick = [this] { closeToolWindowOf (*this); };
  318. for (juce::Component* b : { (juce::Component*) &previewToggle, (juce::Component*) &regenerateButton, (juce::Component*) &resetButton,
  319. (juce::Component*) &editButton, (juce::Component*) &runButton, (juce::Component*) &cancelButton })
  320. addAndMakeVisible (*b);
  321. editButton.setVisible (edit != nullptr);
  322. previewToggle.setVisible (preview != nullptr);
  323. regenerateButton.setVisible (preview != nullptr);
  324. setSize (500, 24 + 34 + (form.description.empty() ? 0 : 44) + (int) form.controls.size() * 36 + 52);
  325. }
  326. void paint (juce::Graphics& g) override { g.fillAll (theme::colour::bg2); }
  327. void resized() override
  328. {
  329. auto area = getLocalBounds().reduced (theme::space::lg);
  330. header.setBounds (area.removeFromTop (26));
  331. area.removeFromTop (8);
  332. if (description.isVisible())
  333. {
  334. description.setBounds (area.removeFromTop (36));
  335. area.removeFromTop (8);
  336. }
  337. for (std::size_t i = 0; i < editors.size(); ++i)
  338. {
  339. auto row = area.removeFromTop (28);
  340. labels[(int) i]->setBounds (row.removeFromLeft (150));
  341. editors[i]->setBounds (row);
  342. area.removeFromTop (8);
  343. }
  344. auto buttons = area.removeFromBottom (30);
  345. previewToggle.setBounds (buttons.removeFromLeft (84));
  346. regenerateButton.setBounds (buttons.removeFromLeft (92));
  347. cancelButton.setBounds (buttons.removeFromRight (70));
  348. buttons.removeFromRight (6);
  349. runButton.setBounds (buttons.removeFromRight (70));
  350. buttons.removeFromRight (6);
  351. editButton.setBounds (buttons.removeFromRight (82));
  352. buttons.removeFromRight (6);
  353. resetButton.setBounds (buttons.removeFromRight (64));
  354. }
  355. private:
  356. void changed()
  357. {
  358. if (previewToggle.getToggleState())
  359. startTimer (250); // (a drag previews once it pauses)
  360. }
  361. void timerCallback() override
  362. {
  363. stopTimer();
  364. if (preview)
  365. preview (form);
  366. }
  367. void reset()
  368. {
  369. using T = ae::script::Control::Type;
  370. form = defaults;
  371. for (std::size_t i = 0; i < form.controls.size(); ++i)
  372. {
  373. const auto& c = form.controls[i];
  374. auto* e = editors[i].get();
  375. if (auto* s = dynamic_cast<juce::Slider*> (e))
  376. s->setValue (c.value, juce::dontSendNotification);
  377. else if (auto* b = dynamic_cast<juce::ComboBox*> (e))
  378. b->setSelectedItemIndex ((int) c.value, juce::dontSendNotification);
  379. else if (auto* t = dynamic_cast<juce::ToggleButton*> (e))
  380. t->setToggleState (c.value != 0.0, juce::dontSendNotification);
  381. else if (auto* x = dynamic_cast<juce::TextEditor*> (e); x != nullptr && c.type == T::text)
  382. x->setText (juce::String::fromUTF8 (c.text.c_str()), false);
  383. }
  384. changed();
  385. }
  386. ae::script::Form form, defaults;
  387. Answer run, preview;
  388. std::function<void()> edit;
  389. juce::Label header, description;
  390. juce::OwnedArray<juce::Label> labels;
  391. std::vector<std::unique_ptr<juce::Component>> editors;
  392. juce::ToggleButton previewToggle;
  393. juce::TextButton regenerateButton, resetButton, editButton, runButton, cancelButton;
  394. };
  395. // --- the editor --------------------------------------------------------------------------------------------------
  396. struct Source
  397. {
  398. enum class Kind
  399. {
  400. none,
  401. file,
  402. channel,
  403. insert
  404. };
  405. Kind kind = Kind::none;
  406. int index = -1; // channel or insert
  407. juce::String path;
  408. int clip = -1; // a channel opened from a Playlist audio clip: that clip
  409. };
  410. class AudioEditor final : public juce::Component,
  411. public juce::FileDragAndDropTarget,
  412. public audiotools::Host,
  413. public juce::DragAndDropTarget,
  414. private juce::Timer
  415. {
  416. public:
  417. AudioEditor (AudioEngine& e, Source s) : engine (e), source (std::move (s))
  418. {
  419. auto setupIcon = [this] (IconButton& b, const juce::String& tip) {
  420. b.setFlat (true);
  421. b.setTooltip (tip);
  422. addAndMakeVisible (b);
  423. };
  424. setupIcon (menuButton, tr ("Menu: file, edit, tools, regions, view"));
  425. setupIcon (undoButton, tr ("Undo") + " (Ctrl+Z)");
  426. setupIcon (redoButton, tr ("Redo") + " (Ctrl+Y)");
  427. setupIcon (historyButton, tr ("Undo history"));
  428. setupIcon (recordButton, tr ("Record") + " (R)");
  429. setupIcon (recordMenuButton, tr ("What and when to record"));
  430. setupIcon (playButton, tr ("Play / stop the selection") + " (Space)");
  431. setupIcon (stopButton, tr ("Stop"));
  432. setupIcon (snapButton, tr ("Snap the selection to zero crossings"));
  433. setupIcon (fitButton, tr ("Zoom out full"));
  434. setupIcon (saveButton, tr ("Save as WAV..."));
  435. // Follow (issue #12): the view pages along with the playback position; off, it stays where you look
  436. setupIcon (followButton, tr ("Follow: the view pages along with the playback position; off, it stays where you scrolled"));
  437. followButton.setClickingTogglesState (false);
  438. followButton.setOnColour (theme::colour::bg6);
  439. followButton.setIconColourWhenOn (theme::colour::accent);
  440. followButton.setToggleState (EditorGlobals::get().isFollowingView (EditorGlobals::FollowView::audioEditor), juce::dontSendNotification);
  441. followButton.onClick = [this] {
  442. auto& g = EditorGlobals::get();
  443. g.setFollowingView (EditorGlobals::FollowView::audioEditor, ! g.isFollowingView (EditorGlobals::FollowView::audioEditor));
  444. followButton.setToggleState (g.isFollowingView (EditorGlobals::FollowView::audioEditor), juce::dontSendNotification);
  445. };
  446. recordButton.setOnColour (theme::colour::record);
  447. recordButton.setClickingTogglesState (false);
  448. snapButton.setClickingTogglesState (true);
  449. menuButton.onClick = [this] { mainMenu().showMenuAsync (juce::PopupMenu::Options().withTargetComponent (&menuButton)); };
  450. warpButton.setButtonText (tr ("Warp markers")); // ("Warp" alone is a synth control's name in the tables)
  451. warpButton.setTooltip (tr ("Warp markers: tie points of the audio to beats; the audio between them stretches (the channel's markers)"));
  452. warpButton.setClickingTogglesState (true);
  453. warpButton.setColour (juce::TextButton::buttonOnColourId, theme::colour::accent);
  454. warpButton.onClick = [this] { setWarpMode (warpButton.getToggleState()); };
  455. autoWarpButton.setButtonText (tr ("Auto-warp"));
  456. autoWarpButton.setTooltip (tr ("Place warp markers from the tempo (the file name's, else its length) and, in a long recording, on every bar"));
  457. autoWarpButton.onClick = [this] { autoWarp(); };
  458. addChildComponent (warpButton);
  459. addChildComponent (autoWarpButton);
  460. warpButton.setVisible (source.kind == Source::Kind::channel);
  461. undoButton.onClick = [this] { undo(); };
  462. redoButton.onClick = [this] { redo(); };
  463. historyButton.onClick = [this] { historyMenu().showMenuAsync (juce::PopupMenu::Options().withTargetComponent (&historyButton)); };
  464. recordButton.onClick = [this] { toggleRecording(); };
  465. recordMenuButton.onClick = [this] { recordMenu().showMenuAsync (juce::PopupMenu::Options().withTargetComponent (&recordMenuButton)); };
  466. playButton.onClick = [this] { playing ? stopPlayback() : startPlayback(); };
  467. stopButton.onClick = [this] {
  468. stopPlayback();
  469. if (recState != RecState::idle)
  470. stopRecording();
  471. };
  472. snapButton.onClick = [this] { snapZero = snapButton.getToggleState(); };
  473. fitButton.onClick = [this] { zoomToFit(); };
  474. saveButton.onClick = [this] { saveAs (bits); };
  475. auto setupText = [this] (juce::TextButton& b, const juce::String& text, const juce::String& tip) {
  476. b.setButtonText (text);
  477. b.setTooltip (tip);
  478. addAndMakeVisible (b);
  479. };
  480. setupText (loopButton, tr ("Loop"), tr ("Loop the playback") + " (L)");
  481. loopButton.setClickingTogglesState (true);
  482. loopButton.setColour (juce::TextButton::buttonOnColourId, theme::colour::accent);
  483. loopButton.onClick = [this] {
  484. loopPlay = loopButton.getToggleState();
  485. if (playing)
  486. startPlayback();
  487. };
  488. // the playback volume (round 162, issue #9): how loud the editor plays, without changing the audio (the
  489. // Amp... tool changes the audio itself); remembered with the settings
  490. volumeKnob.setRange (0.0, controls::maxUtilityVolume, 0.01);
  491. volumeKnob.setDoubleClickReturnValue (true, 1.0);
  492. volumeKnob.textFromValueFunction = [] (double v) { return ui::utilityVolumeText (v); };
  493. volumeKnob.valueFromTextFunction = [] (const juce::String& t) { return t.retainCharacters ("0123456789.").getDoubleValue() / 100.0; };
  494. volumeKnob.setMouseClickGrabsKeyboardFocus (false);
  495. volumeKnob.setWantsKeyboardFocus (false);
  496. volumeKnob.setValue (engine.getEditorVolume(), juce::dontSendNotification);
  497. volumeKnob.onValueChange = [this] {
  498. engine.setEditorVolume (volumeKnob.getValue());
  499. refreshVolumeKnob();
  500. };
  501. addAndMakeVisible (volumeKnob);
  502. refreshVolumeKnob();
  503. setupText (viewButton, tr ("Spectrum"), tr ("Show the waveform or the spectrogram") + " (S)");
  504. viewButton.setClickingTogglesState (true);
  505. viewButton.setColour (juce::TextButton::buttonOnColourId, theme::colour::accent);
  506. viewButton.onClick = [this] {
  507. spectrumView = viewButton.getToggleState();
  508. repaint();
  509. };
  510. setupText (envButton, tr ("Edit: Wave"), tr ("What the mouse edits: the waveform, or the volume / panning / stereo separation envelope drawn over it (E)"));
  511. envButton.onClick = [this] { envModeMenu().showMenuAsync (juce::PopupMenu::Options().withTargetComponent (&envButton)); };
  512. setupText (sendButton, tr ("Send"), tr ("Send to the Playlist as an audio clip, to a new Sampler channel or back to the channel"));
  513. sendButton.setColour (juce::TextButton::buttonColourId, theme::colour::accentMuted);
  514. sendButton.onClick = [this] { sendMenu().showMenuAsync (juce::PopupMenu::Options().withTargetComponent (&sendButton)); };
  515. // quick tools (the second row)
  516. struct Quick
  517. {
  518. const char* text;
  519. const char* tip;
  520. std::function<void()> action;
  521. };
  522. const Quick quick[] = {
  523. { TR_NOOP ("Cut"), TR_NOOP ("Cut the selection (Ctrl+X)"), [this] { cutSelection(); } },
  524. { TR_NOOP ("Copy"), TR_NOOP ("Copy the selection (Ctrl+C)"), [this] { copySelection(); } },
  525. { TR_NOOP ("Paste"), TR_NOOP ("Paste at the cursor, or over the selection (Ctrl+V)"), [this] { paste (false); } },
  526. { TR_NOOP ("Delete"), TR_NOOP ("Delete the selection (Del)"), [this] { deleteSelection(); } },
  527. { TR_NOOP ("Trim"), TR_NOOP ("Keep only the selection"), [this] { trimSelection(); } },
  528. { TR_NOOP ("Silence"), TR_NOOP ("Silence the selection (Clear)"), [this] { edit (tr ("Silence"), [] (ae::Document& d, ae::Range r) { ae::clear (d, r); }, true); } },
  529. { TR_NOOP ("Fade in"), TR_NOOP ("Fade in over the selection (curve: the arrow next to Fade out)"), [this] { fade (true); } },
  530. { TR_NOOP ("Fade out"), TR_NOOP ("Fade out over the selection"), [this] { fade (false); } },
  531. { "~", TR_NOOP ("Fade curve"), [this] { curveMenu().showMenuAsync (juce::PopupMenu::Options().withTargetComponent (quickButtons[8])); } },
  532. { TR_NOOP ("Normalize"), TR_NOOP ("Normalize the selection (or everything) to 0 dB"), [this] { edit (tr ("Normalize"), [] (ae::Document& d, ae::Range r) { ae::normalize (d, r); }); } },
  533. { TR_NOOP ("Amp..."), TR_NOOP ("Volume and panning"), [this] { showAmp(); } },
  534. { TR_NOOP ("Reverse"), TR_NOOP ("Reverse the selection (or everything)"), [this] { edit (tr ("Reverse"), [] (ae::Document& d, ae::Range r) { ae::reverse (d, r); }); } },
  535. { TR_NOOP ("Invert"), TR_NOOP ("Reverse the polarity"), [this] { edit (tr ("Reverse polarity"), [] (ae::Document& d, ae::Range r) { ae::invert (d, r); }); } },
  536. { TR_NOOP ("Center"), TR_NOOP ("Remove the DC offset"), [this] { edit (tr ("Remove DC offset"), [] (ae::Document& d, ae::Range r) { ae::removeDc (d, r); }); } },
  537. { TR_NOOP ("Stretch..."), TR_NOOP ("Time stretch / pitch shift"), [this] { openEdisonTool (audiotools::Tool::stretch); } },
  538. { TR_NOOP ("Resample..."), TR_NOOP ("Change the sample rate"), [this] { showResample(); } },
  539. { TR_NOOP ("Marker"), TR_NOOP ("Add a marker at the cursor (M)"), [this] { addMarkerAtCursor(); } },
  540. { TR_NOOP ("Region"), TR_NOOP ("Make the selection a region"), [this] { addRegionFromSelection(); } },
  541. { TR_NOOP ("Set loop"), TR_NOOP ("Make the selection the loop"), [this] { setLoopFromSelection(); } },
  542. };
  543. for (const auto& q : quick)
  544. {
  545. auto* b = quickButtons.add (new juce::TextButton (q.text[0] == '~' ? juce::String (juce::CharPointer_UTF8 ("\xe2\x96\xbe")) : tr (q.text)));
  546. b->setTooltip (tr (q.tip));
  547. b->onClick = q.action;
  548. addAndMakeVisible (b);
  549. }
  550. setWantsKeyboardFocus (true);
  551. setSize (1120, 600);
  552. history.reset (doc, tr ("Empty").toStdString());
  553. updateButtons();
  554. startTimerHz (30);
  555. }
  556. ~AudioEditor() override
  557. {
  558. if (playing)
  559. engine.previewSample (nullptr);
  560. if (recState != RecState::idle)
  561. engine.getMeters().capture.setSource (AudioCapture::off);
  562. releaseInput();
  563. }
  564. // --- opening ---------------------------------------------------------------------------------------------
  565. bool loadFile (const juce::File& file)
  566. {
  567. auto data = engine.getSampleLibrary().load (file.getFullPathName());
  568. if (data == nullptr)
  569. {
  570. setStatus (tr ("Could not read {0}", { file.getFileName() }), true);
  571. return false;
  572. }
  573. ae::Document d;
  574. d.audio.sampleRate = data->sampleRate;
  575. d.audio.channels.emplace_back (data->leftData(), data->leftData() + data->frames());
  576. if (data->isStereo())
  577. d.audio.channels.emplace_back (data->rightData(), data->rightData() + data->frames());
  578. if (data->loopStart >= 0 && data->loopEnd > data->loopStart)
  579. ae::setLoop (d, { data->loopStart, data->loopEnd });
  580. if (file.hasFileExtension ("wav"))
  581. {
  582. juce::MemoryBlock bytes;
  583. if (file.loadFileAsData (bytes))
  584. {
  585. ae::Document marks = d;
  586. if (ae::decodeWavMarkers (static_cast<const std::uint8_t*> (bytes.getData()), bytes.getSize(), marks))
  587. {
  588. d.markers = marks.markers;
  589. if (marks.hasLoop())
  590. ae::setLoop (d, { marks.loopStart, marks.loopEnd });
  591. }
  592. }
  593. }
  594. d.title = file.getFileNameWithoutExtension().toStdString();
  595. setDocument (std::move (d), tr ("Open"));
  596. lastFile = file;
  597. return true;
  598. }
  599. void setDocument (ae::Document d, const juce::String& label)
  600. {
  601. doc = std::move (d);
  602. history.reset (doc, label.toStdString());
  603. selection = {};
  604. cursor = 0;
  605. modified = false;
  606. documentChanged();
  607. zoomToFit();
  608. updateTitle();
  609. }
  610. void selectForSnapshot (ae::Range r, bool spectrum)
  611. {
  612. selection = r;
  613. cursor = r.start;
  614. spectrumView = spectrum;
  615. viewButton.setToggleState (spectrum, juce::dontSendNotification);
  616. repaint();
  617. }
  618. juce::PopupMenu mainMenu();
  619. // --- warp markers (round 175a, M3) ------------------------------------------------------------------------
  620. // The channel's markers sit in a lane above the waveform, each at the file time it ties to, labelled with its
  621. // beat (bar.beat). Drag one sideways to tie its beat to another point of the audio (it snaps to the attacks,
  622. // shown as small ticks; [Alt] no snap); double-click the lane to add a marker or to remove one; Del removes the
  623. // selected one. Edits go to the song at once (undoable there); opened from a Playlist clip whose channel other
  624. // clips share, the clip first gets its own copy of the channel, so the others keep their timing.
  625. const ChannelDef* warpChannel() const
  626. {
  627. const auto& song = engine.getSong();
  628. return source.kind == Source::Kind::channel && juce::isPositiveAndBelow (source.index, (int) song.channels.size())
  629. ? &song.channels[(std::size_t) source.index]
  630. : nullptr;
  631. }
  632. double warpFileSeconds() const
  633. {
  634. if (const auto* c = warpChannel())
  635. if (const auto data = engine.getSampleLibrary().findLoaded (juce::String::fromUTF8 (c->samplePath.c_str())); data != nullptr && data->sampleRate > 0.0)
  636. return (double) data->frames() / data->sampleRate;
  637. return doc.audio.sampleRate > 0.0 ? (double) doc.audio.frames() / doc.audio.sampleRate : 0.0;
  638. }
  639. std::vector<WarpPoint> warpMarkers() const
  640. {
  641. const auto* c = warpChannel();
  642. return c != nullptr && c->sampler.keepPitch && c->sampler.warp.size() >= 2 ? c->sampler.warp : std::vector<WarpPoint> {};
  643. }
  644. void setWarpModeForPanel (bool on) { setWarpMode (on); }
  645. void setWarpMode (bool on)
  646. {
  647. warpMode = on && source.kind == Source::Kind::channel;
  648. warpButton.setToggleState (warpMode, juce::dontSendNotification);
  649. autoWarpButton.setVisible (warpMode);
  650. warpSelected = warpDrag = -1;
  651. resized();
  652. repaint();
  653. }
  654. void editWarp (const std::function<void (SamplerSettings&, double)>& fn)
  655. {
  656. const auto seconds = warpFileSeconds();
  657. if (source.kind != Source::Kind::channel || ! (seconds > 0.0))
  658. return;
  659. auto channel = source.index;
  660. engine.editSong ([&, clip = source.clip] (Song& s) {
  661. if (clip >= 0)
  662. if (const auto own = warpedit::channelForClipEdit (s, clip); own >= 0)
  663. channel = own;
  664. if (! juce::isPositiveAndBelow (channel, (int) s.channels.size()))
  665. return;
  666. auto& sampler = s.channels[(std::size_t) channel].sampler;
  667. warpedit::ensureMarkers (sampler, seconds, s.bpm);
  668. fn (sampler, seconds);
  669. warpedit::syncLength (sampler, seconds);
  670. });
  671. source.index = channel;
  672. repaint();
  673. }
  674. void findWarpAttacks()
  675. {
  676. if (warpAttacksOf == doc.audio.channels.data() && ! warpAttacks.empty())
  677. return;
  678. warpAttacks.clear();
  679. warpAttacksOf = doc.audio.channels.data();
  680. if (doc.audio.empty() || ! (doc.audio.sampleRate > 0.0))
  681. return;
  682. std::vector<float> mono (doc.audio.channels[0]);
  683. if (doc.audio.numChannels() > 1)
  684. for (std::size_t i = 0; i < mono.size(); ++i)
  685. mono[i] = 0.5f * (mono[i] + doc.audio.channels[1][i]);
  686. for (const auto a : stretchdetail::detectAttacks (mono.data(), (long) mono.size(), doc.audio.sampleRate, 6.0))
  687. warpAttacks.push_back ((double) a / doc.audio.sampleRate);
  688. }
  689. double secondsToX (double seconds) const { return frameToX (seconds * doc.audio.sampleRate); }
  690. int warpMarkerAtX (int x) const
  691. {
  692. const auto markers = warpMarkers();
  693. int best = -1;
  694. double bestDx = 5.0;
  695. for (std::size_t k = 0; k < markers.size(); ++k)
  696. if (const auto dx = std::abs (secondsToX (markers[k].seconds) - x); dx <= bestDx)
  697. {
  698. bestDx = dx;
  699. best = (int) k;
  700. }
  701. return best;
  702. }
  703. void paintWarpLane (juce::Graphics& g)
  704. {
  705. using namespace theme;
  706. g.setColour (colour::bg1);
  707. g.fillRect (warpLane);
  708. if (doc.audio.empty())
  709. return;
  710. findWarpAttacks();
  711. // the attacks: short ticks along the lane's bottom
  712. g.setColour (colour::textDisabled.withAlpha (0.45f));
  713. for (const auto a : warpAttacks)
  714. if (const auto x = secondsToX (a); x >= warpLane.getX() && x <= warpLane.getRight())
  715. g.drawVerticalLine ((int) std::round (x), (float) warpLane.getBottom() - 4.0f, (float) warpLane.getBottom());
  716. const auto markers = warpMarkers();
  717. if (markers.empty())
  718. {
  719. g.setColour (colour::textDisabled);
  720. g.setFont (font (type::small));
  721. g.drawText (tr ("No warp markers: double-click here to add one, or Auto-warp"), warpLane.reduced (6, 0), juce::Justification::centredLeft);
  722. return;
  723. }
  724. const auto perBar = juce::jmax (1, engine.getSong().beatsPerBar);
  725. g.setFont (font (type::small));
  726. for (std::size_t k = 0; k < markers.size(); ++k)
  727. {
  728. const auto seconds = (int) k == warpDrag ? warpDragSeconds : markers[k].seconds;
  729. const auto x = (float) secondsToX (seconds);
  730. if (x < warpLane.getX() - 40.0f || x > warpLane.getRight() + 2.0f)
  731. continue;
  732. const auto selected = (int) k == warpSelected;
  733. const auto fill = k == 0 ? colour::textDisabled : (selected ? colour::accent : colour::accent.withMultipliedSaturation (0.55f).brighter (0.2f));
  734. juce::Path flag;
  735. flag.addTriangle (x - 5.0f, (float) warpLane.getY() + 2.0f, x + 5.0f, (float) warpLane.getY() + 2.0f, x, (float) warpLane.getY() + 10.0f);
  736. g.setColour (fill);
  737. g.fillPath (flag);
  738. g.setColour (fill.withAlpha (selected ? 0.8f : 0.4f));
  739. g.drawVerticalLine ((int) std::round (x), (float) warpLane.getY() + 10.0f, (float) waveArea.getBottom());
  740. const auto b = markers[k].beats;
  741. const auto bar = (int) std::floor (b / perBar) + 1;
  742. const auto beat = b - (bar - 1) * perBar + 1.0;
  743. const auto label = juce::String (bar) + "." + (std::abs (beat - std::round (beat)) < 0.005 ? juce::String ((int) std::round (beat)) : juce::String (beat, 2));
  744. g.setColour (colour::textSecondary);
  745. g.drawText (label, juce::Rectangle<float> (x + 6.0f, (float) warpLane.getY(), 48.0f, (float) warpLane.getHeight()), juce::Justification::centredLeft);
  746. }
  747. }
  748. void warpMouseDown (const juce::MouseEvent& e)
  749. {
  750. const auto m = warpMarkerAtX (e.x);
  751. warpSelected = m;
  752. if (m > 0 && ! e.mods.isPopupMenu())
  753. {
  754. warpDrag = m;
  755. warpDragSeconds = warpMarkers()[(std::size_t) m].seconds;
  756. drag = Drag::warp;
  757. }
  758. else if (e.mods.isPopupMenu())
  759. {
  760. juce::PopupMenu menu;
  761. menu.addItem (tr ("Remove this warp marker"), m > 0, false, [this, m] { removeWarpMarker (m); });
  762. menu.addItem (tr ("Auto-warp"), [this] { autoWarp(); });
  763. menu.addItem (tr ("Remove all warp markers"), warpMarkers().size() > 2, false, [this] {
  764. editWarp ([] (SamplerSettings& s, double) { warpedit::clearMarkers (s); });
  765. });
  766. menu.showMenuAsync (juce::PopupMenu::Options().withMousePosition());
  767. }
  768. repaint();
  769. }
  770. void warpMouseDrag (const juce::MouseEvent& e)
  771. {
  772. const auto markers = warpMarkers();
  773. if (warpDrag <= 0 || warpDrag >= (int) markers.size())
  774. return;
  775. auto seconds = (double) xToFrame (e.x) / doc.audio.sampleRate;
  776. if (! e.mods.isAltDown()) // onto an attack within 6 px
  777. for (const auto a : warpAttacks)
  778. if (std::abs (secondsToX (a) - e.x) <= 6.0)
  779. {
  780. seconds = a;
  781. break;
  782. }
  783. const auto lo = markers[(std::size_t) warpDrag - 1].seconds + warpedit::minSecondGap;
  784. const auto hi = warpDrag + 1 < (int) markers.size() ? markers[(std::size_t) warpDrag + 1].seconds - warpedit::minSecondGap : warpFileSeconds();
  785. warpDragSeconds = juce::jlimit (lo, juce::jmax (lo, hi), seconds);
  786. repaint();
  787. }
  788. void warpMouseUp()
  789. {
  790. const auto index = warpDrag, at = warpDrag;
  791. const auto seconds = warpDragSeconds;
  792. warpDrag = -1;
  793. drag = Drag::none;
  794. const auto markers = warpMarkers();
  795. if (index > 0 && index < (int) markers.size() && std::abs (markers[(std::size_t) index].seconds - seconds) > 1.0e-6)
  796. editWarp ([at, seconds] (SamplerSettings& s, double) {
  797. // the marker keeps its beat and ties it to another point of the audio
  798. if (juce::isPositiveAndBelow (at, (int) s.warp.size()))
  799. s.warp[(std::size_t) at].seconds = seconds;
  800. });
  801. repaint();
  802. }
  803. void warpDoubleClick (const juce::MouseEvent& e)
  804. {
  805. if (const auto m = warpMarkerAtX (e.x); m >= 0)
  806. {
  807. removeWarpMarker (m);
  808. return;
  809. }
  810. auto seconds = (double) xToFrame (e.x) / doc.audio.sampleRate;
  811. if (! e.mods.isAltDown())
  812. for (const auto a : warpAttacks)
  813. if (std::abs (secondsToX (a) - e.x) <= 6.0)
  814. {
  815. seconds = a;
  816. break;
  817. }
  818. editWarp ([seconds] (SamplerSettings& s, double) { warpedit::addMarker (s, seconds); });
  819. warpSelected = warpMarkerAtX ((int) std::round (secondsToX (seconds)));
  820. }
  821. void removeWarpMarker (int index)
  822. {
  823. if (index <= 0)
  824. return;
  825. editWarp ([index] (SamplerSettings& s, double) { warpedit::removeMarker (s, index); });
  826. warpSelected = -1;
  827. }
  828. void autoWarp()
  829. {
  830. if (doc.audio.empty() || source.kind != Source::Kind::channel)
  831. return;
  832. SampleData sample;
  833. sample.sampleRate = doc.audio.sampleRate;
  834. sample.left = doc.audio.channels[0];
  835. if (doc.audio.numChannels() > 1)
  836. sample.right = doc.audio.channels[1];
  837. autowarp::Options o;
  838. o.songBpm = engine.getSong().bpm;
  839. o.beatsPerBar = juce::jmax (1, engine.getSong().beatsPerBar);
  840. o.knownBpm = autowarp::bpmInName (juce::File (source.path).getFileNameWithoutExtension().toStdString());
  841. const auto result = autowarp::analyse (sample, o);
  842. if (result.markers.size() < 2)
  843. {
  844. setStatus (tr ("Auto-warp found no beat to lock to"), true);
  845. return;
  846. }
  847. editWarp ([markers = result.markers] (SamplerSettings& s, double) {
  848. s.warp = markers;
  849. s.keepPitch = true;
  850. });
  851. if (! warpMode)
  852. setWarpMode (true);
  853. setStatus (tr ("Auto-warp: {0} markers at {1} BPM", { juce::String ((int) result.markers.size()), juce::String (result.bpm, 2) }), false);
  854. }
  855. void setEnvModeForSnapshot (int mode) { setEnvMode ((EnvMode) juce::jlimit (0, 3, mode)); }
  856. // --- layout and painting ---------------------------------------------------------------------------------
  857. void resized() override
  858. {
  859. auto area = getLocalBounds();
  860. auto bar = area.removeFromTop (36).reduced (6, 4);
  861. auto place = [&bar] (juce::Component& c, int w, int gap = 2) {
  862. c.setBounds (bar.removeFromLeft (w));
  863. bar.removeFromLeft (gap);
  864. };
  865. place (menuButton, 28, 8);
  866. place (undoButton, 28);
  867. place (redoButton, 28);
  868. place (historyButton, 18, 12);
  869. place (recordButton, 30);
  870. place (recordMenuButton, 18, 6);
  871. place (playButton, 30);
  872. place (stopButton, 30, 6);
  873. place (loopButton, 54, 4);
  874. place (volumeKnob, 26, 12);
  875. place (viewButton, 76, 6);
  876. place (envButton, 120, 6);
  877. place (snapButton, 28);
  878. place (fitButton, 28);
  879. place (followButton, 28, 8);
  880. if (warpButton.isVisible())
  881. place (warpButton, 100);
  882. if (autoWarpButton.isVisible())
  883. place (autoWarpButton, 78);
  884. sendButton.setBounds (bar.removeFromRight (70));
  885. bar.removeFromRight (6);
  886. saveButton.setBounds (bar.removeFromRight (28));
  887. // each button gets the width its text needs, plus an equal share of what is left (round 165o: translated
  888. // labels such as "Normalisieren" or "Ausschneiden" are never cut). When one row cannot hold them all (German,
  889. // Russian, Polish… at the default width) the buttons go on two rows instead; English keeps its single row.
  890. const auto n = quickButtons.size();
  891. const auto curveWidth = 18;
  892. const juce::Font font (theme::font (theme::type::body));
  893. std::vector<float> natural;
  894. float total = 0.0f;
  895. for (int i = 0; i < n; ++i)
  896. {
  897. natural.push_back (i == 8 ? (float) curveWidth : juce::GlyphArrangement::getStringWidth (font, quickButtons[i]->getButtonText()) + 18.0f);
  898. total += natural.back() + (i == 7 ? 0.0f : 2.0f);
  899. }
  900. const auto rowWidth = (float) (area.getWidth() - 12);
  901. const auto twoRows = total - 14.0f * (float) (n - 1) > rowWidth && n > 9; // not even with 4 px padding
  902. auto tools = area.removeFromTop (twoRows ? 56 : 30).reduced (6, 2);
  903. // lays out buttons [first, last) in one row: natural widths plus an equal share of the free space; still too
  904. // narrow -> the padding goes first (down to 4 px a side), then the text squeezes (drawFittedText)
  905. auto layoutRow = [&] (juce::Rectangle<int> row, int first, int last)
  906. {
  907. float need = 0.0f;
  908. int stretchable = 0;
  909. for (int i = first; i < last; ++i)
  910. {
  911. need += natural[(std::size_t) i] + (i == 7 || i == last - 1 ? 0.0f : 2.0f);
  912. stretchable += i == 8 ? 0 : 1;
  913. }
  914. const auto avail = (float) row.getWidth();
  915. const auto extra = juce::jmax (0.0f, avail - need) / (float) juce::jmax (1, stretchable);
  916. auto shrink = 0.0f, scale = 1.0f;
  917. if (need > avail)
  918. {
  919. const auto padding = 14.0f * (float) stretchable;
  920. shrink = 14.0f * juce::jlimit (0.0f, 1.0f, (need - avail) / padding);
  921. const auto after = need - shrink * (float) stretchable;
  922. scale = after > avail ? avail / after : 1.0f;
  923. }
  924. float x = (float) row.getX();
  925. for (int i = first; i < last; ++i)
  926. {
  927. const auto w = i == 8 ? (float) curveWidth : (natural[(std::size_t) i] - shrink) * scale + extra;
  928. quickButtons[i]->setBounds (juce::roundToInt (x), row.getY(), juce::roundToInt (x + w) - juce::roundToInt (x), row.getHeight());
  929. x += w + (i == 7 ? 0.0f : 2.0f);
  930. }
  931. };
  932. if (! twoRows)
  933. layoutRow (tools, 0, n);
  934. else
  935. {
  936. // split near half the total width, never between Fade out (7) and its curve menu (8)
  937. int split = 1;
  938. float run = 0.0f;
  939. while (split < n - 1 && run + natural[(std::size_t) split - 1] < total * 0.5f)
  940. run += natural[(std::size_t) split++ - 1] + 2.0f;
  941. if (split == 8)
  942. ++split;
  943. const auto top = tools.removeFromTop (tools.getHeight() / 2);
  944. layoutRow (top.withTrimmedBottom (1), 0, split);
  945. layoutRow (tools.withTrimmedTop (1), split, n);
  946. }
  947. infoArea = area.removeFromBottom (24);
  948. overviewArea = area.removeFromBottom (18).reduced (6, 2);
  949. area.removeFromBottom (2);
  950. area = area.reduced (6, 0);
  951. levelArea = area.removeFromLeft (34);
  952. rulerArea = area.removeFromTop (24);
  953. rulerArea.setX (area.getX());
  954. warpLane = warpMode ? area.removeFromTop (18) : juce::Rectangle<int>();
  955. waveArea = area;
  956. clampView();
  957. }
  958. void paint (juce::Graphics& g) override
  959. {
  960. using namespace theme;
  961. g.fillAll (colour::bg2);
  962. g.setColour (colour::bg3);
  963. g.fillRect (getLocalBounds().removeFromTop (36));
  964. g.setColour (colour::border);
  965. g.drawHorizontalLine (36, 0.0f, (float) getWidth());
  966. paintRuler (g);
  967. paintLevels (g);
  968. if (spectrumView)
  969. paintSpectrum (g);
  970. else
  971. paintWave (g);
  972. paintOverlays (g);
  973. if (warpMode)
  974. paintWarpLane (g);
  975. paintOverview (g);
  976. paintInfo (g);
  977. }
  978. // --- mouse ----------------------------------------------------------------------------------------------
  979. void mouseDown (const juce::MouseEvent& e) override
  980. {
  981. grabKeyboardFocus();
  982. drag = Drag::none;
  983. if (doc.audio.empty())
  984. {
  985. if (e.mods.isPopupMenu())
  986. mainMenu().showMenuAsync (juce::PopupMenu::Options().withMousePosition());
  987. return;
  988. }
  989. const auto pos = e.getPosition();
  990. if (warpMode && warpLane.contains (pos))
  991. {
  992. warpMouseDown (e);
  993. return;
  994. }
  995. if (overviewArea.contains (pos))
  996. {
  997. drag = Drag::overview;
  998. centreViewOnOverview (e.x);
  999. return;
  1000. }
  1001. if (rulerArea.contains (pos))
  1002. {
  1003. // the loop handles live in the ruler's bottom strip
  1004. if (doc.hasLoop() && pos.y >= rulerArea.getBottom() - 7)
  1005. {
  1006. if (std::abs (frameToX ((double) doc.loopStart) - (float) e.x) < 6.0f)
  1007. {
  1008. beginPointDrag (Drag::loopStart);
  1009. return;
  1010. }
  1011. if (std::abs (frameToX ((double) doc.loopEnd) - (float) e.x) < 6.0f)
  1012. {
  1013. beginPointDrag (Drag::loopEnd);
  1014. return;
  1015. }
  1016. }
  1017. if (const auto m = markerAt (e.x); m >= 0)
  1018. {
  1019. if (e.mods.isPopupMenu())
  1020. markerMenu (m).showMenuAsync (juce::PopupMenu::Options().withMousePosition());
  1021. else
  1022. {
  1023. dragMarkerIndex = m;
  1024. beginPointDrag (Drag::marker);
  1025. }
  1026. return;
  1027. }
  1028. }
  1029. if (envMode != EnvMode::wave && waveArea.contains (pos) && envelopeMouseDown (e))
  1030. return;
  1031. if (e.mods.isPopupMenu())
  1032. {
  1033. editMenu (true).showMenuAsync (juce::PopupMenu::Options().withMousePosition());
  1034. return;
  1035. }
  1036. if (waveArea.contains (pos) || rulerArea.contains (pos))
  1037. {
  1038. const auto f = snapFrame (xToFrame (e.x));
  1039. if (e.mods.isShiftDown() && ! selection.empty())
  1040. anchor = std::abs (f - selection.start) < std::abs (f - selection.end) ? selection.end : selection.start;
  1041. else if (e.mods.isShiftDown())
  1042. anchor = cursor;
  1043. else
  1044. anchor = f;
  1045. selection = { std::min (anchor, f), std::max (anchor, f) };
  1046. cursor = f;
  1047. drag = Drag::select;
  1048. if (playing && ! e.mods.isShiftDown())
  1049. startPlayback();
  1050. repaint();
  1051. }
  1052. }
  1053. void mouseDrag (const juce::MouseEvent& e) override
  1054. {
  1055. if (drag == Drag::overview)
  1056. {
  1057. centreViewOnOverview (e.x);
  1058. return;
  1059. }
  1060. if (drag == Drag::envPoint || drag == Drag::envBend)
  1061. {
  1062. envelopeMouseDrag (e);
  1063. return;
  1064. }
  1065. if (drag == Drag::warp)
  1066. {
  1067. warpMouseDrag (e);
  1068. return;
  1069. }
  1070. if (drag == Drag::none)
  1071. return;
  1072. // auto-scroll past the edges
  1073. if (e.x < waveArea.getX())
  1074. viewStart -= (waveArea.getX() - e.x) * fpp * 0.25;
  1075. else if (e.x > waveArea.getRight())
  1076. viewStart += (e.x - waveArea.getRight()) * fpp * 0.25;
  1077. clampView();
  1078. const auto f = snapFrame (xToFrame (e.x));
  1079. if (drag == Drag::select)
  1080. {
  1081. selection = { std::min (anchor, f), std::max (anchor, f) };
  1082. cursor = f;
  1083. }
  1084. else if (drag == Drag::marker && juce::isPositiveAndBelow (dragMarkerIndex, (int) doc.markers.size()))
  1085. {
  1086. auto& m = doc.markers[(std::size_t) dragMarkerIndex];
  1087. const auto length = m.end - m.start;
  1088. m.start = juce::jlimit<std::int64_t> (0, doc.audio.frames() - length, f);
  1089. m.end = m.start + length;
  1090. }
  1091. else if (drag == Drag::loopStart)
  1092. doc.loopStart = juce::jlimit<std::int64_t> (0, doc.loopEnd - 1, f);
  1093. else if (drag == Drag::loopEnd)
  1094. doc.loopEnd = juce::jlimit<std::int64_t> (doc.loopStart + 1, doc.audio.frames(), f);
  1095. repaint();
  1096. }
  1097. void mouseUp (const juce::MouseEvent&) override
  1098. {
  1099. if (drag == Drag::warp)
  1100. {
  1101. warpMouseUp();
  1102. return;
  1103. }
  1104. if (drag == Drag::envPoint || drag == Drag::envBend)
  1105. {
  1106. drag = Drag::none;
  1107. envDragPoint = -1;
  1108. if (envChanged)
  1109. commit (tr ("Edit envelope"));
  1110. envChanged = false;
  1111. return;
  1112. }
  1113. if (drag == Drag::marker || drag == Drag::loopStart || drag == Drag::loopEnd)
  1114. {
  1115. const auto& before = history.current();
  1116. const auto moved = before.loopStart != doc.loopStart || before.loopEnd != doc.loopEnd || before.markers.size() != doc.markers.size()
  1117. || ! std::equal (before.markers.begin(), before.markers.end(), doc.markers.begin(),
  1118. [] (const ae::Marker& a, const ae::Marker& b) { return a.start == b.start && a.end == b.end; });
  1119. if (moved)
  1120. {
  1121. ae::sortMarkers (doc);
  1122. commit (drag == Drag::marker ? tr ("Move marker") : tr ("Move loop"));
  1123. }
  1124. }
  1125. drag = Drag::none;
  1126. }
  1127. void mouseDoubleClick (const juce::MouseEvent& e) override
  1128. {
  1129. if (warpMode && ! doc.audio.empty() && warpLane.contains (e.getPosition()))
  1130. {
  1131. warpDoubleClick (e);
  1132. return;
  1133. }
  1134. if (doc.audio.empty() || ! waveArea.contains (e.getPosition()))
  1135. return;
  1136. // the region under the mouse, else the stretch between the markers around it, else everything
  1137. const auto f = xToFrame (e.x);
  1138. std::int64_t from = 0, to = doc.audio.frames();
  1139. for (const auto& m : doc.markers)
  1140. if (m.isRegion() && f >= m.start && f < m.end)
  1141. {
  1142. selection = { m.start, m.end };
  1143. repaint();
  1144. return;
  1145. }
  1146. for (const auto& m : doc.markers)
  1147. {
  1148. if (m.start <= f)
  1149. from = std::max (from, m.start);
  1150. if (m.start > f)
  1151. to = std::min (to, m.start);
  1152. }
  1153. selection = { from, to };
  1154. repaint();
  1155. }
  1156. void mouseWheelMove (const juce::MouseEvent& e, const juce::MouseWheelDetails& w) override
  1157. {
  1158. if (doc.audio.empty())
  1159. return;
  1160. const auto delta = std::abs (w.deltaY) > std::abs (w.deltaX) ? w.deltaY : w.deltaX;
  1161. if (e.mods.isCtrlDown() || e.mods.isCommandDown())
  1162. zoomAround ((float) e.x, delta > 0 ? 0.8 : 1.25);
  1163. else
  1164. {
  1165. viewStart -= delta * (double) waveArea.getWidth() * fpp * 0.5;
  1166. clampView();
  1167. repaint();
  1168. }
  1169. }
  1170. // --- keys -----------------------------------------------------------------------------------------------
  1171. bool keyPressed (const juce::KeyPress& k) override
  1172. {
  1173. const auto ctrl = k.getModifiers().isCtrlDown() || k.getModifiers().isCommandDown();
  1174. const auto shift = k.getModifiers().isShiftDown();
  1175. const auto c = juce::CharacterFunctions::toLowerCase (k.getTextCharacter());
  1176. const auto code = k.getKeyCode();
  1177. if (warpMode && warpSelected > 0 && (code == juce::KeyPress::deleteKey || code == juce::KeyPress::backspaceKey))
  1178. {
  1179. removeWarpMarker (warpSelected);
  1180. return true;
  1181. }
  1182. if (ctrl && (code == 'Z' || c == 'z'))
  1183. shift ? redo() : undo();
  1184. else if (ctrl && (code == 'Y' || c == 'y'))
  1185. redo();
  1186. else if (ctrl && (code == 'X' || c == 'x'))
  1187. cutSelection();
  1188. else if (ctrl && (code == 'C' || c == 'c'))
  1189. copySelection();
  1190. else if (ctrl && (code == 'V' || c == 'v'))
  1191. paste (false);
  1192. else if (ctrl && (code == 'A' || c == 'a'))
  1193. {
  1194. selection = { 0, doc.audio.frames() };
  1195. repaint();
  1196. }
  1197. else if (ctrl && (code == 'S' || c == 's'))
  1198. saveAs (bits);
  1199. else if (code == juce::KeyPress::spaceKey)
  1200. playing ? stopPlayback() : startPlayback();
  1201. else if (code == juce::KeyPress::deleteKey || code == juce::KeyPress::backspaceKey)
  1202. deleteSelection();
  1203. else if (code == juce::KeyPress::escapeKey)
  1204. {
  1205. if (recState != RecState::idle)
  1206. stopRecording();
  1207. selection = {};
  1208. repaint();
  1209. }
  1210. else if (code == juce::KeyPress::homeKey)
  1211. setCursor (0);
  1212. else if (code == juce::KeyPress::endKey)
  1213. setCursor (doc.audio.frames());
  1214. else if (! ctrl && c == 'r')
  1215. toggleRecording();
  1216. else if (! ctrl && c == 'l')
  1217. loopButton.triggerClick();
  1218. else if (! ctrl && c == 's')
  1219. viewButton.triggerClick();
  1220. else if (! ctrl && c == 'm')
  1221. addMarkerAtCursor();
  1222. else if (! ctrl && c == 'e')
  1223. setEnvMode ((EnvMode) (((int) envMode + 1) % 4));
  1224. else if (! ctrl && c == 'f')
  1225. zoomToFit();
  1226. else if (c == '+' || c == '=')
  1227. zoomAround ((float) waveArea.getCentreX(), 0.5);
  1228. else if (c == '-')
  1229. zoomAround ((float) waveArea.getCentreX(), 2.0);
  1230. else
  1231. return false;
  1232. return true;
  1233. }
  1234. // --- drag and drop of files -----------------------------------------------------------------------------
  1235. bool isInterestedInFileDrag (const juce::StringArray& files) override
  1236. {
  1237. return files.size() == 1 && SampleLibrary::isSampleFile (juce::File (files[0]));
  1238. }
  1239. // a sample dragged from LYNX's Browser too (issue #12)
  1240. bool isInterestedInDragSource (const SourceDetails& details) override
  1241. {
  1242. return BrowserComponent::isBrowserDrag (details) && SampleLibrary::isSampleFile (BrowserComponent::draggedFile (details));
  1243. }
  1244. void itemDropped (const SourceDetails& details) override
  1245. {
  1246. const auto file = BrowserComponent::draggedFile (details);
  1247. if (file.existsAsFile())
  1248. filesDropped ({ file.getFullPathName() }, 0, 0);
  1249. }
  1250. // FL's Edison: a dropped file replaces what the editor shows (issue #12); with Ctrl held it is pasted at the
  1251. // cursor instead (LYNX's earlier behaviour)
  1252. void filesDropped (const juce::StringArray& files, int, int) override
  1253. {
  1254. if (files.isEmpty() || recState != RecState::idle)
  1255. return;
  1256. if (doc.audio.empty() || ! juce::ModifierKeys::getCurrentModifiersRealtime().isCommandDown())
  1257. {
  1258. stopPlayback();
  1259. const auto previous = source;
  1260. source = { Source::Kind::file, -1, files[0] };
  1261. if (! loadFile (juce::File (files[0])))
  1262. source = previous;
  1263. return;
  1264. }
  1265. // into a document: pasted at the cursor
  1266. auto data = engine.getSampleLibrary().load (files[0]);
  1267. if (data == nullptr)
  1268. return;
  1269. ae::Audio clip;
  1270. clip.sampleRate = data->sampleRate;
  1271. clip.channels.emplace_back (data->leftData(), data->leftData() + data->frames());
  1272. if (data->isStereo())
  1273. clip.channels.emplace_back (data->rightData(), data->rightData() + data->frames());
  1274. const auto at = cursor;
  1275. ae::insert (doc, at, clip);
  1276. selection = { at, at + ae::conform (clip, doc.audio.numChannels(), doc.audio.sampleRate).frames() };
  1277. commit (tr ("Paste"));
  1278. }
  1279. // menus shared with the snapshot check
  1280. juce::PopupMenu editMenu (bool contextual);
  1281. private:
  1282. enum class Drag
  1283. {
  1284. none,
  1285. warp,
  1286. select,
  1287. marker,
  1288. loopStart,
  1289. loopEnd,
  1290. overview,
  1291. envPoint,
  1292. envBend
  1293. };
  1294. enum class RecState
  1295. {
  1296. idle,
  1297. waiting,
  1298. recording
  1299. };
  1300. // --- coordinates ----------------------------------------------------------------------------------------
  1301. float frameToX (double frame) const noexcept { return (float) waveArea.getX() + (float) ((frame - viewStart) / fpp); }
  1302. std::int64_t xToFrame (int x) const noexcept
  1303. {
  1304. return juce::jlimit<std::int64_t> (0, doc.audio.frames(), (std::int64_t) std::llround (viewStart + (double) (x - waveArea.getX()) * fpp));
  1305. }
  1306. double maxFpp() const noexcept { return juce::jmax (1.0, (double) doc.audio.frames() / juce::jmax (1, waveArea.getWidth())); }
  1307. void clampView()
  1308. {
  1309. fpp = juce::jlimit (1.0 / 32.0, maxFpp(), fpp);
  1310. const auto visible = (double) waveArea.getWidth() * fpp;
  1311. viewStart = juce::jlimit (0.0, juce::jmax (0.0, (double) doc.audio.frames() - visible), viewStart);
  1312. }
  1313. void zoomToFit()
  1314. {
  1315. fpp = maxFpp();
  1316. viewStart = 0.0;
  1317. clampView();
  1318. repaint();
  1319. }
  1320. void zoomAround (float x, double factor)
  1321. {
  1322. const auto frame = viewStart + (x - (float) waveArea.getX()) * fpp;
  1323. fpp *= factor;
  1324. clampView();
  1325. viewStart = frame - (x - (float) waveArea.getX()) * fpp;
  1326. clampView();
  1327. repaint();
  1328. }
  1329. void zoomTo (ae::Range r)
  1330. {
  1331. if (r.empty())
  1332. return;
  1333. fpp = (double) r.length() / juce::jmax (1, waveArea.getWidth());
  1334. clampView();
  1335. viewStart = (double) r.start;
  1336. clampView();
  1337. repaint();
  1338. }
  1339. void centreViewOnOverview (int x)
  1340. {
  1341. const auto frames = (double) doc.audio.frames();
  1342. const auto f = (double) (x - overviewArea.getX()) / juce::jmax (1, overviewArea.getWidth()) * frames;
  1343. viewStart = f - (double) waveArea.getWidth() * fpp * 0.5;
  1344. clampView();
  1345. repaint();
  1346. }
  1347. std::int64_t snapFrame (std::int64_t f) const
  1348. {
  1349. if (! snapZero)
  1350. return f;
  1351. return ae::nearestZeroCrossing (doc.audio, f, (std::int64_t) juce::jmax (8.0, fpp * 6.0));
  1352. }
  1353. int markerAt (int x) const
  1354. {
  1355. for (int i = (int) doc.markers.size() - 1; i >= 0; --i)
  1356. if (std::abs (frameToX ((double) doc.markers[(std::size_t) i].start) - (float) x) < 5.0f)
  1357. return i;
  1358. return -1;
  1359. }
  1360. // markers and loop ends move live; mouseUp commits the move against the history's current state
  1361. void beginPointDrag (Drag d) { drag = d; }
  1362. void setCursor (std::int64_t f)
  1363. {
  1364. cursor = juce::jlimit<std::int64_t> (0, doc.audio.frames(), f);
  1365. selection = {};
  1366. if (frameToX ((double) cursor) < (float) waveArea.getX() || frameToX ((double) cursor) > (float) waveArea.getRight())
  1367. {
  1368. viewStart = (double) cursor - (double) waveArea.getWidth() * fpp * 0.5;
  1369. clampView();
  1370. }
  1371. repaint();
  1372. }
  1373. // --- painting -------------------------------------------------------------------------------------------
  1374. // per pixel column x of a lane: the min/max of the samples it covers (exact when zoomed in, from the
  1375. // summary when zoomed out)
  1376. bool columnRange (int channel, double from, double to, float& lo, float& hi) const
  1377. {
  1378. const auto frames = doc.audio.frames();
  1379. if (to <= 0.0 || from >= (double) frames)
  1380. return false;
  1381. if (fpp > 256.0 && summary != nullptr)
  1382. {
  1383. const auto p = summary->query (from, to, doc.audio.numChannels() > 1 ? channel : -1);
  1384. if (! p.valid)
  1385. return false;
  1386. lo = p.lo;
  1387. hi = p.hi;
  1388. return true;
  1389. }
  1390. const auto& data = doc.audio.channels[(std::size_t) channel];
  1391. auto a = (std::int64_t) std::floor (from), b = (std::int64_t) std::ceil (to);
  1392. a = juce::jlimit<std::int64_t> (0, frames - 1, a);
  1393. b = juce::jlimit<std::int64_t> (a + 1, frames, b);
  1394. lo = hi = data[(std::size_t) a];
  1395. for (auto i = a + 1; i < b; ++i)
  1396. {
  1397. lo = std::min (lo, data[(std::size_t) i]);
  1398. hi = std::max (hi, data[(std::size_t) i]);
  1399. }
  1400. return true;
  1401. }
  1402. juce::Rectangle<float> laneBounds (int lane) const
  1403. {
  1404. const auto lanes = juce::jmax (1, doc.audio.numChannels());
  1405. const auto h = (float) waveArea.getHeight() / (float) lanes;
  1406. return { (float) waveArea.getX(), (float) waveArea.getY() + h * (float) lane, (float) waveArea.getWidth(), h };
  1407. }
  1408. void paintWave (juce::Graphics& g)
  1409. {
  1410. using namespace theme;
  1411. g.setColour (colour::bg0);
  1412. g.fillRect (waveArea);
  1413. if (doc.audio.empty())
  1414. {
  1415. g.setColour (colour::textSecondary);
  1416. g.setFont (font (type::body));
  1417. g.drawFittedText (recState != RecState::idle ? tr ("Waiting for input...")
  1418. : tr ("Empty: press Record, drop an audio file here or open one from the menu"),
  1419. waveArea.reduced (20), juce::Justification::centred, 2);
  1420. return;
  1421. }
  1422. juce::Graphics::ScopedSaveState save (g);
  1423. g.reduceClipRegion (waveArea);
  1424. paintSelectionAndRegions (g);
  1425. const auto lanes = doc.audio.numChannels();
  1426. for (int lane = 0; lane < lanes; ++lane)
  1427. {
  1428. const auto r = laneBounds (lane);
  1429. const auto centre = r.getCentreY();
  1430. const auto half = r.getHeight() * 0.5f - 2.0f;
  1431. // level guides: centre line and -6 dB
  1432. g.setColour (colour::gridBeat);
  1433. g.drawHorizontalLine ((int) (centre - half * 0.5f), r.getX(), r.getRight());
  1434. g.drawHorizontalLine ((int) (centre + half * 0.5f), r.getX(), r.getRight());
  1435. g.setColour (colour::gridBar);
  1436. g.drawHorizontalLine ((int) centre, r.getX(), r.getRight());
  1437. if (lane > 0)
  1438. {
  1439. g.setColour (colour::border);
  1440. g.drawHorizontalLine ((int) r.getY(), r.getX(), r.getRight());
  1441. }
  1442. const auto width = waveArea.getWidth();
  1443. if (fpp < 1.0)
  1444. {
  1445. // zoomed in past one sample per pixel: the samples joined by a line, dots when far apart
  1446. const auto& data = doc.audio.channels[(std::size_t) lane];
  1447. const auto first = juce::jmax<std::int64_t> (0, (std::int64_t) std::floor (viewStart) - 1);
  1448. const auto last = juce::jmin<std::int64_t> (doc.audio.frames() - 1, (std::int64_t) std::ceil (viewStart + width * fpp) + 1);
  1449. juce::Path line;
  1450. for (auto i = first; i <= last; ++i)
  1451. {
  1452. const auto p = juce::Point<float> (frameToX ((double) i), centre - juce::jlimit (-1.0f, 1.0f, data[(std::size_t) i]) * half);
  1453. i == first ? line.startNewSubPath (p) : line.lineTo (p);
  1454. }
  1455. g.setColour (waveColour());
  1456. g.strokePath (line, juce::PathStrokeType (1.5f, juce::PathStrokeType::curved, juce::PathStrokeType::rounded));
  1457. if (fpp < 1.0 / 6.0)
  1458. for (auto i = first; i <= last; ++i)
  1459. g.fillEllipse (juce::Rectangle<float> (4.0f, 4.0f).withCentre ({ frameToX ((double) i), centre - juce::jlimit (-1.0f, 1.0f, data[(std::size_t) i]) * half }));
  1460. continue;
  1461. }
  1462. // one filled shape: the top edge (maxima) left to right, the bottom edge (minima) back
  1463. std::vector<float> tops ((std::size_t) width), bottoms ((std::size_t) width);
  1464. std::vector<char> valid ((std::size_t) width);
  1465. for (int x = 0; x < width; ++x)
  1466. {
  1467. const auto from = viewStart + x * fpp;
  1468. float lo = 0.0f, hi = 0.0f;
  1469. valid[(std::size_t) x] = columnRange (lane, from, from + fpp, lo, hi) ? 1 : 0;
  1470. tops[(std::size_t) x] = centre - juce::jlimit (-1.0f, 1.0f, hi) * half;
  1471. bottoms[(std::size_t) x] = centre - juce::jlimit (-1.0f, 1.0f, lo) * half;
  1472. if (bottoms[(std::size_t) x] - tops[(std::size_t) x] < 1.0f) // silence still shows as a hairline
  1473. {
  1474. const auto mid = (bottoms[(std::size_t) x] + tops[(std::size_t) x]) * 0.5f;
  1475. tops[(std::size_t) x] = mid - 0.5f;
  1476. bottoms[(std::size_t) x] = mid + 0.5f;
  1477. }
  1478. }
  1479. juce::Path wave;
  1480. for (int x = 0; x < width;)
  1481. {
  1482. while (x < width && ! valid[(std::size_t) x])
  1483. ++x;
  1484. if (x >= width)
  1485. break;
  1486. const auto start = x;
  1487. while (x < width && valid[(std::size_t) x])
  1488. ++x;
  1489. const auto px = [this] (int i) { return (float) (waveArea.getX() + i); };
  1490. wave.startNewSubPath (px (start), tops[(std::size_t) start]);
  1491. for (int i = start + 1; i < x; ++i)
  1492. wave.lineTo (px (i), tops[(std::size_t) i]);
  1493. wave.lineTo (px (x), tops[(std::size_t) (x - 1)]);
  1494. wave.lineTo (px (x), bottoms[(std::size_t) (x - 1)]);
  1495. for (int i = x - 1; i >= start; --i)
  1496. wave.lineTo (px (i), bottoms[(std::size_t) i]);
  1497. wave.closeSubPath();
  1498. }
  1499. g.setColour (waveColour());
  1500. g.fillPath (wave);
  1501. }
  1502. }
  1503. void paintSelectionAndRegions (juce::Graphics& g)
  1504. {
  1505. using namespace theme;
  1506. for (const auto& m : doc.markers)
  1507. if (m.isRegion())
  1508. {
  1509. g.setColour (colour::warning.withAlpha (0.07f));
  1510. g.fillRect (juce::Rectangle<float>::leftTopRightBottom (frameToX ((double) m.start), (float) waveArea.getY(), frameToX ((double) m.end),
  1511. (float) waveArea.getBottom()));
  1512. }
  1513. if (! selection.empty())
  1514. {
  1515. g.setColour (colour::selectionFill);
  1516. g.fillRect (juce::Rectangle<float>::leftTopRightBottom (frameToX ((double) selection.start), (float) waveArea.getY(),
  1517. frameToX ((double) selection.end), (float) waveArea.getBottom()));
  1518. }
  1519. }
  1520. void paintSpectrum (juce::Graphics& g)
  1521. {
  1522. using namespace theme;
  1523. g.setColour (colour::bg0);
  1524. g.fillRect (waveArea);
  1525. if (doc.audio.empty())
  1526. {
  1527. paintWave (g);
  1528. return;
  1529. }
  1530. const auto columns = juce::jmax (1, waveArea.getWidth() / 2);
  1531. const auto height = juce::jmax (1, waveArea.getHeight());
  1532. const auto key = juce::String (docVersion) + "|" + juce::String (viewStart) + "|" + juce::String (fpp) + "|" + juce::String (columns) + "x"
  1533. + juce::String (height) + "|" + juce::String (fftSize) + (logFrequency ? "l" : "n");
  1534. if (key != spectrumKey)
  1535. {
  1536. const auto from = (std::int64_t) viewStart;
  1537. const auto to = juce::jmin (doc.audio.frames(), (std::int64_t) std::ceil (viewStart + waveArea.getWidth() * fpp));
  1538. const auto spec = ae::spectrogram (doc.audio, { from, to }, columns, fftSize);
  1539. spectrumImage = juce::Image (juce::Image::RGB, columns, height, false);
  1540. const auto nyquist = doc.audio.sampleRate * 0.5;
  1541. const auto binHz = doc.audio.sampleRate / fftSize;
  1542. for (int y = 0; y < height; ++y)
  1543. {
  1544. const auto t = 1.0 - (double) y / juce::jmax (1, height - 1);
  1545. const auto hz = logFrequency ? 20.0 * std::pow (nyquist / 20.0, t) : t * nyquist;
  1546. const auto bin = juce::jlimit (0, spec.bins - 1, (int) std::lround (hz / binHz));
  1547. // the bins between this row and the next (log scale, high frequencies) are summarised by their max
  1548. const auto nextT = 1.0 - (double) (y + 1) / juce::jmax (1, height - 1);
  1549. const auto nextHz = logFrequency ? 20.0 * std::pow (nyquist / 20.0, nextT) : nextT * nyquist;
  1550. const auto binLow = juce::jlimit (0, spec.bins - 1, (int) std::lround (nextHz / binHz));
  1551. for (int c = 0; c < columns; ++c)
  1552. {
  1553. auto db = spec.at (c, bin);
  1554. for (int b = binLow; b < bin; ++b)
  1555. db = std::max (db, spec.at (c, b));
  1556. spectrumImage.setPixelAt (c, y, spectrumColour (db));
  1557. }
  1558. }
  1559. spectrumKey = key;
  1560. }
  1561. g.drawImage (spectrumImage, waveArea.toFloat());
  1562. juce::Graphics::ScopedSaveState save (g);
  1563. g.reduceClipRegion (waveArea);
  1564. if (! selection.empty())
  1565. {
  1566. g.setColour (juce::Colours::white.withAlpha (0.10f));
  1567. g.fillRect (juce::Rectangle<float>::leftTopRightBottom (frameToX ((double) selection.start), (float) waveArea.getY(),
  1568. frameToX ((double) selection.end), (float) waveArea.getBottom()));
  1569. }
  1570. }
  1571. void paintLevels (juce::Graphics& g)
  1572. {
  1573. using namespace theme;
  1574. g.setColour (colour::bg2);
  1575. g.fillRect (levelArea);
  1576. g.setFont (font (type::caption));
  1577. g.setColour (colour::textSecondary);
  1578. if (doc.audio.empty())
  1579. return;
  1580. if (spectrumView)
  1581. {
  1582. const auto nyquist = doc.audio.sampleRate * 0.5;
  1583. for (double hz : { 50.0, 100.0, 200.0, 500.0, 1000.0, 2000.0, 5000.0, 10000.0, 20000.0 })
  1584. {
  1585. if (hz >= nyquist)
  1586. continue;
  1587. const auto t = logFrequency ? std::log (hz / 20.0) / std::log (nyquist / 20.0) : hz / nyquist;
  1588. const auto y = (float) waveArea.getBottom() - (float) t * (float) waveArea.getHeight();
  1589. g.drawText (hz >= 1000.0 ? juce::String (hz / 1000.0, 0) + "k" : juce::String ((int) hz), juce::Rectangle<float> (0.0f, y - 6.0f, 30.0f, 12.0f).withX ((float) levelArea.getX()),
  1590. juce::Justification::centredRight);
  1591. }
  1592. return;
  1593. }
  1594. for (int lane = 0; lane < doc.audio.numChannels(); ++lane)
  1595. {
  1596. const auto r = laneBounds (lane);
  1597. const auto half = r.getHeight() * 0.5f - 2.0f;
  1598. auto label = [&] (float level, const juce::String& text) {
  1599. const auto y = r.getCentreY() - level * half;
  1600. g.drawText (text, juce::Rectangle<float> ((float) levelArea.getX(), y - 6.0f, 30.0f, 12.0f), juce::Justification::centredRight);
  1601. };
  1602. if (r.getHeight() > 70.0f)
  1603. {
  1604. label (0.5f, "-6");
  1605. label (-0.5f, "-6");
  1606. }
  1607. label (0.0f, doc.audio.numChannels() > 1 ? (lane == 0 ? "L" : "R") : "0");
  1608. }
  1609. }
  1610. void paintRuler (juce::Graphics& g)
  1611. {
  1612. using namespace theme;
  1613. g.setColour (colour::bg3);
  1614. g.fillRect (rulerArea);
  1615. if (doc.audio.empty())
  1616. return;
  1617. // a time step that leaves ~90 px between labels
  1618. const auto rate = doc.audio.sampleRate;
  1619. const auto secondsPerPixel = fpp / rate;
  1620. double step = 0.001;
  1621. for (double s : { 0.0001, 0.0002, 0.0005, 0.001, 0.002, 0.005, 0.01, 0.02, 0.05, 0.1, 0.2, 0.5, 1.0, 2.0, 5.0, 10.0, 15.0, 30.0, 60.0, 120.0, 300.0, 600.0 })
  1622. if (s / secondsPerPixel >= 90.0)
  1623. {
  1624. step = s;
  1625. break;
  1626. }
  1627. const auto bars = timeFormat == TimeFormat::bars;
  1628. const auto beatSeconds = 60.0 / juce::jmax (1.0, engine.getSong().bpm);
  1629. if (bars)
  1630. {
  1631. step = beatSeconds;
  1632. while (step / secondsPerPixel < 90.0)
  1633. step *= 2.0;
  1634. }
  1635. g.setFont (font (type::caption));
  1636. const auto firstSecond = viewStart / rate;
  1637. const auto lastSecond = (viewStart + waveArea.getWidth() * fpp) / rate;
  1638. for (auto t = std::floor (firstSecond / step) * step; t <= lastSecond; t += step)
  1639. {
  1640. const auto x = frameToX (t * rate);
  1641. if (x < (float) rulerArea.getX())
  1642. continue;
  1643. g.setColour (colour::gridBar);
  1644. g.drawVerticalLine ((int) x, (float) rulerArea.getBottom() - 7.0f, (float) rulerArea.getBottom());
  1645. g.setColour (colour::textSecondary);
  1646. g.drawText (formatTime ((std::int64_t) std::llround (t * rate)), juce::Rectangle<float> (x + 3.0f, (float) rulerArea.getY(), 90.0f, 13.0f),
  1647. juce::Justification::centredLeft);
  1648. }
  1649. // regions and markers: flags with their names; the loop: a bar along the bottom
  1650. for (const auto& m : doc.markers)
  1651. {
  1652. const auto x = frameToX ((double) m.start);
  1653. if (m.isRegion())
  1654. {
  1655. g.setColour (colour::warning.withAlpha (0.22f));
  1656. g.fillRect (juce::Rectangle<float>::leftTopRightBottom (x, (float) rulerArea.getY() + 12.0f, frameToX ((double) m.end), (float) rulerArea.getBottom() - 5.0f));
  1657. }
  1658. juce::Path flag;
  1659. flag.addTriangle (x, (float) rulerArea.getY() + 12.0f, x + 7.0f, (float) rulerArea.getY() + 15.5f, x, (float) rulerArea.getY() + 19.0f);
  1660. g.setColour (colour::warning);
  1661. g.fillPath (flag);
  1662. g.drawVerticalLine ((int) x, (float) rulerArea.getY() + 12.0f, (float) rulerArea.getBottom());
  1663. if (! m.name.empty())
  1664. g.drawText (juce::String::fromUTF8 (m.name.c_str()), juce::Rectangle<float> (x + 8.0f, (float) rulerArea.getY() + 12.0f, 120.0f, 8.0f),
  1665. juce::Justification::centredLeft);
  1666. }
  1667. if (doc.hasLoop())
  1668. {
  1669. const auto a = frameToX ((double) doc.loopStart), b = frameToX ((double) doc.loopEnd);
  1670. g.setColour (colour::accent);
  1671. g.fillRect (juce::Rectangle<float>::leftTopRightBottom (a, (float) rulerArea.getBottom() - 4.0f, b, (float) rulerArea.getBottom()));
  1672. g.fillRect (juce::Rectangle<float> (a, (float) rulerArea.getBottom() - 8.0f, 2.0f, 8.0f));
  1673. g.fillRect (juce::Rectangle<float> (b - 2.0f, (float) rulerArea.getBottom() - 8.0f, 2.0f, 8.0f));
  1674. }
  1675. }
  1676. void paintOverlays (juce::Graphics& g)
  1677. {
  1678. using namespace theme;
  1679. if (doc.audio.empty())
  1680. return;
  1681. juce::Graphics::ScopedSaveState save (g);
  1682. g.reduceClipRegion (waveArea);
  1683. for (const auto& m : doc.markers)
  1684. {
  1685. g.setColour (colour::warning.withAlpha (0.55f));
  1686. g.drawVerticalLine ((int) frameToX ((double) m.start), (float) waveArea.getY(), (float) waveArea.getBottom());
  1687. if (m.isRegion())
  1688. {
  1689. g.setColour (colour::warning.withAlpha (0.3f));
  1690. g.drawVerticalLine ((int) frameToX ((double) m.end), (float) waveArea.getY(), (float) waveArea.getBottom());
  1691. }
  1692. }
  1693. if (doc.hasLoop())
  1694. {
  1695. g.setColour (colour::accent.withAlpha (0.6f));
  1696. const float dash[] = { 4.0f, 3.0f };
  1697. for (auto f : { doc.loopStart, doc.loopEnd })
  1698. {
  1699. const auto x = frameToX ((double) f);
  1700. g.drawDashedLine ({ x, (float) waveArea.getY(), x, (float) waveArea.getBottom() }, dash, 2);
  1701. }
  1702. }
  1703. paintEnvelopes (g);
  1704. if (! selection.empty())
  1705. {
  1706. g.setColour (colour::selection.withAlpha (0.8f));
  1707. g.drawVerticalLine ((int) frameToX ((double) selection.start), (float) waveArea.getY(), (float) waveArea.getBottom());
  1708. g.drawVerticalLine ((int) frameToX ((double) selection.end), (float) waveArea.getY(), (float) waveArea.getBottom());
  1709. }
  1710. else
  1711. {
  1712. g.setColour (colour::textPrimary.withAlpha (0.7f));
  1713. g.drawVerticalLine ((int) frameToX ((double) cursor), (float) waveArea.getY(), (float) waveArea.getBottom());
  1714. }
  1715. if (playing && playhead >= 0)
  1716. {
  1717. g.setColour (colour::playhead);
  1718. g.fillRect (juce::Rectangle<float> (frameToX ((double) playhead) - 0.5f, (float) waveArea.getY(), 2.0f, (float) waveArea.getHeight()));
  1719. }
  1720. if (recState != RecState::idle)
  1721. {
  1722. auto badge = juce::Rectangle<float> ((float) waveArea.getX() + 8.0f, (float) waveArea.getY() + 8.0f, recState == RecState::recording ? 70.0f : 150.0f, 20.0f);
  1723. g.setColour (colour::bg1.withAlpha (0.85f));
  1724. g.fillRoundedRectangle (badge, radius::md);
  1725. g.setColour (colour::record);
  1726. g.fillEllipse (badge.removeFromLeft (20.0f).reduced (5.0f));
  1727. g.setFont (font (type::small, true));
  1728. g.drawText (recState == RecState::recording ? juce::String ("REC") : tr ("Waiting..."), badge, juce::Justification::centredLeft);
  1729. }
  1730. }
  1731. void paintOverview (juce::Graphics& g)
  1732. {
  1733. using namespace theme;
  1734. g.setColour (colour::bg0);
  1735. g.fillRoundedRectangle (overviewArea.toFloat(), radius::sm);
  1736. if (doc.audio.empty() || summary == nullptr)
  1737. return;
  1738. const auto frames = (double) doc.audio.frames();
  1739. const auto perPixel = frames / juce::jmax (1, overviewArea.getWidth());
  1740. const auto centre = (float) overviewArea.getCentreY();
  1741. const auto half = overviewArea.getHeight() * 0.5f - 1.0f;
  1742. g.setColour (waveColour().withAlpha (0.55f));
  1743. for (int x = 0; x < overviewArea.getWidth(); ++x)
  1744. {
  1745. const auto p = summary->query (x * perPixel, (x + 1) * perPixel, -1);
  1746. if (! p.valid)
  1747. break;
  1748. const auto a = juce::jmin (1.0f, std::max (std::abs (p.lo), std::abs (p.hi)));
  1749. g.drawVerticalLine (overviewArea.getX() + x, centre - a * half, centre + a * half + 1.0f);
  1750. }
  1751. const auto x0 = (float) overviewArea.getX() + (float) (viewStart / frames) * overviewArea.getWidth();
  1752. const auto w = (float) ((double) waveArea.getWidth() * fpp / frames) * overviewArea.getWidth();
  1753. g.setColour (colour::accent.withAlpha (0.18f));
  1754. g.fillRect (juce::Rectangle<float> (x0, (float) overviewArea.getY(), juce::jmax (3.0f, w), (float) overviewArea.getHeight()));
  1755. g.setColour (colour::accent);
  1756. g.drawRect (juce::Rectangle<float> (x0, (float) overviewArea.getY(), juce::jmax (3.0f, w), (float) overviewArea.getHeight()), 1.0f);
  1757. }
  1758. void paintInfo (juce::Graphics& g)
  1759. {
  1760. using namespace theme;
  1761. g.setColour (colour::bg1);
  1762. g.fillRect (infoArea);
  1763. g.setColour (colour::border);
  1764. g.drawHorizontalLine (infoArea.getY(), 0.0f, (float) getWidth());
  1765. auto area = infoArea.reduced (10, 0);
  1766. g.setFont (font (type::small));
  1767. if (status.isNotEmpty())
  1768. {
  1769. g.setColour (statusIsError ? colour::meterClip : colour::textSecondary);
  1770. g.drawText (status, area.removeFromRight (juce::jmin (420, area.getWidth() / 2)), juce::Justification::centredRight);
  1771. }
  1772. if (doc.audio.empty())
  1773. return;
  1774. juce::StringArray parts;
  1775. parts.add (juce::String (juce::roundToInt (doc.audio.sampleRate)) + " Hz");
  1776. parts.add (doc.audio.numChannels() > 1 ? tr ("Stereo") : tr ("Mono"));
  1777. parts.add (tr ("Length") + " " + formatTime (doc.audio.frames()));
  1778. const auto r = ae::orAll (doc, selection);
  1779. if (! selection.empty())
  1780. parts.add (tr ("Selection") + " " + formatTime (selection.start) + " - " + formatTime (selection.end) + " (" + formatTime (selection.length()) + ")");
  1781. else
  1782. parts.add (tr ("Cursor") + " " + formatTime (cursor));
  1783. const auto p = ae::peak (doc.audio, r);
  1784. parts.add (tr ("Peak") + " " + (p > 0.0f ? juce::String (20.0f * std::log10 (p), 1) + " dB" : juce::String ("-inf dB")));
  1785. g.setColour (colour::textPrimary);
  1786. g.drawText (parts.joinIntoString (" | "), area, juce::Justification::centredLeft);
  1787. }
  1788. juce::String formatTime (std::int64_t frames) const
  1789. {
  1790. const auto rate = doc.audio.sampleRate;
  1791. switch (timeFormat)
  1792. {
  1793. case TimeFormat::samples: return juce::String (frames);
  1794. case TimeFormat::bars:
  1795. {
  1796. const auto beats = (double) frames / rate * engine.getSong().bpm / 60.0;
  1797. const auto perBar = juce::jmax (1, engine.getSong().beatsPerBar);
  1798. const auto bar = (int) (beats / perBar);
  1799. const auto beat = (int) beats - bar * perBar;
  1800. const auto tick = (int) ((beats - std::floor (beats)) * 96.0);
  1801. return juce::String (bar + 1) + ":" + juce::String (beat + 1) + ":" + juce::String (tick).paddedLeft ('0', 2);
  1802. }
  1803. case TimeFormat::automatic:
  1804. if (fpp < 1.0)
  1805. return juce::String (frames);
  1806. [[fallthrough]];
  1807. case TimeFormat::seconds: return formatSeconds ((double) frames / rate);
  1808. }
  1809. return {};
  1810. }
  1811. // --- edits ----------------------------------------------------------------------------------------------
  1812. void commit (const juce::String& label)
  1813. {
  1814. history.commit (doc, label.toStdString());
  1815. modified = true;
  1816. documentChanged();
  1817. }
  1818. // runs `fn` on the selection (an empty selection: the whole audio, unless `needsSelection`)
  1819. void edit (const juce::String& label, const std::function<void (ae::Document&, ae::Range)>& fn, bool needsSelection = false)
  1820. {
  1821. if (doc.audio.empty() || recState != RecState::idle)
  1822. return;
  1823. if (needsSelection && selection.empty())
  1824. {
  1825. setStatus (tr ("Select a part first (drag over the waveform)"), false);
  1826. return;
  1827. }
  1828. stopPlayback();
  1829. const auto frames = doc.audio.frames();
  1830. const auto edited = ae::orAll (doc, selection);
  1831. fn (doc, selection);
  1832. if (ae::hasEnvelopes (doc) && doc.audio.frames() != frames)
  1833. ae::remapEnvelopes (doc, frames, edited, edited.length() + (doc.audio.frames() - frames));
  1834. // a length-changing edit of the selection keeps the edited part selected
  1835. if (! selection.empty())
  1836. selection.end = juce::jmax (selection.start, selection.end + (doc.audio.frames() - frames));
  1837. commit (label);
  1838. }
  1839. void documentChanged()
  1840. {
  1841. ++docVersion;
  1842. selection = ae::clamp (doc, selection);
  1843. cursor = juce::jlimit<std::int64_t> (0, doc.audio.frames(), cursor);
  1844. rebuildSummary();
  1845. clampView();
  1846. updateButtons();
  1847. updateTitle();
  1848. repaint();
  1849. }
  1850. void rebuildSummary()
  1851. {
  1852. if (doc.audio.empty())
  1853. {
  1854. summary.reset();
  1855. return;
  1856. }
  1857. const auto* l = doc.audio.channels[0].data();
  1858. const auto* r = doc.audio.numChannels() > 1 ? doc.audio.channels[1].data() : nullptr;
  1859. summary = std::make_shared<wave::Summary> (wave::analyse (l, r, (std::size_t) doc.audio.frames(), doc.audio.sampleRate));
  1860. }
  1861. void undo()
  1862. {
  1863. if (! history.canUndo() || recState != RecState::idle)
  1864. return;
  1865. stopPlayback();
  1866. doc = history.undo();
  1867. modified = true;
  1868. documentChanged();
  1869. }
  1870. void redo()
  1871. {
  1872. if (! history.canRedo() || recState != RecState::idle)
  1873. return;
  1874. stopPlayback();
  1875. doc = history.redo();
  1876. modified = true;
  1877. documentChanged();
  1878. }
  1879. void copySelection()
  1880. {
  1881. if (selection.empty())
  1882. return;
  1883. clipboard() = ae::copy (doc.audio, selection);
  1884. setStatus (tr ("Copied {0}", { formatTime (selection.length()) }), false);
  1885. }
  1886. void cutSelection()
  1887. {
  1888. if (selection.empty())
  1889. return;
  1890. clipboard() = ae::copy (doc.audio, selection);
  1891. const auto at = selection.start;
  1892. edit (tr ("Cut"), [] (ae::Document& d, ae::Range r) { ae::erase (d, r); }, true);
  1893. selection = {};
  1894. cursor = at;
  1895. repaint();
  1896. }
  1897. void trimSelection()
  1898. {
  1899. if (selection.empty())
  1900. return;
  1901. edit (tr ("Trim"), [] (ae::Document& d, ae::Range r) { ae::trim (d, r); }, true);
  1902. selection = {};
  1903. cursor = 0;
  1904. zoomToFit();
  1905. }
  1906. void deleteSelection()
  1907. {
  1908. if (selection.empty())
  1909. return;
  1910. const auto at = selection.start;
  1911. edit (tr ("Delete"), [] (ae::Document& d, ae::Range r) { ae::erase (d, r); }, true);
  1912. selection = {};
  1913. cursor = at;
  1914. repaint();
  1915. }
  1916. // insert at the cursor, replace the selection, or (mix) sum at the cursor / selection start
  1917. void paste (bool mix)
  1918. {
  1919. const auto& clip = clipboard();
  1920. if (clip.empty() || recState != RecState::idle)
  1921. return;
  1922. stopPlayback();
  1923. const auto wasEmpty = doc.audio.empty();
  1924. const auto at = selection.empty() ? cursor : selection.start;
  1925. const auto length = wasEmpty ? clip.frames() : ae::conform (clip, doc.audio.numChannels(), doc.audio.sampleRate).frames();
  1926. if (mix)
  1927. ae::pasteMix (doc, at, clip);
  1928. else if (! selection.empty())
  1929. ae::pasteReplace (doc, selection, clip);
  1930. else
  1931. ae::insert (doc, at, clip);
  1932. selection = { at, at + length };
  1933. commit (mix ? tr ("Paste mix") : tr ("Paste"));
  1934. if (wasEmpty)
  1935. zoomToFit();
  1936. }
  1937. // FL's Paste mix (envelope): the first time it shows the mix envelope to shape (top = the clipboard, bottom = the
  1938. // original); the second time it mixes the clipboard in at the cursor / selection start with that envelope
  1939. void pasteMixWithEnvelope()
  1940. {
  1941. const auto& clip = clipboard();
  1942. if (clip.empty() || doc.audio.empty() || recState != RecState::idle)
  1943. return;
  1944. if (envMode != EnvMode::mix)
  1945. {
  1946. if (doc.mixEnvelope.empty())
  1947. doc.mixEnvelope = ae::Envelope::flat (0.5);
  1948. setEnvMode (EnvMode::mix);
  1949. setStatus (tr ("Shape the mix envelope (top: the clipboard, bottom: the original), then choose Edit > Paste mix (envelope): apply."), false);
  1950. repaint();
  1951. return;
  1952. }
  1953. stopPlayback();
  1954. const auto at = selection.empty() ? cursor : selection.start;
  1955. const auto mix = doc.mixEnvelope;
  1956. doc.mixEnvelope = {};
  1957. const auto r = ae::pasteMixEnvelope (doc, at, clip, mix);
  1958. setEnvMode (EnvMode::wave);
  1959. selection = r;
  1960. commit (tr ("Paste mix (envelope)"));
  1961. }
  1962. // FL's Scratch (envelope): the first time it shows the position envelope (a rising diagonal = the audio as it is);
  1963. // the second time it renders the audio played along that envelope
  1964. void scratchWithEnvelope()
  1965. {
  1966. if (doc.audio.empty() || recState != RecState::idle)
  1967. return;
  1968. if (envMode != EnvMode::scratch)
  1969. {
  1970. if (doc.scratchEnvelope.empty())
  1971. doc.scratchEnvelope.points = { { 0.0, 0.0, 0.0f }, { 1.0, 1.0, 0.0f } };
  1972. setEnvMode (EnvMode::scratch);
  1973. setStatus (tr ("Draw the play position over time (rising = forwards, falling = backwards, flat = held), then choose Tools > Scratch (envelope): apply."), false);
  1974. repaint();
  1975. return;
  1976. }
  1977. stopPlayback();
  1978. const auto env = doc.scratchEnvelope;
  1979. doc.scratchEnvelope = {};
  1980. ae::scratch (doc, env);
  1981. setEnvMode (EnvMode::wave);
  1982. commit (tr ("Scratch (envelope)"));
  1983. }
  1984. // the clipboard stretched to the selection's length (pitch kept), or drum-stretched (slices keep their attacks),
  1985. // replacing the selection
  1986. void pasteFitted (bool drum)
  1987. {
  1988. const auto& clip = clipboard();
  1989. if (clip.empty() || selection.empty() || recState != RecState::idle)
  1990. return;
  1991. stopPlayback();
  1992. ae::Document part;
  1993. part.audio = ae::conform (clip, doc.audio.numChannels(), doc.audio.sampleRate);
  1994. const auto ratio = (double) selection.length() / (double) juce::jmax<std::int64_t> (1, part.audio.frames());
  1995. if (drum)
  1996. {
  1997. ae::DrumStretchSettings s;
  1998. s.ratio = ratio;
  1999. ae::drumloopStretch (part, {}, s);
  2000. }
  2001. else
  2002. ae::timeStretch (part, {}, ratio);
  2003. for (auto& ch : part.audio.channels)
  2004. ch.resize ((std::size_t) selection.length(), 0.0f);
  2005. ae::pasteReplace (doc, selection, part.audio);
  2006. commit (drum ? tr ("Paste replace (drum)") : tr ("Paste stretch"));
  2007. }
  2008. void fade (bool in)
  2009. {
  2010. const auto curve = fadeCurve;
  2011. edit (in ? tr ("Fade in") : tr ("Fade out"), [in, curve] (ae::Document& d, ae::Range r) { in ? ae::fadeIn (d, r, curve) : ae::fadeOut (d, r, curve); });
  2012. }
  2013. void addMarkerAtCursor()
  2014. {
  2015. if (doc.audio.empty())
  2016. return;
  2017. ae::addMarker (doc, selection.empty() ? cursor : selection.start, {});
  2018. commit (tr ("Add marker"));
  2019. }
  2020. void addRegionFromSelection()
  2021. {
  2022. if (selection.empty())
  2023. {
  2024. setStatus (tr ("Select a part first (drag over the waveform)"), false);
  2025. return;
  2026. }
  2027. ae::addRegion (doc, selection, tr ("Region").toStdString() + " " + std::to_string (std::count_if (doc.markers.begin(), doc.markers.end(), [] (const ae::Marker& m) { return m.isRegion(); }) + 1));
  2028. commit (tr ("Add region"));
  2029. }
  2030. void setLoopFromSelection()
  2031. {
  2032. if (selection.empty())
  2033. {
  2034. setStatus (tr ("Select a part first (drag over the waveform)"), false);
  2035. return;
  2036. }
  2037. ae::setLoop (doc, selection);
  2038. commit (tr ("Set loop"));
  2039. }
  2040. // --- Tools › Analysis › Convert to score and dump to piano roll (REA_rodada167c.md §4): the whole sample's notes
  2041. // into the selected channel's notes of the current pattern (replacing them), as FL's Edison
  2042. void convertToScore()
  2043. {
  2044. if (doc.audio.empty() || scoreBusy)
  2045. return;
  2046. stopPlayback();
  2047. auto data = std::make_shared<SampleData>();
  2048. data->sampleRate = doc.audio.sampleRate;
  2049. data->left = doc.audio.channels[0];
  2050. if (doc.audio.numChannels() > 1)
  2051. data->right = doc.audio.channels[1];
  2052. scoreBusy = true;
  2053. setStatus (tr ("Detecting score..."), false);
  2054. juce::Component::SafePointer<AudioEditor> self (this);
  2055. std::thread ([self, data] {
  2056. auto notes = std::make_shared<std::vector<newtonefx::DetectedNote>> (newtonefx::detectScore (*data));
  2057. juce::MessageManager::callAsync ([self, notes, rate = data->sampleRate] {
  2058. if (self == nullptr)
  2059. return;
  2060. self->scoreBusy = false;
  2061. if (notes->empty())
  2062. {
  2063. self->setStatus (tr ("No notes found in the sample"), false);
  2064. return;
  2065. }
  2066. self->setStatus (tr ("Dumping score..."), false);
  2067. const auto channel = self->engine.getSelectedChannel();
  2068. int count = 0;
  2069. self->engine.editSong ([&] (Song& s) {
  2070. if (channel >= 0 && channel < (int) s.channels.size())
  2071. count = newtonefx::dumpScore (s, channel, *notes, rate);
  2072. });
  2073. self->setStatus (tr ("{0} notes put in the Piano roll of the selected channel", { juce::String (count) }), false);
  2074. });
  2075. }).detach();
  2076. }
  2077. // --- scripts (Tools › Scripting: Run script / Edit last script; REA_rodada167c.md §2) -----------------------------
  2078. struct ScriptRef
  2079. {
  2080. juce::String name; // menu name
  2081. juce::String key; // the form memory's key (the script's path, or "lynx:<folder>/<name>")
  2082. juce::String folder; // a built-in script's folder
  2083. std::string source; // a built-in script's text (a file is read when it runs)
  2084. juce::File file;
  2085. };
  2086. struct ScriptJob
  2087. {
  2088. ScriptRef ref;
  2089. std::string source;
  2090. ae::Document start;
  2091. ae::Range selection;
  2092. ae::Audio clip;
  2093. std::vector<ae::script::Form> answers;
  2094. std::uint64_t version = 0;
  2095. };
  2096. struct ScriptResult
  2097. {
  2098. ae::script::Outcome outcome;
  2099. ae::Document doc;
  2100. std::optional<ae::Audio> clip;
  2101. };
  2102. // where scripts come from: FL Studio's own folder (System/Config/Audio scripts, read in place), then the user's
  2103. // Documents/LYNX/Audio scripts
  2104. static std::vector<std::pair<juce::String, juce::File>> scriptFolders()
  2105. {
  2106. static const auto fl = [] {
  2107. const auto roots = findFlStudioRoots();
  2108. return roots.factoryData.empty() ? juce::File()
  2109. : platform::localFile (roots.factoryData).getChildFile ("System").getChildFile ("Config").getChildFile ("Audio scripts");
  2110. }();
  2111. std::vector<std::pair<juce::String, juce::File>> out;
  2112. if (fl.isDirectory())
  2113. out.emplace_back ("FL Studio", fl);
  2114. out.emplace_back (tr ("My scripts"), platform::documentsFolder().getChildFile ("Audio scripts"));
  2115. return out;
  2116. }
  2117. juce::PopupMenu scriptMenu()
  2118. {
  2119. juce::PopupMenu menu;
  2120. menu.addSectionHeader ("LYNX SHARE");
  2121. std::map<juce::String, juce::PopupMenu> own;
  2122. for (const auto& b : ae::script::builtins())
  2123. {
  2124. ScriptRef r;
  2125. r.name = juce::String::fromUTF8 (b.name);
  2126. r.folder = juce::String::fromUTF8 (b.folder);
  2127. r.key = "lynx:" + r.folder + "/" + r.name;
  2128. r.source = b.source;
  2129. own[r.folder].addItem (r.name, true, false, [this, r] { runScript (r); });
  2130. }
  2131. for (auto& [folder, sub] : own)
  2132. menu.addSubMenu (folder, sub);
  2133. for (const auto& [title, dir] : scriptFolders())
  2134. {
  2135. menu.addSectionHeader (title);
  2136. auto addFolder = [this] (const juce::File& d, juce::PopupMenu& into, auto& self, int depth) -> bool {
  2137. bool any = false;
  2138. auto subs = d.findChildFiles (juce::File::findDirectories, false);
  2139. subs.sort();
  2140. for (const auto& s : subs)
  2141. {
  2142. juce::PopupMenu sub;
  2143. if (depth < 3 && self (s, sub, self, depth + 1))
  2144. {
  2145. into.addSubMenu (s.getFileName(), sub);
  2146. any = true;
  2147. }
  2148. }
  2149. auto files = d.findChildFiles (juce::File::findFiles, false, "*.pyscript");
  2150. files.sort();
  2151. for (const auto& f : files)
  2152. {
  2153. ScriptRef r;
  2154. r.name = f.getFileNameWithoutExtension();
  2155. r.key = f.getFullPathName();
  2156. r.file = f;
  2157. into.addItem (r.name, true, false, [this, r] { runScript (r); });
  2158. any = true;
  2159. }
  2160. return any;
  2161. };
  2162. if (! dir.isDirectory() || ! addFolder (dir, menu, addFolder, 0))
  2163. menu.addItem (tr ("(no scripts)"), false, false, nullptr);
  2164. }
  2165. menu.addSeparator();
  2166. menu.addItem (tr ("Open my scripts folder"), true, false, [] {
  2167. const auto dir = platform::documentsFolder().getChildFile ("Audio scripts");
  2168. dir.createDirectory();
  2169. if (platform::testMode())
  2170. platform::testModeLog ("open folder " + dir.getFullPathName());
  2171. else
  2172. dir.startAsProcess();
  2173. });
  2174. return menu;
  2175. }
  2176. void runScript (const ScriptRef& ref)
  2177. {
  2178. if (scriptBusy || recState != RecState::idle)
  2179. return;
  2180. auto job = std::make_shared<ScriptJob>();
  2181. job->ref = ref;
  2182. if (ref.file != juce::File())
  2183. {
  2184. juce::MemoryBlock bytes;
  2185. if (! ref.file.loadFileAsData (bytes) || ! juce::CharPointer_UTF8::isValidString (static_cast<const char*> (bytes.getData()), (int) bytes.getSize()))
  2186. {
  2187. showScriptText (tr ("Error"), tr ("Failed to load the script file. Please make sure it is saved in utf8-format."));
  2188. return;
  2189. }
  2190. job->source.assign (static_cast<const char*> (bytes.getData()), bytes.getSize());
  2191. }
  2192. else
  2193. job->source = ref.source;
  2194. lastScript = ref;
  2195. stopPlayback();
  2196. job->start = doc;
  2197. job->selection = selection;
  2198. job->clip = clipboard();
  2199. job->version = docVersion;
  2200. scriptStep (job);
  2201. }
  2202. // runs the script on a worker thread (the Python thread does the work; the UI never waits for it)
  2203. static void launchScript (std::shared_ptr<const ScriptJob> job, std::vector<ae::script::Form> answers,
  2204. std::function<void (std::shared_ptr<ScriptResult>)> done)
  2205. {
  2206. std::thread ([job, answers = std::move (answers), done = std::move (done)] {
  2207. auto r = std::make_shared<ScriptResult>();
  2208. r->doc = job->start;
  2209. ae::script::Host host;
  2210. host.clipboard = [job] (ae::Audio& a) {
  2211. a = job->clip;
  2212. return ! a.empty();
  2213. };
  2214. host.setClipboard = [r] (const ae::Audio& a) { r->clip = a; };
  2215. host.loadFile = [] (const std::string& path, ae::Audio& a) { return readAudioFile (juce::File (juce::String::fromUTF8 (path.c_str())), a); };
  2216. r->outcome = ae::script::run (job->source, r->doc, job->selection, answers, host);
  2217. juce::MessageManager::callAsync ([done, r] { done (r); });
  2218. }).detach();
  2219. }
  2220. void scriptStep (std::shared_ptr<ScriptJob> job)
  2221. {
  2222. scriptBusy = true;
  2223. setStatus (tr ("Running script {0}...", { job->ref.name }), false);
  2224. juce::Component::SafePointer<AudioEditor> self (this);
  2225. launchScript (job, job->answers, [self, job] (std::shared_ptr<ScriptResult> r) {
  2226. if (self != nullptr)
  2227. self->scriptFinished (job, *r);
  2228. });
  2229. }
  2230. void scriptFinished (std::shared_ptr<ScriptJob> job, ScriptResult& r)
  2231. {
  2232. scriptBusy = false;
  2233. using S = ae::script::Outcome::Status;
  2234. auto& out = r.outcome;
  2235. if (out.status == S::failed)
  2236. {
  2237. setStatus (tr ("The script stopped with an error"), true);
  2238. showScriptText (tr ("Script error"), juce::String::fromUTF8 (out.error.c_str()));
  2239. return;
  2240. }
  2241. juce::Component::SafePointer<AudioEditor> self (this);
  2242. if (out.status == S::needsForm)
  2243. {
  2244. setStatus ({}, false);
  2245. auto form = out.form;
  2246. const auto key = job->ref.key.toStdString();
  2247. if (form.controls.size() == 1 && form.controls[0].hint == "file") // Sample.LoadFromFile_Ask
  2248. {
  2249. auto chooser = lynx::ui::makeSharedFileChooser (tr ("Open"), juce::File(), "*.wav;*.flac;*.aif;*.aiff;*.ogg;*.mp3");
  2250. lynx::ui::launchChooser (chooser, juce::FileBrowserComponent::openMode | juce::FileBrowserComponent::canSelectFiles, [self, job, form, chooser] (const juce::FileChooser& fc) {
  2251. if (self == nullptr)
  2252. return;
  2253. auto answer = form;
  2254. answer.controls[0].text = fc.getResult().getFullPathName().toStdString();
  2255. job->answers.push_back (answer);
  2256. self->scriptStep (job);
  2257. });
  2258. return;
  2259. }
  2260. ae::script::restore (key, form);
  2261. auto panel = std::make_unique<ScriptPanel> (
  2262. form,
  2263. [self, job, key] (const ae::script::Form& f) {
  2264. ae::script::remember (key, f);
  2265. job->answers.push_back (f);
  2266. if (self != nullptr)
  2267. self->scriptStep (job);
  2268. },
  2269. [self, job] (const ae::script::Form& f) {
  2270. if (self != nullptr)
  2271. self->previewScript (job, f);
  2272. },
  2273. [self] {
  2274. if (self != nullptr)
  2275. self->editLastScript();
  2276. });
  2277. openToolWindow (std::move (panel), tr ("Configure script"), "audioeditor-script");
  2278. return;
  2279. }
  2280. // done: one undo step (nothing when the script changed nothing)
  2281. for (const auto& m : out.messages)
  2282. showScriptText (tr ("Script message"), juce::String::fromUTF8 (m.c_str()));
  2283. if (r.clip)
  2284. clipboard() = std::move (*r.clip);
  2285. if (docVersion != job->version)
  2286. {
  2287. setStatus (tr ("The audio changed while the script ran: run it again"), true);
  2288. return;
  2289. }
  2290. const bool same = r.doc.audio.sampleRate == doc.audio.sampleRate && r.doc.audio.channels == doc.audio.channels && r.doc.markers.size() == doc.markers.size()
  2291. && std::equal (r.doc.markers.begin(), r.doc.markers.end(), doc.markers.begin(), [] (const ae::Marker& a, const ae::Marker& b) {
  2292. return a.start == b.start && a.end == b.end && a.name == b.name && a.info == b.info && a.keyNum == b.keyNum;
  2293. });
  2294. setStatus (tr ("Script {0} done", { job->ref.name }), false);
  2295. if (same)
  2296. return;
  2297. const bool wasEmpty = doc.audio.empty();
  2298. if (wasEmpty)
  2299. history.reset (doc, tr ("Empty").toStdString());
  2300. doc = std::move (r.doc);
  2301. commit (tr ("Script: {0}", { job->ref.name }));
  2302. if (wasEmpty)
  2303. zoomToFit();
  2304. }
  2305. // Preview: the script with these values on a copy, played from the selection (or the start)
  2306. void previewScript (std::shared_ptr<ScriptJob> job, const ae::script::Form& f)
  2307. {
  2308. auto answers = job->answers;
  2309. answers.push_back (f);
  2310. const auto ticket = ++previewTicket;
  2311. juce::Component::SafePointer<AudioEditor> self (this);
  2312. launchScript (job, std::move (answers), [self, job, ticket] (std::shared_ptr<ScriptResult> r) {
  2313. if (self == nullptr || ticket != self->previewTicket || r->outcome.status != ae::script::Outcome::Status::done || r->doc.audio.empty())
  2314. return;
  2315. const auto from = juce::jlimit<std::int64_t> (0, r->doc.audio.frames(), job->selection.empty() ? 0 : job->selection.start);
  2316. self->playAudio (ae::copy (r->doc.audio, { from, r->doc.audio.frames() }), 0, false);
  2317. });
  2318. }
  2319. // Edit last script: the script's file in the system's editor (a LYNX script is first saved to My scripts)
  2320. void editLastScript()
  2321. {
  2322. if (lastScript.key.isEmpty())
  2323. return;
  2324. auto file = lastScript.file;
  2325. if (file == juce::File())
  2326. {
  2327. file = platform::documentsFolder().getChildFile ("Audio scripts").getChildFile (lastScript.folder).getChildFile (lastScript.name + ".pyscript");
  2328. if (! file.existsAsFile())
  2329. {
  2330. file.getParentDirectory().createDirectory();
  2331. file.replaceWithText (juce::String::fromUTF8 (lastScript.source.c_str()), false, false, "\n");
  2332. }
  2333. lastScript.file = file;
  2334. lastScript.key = file.getFullPathName();
  2335. }
  2336. if (platform::testMode())
  2337. platform::testModeLog ("edit script " + file.getFullPathName());
  2338. else if (! file.startAsProcess())
  2339. file.revealToUser();
  2340. }
  2341. void showScriptText (const juce::String& title, const juce::String& text)
  2342. {
  2343. if (platform::testMode())
  2344. {
  2345. platform::testModeLog (title + ": " + text);
  2346. return;
  2347. }
  2348. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::NoIcon, title, text, tr ("OK"), this);
  2349. }
  2350. // --- tool windows ---------------------------------------------------------------------------------------
  2351. // plays `fn` applied to a copy of the selection (Preview)
  2352. void previewProcessed (const std::function<void (ae::Document&)>& fn)
  2353. {
  2354. ae::Document part;
  2355. part.audio = ae::copy (doc.audio, ae::orAll (doc, selection));
  2356. fn (part);
  2357. playAudio (part.audio, 0, false);
  2358. }
  2359. void openTool (std::unique_ptr<ToolPanel> panel, const juce::String& title)
  2360. {
  2361. openToolWindow (std::move (panel), title, "audioeditor-tool");
  2362. }
  2363. void showAmp() { openEdisonTool (audiotools::Tool::amp); } // Edison's Amp form (round 165l)
  2364. void showResample()
  2365. {
  2366. if (doc.audio.empty())
  2367. return;
  2368. static const int rates[] = { 8000, 11025, 16000, 22050, 32000, 44100, 48000, 88200, 96000, 192000 };
  2369. juce::StringArray names;
  2370. int current = 5;
  2371. for (int i = 0; i < 10; ++i)
  2372. {
  2373. names.add (juce::String (rates[i]) + " Hz");
  2374. if (std::abs (rates[i] - doc.audio.sampleRate) < 1.0)
  2375. current = i;
  2376. }
  2377. juce::Component::SafePointer<AudioEditor> self (this);
  2378. openTool (std::make_unique<ToolPanel> (std::vector<ToolPanel::Param> {}, names, tr ("Sample rate"), current,
  2379. [self] (const std::vector<double>&, int i) {
  2380. if (self != nullptr && i >= 0)
  2381. {
  2382. self->selection = {};
  2383. self->edit (tr ("Resample"), [i] (ae::Document& d, ae::Range) { ae::resample (d, rates[i]); });
  2384. self->zoomToFit();
  2385. }
  2386. },
  2387. nullptr),
  2388. tr ("Resample"));
  2389. }
  2390. void showInsertSilence()
  2391. {
  2392. if (doc.audio.empty())
  2393. return;
  2394. juce::Component::SafePointer<AudioEditor> self (this);
  2395. openTool (std::make_unique<ToolPanel> (std::vector<ToolPanel::Param> { { tr ("Length"), 1.0, 10000.0, 500.0, 1.0, " ms" } }, juce::StringArray {},
  2396. juce::String {}, 0,
  2397. [self] (const std::vector<double>& v, int) {
  2398. if (self == nullptr)
  2399. return;
  2400. const auto frames = (std::int64_t) std::llround (v[0] * 0.001 * self->doc.audio.sampleRate);
  2401. const auto at = self->cursor;
  2402. ae::insertSilence (self->doc, at, frames);
  2403. self->selection = { at, at + frames };
  2404. self->commit (tr ("Insert silence"));
  2405. },
  2406. nullptr),
  2407. tr ("Insert silence"));
  2408. }
  2409. void showNormalizeTo()
  2410. {
  2411. if (doc.audio.empty())
  2412. return;
  2413. juce::Component::SafePointer<AudioEditor> self (this);
  2414. openTool (std::make_unique<ToolPanel> (std::vector<ToolPanel::Param> { { tr ("Peak"), -24.0, 0.0, -0.3, 0.1, " dB" } }, juce::StringArray {}, juce::String {}, 0,
  2415. [self] (const std::vector<double>& v, int) {
  2416. if (self != nullptr)
  2417. self->edit (tr ("Normalize"), [v] (ae::Document& d, ae::Range r) { ae::normalize (d, r, (float) v[0]); });
  2418. },
  2419. nullptr),
  2420. tr ("Normalize"));
  2421. }
  2422. void autoSlice (float sensitivity)
  2423. {
  2424. if (doc.audio.empty())
  2425. return;
  2426. const auto r = ae::orAll (doc, selection);
  2427. auto part = ae::copy (doc.audio, r);
  2428. int added = 0;
  2429. for (auto f : ae::detectOnsets (part, sensitivity))
  2430. if (f > 0 || r.start > 0)
  2431. {
  2432. ae::addMarker (doc, r.start + f, {});
  2433. ++added;
  2434. }
  2435. if (added > 0)
  2436. commit (tr ("Auto-slice"));
  2437. setStatus (tr ("{0} markers added", { juce::String (added) }), false);
  2438. }
  2439. void gridSlice (double beats)
  2440. {
  2441. if (doc.audio.empty())
  2442. return;
  2443. const auto step = beats * 60.0 / juce::jmax (1.0, engine.getSong().bpm) * doc.audio.sampleRate;
  2444. const auto r = ae::orAll (doc, selection);
  2445. int added = 0;
  2446. for (auto f = (double) r.start + step; f < (double) r.end - 1.0; f += step, ++added)
  2447. ae::addMarker (doc, (std::int64_t) std::llround (f), {});
  2448. if (added > 0)
  2449. commit (tr ("Grid slice"));
  2450. }
  2451. // --- playback -------------------------------------------------------------------------------------------
  2452. void playAudio (const ae::Audio& audio, std::int64_t from, bool loop)
  2453. {
  2454. if (audio.empty())
  2455. return;
  2456. auto data = std::make_shared<SampleData>();
  2457. data->sampleRate = audio.sampleRate;
  2458. data->left = audio.channels[0];
  2459. if (audio.numChannels() > 1)
  2460. data->right = audio.channels[1];
  2461. engine.previewSample (data, loop, 1.0f, true); // (at the volume knob's level)
  2462. playing = true;
  2463. playFrom = from;
  2464. playStartedMs = juce::Time::getMillisecondCounterHiRes();
  2465. playhead = from;
  2466. playButton.setIcon (Icon::pause);
  2467. }
  2468. void startPlayback()
  2469. {
  2470. if (doc.audio.empty() || recState != RecState::idle)
  2471. return;
  2472. auto r = selection;
  2473. if (r.empty() && loopPlay && doc.hasLoop())
  2474. r = { doc.loopStart, doc.loopEnd };
  2475. if (r.empty())
  2476. r = { cursor, doc.audio.frames() };
  2477. if (r.length() < 2)
  2478. r = { 0, doc.audio.frames() };
  2479. if (ae::hasEnvelopes (doc))
  2480. {
  2481. // the envelopes are heard before they are mixed down (like Edison)
  2482. ae::Document mixed;
  2483. mixed.audio = doc.audio;
  2484. mixed.volumeEnvelope = doc.volumeEnvelope;
  2485. mixed.panEnvelope = doc.panEnvelope;
  2486. mixed.separationEnvelope = doc.separationEnvelope;
  2487. ae::mixdownEnvelopes (mixed);
  2488. playAudio (ae::copy (mixed.audio, r), r.start, loopPlay);
  2489. return;
  2490. }
  2491. playAudio (ae::copy (doc.audio, r), r.start, loopPlay);
  2492. }
  2493. void stopPlayback()
  2494. {
  2495. if (! playing)
  2496. return;
  2497. engine.previewSample (nullptr);
  2498. playing = false;
  2499. playhead = -1;
  2500. playButton.setIcon (Icon::play);
  2501. repaint();
  2502. }
  2503. // --- recording ------------------------------------------------------------------------------------------
  2504. void toggleRecording()
  2505. {
  2506. if (recState == RecState::idle)
  2507. startRecording();
  2508. else
  2509. stopRecording();
  2510. }
  2511. void startRecording()
  2512. {
  2513. stopPlayback();
  2514. auto* device = engine.getDeviceManager().getCurrentAudioDevice();
  2515. if (device == nullptr)
  2516. {
  2517. setStatus (tr ("No audio device is open (Settings > Audio)"), true);
  2518. return;
  2519. }
  2520. if (recordSource == AudioCapture::input)
  2521. {
  2522. if (! engine.hasAudioInput())
  2523. {
  2524. if (const auto result = engine.openAudioInput(); result.issue != AudioEngine::InputIssue::none)
  2525. {
  2526. setStatus (result.detail.isNotEmpty() ? result.detail : tr ("No active audio input (Settings > Audio)"), true);
  2527. return;
  2528. }
  2529. openedInput = true; // closed again when the recording stops (round 165q)
  2530. }
  2531. device = engine.getDeviceManager().getCurrentAudioDevice();
  2532. if (device == nullptr || device->getActiveInputChannels().countNumberOfSetBits() == 0)
  2533. {
  2534. setStatus (tr ("No active audio input (Settings > Audio)"), true);
  2535. return;
  2536. }
  2537. }
  2538. recordRate = device->getCurrentSampleRate();
  2539. recordStereo = recordSource != AudioCapture::input || device->getActiveInputChannels().countNumberOfSetBits() > 1;
  2540. recL.clear();
  2541. recR.clear();
  2542. beforeRecording = doc;
  2543. recordAt = selection.empty() ? cursor : selection.start;
  2544. if (doc.audio.empty())
  2545. recordAt = 0;
  2546. engine.getMeters().capture.setSource (recordSource);
  2547. recState = recordMode == RecordMode::now ? RecState::recording : RecState::waiting;
  2548. recordButton.setToggleState (true, juce::dontSendNotification);
  2549. if (recordMode == RecordMode::onPlay && ! engine.getTransport().playing.load())
  2550. setStatus (tr ("Recording starts when the song plays"), false);
  2551. else if (recordMode == RecordMode::onInput)
  2552. setStatus (tr ("Recording starts when the input is heard"), false);
  2553. else
  2554. setStatus (tr ("Recording from {0}", { sourceName (recordSource) }), false);
  2555. repaint();
  2556. }
  2557. void drainRecording()
  2558. {
  2559. std::vector<float> l, r;
  2560. engine.getMeters().capture.pull (l, r);
  2561. if (l.empty())
  2562. return;
  2563. std::size_t from = 0;
  2564. if (recState == RecState::waiting)
  2565. {
  2566. if (recordMode == RecordMode::onPlay)
  2567. {
  2568. if (! engine.getTransport().playing.load())
  2569. return;
  2570. }
  2571. else
  2572. {
  2573. while (from < l.size() && std::abs (l[from]) < inputThreshold && std::abs (r[from]) < inputThreshold)
  2574. ++from;
  2575. if (from == l.size())
  2576. return;
  2577. }
  2578. recState = RecState::recording;
  2579. setStatus (tr ("Recording from {0}", { sourceName (recordSource) }), false);
  2580. }
  2581. recL.insert (recL.end(), l.begin() + (std::ptrdiff_t) from, l.end());
  2582. recR.insert (recR.end(), r.begin() + (std::ptrdiff_t) from, r.end());
  2583. if (recordMode == RecordMode::onPlay && ! engine.getTransport().playing.load())
  2584. stopRecording();
  2585. }
  2586. ae::Audio recordedAudio() const
  2587. {
  2588. ae::Audio a;
  2589. a.sampleRate = recordRate;
  2590. a.channels.push_back (recL);
  2591. if (recordStereo)
  2592. a.channels.push_back (recR);
  2593. return a;
  2594. }
  2595. // the document = what it was, with the recording inserted at the cursor
  2596. void showRecording()
  2597. {
  2598. doc = beforeRecording;
  2599. const auto rec = recordedAudio();
  2600. if (doc.audio.empty())
  2601. {
  2602. doc.audio = rec;
  2603. doc.title = tr ("Recording").toStdString();
  2604. }
  2605. else
  2606. ae::insert (doc, recordAt, rec);
  2607. const auto length = doc.audio.frames() - beforeRecording.audio.frames();
  2608. selection = { recordAt, recordAt + length };
  2609. cursor = recordAt + length;
  2610. rebuildSummary();
  2611. ++docVersion;
  2612. // follow the end
  2613. const auto visible = (double) waveArea.getWidth() * fpp;
  2614. if (beforeRecording.audio.empty() || (double) cursor > viewStart + visible)
  2615. {
  2616. if (beforeRecording.audio.empty() && (double) cursor > visible)
  2617. fpp = juce::jmax (fpp, (double) cursor / juce::jmax (1, waveArea.getWidth()) * 1.25);
  2618. viewStart = juce::jmax (0.0, (double) cursor - visible * 0.8);
  2619. }
  2620. clampView();
  2621. repaint();
  2622. }
  2623. // the input this editor opened for its recording: closed again (FL does not keep the microphone open; Windows
  2624. // showed its microphone-in-use icon until LYNX quit — round 165q)
  2625. void releaseInput()
  2626. {
  2627. if (! openedInput)
  2628. return;
  2629. openedInput = false;
  2630. engine.releaseAudioInputIfUnused();
  2631. }
  2632. void stopRecording()
  2633. {
  2634. if (recState == RecState::idle)
  2635. return;
  2636. drainRecording();
  2637. engine.getMeters().capture.setSource (AudioCapture::off);
  2638. releaseInput();
  2639. const auto got = ! recL.empty();
  2640. const auto dropped = engine.getMeters().capture.droppedFrames();
  2641. recState = RecState::idle;
  2642. recordButton.setToggleState (false, juce::dontSendNotification);
  2643. if (got)
  2644. {
  2645. showRecording();
  2646. commit (tr ("Record"));
  2647. setStatus (tr ("Recorded {0}", { formatTime ((std::int64_t) recL.size()) }) + (dropped > 0 ? " (" + tr ("{0} frames lost", { juce::String (dropped) }) + ")" : ""), dropped > 0);
  2648. }
  2649. else
  2650. {
  2651. doc = beforeRecording;
  2652. documentChanged();
  2653. setStatus (tr ("Nothing was recorded"), false);
  2654. }
  2655. recL.clear();
  2656. recR.clear();
  2657. }
  2658. juce::String sourceName (int s) const
  2659. {
  2660. if (s == AudioCapture::input)
  2661. return tr ("the audio input");
  2662. if (s == 0)
  2663. return tr ("the Master");
  2664. const auto& mixer = engine.getSong().mixer;
  2665. if (juce::isPositiveAndBelow (s, (int) mixer.size()) && ! mixer[(std::size_t) s].name.empty())
  2666. return tr ("insert {0}", { juce::String (s) }) + " (" + juce::String::fromUTF8 (mixer[(std::size_t) s].name.c_str()) + ")";
  2667. return tr ("insert {0}", { juce::String (s) });
  2668. }
  2669. public:
  2670. void recordInputWithSong()
  2671. {
  2672. recordSource = AudioCapture::input;
  2673. recordMode = RecordMode::onPlay;
  2674. startRecording();
  2675. }
  2676. void setRecordSource (int s)
  2677. {
  2678. recordSource = s;
  2679. setStatus (tr ("Press Record to capture {0}", { sourceName (s) }), false);
  2680. }
  2681. private:
  2682. // --- output ---------------------------------------------------------------------------------------------
  2683. juce::String safeTitle() const
  2684. {
  2685. auto t = juce::File::createLegalFileName (juce::String::fromUTF8 (doc.title.c_str())).trim();
  2686. return t.isEmpty() ? juce::String ("Audio") : t;
  2687. }
  2688. // the edited audio as a new WAV in Music\LYNX\Edits (a new name each time: the Sampler and the waveform caches
  2689. // key on the path, so nothing stale is ever shown)
  2690. juce::File writeEditFile()
  2691. {
  2692. const auto folder = juce::File::getSpecialLocation (juce::File::userMusicDirectory).getChildFile ("LYNX/Edits");
  2693. folder.createDirectory();
  2694. const auto file = folder.getNonexistentChildFile (safeTitle() + " (edit)", ".wav");
  2695. if (! writeWav (file, bits))
  2696. return {};
  2697. return file;
  2698. }
  2699. bool writeWav (const juce::File& file, ae::WavFormat format)
  2700. {
  2701. const auto bytes = ae::encodeWav (doc, format);
  2702. if (! file.replaceWithData (bytes.data(), bytes.size()))
  2703. {
  2704. setStatus (tr ("Could not write {0}", { file.getFullPathName() }), true);
  2705. return false;
  2706. }
  2707. engine.getSampleLibrary().forget (file.getFullPathName());
  2708. return true;
  2709. }
  2710. void saveAs (ae::WavFormat format)
  2711. {
  2712. if (doc.audio.empty())
  2713. return;
  2714. auto start = lastFile.existsAsFile() ? lastFile.getSiblingFile (safeTitle() + ".wav")
  2715. : juce::File::getSpecialLocation (juce::File::userMusicDirectory).getChildFile (safeTitle() + ".wav");
  2716. chooser = lynx::ui::makeFileChooser (tr ("Save as WAV"), start, "*.wav");
  2717. juce::Component::SafePointer<AudioEditor> self (this);
  2718. lynx::ui::launchChooser (chooser, juce::FileBrowserComponent::saveMode | juce::FileBrowserComponent::canSelectFiles | juce::FileBrowserComponent::warnAboutOverwriting,
  2719. [self, format] (const juce::FileChooser& fc) {
  2720. if (self == nullptr || fc.getResult() == juce::File {})
  2721. return;
  2722. const auto file = fc.getResult().withFileExtension ("wav");
  2723. if (self->writeWav (file, format))
  2724. {
  2725. self->bits = format;
  2726. self->lastFile = file;
  2727. self->modified = false;
  2728. self->setStatus (tr ("Saved {0}", { file.getFileName() }), false);
  2729. self->updateTitle();
  2730. }
  2731. });
  2732. }
  2733. void openFileDialog()
  2734. {
  2735. chooser = lynx::ui::makeFileChooser (tr ("Open audio file"), lastFile, engine.getSampleLibrary().wildcard());
  2736. juce::Component::SafePointer<AudioEditor> self (this);
  2737. lynx::ui::launchChooser (chooser, juce::FileBrowserComponent::openMode | juce::FileBrowserComponent::canSelectFiles, [self] (const juce::FileChooser& fc) {
  2738. if (self == nullptr || ! fc.getResult().existsAsFile())
  2739. return;
  2740. self->stopPlayback();
  2741. self->source = { Source::Kind::file, -1, fc.getResult().getFullPathName() };
  2742. self->loadFile (fc.getResult());
  2743. });
  2744. }
  2745. // each region (or each stretch between markers when there are no regions) as its own WAV in a folder
  2746. void exportRegions()
  2747. {
  2748. std::vector<ae::Range> parts;
  2749. std::vector<std::string> names;
  2750. for (const auto& m : doc.markers)
  2751. if (m.isRegion())
  2752. {
  2753. parts.push_back ({ m.start, m.end });
  2754. names.push_back (m.name);
  2755. }
  2756. if (parts.empty())
  2757. {
  2758. std::int64_t from = 0;
  2759. for (const auto& m : doc.markers)
  2760. if (m.start > from)
  2761. {
  2762. parts.push_back ({ from, m.start });
  2763. names.push_back ({});
  2764. from = m.start;
  2765. }
  2766. if (from > 0 && from < doc.audio.frames())
  2767. {
  2768. parts.push_back ({ from, doc.audio.frames() });
  2769. names.push_back ({});
  2770. }
  2771. }
  2772. if (parts.empty())
  2773. {
  2774. setStatus (tr ("No regions or markers to export"), true);
  2775. return;
  2776. }
  2777. chooser = lynx::ui::makeFileChooser (tr ("Export regions to a folder"), juce::File::getSpecialLocation (juce::File::userMusicDirectory));
  2778. juce::Component::SafePointer<AudioEditor> self (this);
  2779. lynx::ui::launchChooser (chooser, juce::FileBrowserComponent::openMode | juce::FileBrowserComponent::canSelectDirectories,
  2780. [self, parts, names] (const juce::FileChooser& fc) {
  2781. if (self == nullptr || ! fc.getResult().isDirectory())
  2782. return;
  2783. int written = 0;
  2784. for (std::size_t i = 0; i < parts.size(); ++i)
  2785. {
  2786. ae::Document part;
  2787. part.audio = ae::copy (self->doc.audio, parts[i]);
  2788. const auto name = names[i].empty() ? self->safeTitle() + " " + juce::String (i + 1).paddedLeft ('0', 2)
  2789. : juce::File::createLegalFileName (juce::String::fromUTF8 (names[i].c_str()));
  2790. const auto bytes = ae::encodeWav (part, self->bits);
  2791. written += fc.getResult().getNonexistentChildFile (name, ".wav").replaceWithData (bytes.data(), bytes.size()) ? 1 : 0;
  2792. }
  2793. self->setStatus (tr ("{0} files written", { juce::String (written) }), false);
  2794. });
  2795. }
  2796. void sendToPlaylist()
  2797. {
  2798. if (doc.audio.empty())
  2799. return;
  2800. const auto file = writeEditFile();
  2801. if (file == juce::File {})
  2802. return;
  2803. const auto& song = engine.getSong();
  2804. const auto length = juce::jmax<std::int64_t> (ppq / 4, (std::int64_t) (doc.audio.seconds() * song.bpm / 60.0 * ppq));
  2805. const auto start = (std::int64_t) (engine.getTransport().positionTicks.load() / ppq) * ppq; // at the beat of the song position
  2806. // the first track with room for it
  2807. int track = 0;
  2808. for (;; ++track)
  2809. {
  2810. const auto busy = std::any_of (song.playlist.begin(), song.playlist.end(),
  2811. [&] (const Clip& c) { return c.track == track && c.start < start + length && c.end() > start; });
  2812. if (! busy)
  2813. break;
  2814. }
  2815. const auto path = file.getFullPathName().toStdString();
  2816. const auto name = safeTitle().toStdString();
  2817. engine.editSong ([=] (Song& s) {
  2818. ChannelDef c;
  2819. c.name = name;
  2820. c.instrument = InstrumentKind::audioClip;
  2821. c.samplePath = path;
  2822. c.mixerTrack = s.claimFreeInsert();
  2823. s.channels.push_back (c);
  2824. Clip clip;
  2825. clip.kind = ClipKind::audio;
  2826. clip.channel = (int) s.channels.size() - 1;
  2827. clip.track = track;
  2828. clip.start = start;
  2829. clip.length = length;
  2830. s.playlist.push_back (clip);
  2831. s.mode = PlayMode::song;
  2832. });
  2833. modified = false;
  2834. setStatus (tr ("Sent to the Playlist (track {0})", { juce::String (track + 1) }), false);
  2835. updateTitle();
  2836. }
  2837. // FL's Edison "Send to channel" of a part (issue #12): the selection (or a region) as a new Sampler channel's
  2838. // sample; the editor keeps the whole audio (nothing cut or cropped)
  2839. void sendRangeToNewSampler (ae::Range range)
  2840. {
  2841. range = ae::clamp (doc, range);
  2842. if (doc.audio.empty() || range.empty())
  2843. return;
  2844. ae::Document part;
  2845. part.audio = ae::copy (doc.audio, range);
  2846. part.title = doc.title;
  2847. if (doc.hasLoop() && doc.loopStart >= range.start && doc.loopEnd <= range.end)
  2848. ae::setLoop (part, { doc.loopStart - range.start, doc.loopEnd - range.start });
  2849. const auto folder = juce::File::getSpecialLocation (juce::File::userMusicDirectory).getChildFile ("LYNX/Edits");
  2850. folder.createDirectory();
  2851. const auto file = folder.getNonexistentChildFile (safeTitle() + " (part)", ".wav");
  2852. const auto bytes = ae::encodeWav (part, bits);
  2853. if (! file.replaceWithData (bytes.data(), bytes.size()))
  2854. {
  2855. setStatus (tr ("Could not write {0}", { file.getFullPathName() }), true);
  2856. return;
  2857. }
  2858. engine.getSampleLibrary().forget (file.getFullPathName());
  2859. const auto path = file.getFullPathName().toStdString();
  2860. const auto name = (safeTitle() + " (part)").toStdString();
  2861. int index = 0;
  2862. engine.editSong ([&] (Song& s) {
  2863. ChannelDef c;
  2864. c.name = name;
  2865. c.instrument = InstrumentKind::sampler;
  2866. c.samplePath = path;
  2867. c.mixerTrack = s.claimFreeInsert();
  2868. s.channels.push_back (c);
  2869. index = (int) s.channels.size() - 1;
  2870. });
  2871. engine.setSelectedChannel (index);
  2872. setStatus (tr ("The selection went to a new Sampler channel ({0})", { juce::String::fromUTF8 (name.c_str()) }), false);
  2873. }
  2874. void sendToNewSampler()
  2875. {
  2876. if (doc.audio.empty())
  2877. return;
  2878. const auto file = writeEditFile();
  2879. if (file == juce::File {})
  2880. return;
  2881. const auto path = file.getFullPathName().toStdString();
  2882. const auto name = safeTitle().toStdString();
  2883. int index = 0;
  2884. engine.editSong ([&] (Song& s) {
  2885. ChannelDef c;
  2886. c.name = name;
  2887. c.instrument = InstrumentKind::sampler;
  2888. c.samplePath = path;
  2889. c.mixerTrack = s.claimFreeInsert();
  2890. s.channels.push_back (c);
  2891. index = (int) s.channels.size() - 1;
  2892. });
  2893. engine.setSelectedChannel (index);
  2894. modified = false;
  2895. setStatus (tr ("Sent to a new Sampler channel"), false);
  2896. updateTitle();
  2897. }
  2898. bool sourceChannelValid() const
  2899. {
  2900. const auto& channels = engine.getSong().channels;
  2901. return source.kind == Source::Kind::channel && juce::isPositiveAndBelow (source.index, (int) channels.size())
  2902. && juce::String::fromUTF8 (channels[(std::size_t) source.index].samplePath.c_str()) == source.path;
  2903. }
  2904. void sendBackToChannel()
  2905. {
  2906. if (doc.audio.empty() || ! sourceChannelValid())
  2907. return;
  2908. const auto file = writeEditFile();
  2909. if (file == juce::File {})
  2910. return;
  2911. const auto path = file.getFullPathName().toStdString();
  2912. const auto ch = source.index;
  2913. engine.editSong ([=] (Song& s) { s.channels[(std::size_t) ch].samplePath = path; });
  2914. source.path = file.getFullPathName();
  2915. modified = false;
  2916. setStatus (tr ("The channel now plays the edited audio"), false);
  2917. updateTitle();
  2918. }
  2919. // --- menus ----------------------------------------------------------------------------------------------
  2920. juce::PopupMenu historyMenu()
  2921. {
  2922. juce::PopupMenu menu;
  2923. menu.addSectionHeader (tr ("Undo history"));
  2924. for (int i = history.size() - 1; i >= 0; --i)
  2925. menu.addItem (juce::String::fromUTF8 (history.label (i).c_str()), true, i == history.getPosition(), [this, i] {
  2926. if (recState != RecState::idle)
  2927. return;
  2928. stopPlayback();
  2929. doc = history.jumpTo (i);
  2930. modified = true;
  2931. documentChanged();
  2932. });
  2933. return menu;
  2934. }
  2935. juce::PopupMenu curveMenu()
  2936. {
  2937. juce::PopupMenu menu;
  2938. const std::pair<ae::Curve, const char*> curves[] = { { ae::Curve::smooth, TR_NOOP ("Smooth (S-curve)") },
  2939. { ae::Curve::linear, TR_NOOP ("Linear") },
  2940. { ae::Curve::exponential, TR_NOOP ("Slow start") },
  2941. { ae::Curve::logarithmic, TR_NOOP ("Fast start") } };
  2942. menu.addSectionHeader (tr ("Fade curve"));
  2943. for (const auto& [curve, name] : curves)
  2944. menu.addItem (tr (name), true, fadeCurve == curve, [this, c = curve] { fadeCurve = c; });
  2945. return menu;
  2946. }
  2947. juce::PopupMenu recordMenu()
  2948. {
  2949. juce::PopupMenu menu;
  2950. menu.addSectionHeader (tr ("Record from"));
  2951. menu.addItem (tr ("Audio input"), true, recordSource == AudioCapture::input, [this] { recordSource = AudioCapture::input; });
  2952. menu.addItem (tr ("Master output"), true, recordSource == 0, [this] { recordSource = 0; });
  2953. juce::PopupMenu inserts;
  2954. const auto& mixer = engine.getSong().mixer;
  2955. for (int t = 1; t < (int) mixer.size(); ++t)
  2956. inserts.addItem (sourceName (t), true, recordSource == t, [this, t] { recordSource = t; });
  2957. menu.addSubMenu (tr ("Mixer insert"), inserts, inserts.getNumItems() > 0, nullptr, recordSource > 0);
  2958. menu.addSectionHeader (tr ("Start"));
  2959. menu.addItem (tr ("Immediately"), true, recordMode == RecordMode::now, [this] { recordMode = RecordMode::now; });
  2960. menu.addItem (tr ("When the input is heard"), true, recordMode == RecordMode::onInput, [this] { recordMode = RecordMode::onInput; });
  2961. menu.addItem (tr ("When the song plays (stops with it)"), true, recordMode == RecordMode::onPlay, [this] { recordMode = RecordMode::onPlay; });
  2962. return menu;
  2963. }
  2964. juce::PopupMenu sendMenu()
  2965. {
  2966. juce::PopupMenu menu;
  2967. const auto has = ! doc.audio.empty();
  2968. menu.addItem (tr ("Send to the Playlist as an audio clip"), has, false, [this] { sendToPlaylist(); });
  2969. menu.addItem (tr ("Send to a new Sampler channel"), has, false, [this] { sendToNewSampler(); });
  2970. menu.addItem (tr ("Send the selection to a new Sampler channel"), has && ! selection.empty(), false,
  2971. [this] { sendRangeToNewSampler (selection); });
  2972. if (source.kind == Source::Kind::channel)
  2973. {
  2974. const auto& channels = engine.getSong().channels;
  2975. const auto name = juce::isPositiveAndBelow (source.index, (int) channels.size())
  2976. ? juce::String::fromUTF8 (channels[(std::size_t) source.index].name.c_str())
  2977. : juce::String();
  2978. menu.addItem (tr ("Replace the sample of \"{0}\"", { name }), has && sourceChannelValid(), false, [this] { sendBackToChannel(); });
  2979. }
  2980. return menu;
  2981. }
  2982. juce::PopupMenu markerMenu (int index)
  2983. {
  2984. juce::PopupMenu menu;
  2985. const auto m = doc.markers[(std::size_t) index];
  2986. menu.addSectionHeader (m.name.empty() ? (m.isRegion() ? tr ("Region") : tr ("Marker")) : juce::String::fromUTF8 (m.name.c_str()));
  2987. menu.addItem (tr ("Rename..."), [this, index] { renameMarker (index); });
  2988. if (m.isRegion())
  2989. {
  2990. menu.addItem (tr ("Select"), [this, m] {
  2991. selection = { m.start, m.end };
  2992. repaint();
  2993. });
  2994. menu.addItem (tr ("Zoom on"), [this, m] { zoomTo ({ m.start, m.end }); });
  2995. menu.addItem (tr ("Send to a new Sampler channel"), [this, m] { sendRangeToNewSampler ({ m.start, m.end }); });
  2996. menu.addItem (tr ("Set loop"), [this, m] {
  2997. ae::setLoop (doc, { m.start, m.end });
  2998. commit (tr ("Set loop"));
  2999. });
  3000. menu.addItem (tr ("Turn into marker"), [this, index] {
  3001. doc.markers[(std::size_t) index].end = doc.markers[(std::size_t) index].start;
  3002. commit (tr ("Turn into marker"));
  3003. });
  3004. }
  3005. menu.addItem (tr ("Delete"), [this, index] {
  3006. doc.markers.erase (doc.markers.begin() + index);
  3007. commit (tr ("Delete marker"));
  3008. });
  3009. return menu;
  3010. }
  3011. void renameMarker (int index)
  3012. {
  3013. auto* box = new juce::AlertWindow (tr ("Rename"), {}, juce::MessageBoxIconType::NoIcon, this);
  3014. box->addTextEditor ("name", juce::String::fromUTF8 (doc.markers[(std::size_t) index].name.c_str()));
  3015. box->addButton (tr ("Accept"), 1, juce::KeyPress (juce::KeyPress::returnKey));
  3016. box->addButton (tr ("Cancel"), 0, juce::KeyPress (juce::KeyPress::escapeKey));
  3017. juce::Component::SafePointer<AudioEditor> self (this);
  3018. box->enterModalState (true, juce::ModalCallbackFunction::create ([self, box, index] (int result) {
  3019. if (self != nullptr && result == 1 && juce::isPositiveAndBelow (index, (int) self->doc.markers.size()))
  3020. {
  3021. self->doc.markers[(std::size_t) index].name = box->getTextEditorContents ("name").toStdString();
  3022. self->commit (tr ("Rename marker"));
  3023. }
  3024. }),
  3025. true);
  3026. }
  3027. void setStatus (const juce::String& text, bool error)
  3028. {
  3029. status = text;
  3030. statusIsError = error;
  3031. repaint (infoArea);
  3032. }
  3033. void updateButtons()
  3034. {
  3035. undoButton.setEnabled (history.canUndo());
  3036. redoButton.setEnabled (history.canRedo());
  3037. const auto has = ! doc.audio.empty();
  3038. for (auto* b : quickButtons)
  3039. b->setEnabled (has);
  3040. playButton.setEnabled (has);
  3041. saveButton.setEnabled (has);
  3042. }
  3043. void updateTitle()
  3044. {
  3045. if (auto* window = findParentComponentOfClass<juce::DocumentWindow>())
  3046. window->setName (tr ("Audio editor") + (doc.title.empty() ? juce::String() : " - " + juce::String::fromUTF8 (doc.title.c_str())) + (modified ? " *" : ""));
  3047. }
  3048. void parentHierarchyChanged() override { updateTitle(); }
  3049. void timerCallback() override
  3050. {
  3051. if (recState != RecState::idle)
  3052. {
  3053. drainRecording();
  3054. if (recState == RecState::recording && ++recordTicks % 6 == 0) // the view follows ~5 times a second
  3055. showRecording();
  3056. if (recState == RecState::idle)
  3057. return;
  3058. repaint();
  3059. }
  3060. if (playing)
  3061. {
  3062. const auto pos = engine.getPreviewPosition();
  3063. if (pos < 0.0)
  3064. {
  3065. if (juce::Time::getMillisecondCounterHiRes() - playStartedMs > 250.0)
  3066. stopPlayback();
  3067. return;
  3068. }
  3069. const auto before = playhead;
  3070. playhead = playFrom < 0 ? -1 : playFrom + (std::int64_t) pos; // (a tool preview is not on the timeline)
  3071. // page along with the playhead (Follow on, issue #12)
  3072. if (playhead >= 0 && EditorGlobals::get().isFollowingView (EditorGlobals::FollowView::audioEditor)
  3073. && ((double) playhead > viewStart + (double) waveArea.getWidth() * fpp || (double) playhead < viewStart) && fpp < maxFpp())
  3074. {
  3075. viewStart = (double) playhead;
  3076. clampView();
  3077. repaint();
  3078. }
  3079. else if (before != playhead)
  3080. repaint (waveArea.withTrimmedTop (-2));
  3081. }
  3082. }
  3083. // --- Edison's tools (round 165l): the tool windows' host ---------------------------------------------------
  3084. public:
  3085. const ae::Document& toolDocument() const override { return doc; }
  3086. ae::Range toolSelection() const override { return selection; }
  3087. void toolApply (const juce::String& label, ae::Document d, ae::Range newSelection) override
  3088. {
  3089. if (recState != RecState::idle)
  3090. return;
  3091. stopPlayback();
  3092. const auto frames = doc.audio.frames();
  3093. const auto edited = ae::orAll (doc, selection);
  3094. doc = std::move (d);
  3095. if (ae::hasEnvelopes (doc) && doc.audio.frames() != frames)
  3096. ae::remapEnvelopes (doc, frames, edited, edited.length() + (doc.audio.frames() - frames));
  3097. selection = ae::clamp (doc, newSelection);
  3098. commit (label);
  3099. }
  3100. void toolPreview (const ae::Audio& audio) override
  3101. {
  3102. stopPlayback();
  3103. playAudio (audio, -1, false);
  3104. }
  3105. void toolStopPreview() override { stopPlayback(); }
  3106. double toolBpm() const override { return juce::jmax (1.0, engine.getSong().bpm); }
  3107. ae::NoiseProfile& toolNoiseProfile() override { return noiseProfile; }
  3108. const ae::Audio& toolClipboard() const override { return clipboard(); }
  3109. ae::Envelope* toolEnvelope() override
  3110. {
  3111. if (envMode == EnvMode::wave)
  3112. setEnvMode (EnvMode::volume);
  3113. return &currentEnvelope();
  3114. }
  3115. void toolEnvelopeChanged (bool commitIt, const juce::String& label) override
  3116. {
  3117. if (commitIt)
  3118. commit (label);
  3119. else
  3120. repaint();
  3121. }
  3122. juce::Component& toolComponent() override { return *this; }
  3123. private:
  3124. enum class EnvMode
  3125. {
  3126. wave,
  3127. volume,
  3128. panning,
  3129. separation,
  3130. mix, // the mix envelope of Paste mix (envelope)
  3131. scratch // the position envelope of Scratch (envelope)
  3132. };
  3133. EnvMode envMode = EnvMode::wave;
  3134. ae::NoiseProfile noiseProfile;
  3135. float noiseThreshold = -1.0f;
  3136. int envDragPoint = -1;
  3137. bool envChanged = false;
  3138. float envBendStartY = 0.0f, envBendStartTension = 0.0f;
  3139. ae::Envelope& currentEnvelope()
  3140. {
  3141. return envMode == EnvMode::panning ? doc.panEnvelope : envMode == EnvMode::separation ? doc.separationEnvelope : envMode == EnvMode::mix ? doc.mixEnvelope : envMode == EnvMode::scratch ? doc.scratchEnvelope : doc.volumeEnvelope;
  3142. }
  3143. static const char* envModeName (EnvMode m)
  3144. {
  3145. switch (m)
  3146. {
  3147. case EnvMode::wave: return TR_NOOP ("Edit: Wave");
  3148. case EnvMode::volume: return TR_NOOP ("Edit: Volume");
  3149. case EnvMode::panning: return TR_NOOP ("Edit: Panning");
  3150. case EnvMode::separation: return TR_NOOP ("Edit: Stereo sep");
  3151. case EnvMode::mix: return TR_NOOP ("Edit: Paste mix");
  3152. case EnvMode::scratch: return TR_NOOP ("Edit: Scratch");
  3153. }
  3154. return "";
  3155. }
  3156. void setEnvMode (EnvMode m)
  3157. {
  3158. envMode = m;
  3159. envButton.setButtonText (tr (envModeName (m)));
  3160. envButton.setToggleState (m != EnvMode::wave, juce::dontSendNotification);
  3161. if (m != EnvMode::wave)
  3162. setStatus (tr ("Right-click (or click) adds a point, drag moves it, right-click or Alt+click on a point deletes it, the hollow handles bend. Tools > Mixdown amp envelopes applies it."), false);
  3163. repaint();
  3164. }
  3165. juce::PopupMenu envModeMenu()
  3166. {
  3167. juce::PopupMenu m;
  3168. for (auto mode : { EnvMode::wave, EnvMode::volume, EnvMode::panning, EnvMode::separation })
  3169. m.addItem (tr (envModeName (mode)), mode == EnvMode::wave || doc.audio.numChannels() > 1 || mode == EnvMode::volume, envMode == mode, [this, mode] { setEnvMode (mode); });
  3170. if (envMode == EnvMode::mix || envMode == EnvMode::scratch)
  3171. m.addItem (tr (envModeName (envMode)), true, true, [] {});
  3172. return m;
  3173. }
  3174. // envelope y 0..1 <-> the wave area's height
  3175. float envY (double y) const noexcept { return (float) waveArea.getBottom() - 4.0f - (float) y * ((float) waveArea.getHeight() - 8.0f); }
  3176. double envValue (float py) const noexcept { return juce::jlimit (0.0, 1.0, (double) (((float) waveArea.getBottom() - 4.0f - py) / ((float) waveArea.getHeight() - 8.0f))); }
  3177. float envX (double x) const noexcept { return frameToX (x * (double) juce::jmax<std::int64_t> (1, doc.audio.frames() - 1)); }
  3178. double envPosition (int px) const noexcept { return juce::jlimit (0.0, 1.0, (double) xToFrame (px) / (double) juce::jmax<std::int64_t> (1, doc.audio.frames() - 1)); }
  3179. int envelopeHit (juce::Point<float> p)
  3180. {
  3181. auto& env = currentEnvelope();
  3182. for (int i = 0; i < (int) env.points.size(); ++i)
  3183. if (juce::Point<float> (envX (env.points[(std::size_t) i].x), envY (env.points[(std::size_t) i].y)).getDistanceFrom (p) < 7.0f)
  3184. return i;
  3185. return -1;
  3186. }
  3187. // the segment (its end point) whose hollow tension handle is under p, or -1
  3188. int envelopeHandleHit (juce::Point<float> p)
  3189. {
  3190. auto& env = currentEnvelope();
  3191. for (int i = 1; i < (int) env.points.size(); ++i)
  3192. {
  3193. const auto& a = env.points[(std::size_t) i - 1];
  3194. const auto& b = env.points[(std::size_t) i];
  3195. if (envX (b.x) - envX (a.x) < 14.0f)
  3196. continue;
  3197. const auto mx = 0.5 * (a.x + b.x);
  3198. if (juce::Point<float> (envX (mx), envY (env.at (mx))).getDistanceFrom (p) < 6.0f)
  3199. return i;
  3200. }
  3201. return -1;
  3202. }
  3203. // FL's point editing on the envelope: right-click (or click) on an empty spot adds a point and drags it, drag a
  3204. // point moves it, right-click or Alt+click on a point deletes it, the hollow handle between two points bends the
  3205. // segment (right-click it: straight). Returns true when the click was for the envelope.
  3206. bool envelopeMouseDown (const juce::MouseEvent& e)
  3207. {
  3208. auto& env = currentEnvelope();
  3209. const auto hit = envelopeHit (e.position);
  3210. envChanged = false;
  3211. if (env.empty())
  3212. env = ae::Envelope::flat (0.5); // a new envelope starts flat at its neutral value (unity / centre)
  3213. if (hit >= 0 && (e.mods.isPopupMenu() || e.mods.isAltDown()))
  3214. {
  3215. env.points.erase (env.points.begin() + hit);
  3216. if (env.points.empty())
  3217. env = {};
  3218. commit (tr ("Delete envelope point"));
  3219. return true;
  3220. }
  3221. if (const auto h = envelopeHandleHit (e.position); h > 0 && hit < 0)
  3222. {
  3223. if (e.mods.isPopupMenu())
  3224. {
  3225. env.points[(std::size_t) h].tension = 0.0f;
  3226. commit (tr ("Edit envelope"));
  3227. return true;
  3228. }
  3229. envDragPoint = h;
  3230. envBendStartY = e.position.y;
  3231. envBendStartTension = env.points[(std::size_t) h].tension;
  3232. drag = Drag::envBend;
  3233. return true;
  3234. }
  3235. envDragPoint = hit >= 0 ? hit : env.insert (envPosition (e.x), envValue (e.position.y));
  3236. envChanged = hit < 0;
  3237. drag = Drag::envPoint;
  3238. repaint();
  3239. return true;
  3240. }
  3241. void envelopeMouseDrag (const juce::MouseEvent& e)
  3242. {
  3243. auto& env = currentEnvelope();
  3244. if (! juce::isPositiveAndBelow (envDragPoint, (int) env.points.size()))
  3245. return;
  3246. auto& p = env.points[(std::size_t) envDragPoint];
  3247. if (drag == Drag::envBend)
  3248. {
  3249. const auto rising = p.y >= env.points[(std::size_t) envDragPoint - 1].y;
  3250. p.tension = juce::jlimit (-1.0f, 1.0f, envBendStartTension + (e.position.y - envBendStartY) / 120.0f * (rising ? 1.0f : -1.0f));
  3251. }
  3252. else
  3253. {
  3254. const auto lo = envDragPoint > 0 ? env.points[(std::size_t) envDragPoint - 1].x : 0.0;
  3255. const auto hi = envDragPoint + 1 < (int) env.points.size() ? env.points[(std::size_t) envDragPoint + 1].x : 1.0;
  3256. p.x = juce::jlimit (lo, hi, envPosition (e.x));
  3257. p.y = envValue (e.position.y);
  3258. const auto y = p.y;
  3259. setStatus (envMode == EnvMode::volume ? tr ("Volume {0} dB", { juce::String (20.0 * std::log10 (juce::jmax (1.0e-6f, ae::envelopeGain (y))), 1) })
  3260. : envMode == EnvMode::mix ? tr ("Clipboard {0}%", { juce::String (juce::roundToInt (y * 100.0)) })
  3261. : envMode == EnvMode::scratch ? tr ("Play position {0} s", { juce::String (y * (double) doc.audio.frames() / doc.audio.sampleRate, 3) })
  3262. : envMode == EnvMode::panning ? tr ("Panning {0}", { juce::String (juce::roundToInt ((y * 2.0 - 1.0) * 100.0)) })
  3263. : tr ("Stereo separation {0}", { juce::String (juce::roundToInt ((y * 2.0 - 1.0) * 100.0)) }),
  3264. false);
  3265. }
  3266. envChanged = true;
  3267. repaint();
  3268. }
  3269. void paintEnvelopes (juce::Graphics& g)
  3270. {
  3271. struct Lane
  3272. {
  3273. const ae::Envelope* env;
  3274. EnvMode mode;
  3275. juce::Colour colour;
  3276. };
  3277. const Lane lanes[] = { { &doc.volumeEnvelope, EnvMode::volume, theme::colour::meterLow },
  3278. { &doc.panEnvelope, EnvMode::panning, theme::colour::info },
  3279. { &doc.separationEnvelope, EnvMode::separation, theme::colour::warning },
  3280. { &doc.mixEnvelope, EnvMode::mix, theme::colour::accent },
  3281. { &doc.scratchEnvelope, EnvMode::scratch, theme::colour::accent } };
  3282. for (const auto& l : lanes)
  3283. {
  3284. const auto active = envMode == l.mode;
  3285. if (l.env->empty() && ! active)
  3286. continue;
  3287. if (active)
  3288. {
  3289. // the neutral line (unity / centre)
  3290. g.setColour (l.colour.withAlpha (0.25f));
  3291. g.drawHorizontalLine ((int) envY (0.5), (float) waveArea.getX(), (float) waveArea.getRight());
  3292. }
  3293. if (l.env->empty())
  3294. continue;
  3295. juce::Path path;
  3296. for (int x = waveArea.getX(); x <= waveArea.getRight(); x += 2)
  3297. {
  3298. const auto pt = juce::Point<float> ((float) x, envY (l.env->at (envPosition (x))));
  3299. if (x == waveArea.getX())
  3300. path.startNewSubPath (pt);
  3301. else
  3302. path.lineTo (pt);
  3303. }
  3304. g.setColour (l.colour.withAlpha (active ? 0.95f : 0.4f));
  3305. g.strokePath (path, juce::PathStrokeType (active ? 1.8f : 1.2f));
  3306. if (active)
  3307. for (int i = 1; i < (int) l.env->points.size(); ++i)
  3308. {
  3309. const auto& a = l.env->points[(std::size_t) i - 1];
  3310. const auto& b = l.env->points[(std::size_t) i];
  3311. if (envX (b.x) - envX (a.x) < 14.0f)
  3312. continue;
  3313. const auto mx = 0.5 * (a.x + b.x);
  3314. g.setColour (l.colour.withAlpha (0.8f));
  3315. g.drawEllipse (envX (mx) - 3.0f, envY (l.env->at (mx)) - 3.0f, 6.0f, 6.0f, 1.2f);
  3316. }
  3317. if (active)
  3318. for (const auto& p : l.env->points)
  3319. {
  3320. const auto c = juce::Point<float> (envX (p.x), envY (p.y));
  3321. g.setColour (l.colour);
  3322. g.fillEllipse (c.x - 3.5f, c.y - 3.5f, 7.0f, 7.0f);
  3323. g.setColour (theme::colour::bg0);
  3324. g.drawEllipse (c.x - 3.5f, c.y - 3.5f, 7.0f, 7.0f, 1.0f);
  3325. }
  3326. }
  3327. }
  3328. void openEdisonTool (audiotools::Tool t)
  3329. {
  3330. if (doc.audio.empty() || recState != RecState::idle)
  3331. return;
  3332. audiotools::showTool (*this, t);
  3333. }
  3334. void envelopeEdit (const juce::String& label, const std::function<void (ae::Envelope&)>& fn)
  3335. {
  3336. if (doc.audio.empty())
  3337. return;
  3338. if (envMode == EnvMode::wave)
  3339. setEnvMode (EnvMode::volume);
  3340. auto& env = currentEnvelope();
  3341. if (env.empty())
  3342. env = ae::Envelope::flat (0.5);
  3343. fn (env);
  3344. commit (label);
  3345. }
  3346. void acquireThreshold()
  3347. {
  3348. if (doc.audio.empty())
  3349. return;
  3350. if (selection.empty())
  3351. {
  3352. setStatus (tr ("Select a part with only the background noise first"), false);
  3353. return;
  3354. }
  3355. noiseThreshold = ae::acquireNoiseThreshold (doc.audio, selection);
  3356. setStatus (tr ("Noise threshold: {0} dB", { juce::String (juce::Decibels::gainToDecibels (noiseThreshold, -120.0f), 1) }), false);
  3357. repaint();
  3358. }
  3359. float gateThreshold()
  3360. {
  3361. if (noiseThreshold >= 0.0f)
  3362. return noiseThreshold * 1.12f; // a little over what was measured
  3363. // not acquired: -48 dB under the peak
  3364. return ae::peak (doc.audio, {}) * juce::Decibels::decibelsToGain (-48.0f);
  3365. }
  3366. void regionsTool (const juce::String& label, const std::function<int (ae::Document&)>& fn)
  3367. {
  3368. if (std::none_of (doc.markers.begin(), doc.markers.end(), [] (const ae::Marker& m) { return m.isRegion(); }))
  3369. {
  3370. setStatus (tr ("There are no regions (Regions > Auto-slice or Trim all noise & slice up make them)"), false);
  3371. return;
  3372. }
  3373. stopPlayback();
  3374. const auto n = fn (doc);
  3375. commit (label);
  3376. setStatus (tr ("{0} regions", { juce::String (n) }), false);
  3377. }
  3378. AudioEngine& engine;
  3379. Source source;
  3380. ae::Document doc;
  3381. ae::History history;
  3382. std::shared_ptr<wave::Summary> summary;
  3383. int docVersion = 0;
  3384. bool modified = false;
  3385. juce::File lastFile;
  3386. ae::WavFormat bits = ae::WavFormat::int24;
  3387. ae::Range selection;
  3388. std::int64_t cursor = 0, anchor = 0;
  3389. double viewStart = 0.0, fpp = 1.0;
  3390. Drag drag = Drag::none;
  3391. int dragMarkerIndex = -1;
  3392. bool spectrumView = false, logFrequency = true;
  3393. int fftSize = 2048;
  3394. juce::Image spectrumImage;
  3395. juce::String spectrumKey;
  3396. TimeFormat timeFormat = TimeFormat::automatic;
  3397. bool snapZero = false;
  3398. ae::Curve fadeCurve = ae::Curve::smooth;
  3399. bool playing = false, loopPlay = false;
  3400. ScriptRef lastScript; // Edit last script
  3401. bool scriptBusy = false; // a script is running (its form may be open)
  3402. bool scoreBusy = false; // Convert to score is analysing
  3403. std::uint64_t previewTicket = 0;
  3404. std::int64_t playFrom = 0, playhead = -1;
  3405. double playStartedMs = 0.0;
  3406. RecState recState = RecState::idle;
  3407. bool openedInput = false; // startRecording opened the device input itself (released when it stops)
  3408. RecordMode recordMode = RecordMode::now;
  3409. int recordSource = AudioCapture::input;
  3410. std::vector<float> recL, recR;
  3411. ae::Document beforeRecording;
  3412. std::int64_t recordAt = 0;
  3413. double recordRate = 44100.0;
  3414. bool recordStereo = true;
  3415. int recordTicks = 0;
  3416. juce::String status;
  3417. bool statusIsError = false;
  3418. std::unique_ptr<juce::FileChooser> chooser;
  3419. juce::Rectangle<int> rulerArea, waveArea, levelArea, overviewArea, infoArea;
  3420. IconButton menuButton { "menu", Icon::panelMenu }, undoButton { "undo", Icon::undo }, redoButton { "redo", Icon::redo },
  3421. historyButton { "history", Icon::chevronDown }, recordButton { "record", Icon::record }, recordMenuButton { "recordMenu", Icon::chevronDown },
  3422. playButton { "play", Icon::play }, stopButton { "stop", Icon::stop }, snapButton { "snap", Icon::magnet }, fitButton { "fit", Icon::zoom },
  3423. saveButton { "save", Icon::save }, followButton { "follow", Icon::follow };
  3424. juce::TextButton loopButton, viewButton, sendButton, envButton;
  3425. // warp markers (round 175a, M3): a lane above the waveform with the channel's markers, for a channel source
  3426. juce::TextButton warpButton, autoWarpButton;
  3427. bool warpMode = false;
  3428. juce::Rectangle<int> warpLane;
  3429. int warpDrag = -1, warpSelected = -1; // marker index (in the channel's markers)
  3430. double warpDragSeconds = 0.0; // where the dragged marker goes (applied on release)
  3431. std::vector<double> warpAttacks; // the file's attacks (seconds): the transient ticks, and where drags snap
  3432. const void* warpAttacksOf = nullptr; // the audio they were found in
  3433. juce::Slider volumeKnob { juce::Slider::RotaryHorizontalVerticalDrag, juce::Slider::NoTextBox };
  3434. juce::OwnedArray<juce::TextButton> quickButtons;
  3435. void refreshVolumeKnob()
  3436. {
  3437. volumeKnob.setValue (engine.getEditorVolume(), juce::dontSendNotification);
  3438. const auto text = tr ("Playback volume: {0} (the audio is not changed; Tools > Amp... changes it)", { ui::utilityVolumeText (engine.getEditorVolume()) });
  3439. volumeKnob.setTooltip (text);
  3440. ui::setHint (volumeKnob, text + " " + tr ("[LMB] drag [Wheel] step [2xLMB] 100% [RMB] type a value"), true);
  3441. }
  3442. };
  3443. juce::PopupMenu AudioEditor::editMenu (bool contextual)
  3444. {
  3445. juce::PopupMenu menu;
  3446. const auto has = ! doc.audio.empty();
  3447. const auto sel = ! selection.empty();
  3448. const auto clip = ! clipboard().empty();
  3449. if (! contextual)
  3450. {
  3451. menu.addItem (tr ("Undo") + "\tCtrl+Z", history.canUndo(), false, [this] { undo(); });
  3452. menu.addItem (tr ("Redo") + "\tCtrl+Y", history.canRedo(), false, [this] { redo(); });
  3453. menu.addSubMenu (tr ("Undo history"), historyMenu());
  3454. menu.addSeparator();
  3455. }
  3456. menu.addItem (tr ("Cut") + "\tCtrl+X", sel, false, [this] { cutSelection(); });
  3457. menu.addItem (tr ("Copy") + "\tCtrl+C", sel, false, [this] { copySelection(); });
  3458. menu.addItem (tr ("Paste insert") + "\tCtrl+V", clip && selection.empty(), false, [this] { paste (false); });
  3459. menu.addItem (tr ("Paste replace"), clip && sel, false, [this] { paste (false); });
  3460. menu.addItem (tr ("Paste mix"), clip && has, false, [this] { paste (true); });
  3461. menu.addItem (envMode == EnvMode::mix ? tr ("Paste mix (envelope): apply") : tr ("Paste mix (envelope)"), clip && has, false, [this] { pasteMixWithEnvelope(); });
  3462. menu.addItem (tr ("Paste mix (spectral)..."), clip && has, false, [this] {
  3463. if (selection.empty())
  3464. selection = { cursor, juce::jmin (doc.audio.frames(), cursor + ae::conform (clipboard(), doc.audio.numChannels(), doc.audio.sampleRate).frames()) };
  3465. openEdisonTool (audiotools::Tool::pasteSpectral);
  3466. });
  3467. // Edison's "Paste stretch" / "Paste replace (drum)" (round 165l): the clipboard brought to the selection's length
  3468. menu.addItem (tr ("Paste stretch"), clip && sel, false, [this] { pasteFitted (false); });
  3469. menu.addItem (tr ("Paste replace (drum)"), clip && sel, false, [this] { pasteFitted (true); });
  3470. menu.addSeparator();
  3471. menu.addItem (tr ("Delete") + "\tDel", sel, false, [this] { deleteSelection(); });
  3472. menu.addItem (tr ("Clear (silence)"), sel, false, [this] { edit (tr ("Silence"), [] (ae::Document& d, ae::Range r) { ae::clear (d, r); }, true); });
  3473. menu.addItem (tr ("Trim (keep the selection)"), sel, false, [this] { trimSelection(); });
  3474. // (right-click on the selection: issue #12)
  3475. menu.addItem (tr ("Send the selection to a new Sampler channel"), sel, false, [this] { sendRangeToNewSampler (selection); });
  3476. menu.addItem (tr ("Insert silence..."), has, false, [this] { showInsertSilence(); });
  3477. menu.addItem (tr ("Delete the part after the loop"), has && doc.hasLoop(), false,
  3478. [this] { edit (tr ("Delete after loop"), [] (ae::Document& d, ae::Range) { ae::deleteAfterLoop (d); }); });
  3479. menu.addSeparator();
  3480. menu.addItem (tr ("Select all") + "\tCtrl+A", has, false, [this] {
  3481. selection = { 0, doc.audio.frames() };
  3482. repaint();
  3483. });
  3484. menu.addItem (tr ("Deselect") + "\tEsc", sel, false, [this] {
  3485. selection = {};
  3486. repaint();
  3487. });
  3488. if (contextual)
  3489. {
  3490. menu.addSeparator();
  3491. menu.addItem (tr ("Add marker") + "\tM", has, false, [this] { addMarkerAtCursor(); });
  3492. menu.addItem (tr ("Add region"), sel, false, [this] { addRegionFromSelection(); });
  3493. menu.addItem (tr ("Set loop"), sel, false, [this] { setLoopFromSelection(); });
  3494. menu.addItem (tr ("Zoom on the selection"), sel, false, [this] { zoomTo (selection); });
  3495. }
  3496. return menu;
  3497. }
  3498. juce::PopupMenu AudioEditor::mainMenu()
  3499. {
  3500. const auto has = ! doc.audio.empty();
  3501. juce::PopupMenu file;
  3502. file.addItem (tr ("New (empty)"), [this] {
  3503. stopPlayback();
  3504. source = {};
  3505. setDocument ({}, tr ("Empty"));
  3506. });
  3507. file.addItem (tr ("Open audio file..."), [this] { openFileDialog(); });
  3508. juce::PopupMenu save;
  3509. save.addItem (tr ("16-bit"), has, bits == ae::WavFormat::int16, [this] { saveAs (ae::WavFormat::int16); });
  3510. save.addItem (tr ("24-bit"), has, bits == ae::WavFormat::int24, [this] { saveAs (ae::WavFormat::int24); });
  3511. save.addItem (tr ("32-bit float"), has, bits == ae::WavFormat::float32, [this] { saveAs (ae::WavFormat::float32); });
  3512. file.addSubMenu (tr ("Save as WAV"), save, has);
  3513. file.addItem (tr ("Export regions as files..."), has && ! doc.markers.empty(), false, [this] { exportRegions(); });
  3514. file.addSeparator();
  3515. file.addItem (tr ("Send to the Playlist as an audio clip"), has, false, [this] { sendToPlaylist(); });
  3516. file.addItem (tr ("Send to a new Sampler channel"), has, false, [this] { sendToNewSampler(); });
  3517. juce::PopupMenu tools;
  3518. using T = audiotools::Tool;
  3519. const auto envOn = has && envMode != EnvMode::wave;
  3520. const auto envAny = has && ae::hasEnvelopes (doc);
  3521. tools.addSectionHeader (tr ("Envelope"));
  3522. tools.addSubMenu (tr ("Edit"), envModeMenu(), has);
  3523. tools.addItem (tr ("Cancel all envelopes"), envAny, false, [this] {
  3524. doc.volumeEnvelope = doc.panEnvelope = doc.separationEnvelope = doc.mixEnvelope = doc.scratchEnvelope = {};
  3525. if (envMode == EnvMode::mix || envMode == EnvMode::scratch)
  3526. setEnvMode (EnvMode::wave);
  3527. commit (tr ("Cancel all envelopes"));
  3528. });
  3529. tools.addItem (tr ("Add points at selection"), has && ! selection.empty(), false, [this] {
  3530. const auto n = (double) juce::jmax<std::int64_t> (1, doc.audio.frames() - 1);
  3531. const std::vector<double> xs { (double) selection.start / n, (double) selection.end / n };
  3532. envelopeEdit (tr ("Add points at selection"), [xs] (ae::Envelope& e) { ae::addPointsAt (e, xs); });
  3533. });
  3534. tools.addItem (tr ("Add points at regions"), has && ! doc.markers.empty(), false, [this] {
  3535. const auto n = (double) juce::jmax<std::int64_t> (1, doc.audio.frames() - 1);
  3536. std::vector<double> xs;
  3537. for (const auto& m : doc.markers)
  3538. {
  3539. xs.push_back ((double) m.start / n);
  3540. if (m.isRegion())
  3541. xs.push_back ((double) m.end / n);
  3542. }
  3543. envelopeEdit (tr ("Add points at regions"), [xs] (ae::Envelope& e) { ae::addPointsAt (e, xs); });
  3544. });
  3545. tools.addItem (tr ("Flip vertically"), envOn, false, [this] { envelopeEdit (tr ("Flip vertically"), [] (ae::Envelope& e) { ae::flipLevels (e); }); });
  3546. tools.addItem (tr ("Scale levels..."), has, false, [this] { openEdisonTool (T::scaleLevels); });
  3547. tools.addItem (tr ("Normalize levels"), envOn, false, [this] { envelopeEdit (tr ("Normalize levels"), [] (ae::Envelope& e) { ae::normalizeLevels (e); }); });
  3548. tools.addItem (tr ("Decimate points..."), has, false, [this] { openEdisonTool (T::decimate); });
  3549. tools.addItem (tr ("Filter..."), has, false, [this] { openEdisonTool (T::envFilter); });
  3550. tools.addItem (tr ("Smooth up..."), has, false, [this] { openEdisonTool (T::smoothUp); });
  3551. tools.addItem (tr ("Turn all points smooth"), envOn, false, [this] { envelopeEdit (tr ("Turn all points smooth"), [] (ae::Envelope& e) { ae::makePointsSmooth (e); }); });
  3552. tools.addItem (tr ("Create sequence..."), has, false, [this] { openEdisonTool (T::createSequence); });
  3553. tools.addSectionHeader (tr ("Amp"));
  3554. tools.addItem (tr ("Mixdown amp envelopes"), envAny, false, [this] {
  3555. stopPlayback();
  3556. ae::mixdownEnvelopes (doc);
  3557. setEnvMode (EnvMode::wave);
  3558. commit (tr ("Mixdown amp envelopes"));
  3559. });
  3560. tools.addItem (tr ("Amp..."), has, false, [this] { showAmp(); });
  3561. tools.addItem (tr ("Reverse polarity"), has, false, [this] { edit (tr ("Reverse polarity"), [] (ae::Document& d, ae::Range r) { ae::invert (d, r); }); });
  3562. tools.addItem (tr ("Normalize"), has, false, [this] { edit (tr ("Normalize"), [] (ae::Document& d, ae::Range r) { ae::normalize (d, r); }); });
  3563. tools.addItem (tr ("Normalize to..."), has, false, [this] { showNormalizeTo(); });
  3564. tools.addItem (tr ("Lossy normalize"), has, false, [this] { edit (tr ("Lossy normalize"), [] (ae::Document& d, ae::Range r) { ae::lossyNormalize (d, r); }); });
  3565. tools.addItem (tr ("Fade in"), has, false, [this] { fade (true); });
  3566. tools.addItem (tr ("Fade out"), has, false, [this] { fade (false); });
  3567. tools.addSubMenu (tr ("Fade curve"), curveMenu());
  3568. tools.addItem (tr ("Declick in"), has, false, [this] { edit (tr ("Declick in"), [] (ae::Document& d, ae::Range r) { ae::declickIn (d, r); }); });
  3569. tools.addItem (tr ("Declick out"), has, false, [this] { edit (tr ("Declick out"), [] (ae::Document& d, ae::Range r) { ae::declickOut (d, r); }); });
  3570. tools.addSectionHeader (tr ("Waveform"));
  3571. tools.addItem (tr ("Remove DC offset (center)"), has, false, [this] { edit (tr ("Remove DC offset"), [] (ae::Document& d, ae::Range r) { ae::removeDc (d, r); }); });
  3572. tools.addSectionHeader (tr ("Time"));
  3573. tools.addItem (tr ("Reverse"), has, false, [this] { edit (tr ("Reverse"), [] (ae::Document& d, ae::Range r) { ae::reverse (d, r); }); });
  3574. tools.addItem (tr ("Time stretch / pitch shift..."), has, false, [this] { openEdisonTool (T::stretch); });
  3575. tools.addItem (tr ("Drum(loop) stretch..."), has, false, [this] { openEdisonTool (T::drumStretch); });
  3576. tools.addItem (tr ("Claw machine..."), has, false, [this] { openEdisonTool (T::claw); });
  3577. tools.addItem (envMode == EnvMode::scratch ? tr ("Scratch (envelope): apply") : tr ("Scratch (envelope)"), has, false, [this] { scratchWithEnvelope(); });
  3578. tools.addItem (tr ("Resample..."), has, false, [this] { showResample(); });
  3579. tools.addSectionHeader (tr ("Channels"));
  3580. const auto stereo = doc.audio.numChannels() > 1;
  3581. tools.addItem (tr ("Swap channels"), has && stereo, false, [this] { edit (tr ("Swap channels"), [] (ae::Document& d, ae::Range) { ae::swapChannels (d); }); });
  3582. tools.addItem (tr ("Convert to mono (mix)"), has && stereo, false, [this] { edit (tr ("Convert to mono"), [] (ae::Document& d, ae::Range) { ae::toMono (d, ae::MonoSource::merged); }); });
  3583. tools.addItem (tr ("Convert the left channel to mono"), has && stereo, false, [this] { edit (tr ("Convert to mono"), [] (ae::Document& d, ae::Range) { ae::toMono (d, ae::MonoSource::left); }); });
  3584. tools.addItem (tr ("Convert the right channel to mono"), has && stereo, false, [this] { edit (tr ("Convert to mono"), [] (ae::Document& d, ae::Range) { ae::toMono (d, ae::MonoSource::right); }); });
  3585. tools.addItem (tr ("Convert a mono signal to mono format"), has && stereo, false, [this] {
  3586. stopPlayback();
  3587. if (ae::monoIfMono (doc))
  3588. commit (tr ("Convert to mono"));
  3589. else
  3590. setStatus (tr ("The left and right channels differ: the audio is really stereo"), false);
  3591. });
  3592. tools.addItem (tr ("Convert to stereo"), has && ! stereo, false, [this] { edit (tr ("Convert to stereo"), [] (ae::Document& d, ae::Range) { ae::toStereo (d); }); });
  3593. tools.addSectionHeader (tr ("Synthesis"));
  3594. tools.addItem (tr ("Generate noise"), true, false, [this] {
  3595. stopPlayback();
  3596. if (doc.audio.channels.empty())
  3597. {
  3598. doc.audio = ae::silence (2, 44100.0, 0);
  3599. history.reset (doc, tr ("Empty").toStdString());
  3600. }
  3601. const auto at = selection.empty() ? cursor : selection.start;
  3602. const auto length = selection.empty() ? (std::int64_t) doc.audio.sampleRate : selection.length();
  3603. ae::generateNoise (doc, selection, 1.0f, (std::uint32_t) juce::Random::getSystemRandom().nextInt(), length);
  3604. selection = { at, at + length };
  3605. commit (tr ("Generate noise"));
  3606. if (history.size() <= 2)
  3607. zoomToFit();
  3608. });
  3609. tools.addSectionHeader (tr ("Scripting"));
  3610. tools.addSubMenu (tr ("Run script"), scriptMenu(), ! scriptBusy);
  3611. tools.addItem (lastScript.key.isEmpty() ? tr ("Edit last script") : tr ("Edit last script: {0}", { lastScript.name }), ! lastScript.key.isEmpty(), false,
  3612. [this] { editLastScript(); });
  3613. tools.addSectionHeader (tr ("Noise gating"));
  3614. tools.addItem (tr ("Acquire noise threshold"), has && ! selection.empty(), false, [this] { acquireThreshold(); });
  3615. tools.addItem (tr ("Gate noise"), has, false, [this] {
  3616. const auto t = gateThreshold();
  3617. edit (tr ("Gate noise"), [t] (ae::Document& d, ae::Range r) { ae::gateNoise (d, r, t); });
  3618. });
  3619. tools.addItem (tr ("Trim side noise"), has, false, [this] {
  3620. const auto t = gateThreshold();
  3621. edit (tr ("Trim side noise"), [t] (ae::Document& d, ae::Range r) { ae::trimSideNoise (d, r, t); });
  3622. });
  3623. tools.addItem (tr ("Trim all noise && slice up"), has, false, [this] {
  3624. const auto t = gateThreshold();
  3625. int n = 0;
  3626. edit (tr ("Trim all noise & slice up"), [t, &n] (ae::Document& d, ae::Range r) { n = ae::trimNoiseAndSlice (d, r, t); });
  3627. setStatus (tr ("{0} regions", { juce::String (n) }), false);
  3628. });
  3629. tools.addSectionHeader (tr ("Spectral"));
  3630. tools.addItem (tr ("Convolution reverb..."), has, false, [this] { openEdisonTool (T::reverb); });
  3631. tools.addItem (tr ("Blur..."), has, false, [this] { openEdisonTool (T::blur); });
  3632. tools.addItem (tr ("Equalize..."), has, false, [this] { openEdisonTool (T::equalize); });
  3633. tools.addItem (tr ("Acquire noise profile"), has && ! selection.empty(), false, [this] {
  3634. noiseProfile = ae::acquireNoiseProfile (doc.audio, selection);
  3635. setStatus (tr ("Noise profile acquired from the selection: Clean up (denoise) uses it"), false);
  3636. });
  3637. tools.addItem (tr ("Clean up (denoise)..."), has, false, [this] { openEdisonTool (T::denoise); });
  3638. tools.addItem (tr ("Match spectrum..."), has, false, [this] { openEdisonTool (T::matchSpectrum); });
  3639. tools.addItem (tr ("Vocal denoise/isolator..."), has, false, [this] { openEdisonTool (T::vocalDenoise); });
  3640. tools.addItem (tr ("Deverb..."), has, false, [this] { openEdisonTool (T::deverb); });
  3641. tools.addSectionHeader (tr ("Regions"));
  3642. tools.addItem (tr ("Normalize all regions"), has, false, [this] { regionsTool (tr ("Normalize all regions"), [] (ae::Document& d) { return ae::normalizeRegions (d); }); });
  3643. tools.addItem (tr ("Declick in all regions"), has, false, [this] { regionsTool (tr ("Declick in all regions"), [] (ae::Document& d) { return ae::declickRegions (d, true, false); }); });
  3644. tools.addItem (tr ("Declick out all regions"), has, false, [this] { regionsTool (tr ("Declick out all regions"), [] (ae::Document& d) { return ae::declickRegions (d, false, true); }); });
  3645. tools.addItem (tr ("Perfect all regions"), has, false, [this] { regionsTool (tr ("Perfect all regions"), [] (ae::Document& d) { return ae::perfectRegions (d); }); });
  3646. tools.addItem (tr ("Tune loop..."), has, false, [this] { openEdisonTool (T::loopTuner); });
  3647. tools.addSectionHeader (tr ("Analysis"));
  3648. tools.addItem (tr ("Convert to score and dump to piano roll"), has && ! scoreBusy, false, [this] { convertToScore(); });
  3649. juce::PopupMenu regions;
  3650. regions.addItem (tr ("Add marker") + "\tM", has, false, [this] { addMarkerAtCursor(); });
  3651. regions.addItem (tr ("Add region"), has && ! selection.empty(), false, [this] { addRegionFromSelection(); });
  3652. regions.addItem (tr ("Set loop"), has && ! selection.empty(), false, [this] { setLoopFromSelection(); });
  3653. regions.addItem (tr ("Remove loop"), doc.hasLoop(), false, [this] {
  3654. ae::setLoop (doc, {});
  3655. commit (tr ("Remove loop"));
  3656. });
  3657. regions.addItem (tr ("Delete markers in the selection"), has && ! doc.markers.empty(), false, [this] {
  3658. if (ae::removeMarkers (doc, ae::orAll (doc, selection)) > 0)
  3659. commit (tr ("Delete markers"));
  3660. });
  3661. regions.addSeparator();
  3662. juce::PopupMenu slice;
  3663. slice.addItem (tr ("Dull auto-slicing"), has, false, [this] { autoSlice (0.2f); });
  3664. slice.addItem (tr ("Medium auto-slicing"), has, false, [this] { autoSlice (0.5f); });
  3665. slice.addItem (tr ("Sharp auto-slicing"), has, false, [this] { autoSlice (0.85f); });
  3666. slice.addSeparator();
  3667. slice.addItem (tr ("Every beat (project tempo)"), has, false, [this] { gridSlice (1.0); });
  3668. slice.addItem (tr ("Every 1/2 beat"), has, false, [this] { gridSlice (0.5); });
  3669. slice.addItem (tr ("Every 1/4 beat"), has, false, [this] { gridSlice (0.25); });
  3670. regions.addSubMenu (tr ("Auto-slice"), slice, has);
  3671. juce::PopupMenu view;
  3672. view.addItem (tr ("Waveform"), true, ! spectrumView, [this] { viewButton.setToggleState (false, juce::sendNotification); });
  3673. view.addItem (tr ("Spectrogram") + "\tS", true, spectrumView, [this] { viewButton.setToggleState (true, juce::sendNotification); });
  3674. juce::PopupMenu precision;
  3675. for (int size : { 512, 1024, 2048, 4096, 8192 })
  3676. precision.addItem (tr ("{0} bands", { juce::String (size / 2) }), true, fftSize == size, [this, size] {
  3677. fftSize = size;
  3678. repaint();
  3679. });
  3680. view.addSubMenu (tr ("Spectrum precision"), precision);
  3681. view.addItem (tr ("Logarithmic frequency scale"), true, logFrequency, [this] {
  3682. logFrequency = ! logFrequency;
  3683. repaint();
  3684. });
  3685. juce::PopupMenu time;
  3686. const std::pair<TimeFormat, const char*> formats[] = { { TimeFormat::automatic, TR_NOOP ("Auto") },
  3687. { TimeFormat::seconds, TR_NOOP ("Minutes : seconds") },
  3688. { TimeFormat::samples, TR_NOOP ("Samples") },
  3689. { TimeFormat::bars, TR_NOOP ("Bar : beat : tick") } };
  3690. for (const auto& [f, name] : formats)
  3691. time.addItem (tr (name), true, timeFormat == f, [this, f = f] {
  3692. timeFormat = f;
  3693. repaint();
  3694. });
  3695. view.addSubMenu (tr ("Time format"), time);
  3696. view.addSeparator();
  3697. view.addItem (tr ("Zoom in") + "\t+", has, false, [this] { zoomAround ((float) waveArea.getCentreX(), 0.5); });
  3698. view.addItem (tr ("Zoom out") + "\t-", has, false, [this] { zoomAround ((float) waveArea.getCentreX(), 2.0); });
  3699. view.addItem (tr ("Zoom out full") + "\tF", has, false, [this] { zoomToFit(); });
  3700. view.addItem (tr ("Zoom on the selection"), has && ! selection.empty(), false, [this] { zoomTo (selection); });
  3701. view.addItem (tr ("Snap to zero crossings"), true, snapZero, [this] { snapButton.setToggleState (! snapZero, juce::sendNotification); });
  3702. juce::PopupMenu menu;
  3703. menu.addSubMenu (tr ("File"), file);
  3704. menu.addSubMenu (tr ("Edit"), editMenu (false));
  3705. menu.addSubMenu (tr ("Tools"), tools, has);
  3706. menu.addSubMenu (tr ("Regions"), regions, has);
  3707. menu.addSubMenu (tr ("View"), view);
  3708. menu.addSubMenu (tr ("Record"), recordMenu());
  3709. if (source.kind == Source::Kind::channel)
  3710. {
  3711. juce::PopupMenu warp;
  3712. warp.addItem (tr ("Show warp markers"), has, warpMode, [this] { setWarpMode (! warpMode); });
  3713. warp.addItem (tr ("Auto-warp"), has, false, [this] { autoWarp(); });
  3714. warp.addItem (tr ("Remove the selected warp marker"), warpMode && warpSelected > 0, false, [this] { removeWarpMarker (warpSelected); });
  3715. warp.addItem (tr ("Remove all warp markers"), has && warpMarkers().size() > 2, false, [this] {
  3716. editWarp ([] (SamplerSettings& s, double) { warpedit::clearMarkers (s); });
  3717. });
  3718. menu.addSubMenu (tr ("Warp markers"), warp);
  3719. }
  3720. return menu;
  3721. }
  3722. juce::String windowKey (const Source& s)
  3723. {
  3724. switch (s.kind)
  3725. {
  3726. case Source::Kind::file: return "audioeditor:" + s.path;
  3727. case Source::Kind::channel: return "audioeditor:channel:" + juce::String (s.index);
  3728. case Source::Kind::insert: return "audioeditor:insert:" + juce::String (s.index);
  3729. case Source::Kind::none: break;
  3730. }
  3731. return "audioeditor";
  3732. }
  3733. AudioEditor* openWindow (AudioEngine& engine, Source source)
  3734. {
  3735. auto editor = std::make_unique<AudioEditor> (engine, source);
  3736. auto* raw = editor.get();
  3737. if (auto* window = openToolWindow (std::move (editor), tr ("Audio editor"), windowKey (source)))
  3738. {
  3739. window->setResizable (true, false);
  3740. window->setResizeLimits (720, 380, 4000, 3000);
  3741. }
  3742. return raw;
  3743. }
  3744. } // namespace
  3745. void openAudioEditor (AudioEngine& engine)
  3746. {
  3747. openWindow (engine, {});
  3748. }
  3749. void openAudioEditor (AudioEngine& engine, const juce::File& file)
  3750. {
  3751. Source s { Source::Kind::file, -1, file.getFullPathName() };
  3752. openWindow (engine, s)->loadFile (file);
  3753. }
  3754. void openAudioEditorForChannel (AudioEngine& engine, int channel, int clip)
  3755. {
  3756. const auto& song = engine.getSong();
  3757. if (! juce::isPositiveAndBelow (channel, (int) song.channels.size()))
  3758. return;
  3759. const auto& c = song.channels[(std::size_t) channel];
  3760. const auto path = juce::String::fromUTF8 (c.samplePath.c_str());
  3761. auto* editor = openWindow (engine, { Source::Kind::channel, channel, path, clip });
  3762. if (path.isNotEmpty())
  3763. editor->loadFile (juce::File (path));
  3764. }
  3765. std::unique_ptr<juce::Component> makeAudioEditorPanel (AudioEngine& engine, int channel, int clip, bool showWarp)
  3766. {
  3767. const auto& song = engine.getSong();
  3768. if (! juce::isPositiveAndBelow (channel, (int) song.channels.size()))
  3769. return {};
  3770. const auto path = juce::String::fromUTF8 (song.channels[(std::size_t) channel].samplePath.c_str());
  3771. auto editor = std::make_unique<AudioEditor> (engine, Source { Source::Kind::channel, channel, path, clip });
  3772. if (path.isNotEmpty())
  3773. editor->loadFile (juce::File (path));
  3774. if (showWarp)
  3775. editor->setWarpModeForPanel (true);
  3776. return editor;
  3777. }
  3778. void openAudioEditorRecording (AudioEngine& engine)
  3779. {
  3780. openWindow (engine, {})->recordInputWithSong();
  3781. }
  3782. void openAudioEditorForInsert (AudioEngine& engine, int insert)
  3783. {
  3784. auto* editor = openWindow (engine, { Source::Kind::insert, insert, {} });
  3785. editor->setRecordSource (insert);
  3786. }
  3787. std::unique_ptr<juce::Component> makeAudioEditorForSnapshot (AudioEngine& engine, audioedit::Document doc, bool spectrum)
  3788. {
  3789. auto editor = std::make_unique<AudioEditor> (engine, Source {});
  3790. const auto frames = doc.audio.frames();
  3791. editor->setDocument (std::move (doc), tr ("Open"));
  3792. editor->selectForSnapshot ({ frames / 4, frames / 2 }, spectrum);
  3793. return editor;
  3794. }
  3795. std::unique_ptr<juce::Component> makeAudioToolPanelForSnapshot (juce::Component& editor, int tool, int envelopeMode)
  3796. {
  3797. auto* e = dynamic_cast<AudioEditor*> (&editor);
  3798. if (e == nullptr || tool < 0 || tool > (int) audiotools::Tool::deverb)
  3799. return {};
  3800. e->setEnvModeForSnapshot (envelopeMode);
  3801. return audiotools::makeToolPanel (*e, (audiotools::Tool) tool);
  3802. }
  3803. const char* audioToolNameForSnapshot (int tool)
  3804. {
  3805. if (tool < 0 || tool > (int) audiotools::Tool::deverb)
  3806. return nullptr;
  3807. return audiotools::toolTitle ((audiotools::Tool) tool);
  3808. }
  3809. void setAudioEditorEnvelopeModeForSnapshot (juce::Component& editor, int mode)
  3810. {
  3811. if (auto* e = dynamic_cast<AudioEditor*> (&editor))
  3812. e->setEnvModeForSnapshot (mode);
  3813. }
  3814. juce::StringArray audioEditorMenuForSnapshot (juce::Component& component)
  3815. {
  3816. juce::StringArray lines;
  3817. auto* editor = dynamic_cast<AudioEditor*> (&component);
  3818. if (editor == nullptr)
  3819. return lines;
  3820. std::function<void (const juce::PopupMenu&, const juce::String&)> walk = [&] (const juce::PopupMenu& menu, const juce::String& prefix) {
  3821. for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
  3822. {
  3823. const auto& item = it.getItem();
  3824. if (item.isSeparator || item.text.isEmpty())
  3825. continue;
  3826. const auto text = prefix + item.text.upToFirstOccurrenceOf ("\t", false, false);
  3827. if (item.subMenu != nullptr)
  3828. walk (*item.subMenu, text + " > ");
  3829. else if (! item.isSectionHeader)
  3830. lines.add (text + (item.isEnabled ? "" : " (disabled)"));
  3831. }
  3832. };
  3833. walk (editor->mainMenu(), {});
  3834. return lines;
  3835. }
  3836. } // namespace lynx