| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067 |
- #include "ui/AudioEditor.h"
- #include "ui/AudioEditorTools.h"
- #include "ui/BrowserComponent.h"
- #include "ui/EditorTools.h"
- #include <algorithm>
- #include <cmath>
- #include <functional>
- #include <map>
- #include <optional>
- #include <thread>
- #include <juce_audio_formats/juce_audio_formats.h>
- #include "core/AudioCapture.h"
- #include "core/AudioEditTools.h"
- #include "core/AutoWarp.h"
- #include "core/EdisonScript.h"
- #include "core/Instruments.h"
- #include "core/NewtoneFx.h"
- #include "core/WaveAnalysis.h"
- #include "core/ValueMath.h"
- #include "core/WarpEdit.h"
- #include "engine/SampleLibrary.h"
- #include "engine/Text.h"
- #include "platform/Paths.h"
- #include "ui/AudioClipboard.h"
- #include "ui/FileChoosers.h"
- #include "ui/HintBar.h"
- #include "ui/ValueControl.h"
- #include "ui/I18n.h"
- #include "ui/Icons.h"
- #include "ui/Theme.h"
- #include "ui/ToolWindow.h"
- namespace lynx
- {
- namespace
- {
- namespace ae = audioedit;
- // one clipboard for every editor window (copy in one, paste in another); Tools › Clipboard saves it (round 181b)
- ae::Audio& clipboard()
- {
- return audioclipboard::editor();
- }
- // an audio file read on a worker thread (an audio script's Sample.LoadFromFile)
- bool readAudioFile (const juce::File& file, ae::Audio& out)
- {
- juce::AudioFormatManager formats;
- formats.registerBasicFormats();
- std::unique_ptr<juce::AudioFormatReader> reader (formats.createReaderFor (file));
- if (reader == nullptr || reader->lengthInSamples <= 0 || reader->lengthInSamples > (juce::int64) 1 << 31 || reader->numChannels == 0)
- return false;
- const auto channels = (int) juce::jmin (2u, reader->numChannels);
- juce::AudioBuffer<float> buffer (channels, (int) reader->lengthInSamples);
- if (! reader->read (&buffer, 0, buffer.getNumSamples(), 0, true, channels > 1))
- return false;
- out = ae::silence (channels, reader->sampleRate, buffer.getNumSamples());
- for (int c = 0; c < channels; ++c)
- std::copy (buffer.getReadPointer (c), buffer.getReadPointer (c) + buffer.getNumSamples(), out.channels[(std::size_t) c].begin());
- return true;
- }
- // the clean clip look (docs/analise/UI_STUDY_playlist_clips.md): one light filled shape in a tint of the audio colour
- juce::Colour waveColour() { return theme::colour::audioClip.interpolatedWith (juce::Colours::white, 0.7f); }
- enum class TimeFormat
- {
- automatic,
- samples,
- seconds,
- bars
- };
- enum class RecordMode
- {
- now, // starts at once
- onInput, // starts when the input goes above the threshold
- onPlay // starts with the song playback, stops with it
- };
- constexpr float inputThreshold = 0.01f; // -40 dBFS
- juce::String formatSeconds (double s)
- {
- const auto negative = s < 0.0;
- s = std::abs (s);
- const auto minutes = (int) (s / 60.0);
- const auto rest = s - minutes * 60.0;
- return juce::String (negative ? "-" : "") + juce::String (minutes) + ":" + juce::String (rest, 3).paddedLeft ('0', 6);
- }
- // Spectrogram colours (LYNX's own map): the canvas, a deep red, the accent, amber, then white for the loudest.
- juce::Colour spectrumColour (float db)
- {
- const auto t = juce::jlimit (0.0f, 1.0f, (db + 96.0f) / 96.0f);
- static const juce::Colour stops[] = { theme::colour::bg0, juce::Colour (0xff3a1016), theme::colour::accent, theme::colour::warning,
- juce::Colour (0xfffff4dc) };
- static const float at[] = { 0.0f, 0.35f, 0.62f, 0.85f, 1.0f };
- for (int i = 1; i < 5; ++i)
- if (t <= at[i])
- return stops[i - 1].interpolatedWith (stops[i], (t - at[i - 1]) / (at[i] - at[i - 1]));
- return stops[4];
- }
- // --- a small parameter window for the tools (sliders + an optional choice; Preview / Accept / Cancel) ------------
- class ToolPanel final : public juce::Component
- {
- public:
- struct Param
- {
- juce::String name;
- double min = 0.0, max = 1.0, value = 0.0, step = 0.0;
- juce::String suffix;
- };
- using Action = std::function<void (const std::vector<double>&, int)>;
- ToolPanel (std::vector<Param> ps, juce::StringArray choices, const juce::String& choiceName, int choice, Action applyAction, Action previewAction)
- : params (std::move (ps)), apply (std::move (applyAction)), preview (std::move (previewAction))
- {
- for (const auto& p : params)
- {
- auto* label = labels.add (new juce::Label ({}, p.name));
- label->setFont (theme::font (theme::type::body));
- label->setColour (juce::Label::textColourId, theme::colour::textSecondary);
- addAndMakeVisible (label);
- auto* s = sliders.add (new juce::Slider (juce::Slider::LinearHorizontal, juce::Slider::TextBoxRight));
- s->setRange (p.min, p.max, p.step);
- s->setValue (p.value, juce::dontSendNotification);
- s->setDoubleClickReturnValue (true, p.value);
- s->setTextValueSuffix (p.suffix);
- s->setTextBoxStyle (juce::Slider::TextBoxRight, false, 84, 22);
- addAndMakeVisible (s);
- }
- if (! choices.isEmpty())
- {
- choiceLabel.setText (choiceName, juce::dontSendNotification);
- choiceLabel.setFont (theme::font (theme::type::body));
- choiceLabel.setColour (juce::Label::textColourId, theme::colour::textSecondary);
- addAndMakeVisible (choiceLabel);
- choiceBox.addItemList (choices, 1);
- choiceBox.setSelectedItemIndex (choice, juce::dontSendNotification);
- addAndMakeVisible (choiceBox);
- }
- previewButton.setButtonText (tr ("Preview"));
- acceptButton.setButtonText (tr ("Accept"));
- cancelButton.setButtonText (tr ("Cancel"));
- acceptButton.setColour (juce::TextButton::buttonColourId, theme::colour::accent);
- previewButton.onClick = [this] {
- if (preview)
- preview (values(), choiceBox.getSelectedItemIndex());
- };
- acceptButton.onClick = [this] {
- if (apply)
- apply (values(), choiceBox.getSelectedItemIndex());
- closeToolWindowOf (*this);
- };
- cancelButton.onClick = [this] { closeToolWindowOf (*this); };
- previewButton.setVisible (preview != nullptr);
- for (auto* b : { &previewButton, &acceptButton, &cancelButton })
- addAndMakeVisible (*b);
- setSize (420, 24 + (int) params.size() * 36 + (choices.isEmpty() ? 0 : 36) + 52);
- }
- void paint (juce::Graphics& g) override { g.fillAll (theme::colour::bg2); }
- void resized() override
- {
- auto area = getLocalBounds().reduced (theme::space::lg);
- if (choiceBox.getNumItems() > 0)
- {
- auto row = area.removeFromTop (28);
- choiceLabel.setBounds (row.removeFromLeft (120));
- choiceBox.setBounds (row);
- area.removeFromTop (8);
- }
- for (int i = 0; i < sliders.size(); ++i)
- {
- auto row = area.removeFromTop (28);
- labels[i]->setBounds (row.removeFromLeft (120));
- sliders[i]->setBounds (row);
- area.removeFromTop (8);
- }
- auto buttons = area.removeFromBottom (30);
- cancelButton.setBounds (buttons.removeFromRight (90));
- buttons.removeFromRight (8);
- acceptButton.setBounds (buttons.removeFromRight (90));
- buttons.removeFromRight (8);
- previewButton.setBounds (buttons.removeFromRight (90));
- }
- private:
- std::vector<double> values() const
- {
- std::vector<double> v;
- for (auto* s : sliders)
- v.push_back (s->getValue());
- return v;
- }
- std::vector<Param> params;
- juce::OwnedArray<juce::Label> labels;
- juce::OwnedArray<juce::Slider> sliders;
- juce::Label choiceLabel;
- juce::ComboBox choiceBox;
- juce::TextButton previewButton, acceptButton, cancelButton;
- Action apply, preview;
- };
- // --- Edison's script form ("Configure script", REA_rodada167c.md §2): the controls a script's ScriptDialog asks for;
- // Preview (automatic, when a control changes) / Regenerate / Reset / Edit script / Run / Cancel ------------------------
- class ScriptPanel final : public juce::Component,
- private juce::Timer
- {
- public:
- using Answer = std::function<void (const ae::script::Form&)>;
- ScriptPanel (ae::script::Form f, Answer runAction, Answer previewAction, std::function<void()> editAction)
- : form (std::move (f)), defaults (form), run (std::move (runAction)), preview (std::move (previewAction)), edit (std::move (editAction))
- {
- header.setText (juce::String::fromUTF8 (form.title.c_str()), juce::dontSendNotification);
- header.setFont (theme::font (theme::type::title));
- header.setColour (juce::Label::textColourId, theme::colour::textPrimary);
- addAndMakeVisible (header);
- description.setText (juce::String::fromUTF8 (form.description.c_str()), juce::dontSendNotification);
- description.setFont (theme::font (theme::type::body));
- description.setColour (juce::Label::textColourId, theme::colour::textSecondary);
- description.setJustificationType (juce::Justification::topLeft);
- description.setVisible (! form.description.empty());
- addChildComponent (description);
- using T = ae::script::Control::Type;
- for (std::size_t i = 0; i < form.controls.size(); ++i)
- {
- const auto& c = form.controls[i];
- auto* label = labels.add (new juce::Label ({}, juce::String::fromUTF8 (c.name.c_str())));
- label->setFont (theme::font (theme::type::body));
- label->setColour (juce::Label::textColourId, theme::colour::textSecondary);
- label->setTooltip (juce::String::fromUTF8 (c.hint.c_str()));
- addAndMakeVisible (label);
- std::unique_ptr<juce::Component> editor;
- switch (c.type)
- {
- case T::value:
- case T::knob:
- case T::knobInt:
- {
- auto s = std::make_unique<juce::Slider> (juce::Slider::LinearHorizontal, juce::Slider::TextBoxRight);
- const auto lo = std::min (c.minimum, c.maximum), hi = std::max (c.minimum, c.maximum);
- s->setRange (lo, hi > lo ? hi : lo + 1.0, c.type == T::knobInt ? 1.0 : 0.0);
- s->setNumDecimalPlacesToDisplay (c.type == T::knobInt ? 0 : 3);
- s->setValue (c.value, juce::dontSendNotification);
- s->setTextBoxStyle (juce::Slider::TextBoxRight, false, 84, 22);
- s->onValueChange = [this, i, p = s.get()] {
- form.controls[i].value = p->getValue();
- changed();
- };
- editor = std::move (s);
- break;
- }
- case T::combo:
- {
- auto b = std::make_unique<juce::ComboBox>();
- for (std::size_t o = 0; o < c.options.size(); ++o)
- b->addItem (juce::String::fromUTF8 (c.options[o].c_str()), (int) o + 1);
- b->setSelectedItemIndex ((int) c.value, juce::dontSendNotification);
- b->onChange = [this, i, p = b.get()] {
- form.controls[i].value = juce::jmax (0, p->getSelectedItemIndex());
- changed();
- };
- editor = std::move (b);
- break;
- }
- case T::checkbox:
- {
- auto b = std::make_unique<juce::ToggleButton>();
- b->setToggleState (c.value != 0.0, juce::dontSendNotification);
- b->onClick = [this, i, p = b.get()] {
- form.controls[i].value = p->getToggleState() ? 1.0 : 0.0;
- changed();
- };
- editor = std::move (b);
- break;
- }
- case T::text:
- {
- auto t = std::make_unique<juce::TextEditor>();
- t->setText (juce::String::fromUTF8 (c.text.c_str()), false);
- t->onTextChange = [this, i, p = t.get()] {
- form.controls[i].text = p->getText().toStdString();
- changed();
- };
- editor = std::move (t);
- break;
- }
- case T::surface:
- {
- auto l = std::make_unique<juce::Label> (juce::String {}, tr ("(Control Surface presets are not available in LYNX SHARE)"));
- l->setFont (theme::font (theme::type::caption));
- l->setColour (juce::Label::textColourId, theme::colour::textDisabled);
- editor = std::move (l);
- break;
- }
- }
- addAndMakeVisible (*editor);
- editors.push_back (std::move (editor));
- }
- previewToggle.setButtonText (tr ("Preview"));
- previewToggle.setTooltip (tr ("Automatic preview when controls are modified"));
- previewToggle.onClick = [this] {
- if (previewToggle.getToggleState())
- startTimer (1);
- else
- stopTimer();
- };
- regenerateButton.setButtonText (tr ("Regenerate"));
- regenerateButton.onClick = [this] { startTimer (1); };
- resetButton.setButtonText (tr ("Reset"));
- resetButton.onClick = [this] { reset(); };
- editButton.setButtonText (tr ("Edit script"));
- editButton.onClick = [this] {
- if (edit)
- edit();
- };
- runButton.setButtonText (tr ("Run"));
- runButton.setColour (juce::TextButton::buttonColourId, theme::colour::accent);
- runButton.onClick = [this] {
- stopTimer();
- const auto f = form;
- auto action = run;
- closeToolWindowOf (*this); // (deletes this)
- if (action)
- action (f);
- };
- cancelButton.setButtonText (tr ("Cancel"));
- cancelButton.onClick = [this] { closeToolWindowOf (*this); };
- for (juce::Component* b : { (juce::Component*) &previewToggle, (juce::Component*) ®enerateButton, (juce::Component*) &resetButton,
- (juce::Component*) &editButton, (juce::Component*) &runButton, (juce::Component*) &cancelButton })
- addAndMakeVisible (*b);
- editButton.setVisible (edit != nullptr);
- previewToggle.setVisible (preview != nullptr);
- regenerateButton.setVisible (preview != nullptr);
- setSize (500, 24 + 34 + (form.description.empty() ? 0 : 44) + (int) form.controls.size() * 36 + 52);
- }
- void paint (juce::Graphics& g) override { g.fillAll (theme::colour::bg2); }
- void resized() override
- {
- auto area = getLocalBounds().reduced (theme::space::lg);
- header.setBounds (area.removeFromTop (26));
- area.removeFromTop (8);
- if (description.isVisible())
- {
- description.setBounds (area.removeFromTop (36));
- area.removeFromTop (8);
- }
- for (std::size_t i = 0; i < editors.size(); ++i)
- {
- auto row = area.removeFromTop (28);
- labels[(int) i]->setBounds (row.removeFromLeft (150));
- editors[i]->setBounds (row);
- area.removeFromTop (8);
- }
- auto buttons = area.removeFromBottom (30);
- previewToggle.setBounds (buttons.removeFromLeft (84));
- regenerateButton.setBounds (buttons.removeFromLeft (92));
- cancelButton.setBounds (buttons.removeFromRight (70));
- buttons.removeFromRight (6);
- runButton.setBounds (buttons.removeFromRight (70));
- buttons.removeFromRight (6);
- editButton.setBounds (buttons.removeFromRight (82));
- buttons.removeFromRight (6);
- resetButton.setBounds (buttons.removeFromRight (64));
- }
- private:
- void changed()
- {
- if (previewToggle.getToggleState())
- startTimer (250); // (a drag previews once it pauses)
- }
- void timerCallback() override
- {
- stopTimer();
- if (preview)
- preview (form);
- }
- void reset()
- {
- using T = ae::script::Control::Type;
- form = defaults;
- for (std::size_t i = 0; i < form.controls.size(); ++i)
- {
- const auto& c = form.controls[i];
- auto* e = editors[i].get();
- if (auto* s = dynamic_cast<juce::Slider*> (e))
- s->setValue (c.value, juce::dontSendNotification);
- else if (auto* b = dynamic_cast<juce::ComboBox*> (e))
- b->setSelectedItemIndex ((int) c.value, juce::dontSendNotification);
- else if (auto* t = dynamic_cast<juce::ToggleButton*> (e))
- t->setToggleState (c.value != 0.0, juce::dontSendNotification);
- else if (auto* x = dynamic_cast<juce::TextEditor*> (e); x != nullptr && c.type == T::text)
- x->setText (juce::String::fromUTF8 (c.text.c_str()), false);
- }
- changed();
- }
- ae::script::Form form, defaults;
- Answer run, preview;
- std::function<void()> edit;
- juce::Label header, description;
- juce::OwnedArray<juce::Label> labels;
- std::vector<std::unique_ptr<juce::Component>> editors;
- juce::ToggleButton previewToggle;
- juce::TextButton regenerateButton, resetButton, editButton, runButton, cancelButton;
- };
- // --- the editor --------------------------------------------------------------------------------------------------
- struct Source
- {
- enum class Kind
- {
- none,
- file,
- channel,
- insert
- };
- Kind kind = Kind::none;
- int index = -1; // channel or insert
- juce::String path;
- int clip = -1; // a channel opened from a Playlist audio clip: that clip
- };
- class AudioEditor final : public juce::Component,
- public juce::FileDragAndDropTarget,
- public audiotools::Host,
- public juce::DragAndDropTarget,
- private juce::Timer
- {
- public:
- AudioEditor (AudioEngine& e, Source s) : engine (e), source (std::move (s))
- {
- auto setupIcon = [this] (IconButton& b, const juce::String& tip) {
- b.setFlat (true);
- b.setTooltip (tip);
- addAndMakeVisible (b);
- };
- setupIcon (menuButton, tr ("Menu: file, edit, tools, regions, view"));
- setupIcon (undoButton, tr ("Undo") + " (Ctrl+Z)");
- setupIcon (redoButton, tr ("Redo") + " (Ctrl+Y)");
- setupIcon (historyButton, tr ("Undo history"));
- setupIcon (recordButton, tr ("Record") + " (R)");
- setupIcon (recordMenuButton, tr ("What and when to record"));
- setupIcon (playButton, tr ("Play / stop the selection") + " (Space)");
- setupIcon (stopButton, tr ("Stop"));
- setupIcon (snapButton, tr ("Snap the selection to zero crossings"));
- setupIcon (fitButton, tr ("Zoom out full"));
- setupIcon (saveButton, tr ("Save as WAV..."));
- // Follow (issue #12): the view pages along with the playback position; off, it stays where you look
- setupIcon (followButton, tr ("Follow: the view pages along with the playback position; off, it stays where you scrolled"));
- followButton.setClickingTogglesState (false);
- followButton.setOnColour (theme::colour::bg6);
- followButton.setIconColourWhenOn (theme::colour::accent);
- followButton.setToggleState (EditorGlobals::get().isFollowingView (EditorGlobals::FollowView::audioEditor), juce::dontSendNotification);
- followButton.onClick = [this] {
- auto& g = EditorGlobals::get();
- g.setFollowingView (EditorGlobals::FollowView::audioEditor, ! g.isFollowingView (EditorGlobals::FollowView::audioEditor));
- followButton.setToggleState (g.isFollowingView (EditorGlobals::FollowView::audioEditor), juce::dontSendNotification);
- };
- recordButton.setOnColour (theme::colour::record);
- recordButton.setClickingTogglesState (false);
- snapButton.setClickingTogglesState (true);
- menuButton.onClick = [this] { mainMenu().showMenuAsync (juce::PopupMenu::Options().withTargetComponent (&menuButton)); };
- warpButton.setButtonText (tr ("Warp markers")); // ("Warp" alone is a synth control's name in the tables)
- warpButton.setTooltip (tr ("Warp markers: tie points of the audio to beats; the audio between them stretches (the channel's markers)"));
- warpButton.setClickingTogglesState (true);
- warpButton.setColour (juce::TextButton::buttonOnColourId, theme::colour::accent);
- warpButton.onClick = [this] { setWarpMode (warpButton.getToggleState()); };
- autoWarpButton.setButtonText (tr ("Auto-warp"));
- autoWarpButton.setTooltip (tr ("Place warp markers from the tempo (the file name's, else its length) and, in a long recording, on every bar"));
- autoWarpButton.onClick = [this] { autoWarp(); };
- addChildComponent (warpButton);
- addChildComponent (autoWarpButton);
- warpButton.setVisible (source.kind == Source::Kind::channel);
- undoButton.onClick = [this] { undo(); };
- redoButton.onClick = [this] { redo(); };
- historyButton.onClick = [this] { historyMenu().showMenuAsync (juce::PopupMenu::Options().withTargetComponent (&historyButton)); };
- recordButton.onClick = [this] { toggleRecording(); };
- recordMenuButton.onClick = [this] { recordMenu().showMenuAsync (juce::PopupMenu::Options().withTargetComponent (&recordMenuButton)); };
- playButton.onClick = [this] { playing ? stopPlayback() : startPlayback(); };
- stopButton.onClick = [this] {
- stopPlayback();
- if (recState != RecState::idle)
- stopRecording();
- };
- snapButton.onClick = [this] { snapZero = snapButton.getToggleState(); };
- fitButton.onClick = [this] { zoomToFit(); };
- saveButton.onClick = [this] { saveAs (bits); };
- auto setupText = [this] (juce::TextButton& b, const juce::String& text, const juce::String& tip) {
- b.setButtonText (text);
- b.setTooltip (tip);
- addAndMakeVisible (b);
- };
- setupText (loopButton, tr ("Loop"), tr ("Loop the playback") + " (L)");
- loopButton.setClickingTogglesState (true);
- loopButton.setColour (juce::TextButton::buttonOnColourId, theme::colour::accent);
- loopButton.onClick = [this] {
- loopPlay = loopButton.getToggleState();
- if (playing)
- startPlayback();
- };
- // the playback volume (round 162, issue #9): how loud the editor plays, without changing the audio (the
- // Amp... tool changes the audio itself); remembered with the settings
- volumeKnob.setRange (0.0, controls::maxUtilityVolume, 0.01);
- volumeKnob.setDoubleClickReturnValue (true, 1.0);
- volumeKnob.textFromValueFunction = [] (double v) { return ui::utilityVolumeText (v); };
- volumeKnob.valueFromTextFunction = [] (const juce::String& t) { return t.retainCharacters ("0123456789.").getDoubleValue() / 100.0; };
- volumeKnob.setMouseClickGrabsKeyboardFocus (false);
- volumeKnob.setWantsKeyboardFocus (false);
- volumeKnob.setValue (engine.getEditorVolume(), juce::dontSendNotification);
- volumeKnob.onValueChange = [this] {
- engine.setEditorVolume (volumeKnob.getValue());
- refreshVolumeKnob();
- };
- addAndMakeVisible (volumeKnob);
- refreshVolumeKnob();
- setupText (viewButton, tr ("Spectrum"), tr ("Show the waveform or the spectrogram") + " (S)");
- viewButton.setClickingTogglesState (true);
- viewButton.setColour (juce::TextButton::buttonOnColourId, theme::colour::accent);
- viewButton.onClick = [this] {
- spectrumView = viewButton.getToggleState();
- repaint();
- };
- setupText (envButton, tr ("Edit: Wave"), tr ("What the mouse edits: the waveform, or the volume / panning / stereo separation envelope drawn over it (E)"));
- envButton.onClick = [this] { envModeMenu().showMenuAsync (juce::PopupMenu::Options().withTargetComponent (&envButton)); };
- setupText (sendButton, tr ("Send"), tr ("Send to the Playlist as an audio clip, to a new Sampler channel or back to the channel"));
- sendButton.setColour (juce::TextButton::buttonColourId, theme::colour::accentMuted);
- sendButton.onClick = [this] { sendMenu().showMenuAsync (juce::PopupMenu::Options().withTargetComponent (&sendButton)); };
- // quick tools (the second row)
- struct Quick
- {
- const char* text;
- const char* tip;
- std::function<void()> action;
- };
- const Quick quick[] = {
- { TR_NOOP ("Cut"), TR_NOOP ("Cut the selection (Ctrl+X)"), [this] { cutSelection(); } },
- { TR_NOOP ("Copy"), TR_NOOP ("Copy the selection (Ctrl+C)"), [this] { copySelection(); } },
- { TR_NOOP ("Paste"), TR_NOOP ("Paste at the cursor, or over the selection (Ctrl+V)"), [this] { paste (false); } },
- { TR_NOOP ("Delete"), TR_NOOP ("Delete the selection (Del)"), [this] { deleteSelection(); } },
- { TR_NOOP ("Trim"), TR_NOOP ("Keep only the selection"), [this] { trimSelection(); } },
- { TR_NOOP ("Silence"), TR_NOOP ("Silence the selection (Clear)"), [this] { edit (tr ("Silence"), [] (ae::Document& d, ae::Range r) { ae::clear (d, r); }, true); } },
- { TR_NOOP ("Fade in"), TR_NOOP ("Fade in over the selection (curve: the arrow next to Fade out)"), [this] { fade (true); } },
- { TR_NOOP ("Fade out"), TR_NOOP ("Fade out over the selection"), [this] { fade (false); } },
- { "~", TR_NOOP ("Fade curve"), [this] { curveMenu().showMenuAsync (juce::PopupMenu::Options().withTargetComponent (quickButtons[8])); } },
- { 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); }); } },
- { TR_NOOP ("Amp..."), TR_NOOP ("Volume and panning"), [this] { showAmp(); } },
- { TR_NOOP ("Reverse"), TR_NOOP ("Reverse the selection (or everything)"), [this] { edit (tr ("Reverse"), [] (ae::Document& d, ae::Range r) { ae::reverse (d, r); }); } },
- { TR_NOOP ("Invert"), TR_NOOP ("Reverse the polarity"), [this] { edit (tr ("Reverse polarity"), [] (ae::Document& d, ae::Range r) { ae::invert (d, r); }); } },
- { 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); }); } },
- { TR_NOOP ("Stretch..."), TR_NOOP ("Time stretch / pitch shift"), [this] { openEdisonTool (audiotools::Tool::stretch); } },
- { TR_NOOP ("Resample..."), TR_NOOP ("Change the sample rate"), [this] { showResample(); } },
- { TR_NOOP ("Marker"), TR_NOOP ("Add a marker at the cursor (M)"), [this] { addMarkerAtCursor(); } },
- { TR_NOOP ("Region"), TR_NOOP ("Make the selection a region"), [this] { addRegionFromSelection(); } },
- { TR_NOOP ("Set loop"), TR_NOOP ("Make the selection the loop"), [this] { setLoopFromSelection(); } },
- };
- for (const auto& q : quick)
- {
- auto* b = quickButtons.add (new juce::TextButton (q.text[0] == '~' ? juce::String (juce::CharPointer_UTF8 ("\xe2\x96\xbe")) : tr (q.text)));
- b->setTooltip (tr (q.tip));
- b->onClick = q.action;
- addAndMakeVisible (b);
- }
- setWantsKeyboardFocus (true);
- setSize (1120, 600);
- history.reset (doc, tr ("Empty").toStdString());
- updateButtons();
- startTimerHz (30);
- }
- ~AudioEditor() override
- {
- if (playing)
- engine.previewSample (nullptr);
- if (recState != RecState::idle)
- engine.getMeters().capture.setSource (AudioCapture::off);
- releaseInput();
- }
- // --- opening ---------------------------------------------------------------------------------------------
- bool loadFile (const juce::File& file)
- {
- auto data = engine.getSampleLibrary().load (file.getFullPathName());
- if (data == nullptr)
- {
- setStatus (tr ("Could not read {0}", { file.getFileName() }), true);
- return false;
- }
- ae::Document d;
- d.audio.sampleRate = data->sampleRate;
- d.audio.channels.emplace_back (data->leftData(), data->leftData() + data->frames());
- if (data->isStereo())
- d.audio.channels.emplace_back (data->rightData(), data->rightData() + data->frames());
- if (data->loopStart >= 0 && data->loopEnd > data->loopStart)
- ae::setLoop (d, { data->loopStart, data->loopEnd });
- if (file.hasFileExtension ("wav"))
- {
- juce::MemoryBlock bytes;
- if (file.loadFileAsData (bytes))
- {
- ae::Document marks = d;
- if (ae::decodeWavMarkers (static_cast<const std::uint8_t*> (bytes.getData()), bytes.getSize(), marks))
- {
- d.markers = marks.markers;
- if (marks.hasLoop())
- ae::setLoop (d, { marks.loopStart, marks.loopEnd });
- }
- }
- }
- d.title = file.getFileNameWithoutExtension().toStdString();
- setDocument (std::move (d), tr ("Open"));
- lastFile = file;
- return true;
- }
- void setDocument (ae::Document d, const juce::String& label)
- {
- doc = std::move (d);
- history.reset (doc, label.toStdString());
- selection = {};
- cursor = 0;
- modified = false;
- documentChanged();
- zoomToFit();
- updateTitle();
- }
- void selectForSnapshot (ae::Range r, bool spectrum)
- {
- selection = r;
- cursor = r.start;
- spectrumView = spectrum;
- viewButton.setToggleState (spectrum, juce::dontSendNotification);
- repaint();
- }
- juce::PopupMenu mainMenu();
- // --- warp markers (round 175a, M3) ------------------------------------------------------------------------
- // The channel's markers sit in a lane above the waveform, each at the file time it ties to, labelled with its
- // beat (bar.beat). Drag one sideways to tie its beat to another point of the audio (it snaps to the attacks,
- // shown as small ticks; [Alt] no snap); double-click the lane to add a marker or to remove one; Del removes the
- // selected one. Edits go to the song at once (undoable there); opened from a Playlist clip whose channel other
- // clips share, the clip first gets its own copy of the channel, so the others keep their timing.
- const ChannelDef* warpChannel() const
- {
- const auto& song = engine.getSong();
- return source.kind == Source::Kind::channel && juce::isPositiveAndBelow (source.index, (int) song.channels.size())
- ? &song.channels[(std::size_t) source.index]
- : nullptr;
- }
- double warpFileSeconds() const
- {
- if (const auto* c = warpChannel())
- if (const auto data = engine.getSampleLibrary().findLoaded (juce::String::fromUTF8 (c->samplePath.c_str())); data != nullptr && data->sampleRate > 0.0)
- return (double) data->frames() / data->sampleRate;
- return doc.audio.sampleRate > 0.0 ? (double) doc.audio.frames() / doc.audio.sampleRate : 0.0;
- }
- std::vector<WarpPoint> warpMarkers() const
- {
- const auto* c = warpChannel();
- return c != nullptr && c->sampler.keepPitch && c->sampler.warp.size() >= 2 ? c->sampler.warp : std::vector<WarpPoint> {};
- }
- void setWarpModeForPanel (bool on) { setWarpMode (on); }
- void setWarpMode (bool on)
- {
- warpMode = on && source.kind == Source::Kind::channel;
- warpButton.setToggleState (warpMode, juce::dontSendNotification);
- autoWarpButton.setVisible (warpMode);
- warpSelected = warpDrag = -1;
- resized();
- repaint();
- }
- void editWarp (const std::function<void (SamplerSettings&, double)>& fn)
- {
- const auto seconds = warpFileSeconds();
- if (source.kind != Source::Kind::channel || ! (seconds > 0.0))
- return;
- auto channel = source.index;
- engine.editSong ([&, clip = source.clip] (Song& s) {
- if (clip >= 0)
- if (const auto own = warpedit::channelForClipEdit (s, clip); own >= 0)
- channel = own;
- if (! juce::isPositiveAndBelow (channel, (int) s.channels.size()))
- return;
- auto& sampler = s.channels[(std::size_t) channel].sampler;
- warpedit::ensureMarkers (sampler, seconds, s.bpm);
- fn (sampler, seconds);
- warpedit::syncLength (sampler, seconds);
- });
- source.index = channel;
- repaint();
- }
- void findWarpAttacks()
- {
- if (warpAttacksOf == doc.audio.channels.data() && ! warpAttacks.empty())
- return;
- warpAttacks.clear();
- warpAttacksOf = doc.audio.channels.data();
- if (doc.audio.empty() || ! (doc.audio.sampleRate > 0.0))
- return;
- std::vector<float> mono (doc.audio.channels[0]);
- if (doc.audio.numChannels() > 1)
- for (std::size_t i = 0; i < mono.size(); ++i)
- mono[i] = 0.5f * (mono[i] + doc.audio.channels[1][i]);
- for (const auto a : stretchdetail::detectAttacks (mono.data(), (long) mono.size(), doc.audio.sampleRate, 6.0))
- warpAttacks.push_back ((double) a / doc.audio.sampleRate);
- }
- double secondsToX (double seconds) const { return frameToX (seconds * doc.audio.sampleRate); }
- int warpMarkerAtX (int x) const
- {
- const auto markers = warpMarkers();
- int best = -1;
- double bestDx = 5.0;
- for (std::size_t k = 0; k < markers.size(); ++k)
- if (const auto dx = std::abs (secondsToX (markers[k].seconds) - x); dx <= bestDx)
- {
- bestDx = dx;
- best = (int) k;
- }
- return best;
- }
- void paintWarpLane (juce::Graphics& g)
- {
- using namespace theme;
- g.setColour (colour::bg1);
- g.fillRect (warpLane);
- if (doc.audio.empty())
- return;
- findWarpAttacks();
- // the attacks: short ticks along the lane's bottom
- g.setColour (colour::textDisabled.withAlpha (0.45f));
- for (const auto a : warpAttacks)
- if (const auto x = secondsToX (a); x >= warpLane.getX() && x <= warpLane.getRight())
- g.drawVerticalLine ((int) std::round (x), (float) warpLane.getBottom() - 4.0f, (float) warpLane.getBottom());
- const auto markers = warpMarkers();
- if (markers.empty())
- {
- g.setColour (colour::textDisabled);
- g.setFont (font (type::small));
- g.drawText (tr ("No warp markers: double-click here to add one, or Auto-warp"), warpLane.reduced (6, 0), juce::Justification::centredLeft);
- return;
- }
- const auto perBar = juce::jmax (1, engine.getSong().beatsPerBar);
- g.setFont (font (type::small));
- for (std::size_t k = 0; k < markers.size(); ++k)
- {
- const auto seconds = (int) k == warpDrag ? warpDragSeconds : markers[k].seconds;
- const auto x = (float) secondsToX (seconds);
- if (x < warpLane.getX() - 40.0f || x > warpLane.getRight() + 2.0f)
- continue;
- const auto selected = (int) k == warpSelected;
- const auto fill = k == 0 ? colour::textDisabled : (selected ? colour::accent : colour::accent.withMultipliedSaturation (0.55f).brighter (0.2f));
- juce::Path flag;
- flag.addTriangle (x - 5.0f, (float) warpLane.getY() + 2.0f, x + 5.0f, (float) warpLane.getY() + 2.0f, x, (float) warpLane.getY() + 10.0f);
- g.setColour (fill);
- g.fillPath (flag);
- g.setColour (fill.withAlpha (selected ? 0.8f : 0.4f));
- g.drawVerticalLine ((int) std::round (x), (float) warpLane.getY() + 10.0f, (float) waveArea.getBottom());
- const auto b = markers[k].beats;
- const auto bar = (int) std::floor (b / perBar) + 1;
- const auto beat = b - (bar - 1) * perBar + 1.0;
- const auto label = juce::String (bar) + "." + (std::abs (beat - std::round (beat)) < 0.005 ? juce::String ((int) std::round (beat)) : juce::String (beat, 2));
- g.setColour (colour::textSecondary);
- g.drawText (label, juce::Rectangle<float> (x + 6.0f, (float) warpLane.getY(), 48.0f, (float) warpLane.getHeight()), juce::Justification::centredLeft);
- }
- }
- void warpMouseDown (const juce::MouseEvent& e)
- {
- const auto m = warpMarkerAtX (e.x);
- warpSelected = m;
- if (m > 0 && ! e.mods.isPopupMenu())
- {
- warpDrag = m;
- warpDragSeconds = warpMarkers()[(std::size_t) m].seconds;
- drag = Drag::warp;
- }
- else if (e.mods.isPopupMenu())
- {
- juce::PopupMenu menu;
- menu.addItem (tr ("Remove this warp marker"), m > 0, false, [this, m] { removeWarpMarker (m); });
- menu.addItem (tr ("Auto-warp"), [this] { autoWarp(); });
- menu.addItem (tr ("Remove all warp markers"), warpMarkers().size() > 2, false, [this] {
- editWarp ([] (SamplerSettings& s, double) { warpedit::clearMarkers (s); });
- });
- menu.showMenuAsync (juce::PopupMenu::Options().withMousePosition());
- }
- repaint();
- }
- void warpMouseDrag (const juce::MouseEvent& e)
- {
- const auto markers = warpMarkers();
- if (warpDrag <= 0 || warpDrag >= (int) markers.size())
- return;
- auto seconds = (double) xToFrame (e.x) / doc.audio.sampleRate;
- if (! e.mods.isAltDown()) // onto an attack within 6 px
- for (const auto a : warpAttacks)
- if (std::abs (secondsToX (a) - e.x) <= 6.0)
- {
- seconds = a;
- break;
- }
- const auto lo = markers[(std::size_t) warpDrag - 1].seconds + warpedit::minSecondGap;
- const auto hi = warpDrag + 1 < (int) markers.size() ? markers[(std::size_t) warpDrag + 1].seconds - warpedit::minSecondGap : warpFileSeconds();
- warpDragSeconds = juce::jlimit (lo, juce::jmax (lo, hi), seconds);
- repaint();
- }
- void warpMouseUp()
- {
- const auto index = warpDrag, at = warpDrag;
- const auto seconds = warpDragSeconds;
- warpDrag = -1;
- drag = Drag::none;
- const auto markers = warpMarkers();
- if (index > 0 && index < (int) markers.size() && std::abs (markers[(std::size_t) index].seconds - seconds) > 1.0e-6)
- editWarp ([at, seconds] (SamplerSettings& s, double) {
- // the marker keeps its beat and ties it to another point of the audio
- if (juce::isPositiveAndBelow (at, (int) s.warp.size()))
- s.warp[(std::size_t) at].seconds = seconds;
- });
- repaint();
- }
- void warpDoubleClick (const juce::MouseEvent& e)
- {
- if (const auto m = warpMarkerAtX (e.x); m >= 0)
- {
- removeWarpMarker (m);
- return;
- }
- auto seconds = (double) xToFrame (e.x) / doc.audio.sampleRate;
- if (! e.mods.isAltDown())
- for (const auto a : warpAttacks)
- if (std::abs (secondsToX (a) - e.x) <= 6.0)
- {
- seconds = a;
- break;
- }
- editWarp ([seconds] (SamplerSettings& s, double) { warpedit::addMarker (s, seconds); });
- warpSelected = warpMarkerAtX ((int) std::round (secondsToX (seconds)));
- }
- void removeWarpMarker (int index)
- {
- if (index <= 0)
- return;
- editWarp ([index] (SamplerSettings& s, double) { warpedit::removeMarker (s, index); });
- warpSelected = -1;
- }
- void autoWarp()
- {
- if (doc.audio.empty() || source.kind != Source::Kind::channel)
- return;
- SampleData sample;
- sample.sampleRate = doc.audio.sampleRate;
- sample.left = doc.audio.channels[0];
- if (doc.audio.numChannels() > 1)
- sample.right = doc.audio.channels[1];
- autowarp::Options o;
- o.songBpm = engine.getSong().bpm;
- o.beatsPerBar = juce::jmax (1, engine.getSong().beatsPerBar);
- o.knownBpm = autowarp::bpmInName (juce::File (source.path).getFileNameWithoutExtension().toStdString());
- const auto result = autowarp::analyse (sample, o);
- if (result.markers.size() < 2)
- {
- setStatus (tr ("Auto-warp found no beat to lock to"), true);
- return;
- }
- editWarp ([markers = result.markers] (SamplerSettings& s, double) {
- s.warp = markers;
- s.keepPitch = true;
- });
- if (! warpMode)
- setWarpMode (true);
- setStatus (tr ("Auto-warp: {0} markers at {1} BPM", { juce::String ((int) result.markers.size()), juce::String (result.bpm, 2) }), false);
- }
- void setEnvModeForSnapshot (int mode) { setEnvMode ((EnvMode) juce::jlimit (0, 3, mode)); }
- // --- layout and painting ---------------------------------------------------------------------------------
- void resized() override
- {
- auto area = getLocalBounds();
- auto bar = area.removeFromTop (36).reduced (6, 4);
- auto place = [&bar] (juce::Component& c, int w, int gap = 2) {
- c.setBounds (bar.removeFromLeft (w));
- bar.removeFromLeft (gap);
- };
- place (menuButton, 28, 8);
- place (undoButton, 28);
- place (redoButton, 28);
- place (historyButton, 18, 12);
- place (recordButton, 30);
- place (recordMenuButton, 18, 6);
- place (playButton, 30);
- place (stopButton, 30, 6);
- place (loopButton, 54, 4);
- place (volumeKnob, 26, 12);
- place (viewButton, 76, 6);
- place (envButton, 120, 6);
- place (snapButton, 28);
- place (fitButton, 28);
- place (followButton, 28, 8);
- if (warpButton.isVisible())
- place (warpButton, 100);
- if (autoWarpButton.isVisible())
- place (autoWarpButton, 78);
- sendButton.setBounds (bar.removeFromRight (70));
- bar.removeFromRight (6);
- saveButton.setBounds (bar.removeFromRight (28));
- // each button gets the width its text needs, plus an equal share of what is left (round 165o: translated
- // labels such as "Normalisieren" or "Ausschneiden" are never cut). When one row cannot hold them all (German,
- // Russian, Polish… at the default width) the buttons go on two rows instead; English keeps its single row.
- const auto n = quickButtons.size();
- const auto curveWidth = 18;
- const juce::Font font (theme::font (theme::type::body));
- std::vector<float> natural;
- float total = 0.0f;
- for (int i = 0; i < n; ++i)
- {
- natural.push_back (i == 8 ? (float) curveWidth : juce::GlyphArrangement::getStringWidth (font, quickButtons[i]->getButtonText()) + 18.0f);
- total += natural.back() + (i == 7 ? 0.0f : 2.0f);
- }
- const auto rowWidth = (float) (area.getWidth() - 12);
- const auto twoRows = total - 14.0f * (float) (n - 1) > rowWidth && n > 9; // not even with 4 px padding
- auto tools = area.removeFromTop (twoRows ? 56 : 30).reduced (6, 2);
- // lays out buttons [first, last) in one row: natural widths plus an equal share of the free space; still too
- // narrow -> the padding goes first (down to 4 px a side), then the text squeezes (drawFittedText)
- auto layoutRow = [&] (juce::Rectangle<int> row, int first, int last)
- {
- float need = 0.0f;
- int stretchable = 0;
- for (int i = first; i < last; ++i)
- {
- need += natural[(std::size_t) i] + (i == 7 || i == last - 1 ? 0.0f : 2.0f);
- stretchable += i == 8 ? 0 : 1;
- }
- const auto avail = (float) row.getWidth();
- const auto extra = juce::jmax (0.0f, avail - need) / (float) juce::jmax (1, stretchable);
- auto shrink = 0.0f, scale = 1.0f;
- if (need > avail)
- {
- const auto padding = 14.0f * (float) stretchable;
- shrink = 14.0f * juce::jlimit (0.0f, 1.0f, (need - avail) / padding);
- const auto after = need - shrink * (float) stretchable;
- scale = after > avail ? avail / after : 1.0f;
- }
- float x = (float) row.getX();
- for (int i = first; i < last; ++i)
- {
- const auto w = i == 8 ? (float) curveWidth : (natural[(std::size_t) i] - shrink) * scale + extra;
- quickButtons[i]->setBounds (juce::roundToInt (x), row.getY(), juce::roundToInt (x + w) - juce::roundToInt (x), row.getHeight());
- x += w + (i == 7 ? 0.0f : 2.0f);
- }
- };
- if (! twoRows)
- layoutRow (tools, 0, n);
- else
- {
- // split near half the total width, never between Fade out (7) and its curve menu (8)
- int split = 1;
- float run = 0.0f;
- while (split < n - 1 && run + natural[(std::size_t) split - 1] < total * 0.5f)
- run += natural[(std::size_t) split++ - 1] + 2.0f;
- if (split == 8)
- ++split;
- const auto top = tools.removeFromTop (tools.getHeight() / 2);
- layoutRow (top.withTrimmedBottom (1), 0, split);
- layoutRow (tools.withTrimmedTop (1), split, n);
- }
- infoArea = area.removeFromBottom (24);
- overviewArea = area.removeFromBottom (18).reduced (6, 2);
- area.removeFromBottom (2);
- area = area.reduced (6, 0);
- levelArea = area.removeFromLeft (34);
- rulerArea = area.removeFromTop (24);
- rulerArea.setX (area.getX());
- warpLane = warpMode ? area.removeFromTop (18) : juce::Rectangle<int>();
- waveArea = area;
- clampView();
- }
- void paint (juce::Graphics& g) override
- {
- using namespace theme;
- g.fillAll (colour::bg2);
- g.setColour (colour::bg3);
- g.fillRect (getLocalBounds().removeFromTop (36));
- g.setColour (colour::border);
- g.drawHorizontalLine (36, 0.0f, (float) getWidth());
- paintRuler (g);
- paintLevels (g);
- if (spectrumView)
- paintSpectrum (g);
- else
- paintWave (g);
- paintOverlays (g);
- if (warpMode)
- paintWarpLane (g);
- paintOverview (g);
- paintInfo (g);
- }
- // --- mouse ----------------------------------------------------------------------------------------------
- void mouseDown (const juce::MouseEvent& e) override
- {
- grabKeyboardFocus();
- drag = Drag::none;
- if (doc.audio.empty())
- {
- if (e.mods.isPopupMenu())
- mainMenu().showMenuAsync (juce::PopupMenu::Options().withMousePosition());
- return;
- }
- const auto pos = e.getPosition();
- if (warpMode && warpLane.contains (pos))
- {
- warpMouseDown (e);
- return;
- }
- if (overviewArea.contains (pos))
- {
- drag = Drag::overview;
- centreViewOnOverview (e.x);
- return;
- }
- if (rulerArea.contains (pos))
- {
- // the loop handles live in the ruler's bottom strip
- if (doc.hasLoop() && pos.y >= rulerArea.getBottom() - 7)
- {
- if (std::abs (frameToX ((double) doc.loopStart) - (float) e.x) < 6.0f)
- {
- beginPointDrag (Drag::loopStart);
- return;
- }
- if (std::abs (frameToX ((double) doc.loopEnd) - (float) e.x) < 6.0f)
- {
- beginPointDrag (Drag::loopEnd);
- return;
- }
- }
- if (const auto m = markerAt (e.x); m >= 0)
- {
- if (e.mods.isPopupMenu())
- markerMenu (m).showMenuAsync (juce::PopupMenu::Options().withMousePosition());
- else
- {
- dragMarkerIndex = m;
- beginPointDrag (Drag::marker);
- }
- return;
- }
- }
- if (envMode != EnvMode::wave && waveArea.contains (pos) && envelopeMouseDown (e))
- return;
- if (e.mods.isPopupMenu())
- {
- editMenu (true).showMenuAsync (juce::PopupMenu::Options().withMousePosition());
- return;
- }
- if (waveArea.contains (pos) || rulerArea.contains (pos))
- {
- const auto f = snapFrame (xToFrame (e.x));
- if (e.mods.isShiftDown() && ! selection.empty())
- anchor = std::abs (f - selection.start) < std::abs (f - selection.end) ? selection.end : selection.start;
- else if (e.mods.isShiftDown())
- anchor = cursor;
- else
- anchor = f;
- selection = { std::min (anchor, f), std::max (anchor, f) };
- cursor = f;
- drag = Drag::select;
- if (playing && ! e.mods.isShiftDown())
- startPlayback();
- repaint();
- }
- }
- void mouseDrag (const juce::MouseEvent& e) override
- {
- if (drag == Drag::overview)
- {
- centreViewOnOverview (e.x);
- return;
- }
- if (drag == Drag::envPoint || drag == Drag::envBend)
- {
- envelopeMouseDrag (e);
- return;
- }
- if (drag == Drag::warp)
- {
- warpMouseDrag (e);
- return;
- }
- if (drag == Drag::none)
- return;
- // auto-scroll past the edges
- if (e.x < waveArea.getX())
- viewStart -= (waveArea.getX() - e.x) * fpp * 0.25;
- else if (e.x > waveArea.getRight())
- viewStart += (e.x - waveArea.getRight()) * fpp * 0.25;
- clampView();
- const auto f = snapFrame (xToFrame (e.x));
- if (drag == Drag::select)
- {
- selection = { std::min (anchor, f), std::max (anchor, f) };
- cursor = f;
- }
- else if (drag == Drag::marker && juce::isPositiveAndBelow (dragMarkerIndex, (int) doc.markers.size()))
- {
- auto& m = doc.markers[(std::size_t) dragMarkerIndex];
- const auto length = m.end - m.start;
- m.start = juce::jlimit<std::int64_t> (0, doc.audio.frames() - length, f);
- m.end = m.start + length;
- }
- else if (drag == Drag::loopStart)
- doc.loopStart = juce::jlimit<std::int64_t> (0, doc.loopEnd - 1, f);
- else if (drag == Drag::loopEnd)
- doc.loopEnd = juce::jlimit<std::int64_t> (doc.loopStart + 1, doc.audio.frames(), f);
- repaint();
- }
- void mouseUp (const juce::MouseEvent&) override
- {
- if (drag == Drag::warp)
- {
- warpMouseUp();
- return;
- }
- if (drag == Drag::envPoint || drag == Drag::envBend)
- {
- drag = Drag::none;
- envDragPoint = -1;
- if (envChanged)
- commit (tr ("Edit envelope"));
- envChanged = false;
- return;
- }
- if (drag == Drag::marker || drag == Drag::loopStart || drag == Drag::loopEnd)
- {
- const auto& before = history.current();
- const auto moved = before.loopStart != doc.loopStart || before.loopEnd != doc.loopEnd || before.markers.size() != doc.markers.size()
- || ! std::equal (before.markers.begin(), before.markers.end(), doc.markers.begin(),
- [] (const ae::Marker& a, const ae::Marker& b) { return a.start == b.start && a.end == b.end; });
- if (moved)
- {
- ae::sortMarkers (doc);
- commit (drag == Drag::marker ? tr ("Move marker") : tr ("Move loop"));
- }
- }
- drag = Drag::none;
- }
- void mouseDoubleClick (const juce::MouseEvent& e) override
- {
- if (warpMode && ! doc.audio.empty() && warpLane.contains (e.getPosition()))
- {
- warpDoubleClick (e);
- return;
- }
- if (doc.audio.empty() || ! waveArea.contains (e.getPosition()))
- return;
- // the region under the mouse, else the stretch between the markers around it, else everything
- const auto f = xToFrame (e.x);
- std::int64_t from = 0, to = doc.audio.frames();
- for (const auto& m : doc.markers)
- if (m.isRegion() && f >= m.start && f < m.end)
- {
- selection = { m.start, m.end };
- repaint();
- return;
- }
- for (const auto& m : doc.markers)
- {
- if (m.start <= f)
- from = std::max (from, m.start);
- if (m.start > f)
- to = std::min (to, m.start);
- }
- selection = { from, to };
- repaint();
- }
- void mouseWheelMove (const juce::MouseEvent& e, const juce::MouseWheelDetails& w) override
- {
- if (doc.audio.empty())
- return;
- const auto delta = std::abs (w.deltaY) > std::abs (w.deltaX) ? w.deltaY : w.deltaX;
- if (e.mods.isCtrlDown() || e.mods.isCommandDown())
- zoomAround ((float) e.x, delta > 0 ? 0.8 : 1.25);
- else
- {
- viewStart -= delta * (double) waveArea.getWidth() * fpp * 0.5;
- clampView();
- repaint();
- }
- }
- // --- keys -----------------------------------------------------------------------------------------------
- bool keyPressed (const juce::KeyPress& k) override
- {
- const auto ctrl = k.getModifiers().isCtrlDown() || k.getModifiers().isCommandDown();
- const auto shift = k.getModifiers().isShiftDown();
- const auto c = juce::CharacterFunctions::toLowerCase (k.getTextCharacter());
- const auto code = k.getKeyCode();
- if (warpMode && warpSelected > 0 && (code == juce::KeyPress::deleteKey || code == juce::KeyPress::backspaceKey))
- {
- removeWarpMarker (warpSelected);
- return true;
- }
- if (ctrl && (code == 'Z' || c == 'z'))
- shift ? redo() : undo();
- else if (ctrl && (code == 'Y' || c == 'y'))
- redo();
- else if (ctrl && (code == 'X' || c == 'x'))
- cutSelection();
- else if (ctrl && (code == 'C' || c == 'c'))
- copySelection();
- else if (ctrl && (code == 'V' || c == 'v'))
- paste (false);
- else if (ctrl && (code == 'A' || c == 'a'))
- {
- selection = { 0, doc.audio.frames() };
- repaint();
- }
- else if (ctrl && (code == 'S' || c == 's'))
- saveAs (bits);
- else if (code == juce::KeyPress::spaceKey)
- playing ? stopPlayback() : startPlayback();
- else if (code == juce::KeyPress::deleteKey || code == juce::KeyPress::backspaceKey)
- deleteSelection();
- else if (code == juce::KeyPress::escapeKey)
- {
- if (recState != RecState::idle)
- stopRecording();
- selection = {};
- repaint();
- }
- else if (code == juce::KeyPress::homeKey)
- setCursor (0);
- else if (code == juce::KeyPress::endKey)
- setCursor (doc.audio.frames());
- else if (! ctrl && c == 'r')
- toggleRecording();
- else if (! ctrl && c == 'l')
- loopButton.triggerClick();
- else if (! ctrl && c == 's')
- viewButton.triggerClick();
- else if (! ctrl && c == 'm')
- addMarkerAtCursor();
- else if (! ctrl && c == 'e')
- setEnvMode ((EnvMode) (((int) envMode + 1) % 4));
- else if (! ctrl && c == 'f')
- zoomToFit();
- else if (c == '+' || c == '=')
- zoomAround ((float) waveArea.getCentreX(), 0.5);
- else if (c == '-')
- zoomAround ((float) waveArea.getCentreX(), 2.0);
- else
- return false;
- return true;
- }
- // --- drag and drop of files -----------------------------------------------------------------------------
- bool isInterestedInFileDrag (const juce::StringArray& files) override
- {
- return files.size() == 1 && SampleLibrary::isSampleFile (juce::File (files[0]));
- }
- // a sample dragged from LYNX's Browser too (issue #12)
- bool isInterestedInDragSource (const SourceDetails& details) override
- {
- return BrowserComponent::isBrowserDrag (details) && SampleLibrary::isSampleFile (BrowserComponent::draggedFile (details));
- }
- void itemDropped (const SourceDetails& details) override
- {
- const auto file = BrowserComponent::draggedFile (details);
- if (file.existsAsFile())
- filesDropped ({ file.getFullPathName() }, 0, 0);
- }
- // FL's Edison: a dropped file replaces what the editor shows (issue #12); with Ctrl held it is pasted at the
- // cursor instead (LYNX's earlier behaviour)
- void filesDropped (const juce::StringArray& files, int, int) override
- {
- if (files.isEmpty() || recState != RecState::idle)
- return;
- if (doc.audio.empty() || ! juce::ModifierKeys::getCurrentModifiersRealtime().isCommandDown())
- {
- stopPlayback();
- const auto previous = source;
- source = { Source::Kind::file, -1, files[0] };
- if (! loadFile (juce::File (files[0])))
- source = previous;
- return;
- }
- // into a document: pasted at the cursor
- auto data = engine.getSampleLibrary().load (files[0]);
- if (data == nullptr)
- return;
- ae::Audio clip;
- clip.sampleRate = data->sampleRate;
- clip.channels.emplace_back (data->leftData(), data->leftData() + data->frames());
- if (data->isStereo())
- clip.channels.emplace_back (data->rightData(), data->rightData() + data->frames());
- const auto at = cursor;
- ae::insert (doc, at, clip);
- selection = { at, at + ae::conform (clip, doc.audio.numChannels(), doc.audio.sampleRate).frames() };
- commit (tr ("Paste"));
- }
- // menus shared with the snapshot check
- juce::PopupMenu editMenu (bool contextual);
- private:
- enum class Drag
- {
- none,
- warp,
- select,
- marker,
- loopStart,
- loopEnd,
- overview,
- envPoint,
- envBend
- };
- enum class RecState
- {
- idle,
- waiting,
- recording
- };
- // --- coordinates ----------------------------------------------------------------------------------------
- float frameToX (double frame) const noexcept { return (float) waveArea.getX() + (float) ((frame - viewStart) / fpp); }
- std::int64_t xToFrame (int x) const noexcept
- {
- return juce::jlimit<std::int64_t> (0, doc.audio.frames(), (std::int64_t) std::llround (viewStart + (double) (x - waveArea.getX()) * fpp));
- }
- double maxFpp() const noexcept { return juce::jmax (1.0, (double) doc.audio.frames() / juce::jmax (1, waveArea.getWidth())); }
- void clampView()
- {
- fpp = juce::jlimit (1.0 / 32.0, maxFpp(), fpp);
- const auto visible = (double) waveArea.getWidth() * fpp;
- viewStart = juce::jlimit (0.0, juce::jmax (0.0, (double) doc.audio.frames() - visible), viewStart);
- }
- void zoomToFit()
- {
- fpp = maxFpp();
- viewStart = 0.0;
- clampView();
- repaint();
- }
- void zoomAround (float x, double factor)
- {
- const auto frame = viewStart + (x - (float) waveArea.getX()) * fpp;
- fpp *= factor;
- clampView();
- viewStart = frame - (x - (float) waveArea.getX()) * fpp;
- clampView();
- repaint();
- }
- void zoomTo (ae::Range r)
- {
- if (r.empty())
- return;
- fpp = (double) r.length() / juce::jmax (1, waveArea.getWidth());
- clampView();
- viewStart = (double) r.start;
- clampView();
- repaint();
- }
- void centreViewOnOverview (int x)
- {
- const auto frames = (double) doc.audio.frames();
- const auto f = (double) (x - overviewArea.getX()) / juce::jmax (1, overviewArea.getWidth()) * frames;
- viewStart = f - (double) waveArea.getWidth() * fpp * 0.5;
- clampView();
- repaint();
- }
- std::int64_t snapFrame (std::int64_t f) const
- {
- if (! snapZero)
- return f;
- return ae::nearestZeroCrossing (doc.audio, f, (std::int64_t) juce::jmax (8.0, fpp * 6.0));
- }
- int markerAt (int x) const
- {
- for (int i = (int) doc.markers.size() - 1; i >= 0; --i)
- if (std::abs (frameToX ((double) doc.markers[(std::size_t) i].start) - (float) x) < 5.0f)
- return i;
- return -1;
- }
- // markers and loop ends move live; mouseUp commits the move against the history's current state
- void beginPointDrag (Drag d) { drag = d; }
- void setCursor (std::int64_t f)
- {
- cursor = juce::jlimit<std::int64_t> (0, doc.audio.frames(), f);
- selection = {};
- if (frameToX ((double) cursor) < (float) waveArea.getX() || frameToX ((double) cursor) > (float) waveArea.getRight())
- {
- viewStart = (double) cursor - (double) waveArea.getWidth() * fpp * 0.5;
- clampView();
- }
- repaint();
- }
- // --- painting -------------------------------------------------------------------------------------------
- // per pixel column x of a lane: the min/max of the samples it covers (exact when zoomed in, from the
- // summary when zoomed out)
- bool columnRange (int channel, double from, double to, float& lo, float& hi) const
- {
- const auto frames = doc.audio.frames();
- if (to <= 0.0 || from >= (double) frames)
- return false;
- if (fpp > 256.0 && summary != nullptr)
- {
- const auto p = summary->query (from, to, doc.audio.numChannels() > 1 ? channel : -1);
- if (! p.valid)
- return false;
- lo = p.lo;
- hi = p.hi;
- return true;
- }
- const auto& data = doc.audio.channels[(std::size_t) channel];
- auto a = (std::int64_t) std::floor (from), b = (std::int64_t) std::ceil (to);
- a = juce::jlimit<std::int64_t> (0, frames - 1, a);
- b = juce::jlimit<std::int64_t> (a + 1, frames, b);
- lo = hi = data[(std::size_t) a];
- for (auto i = a + 1; i < b; ++i)
- {
- lo = std::min (lo, data[(std::size_t) i]);
- hi = std::max (hi, data[(std::size_t) i]);
- }
- return true;
- }
- juce::Rectangle<float> laneBounds (int lane) const
- {
- const auto lanes = juce::jmax (1, doc.audio.numChannels());
- const auto h = (float) waveArea.getHeight() / (float) lanes;
- return { (float) waveArea.getX(), (float) waveArea.getY() + h * (float) lane, (float) waveArea.getWidth(), h };
- }
- void paintWave (juce::Graphics& g)
- {
- using namespace theme;
- g.setColour (colour::bg0);
- g.fillRect (waveArea);
- if (doc.audio.empty())
- {
- g.setColour (colour::textSecondary);
- g.setFont (font (type::body));
- g.drawFittedText (recState != RecState::idle ? tr ("Waiting for input...")
- : tr ("Empty: press Record, drop an audio file here or open one from the menu"),
- waveArea.reduced (20), juce::Justification::centred, 2);
- return;
- }
- juce::Graphics::ScopedSaveState save (g);
- g.reduceClipRegion (waveArea);
- paintSelectionAndRegions (g);
- const auto lanes = doc.audio.numChannels();
- for (int lane = 0; lane < lanes; ++lane)
- {
- const auto r = laneBounds (lane);
- const auto centre = r.getCentreY();
- const auto half = r.getHeight() * 0.5f - 2.0f;
- // level guides: centre line and -6 dB
- g.setColour (colour::gridBeat);
- g.drawHorizontalLine ((int) (centre - half * 0.5f), r.getX(), r.getRight());
- g.drawHorizontalLine ((int) (centre + half * 0.5f), r.getX(), r.getRight());
- g.setColour (colour::gridBar);
- g.drawHorizontalLine ((int) centre, r.getX(), r.getRight());
- if (lane > 0)
- {
- g.setColour (colour::border);
- g.drawHorizontalLine ((int) r.getY(), r.getX(), r.getRight());
- }
- const auto width = waveArea.getWidth();
- if (fpp < 1.0)
- {
- // zoomed in past one sample per pixel: the samples joined by a line, dots when far apart
- const auto& data = doc.audio.channels[(std::size_t) lane];
- const auto first = juce::jmax<std::int64_t> (0, (std::int64_t) std::floor (viewStart) - 1);
- const auto last = juce::jmin<std::int64_t> (doc.audio.frames() - 1, (std::int64_t) std::ceil (viewStart + width * fpp) + 1);
- juce::Path line;
- for (auto i = first; i <= last; ++i)
- {
- const auto p = juce::Point<float> (frameToX ((double) i), centre - juce::jlimit (-1.0f, 1.0f, data[(std::size_t) i]) * half);
- i == first ? line.startNewSubPath (p) : line.lineTo (p);
- }
- g.setColour (waveColour());
- g.strokePath (line, juce::PathStrokeType (1.5f, juce::PathStrokeType::curved, juce::PathStrokeType::rounded));
- if (fpp < 1.0 / 6.0)
- for (auto i = first; i <= last; ++i)
- 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 }));
- continue;
- }
- // one filled shape: the top edge (maxima) left to right, the bottom edge (minima) back
- std::vector<float> tops ((std::size_t) width), bottoms ((std::size_t) width);
- std::vector<char> valid ((std::size_t) width);
- for (int x = 0; x < width; ++x)
- {
- const auto from = viewStart + x * fpp;
- float lo = 0.0f, hi = 0.0f;
- valid[(std::size_t) x] = columnRange (lane, from, from + fpp, lo, hi) ? 1 : 0;
- tops[(std::size_t) x] = centre - juce::jlimit (-1.0f, 1.0f, hi) * half;
- bottoms[(std::size_t) x] = centre - juce::jlimit (-1.0f, 1.0f, lo) * half;
- if (bottoms[(std::size_t) x] - tops[(std::size_t) x] < 1.0f) // silence still shows as a hairline
- {
- const auto mid = (bottoms[(std::size_t) x] + tops[(std::size_t) x]) * 0.5f;
- tops[(std::size_t) x] = mid - 0.5f;
- bottoms[(std::size_t) x] = mid + 0.5f;
- }
- }
- juce::Path wave;
- for (int x = 0; x < width;)
- {
- while (x < width && ! valid[(std::size_t) x])
- ++x;
- if (x >= width)
- break;
- const auto start = x;
- while (x < width && valid[(std::size_t) x])
- ++x;
- const auto px = [this] (int i) { return (float) (waveArea.getX() + i); };
- wave.startNewSubPath (px (start), tops[(std::size_t) start]);
- for (int i = start + 1; i < x; ++i)
- wave.lineTo (px (i), tops[(std::size_t) i]);
- wave.lineTo (px (x), tops[(std::size_t) (x - 1)]);
- wave.lineTo (px (x), bottoms[(std::size_t) (x - 1)]);
- for (int i = x - 1; i >= start; --i)
- wave.lineTo (px (i), bottoms[(std::size_t) i]);
- wave.closeSubPath();
- }
- g.setColour (waveColour());
- g.fillPath (wave);
- }
- }
- void paintSelectionAndRegions (juce::Graphics& g)
- {
- using namespace theme;
- for (const auto& m : doc.markers)
- if (m.isRegion())
- {
- g.setColour (colour::warning.withAlpha (0.07f));
- g.fillRect (juce::Rectangle<float>::leftTopRightBottom (frameToX ((double) m.start), (float) waveArea.getY(), frameToX ((double) m.end),
- (float) waveArea.getBottom()));
- }
- if (! selection.empty())
- {
- g.setColour (colour::selectionFill);
- g.fillRect (juce::Rectangle<float>::leftTopRightBottom (frameToX ((double) selection.start), (float) waveArea.getY(),
- frameToX ((double) selection.end), (float) waveArea.getBottom()));
- }
- }
- void paintSpectrum (juce::Graphics& g)
- {
- using namespace theme;
- g.setColour (colour::bg0);
- g.fillRect (waveArea);
- if (doc.audio.empty())
- {
- paintWave (g);
- return;
- }
- const auto columns = juce::jmax (1, waveArea.getWidth() / 2);
- const auto height = juce::jmax (1, waveArea.getHeight());
- const auto key = juce::String (docVersion) + "|" + juce::String (viewStart) + "|" + juce::String (fpp) + "|" + juce::String (columns) + "x"
- + juce::String (height) + "|" + juce::String (fftSize) + (logFrequency ? "l" : "n");
- if (key != spectrumKey)
- {
- const auto from = (std::int64_t) viewStart;
- const auto to = juce::jmin (doc.audio.frames(), (std::int64_t) std::ceil (viewStart + waveArea.getWidth() * fpp));
- const auto spec = ae::spectrogram (doc.audio, { from, to }, columns, fftSize);
- spectrumImage = juce::Image (juce::Image::RGB, columns, height, false);
- const auto nyquist = doc.audio.sampleRate * 0.5;
- const auto binHz = doc.audio.sampleRate / fftSize;
- for (int y = 0; y < height; ++y)
- {
- const auto t = 1.0 - (double) y / juce::jmax (1, height - 1);
- const auto hz = logFrequency ? 20.0 * std::pow (nyquist / 20.0, t) : t * nyquist;
- const auto bin = juce::jlimit (0, spec.bins - 1, (int) std::lround (hz / binHz));
- // the bins between this row and the next (log scale, high frequencies) are summarised by their max
- const auto nextT = 1.0 - (double) (y + 1) / juce::jmax (1, height - 1);
- const auto nextHz = logFrequency ? 20.0 * std::pow (nyquist / 20.0, nextT) : nextT * nyquist;
- const auto binLow = juce::jlimit (0, spec.bins - 1, (int) std::lround (nextHz / binHz));
- for (int c = 0; c < columns; ++c)
- {
- auto db = spec.at (c, bin);
- for (int b = binLow; b < bin; ++b)
- db = std::max (db, spec.at (c, b));
- spectrumImage.setPixelAt (c, y, spectrumColour (db));
- }
- }
- spectrumKey = key;
- }
- g.drawImage (spectrumImage, waveArea.toFloat());
- juce::Graphics::ScopedSaveState save (g);
- g.reduceClipRegion (waveArea);
- if (! selection.empty())
- {
- g.setColour (juce::Colours::white.withAlpha (0.10f));
- g.fillRect (juce::Rectangle<float>::leftTopRightBottom (frameToX ((double) selection.start), (float) waveArea.getY(),
- frameToX ((double) selection.end), (float) waveArea.getBottom()));
- }
- }
- void paintLevels (juce::Graphics& g)
- {
- using namespace theme;
- g.setColour (colour::bg2);
- g.fillRect (levelArea);
- g.setFont (font (type::caption));
- g.setColour (colour::textSecondary);
- if (doc.audio.empty())
- return;
- if (spectrumView)
- {
- const auto nyquist = doc.audio.sampleRate * 0.5;
- for (double hz : { 50.0, 100.0, 200.0, 500.0, 1000.0, 2000.0, 5000.0, 10000.0, 20000.0 })
- {
- if (hz >= nyquist)
- continue;
- const auto t = logFrequency ? std::log (hz / 20.0) / std::log (nyquist / 20.0) : hz / nyquist;
- const auto y = (float) waveArea.getBottom() - (float) t * (float) waveArea.getHeight();
- 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()),
- juce::Justification::centredRight);
- }
- return;
- }
- for (int lane = 0; lane < doc.audio.numChannels(); ++lane)
- {
- const auto r = laneBounds (lane);
- const auto half = r.getHeight() * 0.5f - 2.0f;
- auto label = [&] (float level, const juce::String& text) {
- const auto y = r.getCentreY() - level * half;
- g.drawText (text, juce::Rectangle<float> ((float) levelArea.getX(), y - 6.0f, 30.0f, 12.0f), juce::Justification::centredRight);
- };
- if (r.getHeight() > 70.0f)
- {
- label (0.5f, "-6");
- label (-0.5f, "-6");
- }
- label (0.0f, doc.audio.numChannels() > 1 ? (lane == 0 ? "L" : "R") : "0");
- }
- }
- void paintRuler (juce::Graphics& g)
- {
- using namespace theme;
- g.setColour (colour::bg3);
- g.fillRect (rulerArea);
- if (doc.audio.empty())
- return;
- // a time step that leaves ~90 px between labels
- const auto rate = doc.audio.sampleRate;
- const auto secondsPerPixel = fpp / rate;
- double step = 0.001;
- 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 })
- if (s / secondsPerPixel >= 90.0)
- {
- step = s;
- break;
- }
- const auto bars = timeFormat == TimeFormat::bars;
- const auto beatSeconds = 60.0 / juce::jmax (1.0, engine.getSong().bpm);
- if (bars)
- {
- step = beatSeconds;
- while (step / secondsPerPixel < 90.0)
- step *= 2.0;
- }
- g.setFont (font (type::caption));
- const auto firstSecond = viewStart / rate;
- const auto lastSecond = (viewStart + waveArea.getWidth() * fpp) / rate;
- for (auto t = std::floor (firstSecond / step) * step; t <= lastSecond; t += step)
- {
- const auto x = frameToX (t * rate);
- if (x < (float) rulerArea.getX())
- continue;
- g.setColour (colour::gridBar);
- g.drawVerticalLine ((int) x, (float) rulerArea.getBottom() - 7.0f, (float) rulerArea.getBottom());
- g.setColour (colour::textSecondary);
- g.drawText (formatTime ((std::int64_t) std::llround (t * rate)), juce::Rectangle<float> (x + 3.0f, (float) rulerArea.getY(), 90.0f, 13.0f),
- juce::Justification::centredLeft);
- }
- // regions and markers: flags with their names; the loop: a bar along the bottom
- for (const auto& m : doc.markers)
- {
- const auto x = frameToX ((double) m.start);
- if (m.isRegion())
- {
- g.setColour (colour::warning.withAlpha (0.22f));
- g.fillRect (juce::Rectangle<float>::leftTopRightBottom (x, (float) rulerArea.getY() + 12.0f, frameToX ((double) m.end), (float) rulerArea.getBottom() - 5.0f));
- }
- juce::Path flag;
- flag.addTriangle (x, (float) rulerArea.getY() + 12.0f, x + 7.0f, (float) rulerArea.getY() + 15.5f, x, (float) rulerArea.getY() + 19.0f);
- g.setColour (colour::warning);
- g.fillPath (flag);
- g.drawVerticalLine ((int) x, (float) rulerArea.getY() + 12.0f, (float) rulerArea.getBottom());
- if (! m.name.empty())
- g.drawText (juce::String::fromUTF8 (m.name.c_str()), juce::Rectangle<float> (x + 8.0f, (float) rulerArea.getY() + 12.0f, 120.0f, 8.0f),
- juce::Justification::centredLeft);
- }
- if (doc.hasLoop())
- {
- const auto a = frameToX ((double) doc.loopStart), b = frameToX ((double) doc.loopEnd);
- g.setColour (colour::accent);
- g.fillRect (juce::Rectangle<float>::leftTopRightBottom (a, (float) rulerArea.getBottom() - 4.0f, b, (float) rulerArea.getBottom()));
- g.fillRect (juce::Rectangle<float> (a, (float) rulerArea.getBottom() - 8.0f, 2.0f, 8.0f));
- g.fillRect (juce::Rectangle<float> (b - 2.0f, (float) rulerArea.getBottom() - 8.0f, 2.0f, 8.0f));
- }
- }
- void paintOverlays (juce::Graphics& g)
- {
- using namespace theme;
- if (doc.audio.empty())
- return;
- juce::Graphics::ScopedSaveState save (g);
- g.reduceClipRegion (waveArea);
- for (const auto& m : doc.markers)
- {
- g.setColour (colour::warning.withAlpha (0.55f));
- g.drawVerticalLine ((int) frameToX ((double) m.start), (float) waveArea.getY(), (float) waveArea.getBottom());
- if (m.isRegion())
- {
- g.setColour (colour::warning.withAlpha (0.3f));
- g.drawVerticalLine ((int) frameToX ((double) m.end), (float) waveArea.getY(), (float) waveArea.getBottom());
- }
- }
- if (doc.hasLoop())
- {
- g.setColour (colour::accent.withAlpha (0.6f));
- const float dash[] = { 4.0f, 3.0f };
- for (auto f : { doc.loopStart, doc.loopEnd })
- {
- const auto x = frameToX ((double) f);
- g.drawDashedLine ({ x, (float) waveArea.getY(), x, (float) waveArea.getBottom() }, dash, 2);
- }
- }
- paintEnvelopes (g);
- if (! selection.empty())
- {
- g.setColour (colour::selection.withAlpha (0.8f));
- g.drawVerticalLine ((int) frameToX ((double) selection.start), (float) waveArea.getY(), (float) waveArea.getBottom());
- g.drawVerticalLine ((int) frameToX ((double) selection.end), (float) waveArea.getY(), (float) waveArea.getBottom());
- }
- else
- {
- g.setColour (colour::textPrimary.withAlpha (0.7f));
- g.drawVerticalLine ((int) frameToX ((double) cursor), (float) waveArea.getY(), (float) waveArea.getBottom());
- }
- if (playing && playhead >= 0)
- {
- g.setColour (colour::playhead);
- g.fillRect (juce::Rectangle<float> (frameToX ((double) playhead) - 0.5f, (float) waveArea.getY(), 2.0f, (float) waveArea.getHeight()));
- }
- if (recState != RecState::idle)
- {
- auto badge = juce::Rectangle<float> ((float) waveArea.getX() + 8.0f, (float) waveArea.getY() + 8.0f, recState == RecState::recording ? 70.0f : 150.0f, 20.0f);
- g.setColour (colour::bg1.withAlpha (0.85f));
- g.fillRoundedRectangle (badge, radius::md);
- g.setColour (colour::record);
- g.fillEllipse (badge.removeFromLeft (20.0f).reduced (5.0f));
- g.setFont (font (type::small, true));
- g.drawText (recState == RecState::recording ? juce::String ("REC") : tr ("Waiting..."), badge, juce::Justification::centredLeft);
- }
- }
- void paintOverview (juce::Graphics& g)
- {
- using namespace theme;
- g.setColour (colour::bg0);
- g.fillRoundedRectangle (overviewArea.toFloat(), radius::sm);
- if (doc.audio.empty() || summary == nullptr)
- return;
- const auto frames = (double) doc.audio.frames();
- const auto perPixel = frames / juce::jmax (1, overviewArea.getWidth());
- const auto centre = (float) overviewArea.getCentreY();
- const auto half = overviewArea.getHeight() * 0.5f - 1.0f;
- g.setColour (waveColour().withAlpha (0.55f));
- for (int x = 0; x < overviewArea.getWidth(); ++x)
- {
- const auto p = summary->query (x * perPixel, (x + 1) * perPixel, -1);
- if (! p.valid)
- break;
- const auto a = juce::jmin (1.0f, std::max (std::abs (p.lo), std::abs (p.hi)));
- g.drawVerticalLine (overviewArea.getX() + x, centre - a * half, centre + a * half + 1.0f);
- }
- const auto x0 = (float) overviewArea.getX() + (float) (viewStart / frames) * overviewArea.getWidth();
- const auto w = (float) ((double) waveArea.getWidth() * fpp / frames) * overviewArea.getWidth();
- g.setColour (colour::accent.withAlpha (0.18f));
- g.fillRect (juce::Rectangle<float> (x0, (float) overviewArea.getY(), juce::jmax (3.0f, w), (float) overviewArea.getHeight()));
- g.setColour (colour::accent);
- g.drawRect (juce::Rectangle<float> (x0, (float) overviewArea.getY(), juce::jmax (3.0f, w), (float) overviewArea.getHeight()), 1.0f);
- }
- void paintInfo (juce::Graphics& g)
- {
- using namespace theme;
- g.setColour (colour::bg1);
- g.fillRect (infoArea);
- g.setColour (colour::border);
- g.drawHorizontalLine (infoArea.getY(), 0.0f, (float) getWidth());
- auto area = infoArea.reduced (10, 0);
- g.setFont (font (type::small));
- if (status.isNotEmpty())
- {
- g.setColour (statusIsError ? colour::meterClip : colour::textSecondary);
- g.drawText (status, area.removeFromRight (juce::jmin (420, area.getWidth() / 2)), juce::Justification::centredRight);
- }
- if (doc.audio.empty())
- return;
- juce::StringArray parts;
- parts.add (juce::String (juce::roundToInt (doc.audio.sampleRate)) + " Hz");
- parts.add (doc.audio.numChannels() > 1 ? tr ("Stereo") : tr ("Mono"));
- parts.add (tr ("Length") + " " + formatTime (doc.audio.frames()));
- const auto r = ae::orAll (doc, selection);
- if (! selection.empty())
- parts.add (tr ("Selection") + " " + formatTime (selection.start) + " - " + formatTime (selection.end) + " (" + formatTime (selection.length()) + ")");
- else
- parts.add (tr ("Cursor") + " " + formatTime (cursor));
- const auto p = ae::peak (doc.audio, r);
- parts.add (tr ("Peak") + " " + (p > 0.0f ? juce::String (20.0f * std::log10 (p), 1) + " dB" : juce::String ("-inf dB")));
- g.setColour (colour::textPrimary);
- g.drawText (parts.joinIntoString (" | "), area, juce::Justification::centredLeft);
- }
- juce::String formatTime (std::int64_t frames) const
- {
- const auto rate = doc.audio.sampleRate;
- switch (timeFormat)
- {
- case TimeFormat::samples: return juce::String (frames);
- case TimeFormat::bars:
- {
- const auto beats = (double) frames / rate * engine.getSong().bpm / 60.0;
- const auto perBar = juce::jmax (1, engine.getSong().beatsPerBar);
- const auto bar = (int) (beats / perBar);
- const auto beat = (int) beats - bar * perBar;
- const auto tick = (int) ((beats - std::floor (beats)) * 96.0);
- return juce::String (bar + 1) + ":" + juce::String (beat + 1) + ":" + juce::String (tick).paddedLeft ('0', 2);
- }
- case TimeFormat::automatic:
- if (fpp < 1.0)
- return juce::String (frames);
- [[fallthrough]];
- case TimeFormat::seconds: return formatSeconds ((double) frames / rate);
- }
- return {};
- }
- // --- edits ----------------------------------------------------------------------------------------------
- void commit (const juce::String& label)
- {
- history.commit (doc, label.toStdString());
- modified = true;
- documentChanged();
- }
- // runs `fn` on the selection (an empty selection: the whole audio, unless `needsSelection`)
- void edit (const juce::String& label, const std::function<void (ae::Document&, ae::Range)>& fn, bool needsSelection = false)
- {
- if (doc.audio.empty() || recState != RecState::idle)
- return;
- if (needsSelection && selection.empty())
- {
- setStatus (tr ("Select a part first (drag over the waveform)"), false);
- return;
- }
- stopPlayback();
- const auto frames = doc.audio.frames();
- const auto edited = ae::orAll (doc, selection);
- fn (doc, selection);
- if (ae::hasEnvelopes (doc) && doc.audio.frames() != frames)
- ae::remapEnvelopes (doc, frames, edited, edited.length() + (doc.audio.frames() - frames));
- // a length-changing edit of the selection keeps the edited part selected
- if (! selection.empty())
- selection.end = juce::jmax (selection.start, selection.end + (doc.audio.frames() - frames));
- commit (label);
- }
- void documentChanged()
- {
- ++docVersion;
- selection = ae::clamp (doc, selection);
- cursor = juce::jlimit<std::int64_t> (0, doc.audio.frames(), cursor);
- rebuildSummary();
- clampView();
- updateButtons();
- updateTitle();
- repaint();
- }
- void rebuildSummary()
- {
- if (doc.audio.empty())
- {
- summary.reset();
- return;
- }
- const auto* l = doc.audio.channels[0].data();
- const auto* r = doc.audio.numChannels() > 1 ? doc.audio.channels[1].data() : nullptr;
- summary = std::make_shared<wave::Summary> (wave::analyse (l, r, (std::size_t) doc.audio.frames(), doc.audio.sampleRate));
- }
- void undo()
- {
- if (! history.canUndo() || recState != RecState::idle)
- return;
- stopPlayback();
- doc = history.undo();
- modified = true;
- documentChanged();
- }
- void redo()
- {
- if (! history.canRedo() || recState != RecState::idle)
- return;
- stopPlayback();
- doc = history.redo();
- modified = true;
- documentChanged();
- }
- void copySelection()
- {
- if (selection.empty())
- return;
- clipboard() = ae::copy (doc.audio, selection);
- setStatus (tr ("Copied {0}", { formatTime (selection.length()) }), false);
- }
- void cutSelection()
- {
- if (selection.empty())
- return;
- clipboard() = ae::copy (doc.audio, selection);
- const auto at = selection.start;
- edit (tr ("Cut"), [] (ae::Document& d, ae::Range r) { ae::erase (d, r); }, true);
- selection = {};
- cursor = at;
- repaint();
- }
- void trimSelection()
- {
- if (selection.empty())
- return;
- edit (tr ("Trim"), [] (ae::Document& d, ae::Range r) { ae::trim (d, r); }, true);
- selection = {};
- cursor = 0;
- zoomToFit();
- }
- void deleteSelection()
- {
- if (selection.empty())
- return;
- const auto at = selection.start;
- edit (tr ("Delete"), [] (ae::Document& d, ae::Range r) { ae::erase (d, r); }, true);
- selection = {};
- cursor = at;
- repaint();
- }
- // insert at the cursor, replace the selection, or (mix) sum at the cursor / selection start
- void paste (bool mix)
- {
- const auto& clip = clipboard();
- if (clip.empty() || recState != RecState::idle)
- return;
- stopPlayback();
- const auto wasEmpty = doc.audio.empty();
- const auto at = selection.empty() ? cursor : selection.start;
- const auto length = wasEmpty ? clip.frames() : ae::conform (clip, doc.audio.numChannels(), doc.audio.sampleRate).frames();
- if (mix)
- ae::pasteMix (doc, at, clip);
- else if (! selection.empty())
- ae::pasteReplace (doc, selection, clip);
- else
- ae::insert (doc, at, clip);
- selection = { at, at + length };
- commit (mix ? tr ("Paste mix") : tr ("Paste"));
- if (wasEmpty)
- zoomToFit();
- }
- // FL's Paste mix (envelope): the first time it shows the mix envelope to shape (top = the clipboard, bottom = the
- // original); the second time it mixes the clipboard in at the cursor / selection start with that envelope
- void pasteMixWithEnvelope()
- {
- const auto& clip = clipboard();
- if (clip.empty() || doc.audio.empty() || recState != RecState::idle)
- return;
- if (envMode != EnvMode::mix)
- {
- if (doc.mixEnvelope.empty())
- doc.mixEnvelope = ae::Envelope::flat (0.5);
- setEnvMode (EnvMode::mix);
- setStatus (tr ("Shape the mix envelope (top: the clipboard, bottom: the original), then choose Edit > Paste mix (envelope): apply."), false);
- repaint();
- return;
- }
- stopPlayback();
- const auto at = selection.empty() ? cursor : selection.start;
- const auto mix = doc.mixEnvelope;
- doc.mixEnvelope = {};
- const auto r = ae::pasteMixEnvelope (doc, at, clip, mix);
- setEnvMode (EnvMode::wave);
- selection = r;
- commit (tr ("Paste mix (envelope)"));
- }
- // FL's Scratch (envelope): the first time it shows the position envelope (a rising diagonal = the audio as it is);
- // the second time it renders the audio played along that envelope
- void scratchWithEnvelope()
- {
- if (doc.audio.empty() || recState != RecState::idle)
- return;
- if (envMode != EnvMode::scratch)
- {
- if (doc.scratchEnvelope.empty())
- doc.scratchEnvelope.points = { { 0.0, 0.0, 0.0f }, { 1.0, 1.0, 0.0f } };
- setEnvMode (EnvMode::scratch);
- setStatus (tr ("Draw the play position over time (rising = forwards, falling = backwards, flat = held), then choose Tools > Scratch (envelope): apply."), false);
- repaint();
- return;
- }
- stopPlayback();
- const auto env = doc.scratchEnvelope;
- doc.scratchEnvelope = {};
- ae::scratch (doc, env);
- setEnvMode (EnvMode::wave);
- commit (tr ("Scratch (envelope)"));
- }
- // the clipboard stretched to the selection's length (pitch kept), or drum-stretched (slices keep their attacks),
- // replacing the selection
- void pasteFitted (bool drum)
- {
- const auto& clip = clipboard();
- if (clip.empty() || selection.empty() || recState != RecState::idle)
- return;
- stopPlayback();
- ae::Document part;
- part.audio = ae::conform (clip, doc.audio.numChannels(), doc.audio.sampleRate);
- const auto ratio = (double) selection.length() / (double) juce::jmax<std::int64_t> (1, part.audio.frames());
- if (drum)
- {
- ae::DrumStretchSettings s;
- s.ratio = ratio;
- ae::drumloopStretch (part, {}, s);
- }
- else
- ae::timeStretch (part, {}, ratio);
- for (auto& ch : part.audio.channels)
- ch.resize ((std::size_t) selection.length(), 0.0f);
- ae::pasteReplace (doc, selection, part.audio);
- commit (drum ? tr ("Paste replace (drum)") : tr ("Paste stretch"));
- }
- void fade (bool in)
- {
- const auto curve = fadeCurve;
- 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); });
- }
- void addMarkerAtCursor()
- {
- if (doc.audio.empty())
- return;
- ae::addMarker (doc, selection.empty() ? cursor : selection.start, {});
- commit (tr ("Add marker"));
- }
- void addRegionFromSelection()
- {
- if (selection.empty())
- {
- setStatus (tr ("Select a part first (drag over the waveform)"), false);
- return;
- }
- 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));
- commit (tr ("Add region"));
- }
- void setLoopFromSelection()
- {
- if (selection.empty())
- {
- setStatus (tr ("Select a part first (drag over the waveform)"), false);
- return;
- }
- ae::setLoop (doc, selection);
- commit (tr ("Set loop"));
- }
- // --- Tools › Analysis › Convert to score and dump to piano roll (REA_rodada167c.md §4): the whole sample's notes
- // into the selected channel's notes of the current pattern (replacing them), as FL's Edison
- void convertToScore()
- {
- if (doc.audio.empty() || scoreBusy)
- return;
- stopPlayback();
- auto data = std::make_shared<SampleData>();
- data->sampleRate = doc.audio.sampleRate;
- data->left = doc.audio.channels[0];
- if (doc.audio.numChannels() > 1)
- data->right = doc.audio.channels[1];
- scoreBusy = true;
- setStatus (tr ("Detecting score..."), false);
- juce::Component::SafePointer<AudioEditor> self (this);
- std::thread ([self, data] {
- auto notes = std::make_shared<std::vector<newtonefx::DetectedNote>> (newtonefx::detectScore (*data));
- juce::MessageManager::callAsync ([self, notes, rate = data->sampleRate] {
- if (self == nullptr)
- return;
- self->scoreBusy = false;
- if (notes->empty())
- {
- self->setStatus (tr ("No notes found in the sample"), false);
- return;
- }
- self->setStatus (tr ("Dumping score..."), false);
- const auto channel = self->engine.getSelectedChannel();
- int count = 0;
- self->engine.editSong ([&] (Song& s) {
- if (channel >= 0 && channel < (int) s.channels.size())
- count = newtonefx::dumpScore (s, channel, *notes, rate);
- });
- self->setStatus (tr ("{0} notes put in the Piano roll of the selected channel", { juce::String (count) }), false);
- });
- }).detach();
- }
- // --- scripts (Tools › Scripting: Run script / Edit last script; REA_rodada167c.md §2) -----------------------------
- struct ScriptRef
- {
- juce::String name; // menu name
- juce::String key; // the form memory's key (the script's path, or "lynx:<folder>/<name>")
- juce::String folder; // a built-in script's folder
- std::string source; // a built-in script's text (a file is read when it runs)
- juce::File file;
- };
- struct ScriptJob
- {
- ScriptRef ref;
- std::string source;
- ae::Document start;
- ae::Range selection;
- ae::Audio clip;
- std::vector<ae::script::Form> answers;
- std::uint64_t version = 0;
- };
- struct ScriptResult
- {
- ae::script::Outcome outcome;
- ae::Document doc;
- std::optional<ae::Audio> clip;
- };
- // where scripts come from: FL Studio's own folder (System/Config/Audio scripts, read in place), then the user's
- // Documents/LYNX/Audio scripts
- static std::vector<std::pair<juce::String, juce::File>> scriptFolders()
- {
- static const auto fl = [] {
- const auto roots = findFlStudioRoots();
- return roots.factoryData.empty() ? juce::File()
- : platform::localFile (roots.factoryData).getChildFile ("System").getChildFile ("Config").getChildFile ("Audio scripts");
- }();
- std::vector<std::pair<juce::String, juce::File>> out;
- if (fl.isDirectory())
- out.emplace_back ("FL Studio", fl);
- out.emplace_back (tr ("My scripts"), platform::documentsFolder().getChildFile ("Audio scripts"));
- return out;
- }
- juce::PopupMenu scriptMenu()
- {
- juce::PopupMenu menu;
- menu.addSectionHeader ("LYNX SHARE");
- std::map<juce::String, juce::PopupMenu> own;
- for (const auto& b : ae::script::builtins())
- {
- ScriptRef r;
- r.name = juce::String::fromUTF8 (b.name);
- r.folder = juce::String::fromUTF8 (b.folder);
- r.key = "lynx:" + r.folder + "/" + r.name;
- r.source = b.source;
- own[r.folder].addItem (r.name, true, false, [this, r] { runScript (r); });
- }
- for (auto& [folder, sub] : own)
- menu.addSubMenu (folder, sub);
- for (const auto& [title, dir] : scriptFolders())
- {
- menu.addSectionHeader (title);
- auto addFolder = [this] (const juce::File& d, juce::PopupMenu& into, auto& self, int depth) -> bool {
- bool any = false;
- auto subs = d.findChildFiles (juce::File::findDirectories, false);
- subs.sort();
- for (const auto& s : subs)
- {
- juce::PopupMenu sub;
- if (depth < 3 && self (s, sub, self, depth + 1))
- {
- into.addSubMenu (s.getFileName(), sub);
- any = true;
- }
- }
- auto files = d.findChildFiles (juce::File::findFiles, false, "*.pyscript");
- files.sort();
- for (const auto& f : files)
- {
- ScriptRef r;
- r.name = f.getFileNameWithoutExtension();
- r.key = f.getFullPathName();
- r.file = f;
- into.addItem (r.name, true, false, [this, r] { runScript (r); });
- any = true;
- }
- return any;
- };
- if (! dir.isDirectory() || ! addFolder (dir, menu, addFolder, 0))
- menu.addItem (tr ("(no scripts)"), false, false, nullptr);
- }
- menu.addSeparator();
- menu.addItem (tr ("Open my scripts folder"), true, false, [] {
- const auto dir = platform::documentsFolder().getChildFile ("Audio scripts");
- dir.createDirectory();
- if (platform::testMode())
- platform::testModeLog ("open folder " + dir.getFullPathName());
- else
- dir.startAsProcess();
- });
- return menu;
- }
- void runScript (const ScriptRef& ref)
- {
- if (scriptBusy || recState != RecState::idle)
- return;
- auto job = std::make_shared<ScriptJob>();
- job->ref = ref;
- if (ref.file != juce::File())
- {
- juce::MemoryBlock bytes;
- if (! ref.file.loadFileAsData (bytes) || ! juce::CharPointer_UTF8::isValidString (static_cast<const char*> (bytes.getData()), (int) bytes.getSize()))
- {
- showScriptText (tr ("Error"), tr ("Failed to load the script file. Please make sure it is saved in utf8-format."));
- return;
- }
- job->source.assign (static_cast<const char*> (bytes.getData()), bytes.getSize());
- }
- else
- job->source = ref.source;
- lastScript = ref;
- stopPlayback();
- job->start = doc;
- job->selection = selection;
- job->clip = clipboard();
- job->version = docVersion;
- scriptStep (job);
- }
- // runs the script on a worker thread (the Python thread does the work; the UI never waits for it)
- static void launchScript (std::shared_ptr<const ScriptJob> job, std::vector<ae::script::Form> answers,
- std::function<void (std::shared_ptr<ScriptResult>)> done)
- {
- std::thread ([job, answers = std::move (answers), done = std::move (done)] {
- auto r = std::make_shared<ScriptResult>();
- r->doc = job->start;
- ae::script::Host host;
- host.clipboard = [job] (ae::Audio& a) {
- a = job->clip;
- return ! a.empty();
- };
- host.setClipboard = [r] (const ae::Audio& a) { r->clip = a; };
- host.loadFile = [] (const std::string& path, ae::Audio& a) { return readAudioFile (juce::File (juce::String::fromUTF8 (path.c_str())), a); };
- r->outcome = ae::script::run (job->source, r->doc, job->selection, answers, host);
- juce::MessageManager::callAsync ([done, r] { done (r); });
- }).detach();
- }
- void scriptStep (std::shared_ptr<ScriptJob> job)
- {
- scriptBusy = true;
- setStatus (tr ("Running script {0}...", { job->ref.name }), false);
- juce::Component::SafePointer<AudioEditor> self (this);
- launchScript (job, job->answers, [self, job] (std::shared_ptr<ScriptResult> r) {
- if (self != nullptr)
- self->scriptFinished (job, *r);
- });
- }
- void scriptFinished (std::shared_ptr<ScriptJob> job, ScriptResult& r)
- {
- scriptBusy = false;
- using S = ae::script::Outcome::Status;
- auto& out = r.outcome;
- if (out.status == S::failed)
- {
- setStatus (tr ("The script stopped with an error"), true);
- showScriptText (tr ("Script error"), juce::String::fromUTF8 (out.error.c_str()));
- return;
- }
- juce::Component::SafePointer<AudioEditor> self (this);
- if (out.status == S::needsForm)
- {
- setStatus ({}, false);
- auto form = out.form;
- const auto key = job->ref.key.toStdString();
- if (form.controls.size() == 1 && form.controls[0].hint == "file") // Sample.LoadFromFile_Ask
- {
- auto chooser = lynx::ui::makeSharedFileChooser (tr ("Open"), juce::File(), "*.wav;*.flac;*.aif;*.aiff;*.ogg;*.mp3");
- lynx::ui::launchChooser (chooser, juce::FileBrowserComponent::openMode | juce::FileBrowserComponent::canSelectFiles, [self, job, form, chooser] (const juce::FileChooser& fc) {
- if (self == nullptr)
- return;
- auto answer = form;
- answer.controls[0].text = fc.getResult().getFullPathName().toStdString();
- job->answers.push_back (answer);
- self->scriptStep (job);
- });
- return;
- }
- ae::script::restore (key, form);
- auto panel = std::make_unique<ScriptPanel> (
- form,
- [self, job, key] (const ae::script::Form& f) {
- ae::script::remember (key, f);
- job->answers.push_back (f);
- if (self != nullptr)
- self->scriptStep (job);
- },
- [self, job] (const ae::script::Form& f) {
- if (self != nullptr)
- self->previewScript (job, f);
- },
- [self] {
- if (self != nullptr)
- self->editLastScript();
- });
- openToolWindow (std::move (panel), tr ("Configure script"), "audioeditor-script");
- return;
- }
- // done: one undo step (nothing when the script changed nothing)
- for (const auto& m : out.messages)
- showScriptText (tr ("Script message"), juce::String::fromUTF8 (m.c_str()));
- if (r.clip)
- clipboard() = std::move (*r.clip);
- if (docVersion != job->version)
- {
- setStatus (tr ("The audio changed while the script ran: run it again"), true);
- return;
- }
- const bool same = r.doc.audio.sampleRate == doc.audio.sampleRate && r.doc.audio.channels == doc.audio.channels && r.doc.markers.size() == doc.markers.size()
- && std::equal (r.doc.markers.begin(), r.doc.markers.end(), doc.markers.begin(), [] (const ae::Marker& a, const ae::Marker& b) {
- return a.start == b.start && a.end == b.end && a.name == b.name && a.info == b.info && a.keyNum == b.keyNum;
- });
- setStatus (tr ("Script {0} done", { job->ref.name }), false);
- if (same)
- return;
- const bool wasEmpty = doc.audio.empty();
- if (wasEmpty)
- history.reset (doc, tr ("Empty").toStdString());
- doc = std::move (r.doc);
- commit (tr ("Script: {0}", { job->ref.name }));
- if (wasEmpty)
- zoomToFit();
- }
- // Preview: the script with these values on a copy, played from the selection (or the start)
- void previewScript (std::shared_ptr<ScriptJob> job, const ae::script::Form& f)
- {
- auto answers = job->answers;
- answers.push_back (f);
- const auto ticket = ++previewTicket;
- juce::Component::SafePointer<AudioEditor> self (this);
- launchScript (job, std::move (answers), [self, job, ticket] (std::shared_ptr<ScriptResult> r) {
- if (self == nullptr || ticket != self->previewTicket || r->outcome.status != ae::script::Outcome::Status::done || r->doc.audio.empty())
- return;
- const auto from = juce::jlimit<std::int64_t> (0, r->doc.audio.frames(), job->selection.empty() ? 0 : job->selection.start);
- self->playAudio (ae::copy (r->doc.audio, { from, r->doc.audio.frames() }), 0, false);
- });
- }
- // Edit last script: the script's file in the system's editor (a LYNX script is first saved to My scripts)
- void editLastScript()
- {
- if (lastScript.key.isEmpty())
- return;
- auto file = lastScript.file;
- if (file == juce::File())
- {
- file = platform::documentsFolder().getChildFile ("Audio scripts").getChildFile (lastScript.folder).getChildFile (lastScript.name + ".pyscript");
- if (! file.existsAsFile())
- {
- file.getParentDirectory().createDirectory();
- file.replaceWithText (juce::String::fromUTF8 (lastScript.source.c_str()), false, false, "\n");
- }
- lastScript.file = file;
- lastScript.key = file.getFullPathName();
- }
- if (platform::testMode())
- platform::testModeLog ("edit script " + file.getFullPathName());
- else if (! file.startAsProcess())
- file.revealToUser();
- }
- void showScriptText (const juce::String& title, const juce::String& text)
- {
- if (platform::testMode())
- {
- platform::testModeLog (title + ": " + text);
- return;
- }
- juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::NoIcon, title, text, tr ("OK"), this);
- }
- // --- tool windows ---------------------------------------------------------------------------------------
- // plays `fn` applied to a copy of the selection (Preview)
- void previewProcessed (const std::function<void (ae::Document&)>& fn)
- {
- ae::Document part;
- part.audio = ae::copy (doc.audio, ae::orAll (doc, selection));
- fn (part);
- playAudio (part.audio, 0, false);
- }
- void openTool (std::unique_ptr<ToolPanel> panel, const juce::String& title)
- {
- openToolWindow (std::move (panel), title, "audioeditor-tool");
- }
- void showAmp() { openEdisonTool (audiotools::Tool::amp); } // Edison's Amp form (round 165l)
- void showResample()
- {
- if (doc.audio.empty())
- return;
- static const int rates[] = { 8000, 11025, 16000, 22050, 32000, 44100, 48000, 88200, 96000, 192000 };
- juce::StringArray names;
- int current = 5;
- for (int i = 0; i < 10; ++i)
- {
- names.add (juce::String (rates[i]) + " Hz");
- if (std::abs (rates[i] - doc.audio.sampleRate) < 1.0)
- current = i;
- }
- juce::Component::SafePointer<AudioEditor> self (this);
- openTool (std::make_unique<ToolPanel> (std::vector<ToolPanel::Param> {}, names, tr ("Sample rate"), current,
- [self] (const std::vector<double>&, int i) {
- if (self != nullptr && i >= 0)
- {
- self->selection = {};
- self->edit (tr ("Resample"), [i] (ae::Document& d, ae::Range) { ae::resample (d, rates[i]); });
- self->zoomToFit();
- }
- },
- nullptr),
- tr ("Resample"));
- }
- void showInsertSilence()
- {
- if (doc.audio.empty())
- return;
- juce::Component::SafePointer<AudioEditor> self (this);
- openTool (std::make_unique<ToolPanel> (std::vector<ToolPanel::Param> { { tr ("Length"), 1.0, 10000.0, 500.0, 1.0, " ms" } }, juce::StringArray {},
- juce::String {}, 0,
- [self] (const std::vector<double>& v, int) {
- if (self == nullptr)
- return;
- const auto frames = (std::int64_t) std::llround (v[0] * 0.001 * self->doc.audio.sampleRate);
- const auto at = self->cursor;
- ae::insertSilence (self->doc, at, frames);
- self->selection = { at, at + frames };
- self->commit (tr ("Insert silence"));
- },
- nullptr),
- tr ("Insert silence"));
- }
- void showNormalizeTo()
- {
- if (doc.audio.empty())
- return;
- juce::Component::SafePointer<AudioEditor> self (this);
- 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,
- [self] (const std::vector<double>& v, int) {
- if (self != nullptr)
- self->edit (tr ("Normalize"), [v] (ae::Document& d, ae::Range r) { ae::normalize (d, r, (float) v[0]); });
- },
- nullptr),
- tr ("Normalize"));
- }
- void autoSlice (float sensitivity)
- {
- if (doc.audio.empty())
- return;
- const auto r = ae::orAll (doc, selection);
- auto part = ae::copy (doc.audio, r);
- int added = 0;
- for (auto f : ae::detectOnsets (part, sensitivity))
- if (f > 0 || r.start > 0)
- {
- ae::addMarker (doc, r.start + f, {});
- ++added;
- }
- if (added > 0)
- commit (tr ("Auto-slice"));
- setStatus (tr ("{0} markers added", { juce::String (added) }), false);
- }
- void gridSlice (double beats)
- {
- if (doc.audio.empty())
- return;
- const auto step = beats * 60.0 / juce::jmax (1.0, engine.getSong().bpm) * doc.audio.sampleRate;
- const auto r = ae::orAll (doc, selection);
- int added = 0;
- for (auto f = (double) r.start + step; f < (double) r.end - 1.0; f += step, ++added)
- ae::addMarker (doc, (std::int64_t) std::llround (f), {});
- if (added > 0)
- commit (tr ("Grid slice"));
- }
- // --- playback -------------------------------------------------------------------------------------------
- void playAudio (const ae::Audio& audio, std::int64_t from, bool loop)
- {
- if (audio.empty())
- return;
- auto data = std::make_shared<SampleData>();
- data->sampleRate = audio.sampleRate;
- data->left = audio.channels[0];
- if (audio.numChannels() > 1)
- data->right = audio.channels[1];
- engine.previewSample (data, loop, 1.0f, true); // (at the volume knob's level)
- playing = true;
- playFrom = from;
- playStartedMs = juce::Time::getMillisecondCounterHiRes();
- playhead = from;
- playButton.setIcon (Icon::pause);
- }
- void startPlayback()
- {
- if (doc.audio.empty() || recState != RecState::idle)
- return;
- auto r = selection;
- if (r.empty() && loopPlay && doc.hasLoop())
- r = { doc.loopStart, doc.loopEnd };
- if (r.empty())
- r = { cursor, doc.audio.frames() };
- if (r.length() < 2)
- r = { 0, doc.audio.frames() };
- if (ae::hasEnvelopes (doc))
- {
- // the envelopes are heard before they are mixed down (like Edison)
- ae::Document mixed;
- mixed.audio = doc.audio;
- mixed.volumeEnvelope = doc.volumeEnvelope;
- mixed.panEnvelope = doc.panEnvelope;
- mixed.separationEnvelope = doc.separationEnvelope;
- ae::mixdownEnvelopes (mixed);
- playAudio (ae::copy (mixed.audio, r), r.start, loopPlay);
- return;
- }
- playAudio (ae::copy (doc.audio, r), r.start, loopPlay);
- }
- void stopPlayback()
- {
- if (! playing)
- return;
- engine.previewSample (nullptr);
- playing = false;
- playhead = -1;
- playButton.setIcon (Icon::play);
- repaint();
- }
- // --- recording ------------------------------------------------------------------------------------------
- void toggleRecording()
- {
- if (recState == RecState::idle)
- startRecording();
- else
- stopRecording();
- }
- void startRecording()
- {
- stopPlayback();
- auto* device = engine.getDeviceManager().getCurrentAudioDevice();
- if (device == nullptr)
- {
- setStatus (tr ("No audio device is open (Settings > Audio)"), true);
- return;
- }
- if (recordSource == AudioCapture::input)
- {
- if (! engine.hasAudioInput())
- {
- if (const auto result = engine.openAudioInput(); result.issue != AudioEngine::InputIssue::none)
- {
- setStatus (result.detail.isNotEmpty() ? result.detail : tr ("No active audio input (Settings > Audio)"), true);
- return;
- }
- openedInput = true; // closed again when the recording stops (round 165q)
- }
- device = engine.getDeviceManager().getCurrentAudioDevice();
- if (device == nullptr || device->getActiveInputChannels().countNumberOfSetBits() == 0)
- {
- setStatus (tr ("No active audio input (Settings > Audio)"), true);
- return;
- }
- }
- recordRate = device->getCurrentSampleRate();
- recordStereo = recordSource != AudioCapture::input || device->getActiveInputChannels().countNumberOfSetBits() > 1;
- recL.clear();
- recR.clear();
- beforeRecording = doc;
- recordAt = selection.empty() ? cursor : selection.start;
- if (doc.audio.empty())
- recordAt = 0;
- engine.getMeters().capture.setSource (recordSource);
- recState = recordMode == RecordMode::now ? RecState::recording : RecState::waiting;
- recordButton.setToggleState (true, juce::dontSendNotification);
- if (recordMode == RecordMode::onPlay && ! engine.getTransport().playing.load())
- setStatus (tr ("Recording starts when the song plays"), false);
- else if (recordMode == RecordMode::onInput)
- setStatus (tr ("Recording starts when the input is heard"), false);
- else
- setStatus (tr ("Recording from {0}", { sourceName (recordSource) }), false);
- repaint();
- }
- void drainRecording()
- {
- std::vector<float> l, r;
- engine.getMeters().capture.pull (l, r);
- if (l.empty())
- return;
- std::size_t from = 0;
- if (recState == RecState::waiting)
- {
- if (recordMode == RecordMode::onPlay)
- {
- if (! engine.getTransport().playing.load())
- return;
- }
- else
- {
- while (from < l.size() && std::abs (l[from]) < inputThreshold && std::abs (r[from]) < inputThreshold)
- ++from;
- if (from == l.size())
- return;
- }
- recState = RecState::recording;
- setStatus (tr ("Recording from {0}", { sourceName (recordSource) }), false);
- }
- recL.insert (recL.end(), l.begin() + (std::ptrdiff_t) from, l.end());
- recR.insert (recR.end(), r.begin() + (std::ptrdiff_t) from, r.end());
- if (recordMode == RecordMode::onPlay && ! engine.getTransport().playing.load())
- stopRecording();
- }
- ae::Audio recordedAudio() const
- {
- ae::Audio a;
- a.sampleRate = recordRate;
- a.channels.push_back (recL);
- if (recordStereo)
- a.channels.push_back (recR);
- return a;
- }
- // the document = what it was, with the recording inserted at the cursor
- void showRecording()
- {
- doc = beforeRecording;
- const auto rec = recordedAudio();
- if (doc.audio.empty())
- {
- doc.audio = rec;
- doc.title = tr ("Recording").toStdString();
- }
- else
- ae::insert (doc, recordAt, rec);
- const auto length = doc.audio.frames() - beforeRecording.audio.frames();
- selection = { recordAt, recordAt + length };
- cursor = recordAt + length;
- rebuildSummary();
- ++docVersion;
- // follow the end
- const auto visible = (double) waveArea.getWidth() * fpp;
- if (beforeRecording.audio.empty() || (double) cursor > viewStart + visible)
- {
- if (beforeRecording.audio.empty() && (double) cursor > visible)
- fpp = juce::jmax (fpp, (double) cursor / juce::jmax (1, waveArea.getWidth()) * 1.25);
- viewStart = juce::jmax (0.0, (double) cursor - visible * 0.8);
- }
- clampView();
- repaint();
- }
- // the input this editor opened for its recording: closed again (FL does not keep the microphone open; Windows
- // showed its microphone-in-use icon until LYNX quit — round 165q)
- void releaseInput()
- {
- if (! openedInput)
- return;
- openedInput = false;
- engine.releaseAudioInputIfUnused();
- }
- void stopRecording()
- {
- if (recState == RecState::idle)
- return;
- drainRecording();
- engine.getMeters().capture.setSource (AudioCapture::off);
- releaseInput();
- const auto got = ! recL.empty();
- const auto dropped = engine.getMeters().capture.droppedFrames();
- recState = RecState::idle;
- recordButton.setToggleState (false, juce::dontSendNotification);
- if (got)
- {
- showRecording();
- commit (tr ("Record"));
- setStatus (tr ("Recorded {0}", { formatTime ((std::int64_t) recL.size()) }) + (dropped > 0 ? " (" + tr ("{0} frames lost", { juce::String (dropped) }) + ")" : ""), dropped > 0);
- }
- else
- {
- doc = beforeRecording;
- documentChanged();
- setStatus (tr ("Nothing was recorded"), false);
- }
- recL.clear();
- recR.clear();
- }
- juce::String sourceName (int s) const
- {
- if (s == AudioCapture::input)
- return tr ("the audio input");
- if (s == 0)
- return tr ("the Master");
- const auto& mixer = engine.getSong().mixer;
- if (juce::isPositiveAndBelow (s, (int) mixer.size()) && ! mixer[(std::size_t) s].name.empty())
- return tr ("insert {0}", { juce::String (s) }) + " (" + juce::String::fromUTF8 (mixer[(std::size_t) s].name.c_str()) + ")";
- return tr ("insert {0}", { juce::String (s) });
- }
- public:
- void recordInputWithSong()
- {
- recordSource = AudioCapture::input;
- recordMode = RecordMode::onPlay;
- startRecording();
- }
- void setRecordSource (int s)
- {
- recordSource = s;
- setStatus (tr ("Press Record to capture {0}", { sourceName (s) }), false);
- }
- private:
- // --- output ---------------------------------------------------------------------------------------------
- juce::String safeTitle() const
- {
- auto t = juce::File::createLegalFileName (juce::String::fromUTF8 (doc.title.c_str())).trim();
- return t.isEmpty() ? juce::String ("Audio") : t;
- }
- // the edited audio as a new WAV in Music\LYNX\Edits (a new name each time: the Sampler and the waveform caches
- // key on the path, so nothing stale is ever shown)
- juce::File writeEditFile()
- {
- const auto folder = juce::File::getSpecialLocation (juce::File::userMusicDirectory).getChildFile ("LYNX/Edits");
- folder.createDirectory();
- const auto file = folder.getNonexistentChildFile (safeTitle() + " (edit)", ".wav");
- if (! writeWav (file, bits))
- return {};
- return file;
- }
- bool writeWav (const juce::File& file, ae::WavFormat format)
- {
- const auto bytes = ae::encodeWav (doc, format);
- if (! file.replaceWithData (bytes.data(), bytes.size()))
- {
- setStatus (tr ("Could not write {0}", { file.getFullPathName() }), true);
- return false;
- }
- engine.getSampleLibrary().forget (file.getFullPathName());
- return true;
- }
- void saveAs (ae::WavFormat format)
- {
- if (doc.audio.empty())
- return;
- auto start = lastFile.existsAsFile() ? lastFile.getSiblingFile (safeTitle() + ".wav")
- : juce::File::getSpecialLocation (juce::File::userMusicDirectory).getChildFile (safeTitle() + ".wav");
- chooser = lynx::ui::makeFileChooser (tr ("Save as WAV"), start, "*.wav");
- juce::Component::SafePointer<AudioEditor> self (this);
- lynx::ui::launchChooser (chooser, juce::FileBrowserComponent::saveMode | juce::FileBrowserComponent::canSelectFiles | juce::FileBrowserComponent::warnAboutOverwriting,
- [self, format] (const juce::FileChooser& fc) {
- if (self == nullptr || fc.getResult() == juce::File {})
- return;
- const auto file = fc.getResult().withFileExtension ("wav");
- if (self->writeWav (file, format))
- {
- self->bits = format;
- self->lastFile = file;
- self->modified = false;
- self->setStatus (tr ("Saved {0}", { file.getFileName() }), false);
- self->updateTitle();
- }
- });
- }
- void openFileDialog()
- {
- chooser = lynx::ui::makeFileChooser (tr ("Open audio file"), lastFile, engine.getSampleLibrary().wildcard());
- juce::Component::SafePointer<AudioEditor> self (this);
- lynx::ui::launchChooser (chooser, juce::FileBrowserComponent::openMode | juce::FileBrowserComponent::canSelectFiles, [self] (const juce::FileChooser& fc) {
- if (self == nullptr || ! fc.getResult().existsAsFile())
- return;
- self->stopPlayback();
- self->source = { Source::Kind::file, -1, fc.getResult().getFullPathName() };
- self->loadFile (fc.getResult());
- });
- }
- // each region (or each stretch between markers when there are no regions) as its own WAV in a folder
- void exportRegions()
- {
- std::vector<ae::Range> parts;
- std::vector<std::string> names;
- for (const auto& m : doc.markers)
- if (m.isRegion())
- {
- parts.push_back ({ m.start, m.end });
- names.push_back (m.name);
- }
- if (parts.empty())
- {
- std::int64_t from = 0;
- for (const auto& m : doc.markers)
- if (m.start > from)
- {
- parts.push_back ({ from, m.start });
- names.push_back ({});
- from = m.start;
- }
- if (from > 0 && from < doc.audio.frames())
- {
- parts.push_back ({ from, doc.audio.frames() });
- names.push_back ({});
- }
- }
- if (parts.empty())
- {
- setStatus (tr ("No regions or markers to export"), true);
- return;
- }
- chooser = lynx::ui::makeFileChooser (tr ("Export regions to a folder"), juce::File::getSpecialLocation (juce::File::userMusicDirectory));
- juce::Component::SafePointer<AudioEditor> self (this);
- lynx::ui::launchChooser (chooser, juce::FileBrowserComponent::openMode | juce::FileBrowserComponent::canSelectDirectories,
- [self, parts, names] (const juce::FileChooser& fc) {
- if (self == nullptr || ! fc.getResult().isDirectory())
- return;
- int written = 0;
- for (std::size_t i = 0; i < parts.size(); ++i)
- {
- ae::Document part;
- part.audio = ae::copy (self->doc.audio, parts[i]);
- const auto name = names[i].empty() ? self->safeTitle() + " " + juce::String (i + 1).paddedLeft ('0', 2)
- : juce::File::createLegalFileName (juce::String::fromUTF8 (names[i].c_str()));
- const auto bytes = ae::encodeWav (part, self->bits);
- written += fc.getResult().getNonexistentChildFile (name, ".wav").replaceWithData (bytes.data(), bytes.size()) ? 1 : 0;
- }
- self->setStatus (tr ("{0} files written", { juce::String (written) }), false);
- });
- }
- void sendToPlaylist()
- {
- if (doc.audio.empty())
- return;
- const auto file = writeEditFile();
- if (file == juce::File {})
- return;
- const auto& song = engine.getSong();
- const auto length = juce::jmax<std::int64_t> (ppq / 4, (std::int64_t) (doc.audio.seconds() * song.bpm / 60.0 * ppq));
- const auto start = (std::int64_t) (engine.getTransport().positionTicks.load() / ppq) * ppq; // at the beat of the song position
- // the first track with room for it
- int track = 0;
- for (;; ++track)
- {
- const auto busy = std::any_of (song.playlist.begin(), song.playlist.end(),
- [&] (const Clip& c) { return c.track == track && c.start < start + length && c.end() > start; });
- if (! busy)
- break;
- }
- const auto path = file.getFullPathName().toStdString();
- const auto name = safeTitle().toStdString();
- engine.editSong ([=] (Song& s) {
- ChannelDef c;
- c.name = name;
- c.instrument = InstrumentKind::audioClip;
- c.samplePath = path;
- c.mixerTrack = s.claimFreeInsert();
- s.channels.push_back (c);
- Clip clip;
- clip.kind = ClipKind::audio;
- clip.channel = (int) s.channels.size() - 1;
- clip.track = track;
- clip.start = start;
- clip.length = length;
- s.playlist.push_back (clip);
- s.mode = PlayMode::song;
- });
- modified = false;
- setStatus (tr ("Sent to the Playlist (track {0})", { juce::String (track + 1) }), false);
- updateTitle();
- }
- // FL's Edison "Send to channel" of a part (issue #12): the selection (or a region) as a new Sampler channel's
- // sample; the editor keeps the whole audio (nothing cut or cropped)
- void sendRangeToNewSampler (ae::Range range)
- {
- range = ae::clamp (doc, range);
- if (doc.audio.empty() || range.empty())
- return;
- ae::Document part;
- part.audio = ae::copy (doc.audio, range);
- part.title = doc.title;
- if (doc.hasLoop() && doc.loopStart >= range.start && doc.loopEnd <= range.end)
- ae::setLoop (part, { doc.loopStart - range.start, doc.loopEnd - range.start });
- const auto folder = juce::File::getSpecialLocation (juce::File::userMusicDirectory).getChildFile ("LYNX/Edits");
- folder.createDirectory();
- const auto file = folder.getNonexistentChildFile (safeTitle() + " (part)", ".wav");
- const auto bytes = ae::encodeWav (part, bits);
- if (! file.replaceWithData (bytes.data(), bytes.size()))
- {
- setStatus (tr ("Could not write {0}", { file.getFullPathName() }), true);
- return;
- }
- engine.getSampleLibrary().forget (file.getFullPathName());
- const auto path = file.getFullPathName().toStdString();
- const auto name = (safeTitle() + " (part)").toStdString();
- int index = 0;
- engine.editSong ([&] (Song& s) {
- ChannelDef c;
- c.name = name;
- c.instrument = InstrumentKind::sampler;
- c.samplePath = path;
- c.mixerTrack = s.claimFreeInsert();
- s.channels.push_back (c);
- index = (int) s.channels.size() - 1;
- });
- engine.setSelectedChannel (index);
- setStatus (tr ("The selection went to a new Sampler channel ({0})", { juce::String::fromUTF8 (name.c_str()) }), false);
- }
- void sendToNewSampler()
- {
- if (doc.audio.empty())
- return;
- const auto file = writeEditFile();
- if (file == juce::File {})
- return;
- const auto path = file.getFullPathName().toStdString();
- const auto name = safeTitle().toStdString();
- int index = 0;
- engine.editSong ([&] (Song& s) {
- ChannelDef c;
- c.name = name;
- c.instrument = InstrumentKind::sampler;
- c.samplePath = path;
- c.mixerTrack = s.claimFreeInsert();
- s.channels.push_back (c);
- index = (int) s.channels.size() - 1;
- });
- engine.setSelectedChannel (index);
- modified = false;
- setStatus (tr ("Sent to a new Sampler channel"), false);
- updateTitle();
- }
- bool sourceChannelValid() const
- {
- const auto& channels = engine.getSong().channels;
- return source.kind == Source::Kind::channel && juce::isPositiveAndBelow (source.index, (int) channels.size())
- && juce::String::fromUTF8 (channels[(std::size_t) source.index].samplePath.c_str()) == source.path;
- }
- void sendBackToChannel()
- {
- if (doc.audio.empty() || ! sourceChannelValid())
- return;
- const auto file = writeEditFile();
- if (file == juce::File {})
- return;
- const auto path = file.getFullPathName().toStdString();
- const auto ch = source.index;
- engine.editSong ([=] (Song& s) { s.channels[(std::size_t) ch].samplePath = path; });
- source.path = file.getFullPathName();
- modified = false;
- setStatus (tr ("The channel now plays the edited audio"), false);
- updateTitle();
- }
- // --- menus ----------------------------------------------------------------------------------------------
- juce::PopupMenu historyMenu()
- {
- juce::PopupMenu menu;
- menu.addSectionHeader (tr ("Undo history"));
- for (int i = history.size() - 1; i >= 0; --i)
- menu.addItem (juce::String::fromUTF8 (history.label (i).c_str()), true, i == history.getPosition(), [this, i] {
- if (recState != RecState::idle)
- return;
- stopPlayback();
- doc = history.jumpTo (i);
- modified = true;
- documentChanged();
- });
- return menu;
- }
- juce::PopupMenu curveMenu()
- {
- juce::PopupMenu menu;
- const std::pair<ae::Curve, const char*> curves[] = { { ae::Curve::smooth, TR_NOOP ("Smooth (S-curve)") },
- { ae::Curve::linear, TR_NOOP ("Linear") },
- { ae::Curve::exponential, TR_NOOP ("Slow start") },
- { ae::Curve::logarithmic, TR_NOOP ("Fast start") } };
- menu.addSectionHeader (tr ("Fade curve"));
- for (const auto& [curve, name] : curves)
- menu.addItem (tr (name), true, fadeCurve == curve, [this, c = curve] { fadeCurve = c; });
- return menu;
- }
- juce::PopupMenu recordMenu()
- {
- juce::PopupMenu menu;
- menu.addSectionHeader (tr ("Record from"));
- menu.addItem (tr ("Audio input"), true, recordSource == AudioCapture::input, [this] { recordSource = AudioCapture::input; });
- menu.addItem (tr ("Master output"), true, recordSource == 0, [this] { recordSource = 0; });
- juce::PopupMenu inserts;
- const auto& mixer = engine.getSong().mixer;
- for (int t = 1; t < (int) mixer.size(); ++t)
- inserts.addItem (sourceName (t), true, recordSource == t, [this, t] { recordSource = t; });
- menu.addSubMenu (tr ("Mixer insert"), inserts, inserts.getNumItems() > 0, nullptr, recordSource > 0);
- menu.addSectionHeader (tr ("Start"));
- menu.addItem (tr ("Immediately"), true, recordMode == RecordMode::now, [this] { recordMode = RecordMode::now; });
- menu.addItem (tr ("When the input is heard"), true, recordMode == RecordMode::onInput, [this] { recordMode = RecordMode::onInput; });
- menu.addItem (tr ("When the song plays (stops with it)"), true, recordMode == RecordMode::onPlay, [this] { recordMode = RecordMode::onPlay; });
- return menu;
- }
- juce::PopupMenu sendMenu()
- {
- juce::PopupMenu menu;
- const auto has = ! doc.audio.empty();
- menu.addItem (tr ("Send to the Playlist as an audio clip"), has, false, [this] { sendToPlaylist(); });
- menu.addItem (tr ("Send to a new Sampler channel"), has, false, [this] { sendToNewSampler(); });
- menu.addItem (tr ("Send the selection to a new Sampler channel"), has && ! selection.empty(), false,
- [this] { sendRangeToNewSampler (selection); });
- if (source.kind == Source::Kind::channel)
- {
- const auto& channels = engine.getSong().channels;
- const auto name = juce::isPositiveAndBelow (source.index, (int) channels.size())
- ? juce::String::fromUTF8 (channels[(std::size_t) source.index].name.c_str())
- : juce::String();
- menu.addItem (tr ("Replace the sample of \"{0}\"", { name }), has && sourceChannelValid(), false, [this] { sendBackToChannel(); });
- }
- return menu;
- }
- juce::PopupMenu markerMenu (int index)
- {
- juce::PopupMenu menu;
- const auto m = doc.markers[(std::size_t) index];
- menu.addSectionHeader (m.name.empty() ? (m.isRegion() ? tr ("Region") : tr ("Marker")) : juce::String::fromUTF8 (m.name.c_str()));
- menu.addItem (tr ("Rename..."), [this, index] { renameMarker (index); });
- if (m.isRegion())
- {
- menu.addItem (tr ("Select"), [this, m] {
- selection = { m.start, m.end };
- repaint();
- });
- menu.addItem (tr ("Zoom on"), [this, m] { zoomTo ({ m.start, m.end }); });
- menu.addItem (tr ("Send to a new Sampler channel"), [this, m] { sendRangeToNewSampler ({ m.start, m.end }); });
- menu.addItem (tr ("Set loop"), [this, m] {
- ae::setLoop (doc, { m.start, m.end });
- commit (tr ("Set loop"));
- });
- menu.addItem (tr ("Turn into marker"), [this, index] {
- doc.markers[(std::size_t) index].end = doc.markers[(std::size_t) index].start;
- commit (tr ("Turn into marker"));
- });
- }
- menu.addItem (tr ("Delete"), [this, index] {
- doc.markers.erase (doc.markers.begin() + index);
- commit (tr ("Delete marker"));
- });
- return menu;
- }
- void renameMarker (int index)
- {
- auto* box = new juce::AlertWindow (tr ("Rename"), {}, juce::MessageBoxIconType::NoIcon, this);
- box->addTextEditor ("name", juce::String::fromUTF8 (doc.markers[(std::size_t) index].name.c_str()));
- box->addButton (tr ("Accept"), 1, juce::KeyPress (juce::KeyPress::returnKey));
- box->addButton (tr ("Cancel"), 0, juce::KeyPress (juce::KeyPress::escapeKey));
- juce::Component::SafePointer<AudioEditor> self (this);
- box->enterModalState (true, juce::ModalCallbackFunction::create ([self, box, index] (int result) {
- if (self != nullptr && result == 1 && juce::isPositiveAndBelow (index, (int) self->doc.markers.size()))
- {
- self->doc.markers[(std::size_t) index].name = box->getTextEditorContents ("name").toStdString();
- self->commit (tr ("Rename marker"));
- }
- }),
- true);
- }
- void setStatus (const juce::String& text, bool error)
- {
- status = text;
- statusIsError = error;
- repaint (infoArea);
- }
- void updateButtons()
- {
- undoButton.setEnabled (history.canUndo());
- redoButton.setEnabled (history.canRedo());
- const auto has = ! doc.audio.empty();
- for (auto* b : quickButtons)
- b->setEnabled (has);
- playButton.setEnabled (has);
- saveButton.setEnabled (has);
- }
- void updateTitle()
- {
- if (auto* window = findParentComponentOfClass<juce::DocumentWindow>())
- window->setName (tr ("Audio editor") + (doc.title.empty() ? juce::String() : " - " + juce::String::fromUTF8 (doc.title.c_str())) + (modified ? " *" : ""));
- }
- void parentHierarchyChanged() override { updateTitle(); }
- void timerCallback() override
- {
- if (recState != RecState::idle)
- {
- drainRecording();
- if (recState == RecState::recording && ++recordTicks % 6 == 0) // the view follows ~5 times a second
- showRecording();
- if (recState == RecState::idle)
- return;
- repaint();
- }
- if (playing)
- {
- const auto pos = engine.getPreviewPosition();
- if (pos < 0.0)
- {
- if (juce::Time::getMillisecondCounterHiRes() - playStartedMs > 250.0)
- stopPlayback();
- return;
- }
- const auto before = playhead;
- playhead = playFrom < 0 ? -1 : playFrom + (std::int64_t) pos; // (a tool preview is not on the timeline)
- // page along with the playhead (Follow on, issue #12)
- if (playhead >= 0 && EditorGlobals::get().isFollowingView (EditorGlobals::FollowView::audioEditor)
- && ((double) playhead > viewStart + (double) waveArea.getWidth() * fpp || (double) playhead < viewStart) && fpp < maxFpp())
- {
- viewStart = (double) playhead;
- clampView();
- repaint();
- }
- else if (before != playhead)
- repaint (waveArea.withTrimmedTop (-2));
- }
- }
- // --- Edison's tools (round 165l): the tool windows' host ---------------------------------------------------
- public:
- const ae::Document& toolDocument() const override { return doc; }
- ae::Range toolSelection() const override { return selection; }
- void toolApply (const juce::String& label, ae::Document d, ae::Range newSelection) override
- {
- if (recState != RecState::idle)
- return;
- stopPlayback();
- const auto frames = doc.audio.frames();
- const auto edited = ae::orAll (doc, selection);
- doc = std::move (d);
- if (ae::hasEnvelopes (doc) && doc.audio.frames() != frames)
- ae::remapEnvelopes (doc, frames, edited, edited.length() + (doc.audio.frames() - frames));
- selection = ae::clamp (doc, newSelection);
- commit (label);
- }
- void toolPreview (const ae::Audio& audio) override
- {
- stopPlayback();
- playAudio (audio, -1, false);
- }
- void toolStopPreview() override { stopPlayback(); }
- double toolBpm() const override { return juce::jmax (1.0, engine.getSong().bpm); }
- ae::NoiseProfile& toolNoiseProfile() override { return noiseProfile; }
- const ae::Audio& toolClipboard() const override { return clipboard(); }
- ae::Envelope* toolEnvelope() override
- {
- if (envMode == EnvMode::wave)
- setEnvMode (EnvMode::volume);
- return ¤tEnvelope();
- }
- void toolEnvelopeChanged (bool commitIt, const juce::String& label) override
- {
- if (commitIt)
- commit (label);
- else
- repaint();
- }
- juce::Component& toolComponent() override { return *this; }
- private:
- enum class EnvMode
- {
- wave,
- volume,
- panning,
- separation,
- mix, // the mix envelope of Paste mix (envelope)
- scratch // the position envelope of Scratch (envelope)
- };
- EnvMode envMode = EnvMode::wave;
- ae::NoiseProfile noiseProfile;
- float noiseThreshold = -1.0f;
- int envDragPoint = -1;
- bool envChanged = false;
- float envBendStartY = 0.0f, envBendStartTension = 0.0f;
- ae::Envelope& currentEnvelope()
- {
- return envMode == EnvMode::panning ? doc.panEnvelope : envMode == EnvMode::separation ? doc.separationEnvelope : envMode == EnvMode::mix ? doc.mixEnvelope : envMode == EnvMode::scratch ? doc.scratchEnvelope : doc.volumeEnvelope;
- }
- static const char* envModeName (EnvMode m)
- {
- switch (m)
- {
- case EnvMode::wave: return TR_NOOP ("Edit: Wave");
- case EnvMode::volume: return TR_NOOP ("Edit: Volume");
- case EnvMode::panning: return TR_NOOP ("Edit: Panning");
- case EnvMode::separation: return TR_NOOP ("Edit: Stereo sep");
- case EnvMode::mix: return TR_NOOP ("Edit: Paste mix");
- case EnvMode::scratch: return TR_NOOP ("Edit: Scratch");
- }
- return "";
- }
- void setEnvMode (EnvMode m)
- {
- envMode = m;
- envButton.setButtonText (tr (envModeName (m)));
- envButton.setToggleState (m != EnvMode::wave, juce::dontSendNotification);
- if (m != EnvMode::wave)
- 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);
- repaint();
- }
- juce::PopupMenu envModeMenu()
- {
- juce::PopupMenu m;
- for (auto mode : { EnvMode::wave, EnvMode::volume, EnvMode::panning, EnvMode::separation })
- m.addItem (tr (envModeName (mode)), mode == EnvMode::wave || doc.audio.numChannels() > 1 || mode == EnvMode::volume, envMode == mode, [this, mode] { setEnvMode (mode); });
- if (envMode == EnvMode::mix || envMode == EnvMode::scratch)
- m.addItem (tr (envModeName (envMode)), true, true, [] {});
- return m;
- }
- // envelope y 0..1 <-> the wave area's height
- float envY (double y) const noexcept { return (float) waveArea.getBottom() - 4.0f - (float) y * ((float) waveArea.getHeight() - 8.0f); }
- 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))); }
- float envX (double x) const noexcept { return frameToX (x * (double) juce::jmax<std::int64_t> (1, doc.audio.frames() - 1)); }
- 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)); }
- int envelopeHit (juce::Point<float> p)
- {
- auto& env = currentEnvelope();
- for (int i = 0; i < (int) env.points.size(); ++i)
- if (juce::Point<float> (envX (env.points[(std::size_t) i].x), envY (env.points[(std::size_t) i].y)).getDistanceFrom (p) < 7.0f)
- return i;
- return -1;
- }
- // the segment (its end point) whose hollow tension handle is under p, or -1
- int envelopeHandleHit (juce::Point<float> p)
- {
- auto& env = currentEnvelope();
- for (int i = 1; i < (int) env.points.size(); ++i)
- {
- const auto& a = env.points[(std::size_t) i - 1];
- const auto& b = env.points[(std::size_t) i];
- if (envX (b.x) - envX (a.x) < 14.0f)
- continue;
- const auto mx = 0.5 * (a.x + b.x);
- if (juce::Point<float> (envX (mx), envY (env.at (mx))).getDistanceFrom (p) < 6.0f)
- return i;
- }
- return -1;
- }
- // FL's point editing on the envelope: right-click (or click) on an empty spot adds a point and drags it, drag a
- // point moves it, right-click or Alt+click on a point deletes it, the hollow handle between two points bends the
- // segment (right-click it: straight). Returns true when the click was for the envelope.
- bool envelopeMouseDown (const juce::MouseEvent& e)
- {
- auto& env = currentEnvelope();
- const auto hit = envelopeHit (e.position);
- envChanged = false;
- if (env.empty())
- env = ae::Envelope::flat (0.5); // a new envelope starts flat at its neutral value (unity / centre)
- if (hit >= 0 && (e.mods.isPopupMenu() || e.mods.isAltDown()))
- {
- env.points.erase (env.points.begin() + hit);
- if (env.points.empty())
- env = {};
- commit (tr ("Delete envelope point"));
- return true;
- }
- if (const auto h = envelopeHandleHit (e.position); h > 0 && hit < 0)
- {
- if (e.mods.isPopupMenu())
- {
- env.points[(std::size_t) h].tension = 0.0f;
- commit (tr ("Edit envelope"));
- return true;
- }
- envDragPoint = h;
- envBendStartY = e.position.y;
- envBendStartTension = env.points[(std::size_t) h].tension;
- drag = Drag::envBend;
- return true;
- }
- envDragPoint = hit >= 0 ? hit : env.insert (envPosition (e.x), envValue (e.position.y));
- envChanged = hit < 0;
- drag = Drag::envPoint;
- repaint();
- return true;
- }
- void envelopeMouseDrag (const juce::MouseEvent& e)
- {
- auto& env = currentEnvelope();
- if (! juce::isPositiveAndBelow (envDragPoint, (int) env.points.size()))
- return;
- auto& p = env.points[(std::size_t) envDragPoint];
- if (drag == Drag::envBend)
- {
- const auto rising = p.y >= env.points[(std::size_t) envDragPoint - 1].y;
- p.tension = juce::jlimit (-1.0f, 1.0f, envBendStartTension + (e.position.y - envBendStartY) / 120.0f * (rising ? 1.0f : -1.0f));
- }
- else
- {
- const auto lo = envDragPoint > 0 ? env.points[(std::size_t) envDragPoint - 1].x : 0.0;
- const auto hi = envDragPoint + 1 < (int) env.points.size() ? env.points[(std::size_t) envDragPoint + 1].x : 1.0;
- p.x = juce::jlimit (lo, hi, envPosition (e.x));
- p.y = envValue (e.position.y);
- const auto y = p.y;
- setStatus (envMode == EnvMode::volume ? tr ("Volume {0} dB", { juce::String (20.0 * std::log10 (juce::jmax (1.0e-6f, ae::envelopeGain (y))), 1) })
- : envMode == EnvMode::mix ? tr ("Clipboard {0}%", { juce::String (juce::roundToInt (y * 100.0)) })
- : envMode == EnvMode::scratch ? tr ("Play position {0} s", { juce::String (y * (double) doc.audio.frames() / doc.audio.sampleRate, 3) })
- : envMode == EnvMode::panning ? tr ("Panning {0}", { juce::String (juce::roundToInt ((y * 2.0 - 1.0) * 100.0)) })
- : tr ("Stereo separation {0}", { juce::String (juce::roundToInt ((y * 2.0 - 1.0) * 100.0)) }),
- false);
- }
- envChanged = true;
- repaint();
- }
- void paintEnvelopes (juce::Graphics& g)
- {
- struct Lane
- {
- const ae::Envelope* env;
- EnvMode mode;
- juce::Colour colour;
- };
- const Lane lanes[] = { { &doc.volumeEnvelope, EnvMode::volume, theme::colour::meterLow },
- { &doc.panEnvelope, EnvMode::panning, theme::colour::info },
- { &doc.separationEnvelope, EnvMode::separation, theme::colour::warning },
- { &doc.mixEnvelope, EnvMode::mix, theme::colour::accent },
- { &doc.scratchEnvelope, EnvMode::scratch, theme::colour::accent } };
- for (const auto& l : lanes)
- {
- const auto active = envMode == l.mode;
- if (l.env->empty() && ! active)
- continue;
- if (active)
- {
- // the neutral line (unity / centre)
- g.setColour (l.colour.withAlpha (0.25f));
- g.drawHorizontalLine ((int) envY (0.5), (float) waveArea.getX(), (float) waveArea.getRight());
- }
- if (l.env->empty())
- continue;
- juce::Path path;
- for (int x = waveArea.getX(); x <= waveArea.getRight(); x += 2)
- {
- const auto pt = juce::Point<float> ((float) x, envY (l.env->at (envPosition (x))));
- if (x == waveArea.getX())
- path.startNewSubPath (pt);
- else
- path.lineTo (pt);
- }
- g.setColour (l.colour.withAlpha (active ? 0.95f : 0.4f));
- g.strokePath (path, juce::PathStrokeType (active ? 1.8f : 1.2f));
- if (active)
- for (int i = 1; i < (int) l.env->points.size(); ++i)
- {
- const auto& a = l.env->points[(std::size_t) i - 1];
- const auto& b = l.env->points[(std::size_t) i];
- if (envX (b.x) - envX (a.x) < 14.0f)
- continue;
- const auto mx = 0.5 * (a.x + b.x);
- g.setColour (l.colour.withAlpha (0.8f));
- g.drawEllipse (envX (mx) - 3.0f, envY (l.env->at (mx)) - 3.0f, 6.0f, 6.0f, 1.2f);
- }
- if (active)
- for (const auto& p : l.env->points)
- {
- const auto c = juce::Point<float> (envX (p.x), envY (p.y));
- g.setColour (l.colour);
- g.fillEllipse (c.x - 3.5f, c.y - 3.5f, 7.0f, 7.0f);
- g.setColour (theme::colour::bg0);
- g.drawEllipse (c.x - 3.5f, c.y - 3.5f, 7.0f, 7.0f, 1.0f);
- }
- }
- }
- void openEdisonTool (audiotools::Tool t)
- {
- if (doc.audio.empty() || recState != RecState::idle)
- return;
- audiotools::showTool (*this, t);
- }
- void envelopeEdit (const juce::String& label, const std::function<void (ae::Envelope&)>& fn)
- {
- if (doc.audio.empty())
- return;
- if (envMode == EnvMode::wave)
- setEnvMode (EnvMode::volume);
- auto& env = currentEnvelope();
- if (env.empty())
- env = ae::Envelope::flat (0.5);
- fn (env);
- commit (label);
- }
- void acquireThreshold()
- {
- if (doc.audio.empty())
- return;
- if (selection.empty())
- {
- setStatus (tr ("Select a part with only the background noise first"), false);
- return;
- }
- noiseThreshold = ae::acquireNoiseThreshold (doc.audio, selection);
- setStatus (tr ("Noise threshold: {0} dB", { juce::String (juce::Decibels::gainToDecibels (noiseThreshold, -120.0f), 1) }), false);
- repaint();
- }
- float gateThreshold()
- {
- if (noiseThreshold >= 0.0f)
- return noiseThreshold * 1.12f; // a little over what was measured
- // not acquired: -48 dB under the peak
- return ae::peak (doc.audio, {}) * juce::Decibels::decibelsToGain (-48.0f);
- }
- void regionsTool (const juce::String& label, const std::function<int (ae::Document&)>& fn)
- {
- if (std::none_of (doc.markers.begin(), doc.markers.end(), [] (const ae::Marker& m) { return m.isRegion(); }))
- {
- setStatus (tr ("There are no regions (Regions > Auto-slice or Trim all noise & slice up make them)"), false);
- return;
- }
- stopPlayback();
- const auto n = fn (doc);
- commit (label);
- setStatus (tr ("{0} regions", { juce::String (n) }), false);
- }
- AudioEngine& engine;
- Source source;
- ae::Document doc;
- ae::History history;
- std::shared_ptr<wave::Summary> summary;
- int docVersion = 0;
- bool modified = false;
- juce::File lastFile;
- ae::WavFormat bits = ae::WavFormat::int24;
- ae::Range selection;
- std::int64_t cursor = 0, anchor = 0;
- double viewStart = 0.0, fpp = 1.0;
- Drag drag = Drag::none;
- int dragMarkerIndex = -1;
- bool spectrumView = false, logFrequency = true;
- int fftSize = 2048;
- juce::Image spectrumImage;
- juce::String spectrumKey;
- TimeFormat timeFormat = TimeFormat::automatic;
- bool snapZero = false;
- ae::Curve fadeCurve = ae::Curve::smooth;
- bool playing = false, loopPlay = false;
- ScriptRef lastScript; // Edit last script
- bool scriptBusy = false; // a script is running (its form may be open)
- bool scoreBusy = false; // Convert to score is analysing
- std::uint64_t previewTicket = 0;
- std::int64_t playFrom = 0, playhead = -1;
- double playStartedMs = 0.0;
- RecState recState = RecState::idle;
- bool openedInput = false; // startRecording opened the device input itself (released when it stops)
- RecordMode recordMode = RecordMode::now;
- int recordSource = AudioCapture::input;
- std::vector<float> recL, recR;
- ae::Document beforeRecording;
- std::int64_t recordAt = 0;
- double recordRate = 44100.0;
- bool recordStereo = true;
- int recordTicks = 0;
- juce::String status;
- bool statusIsError = false;
- std::unique_ptr<juce::FileChooser> chooser;
- juce::Rectangle<int> rulerArea, waveArea, levelArea, overviewArea, infoArea;
- IconButton menuButton { "menu", Icon::panelMenu }, undoButton { "undo", Icon::undo }, redoButton { "redo", Icon::redo },
- historyButton { "history", Icon::chevronDown }, recordButton { "record", Icon::record }, recordMenuButton { "recordMenu", Icon::chevronDown },
- playButton { "play", Icon::play }, stopButton { "stop", Icon::stop }, snapButton { "snap", Icon::magnet }, fitButton { "fit", Icon::zoom },
- saveButton { "save", Icon::save }, followButton { "follow", Icon::follow };
- juce::TextButton loopButton, viewButton, sendButton, envButton;
- // warp markers (round 175a, M3): a lane above the waveform with the channel's markers, for a channel source
- juce::TextButton warpButton, autoWarpButton;
- bool warpMode = false;
- juce::Rectangle<int> warpLane;
- int warpDrag = -1, warpSelected = -1; // marker index (in the channel's markers)
- double warpDragSeconds = 0.0; // where the dragged marker goes (applied on release)
- std::vector<double> warpAttacks; // the file's attacks (seconds): the transient ticks, and where drags snap
- const void* warpAttacksOf = nullptr; // the audio they were found in
- juce::Slider volumeKnob { juce::Slider::RotaryHorizontalVerticalDrag, juce::Slider::NoTextBox };
- juce::OwnedArray<juce::TextButton> quickButtons;
- void refreshVolumeKnob()
- {
- volumeKnob.setValue (engine.getEditorVolume(), juce::dontSendNotification);
- const auto text = tr ("Playback volume: {0} (the audio is not changed; Tools > Amp... changes it)", { ui::utilityVolumeText (engine.getEditorVolume()) });
- volumeKnob.setTooltip (text);
- ui::setHint (volumeKnob, text + " " + tr ("[LMB] drag [Wheel] step [2xLMB] 100% [RMB] type a value"), true);
- }
- };
- juce::PopupMenu AudioEditor::editMenu (bool contextual)
- {
- juce::PopupMenu menu;
- const auto has = ! doc.audio.empty();
- const auto sel = ! selection.empty();
- const auto clip = ! clipboard().empty();
- if (! contextual)
- {
- menu.addItem (tr ("Undo") + "\tCtrl+Z", history.canUndo(), false, [this] { undo(); });
- menu.addItem (tr ("Redo") + "\tCtrl+Y", history.canRedo(), false, [this] { redo(); });
- menu.addSubMenu (tr ("Undo history"), historyMenu());
- menu.addSeparator();
- }
- menu.addItem (tr ("Cut") + "\tCtrl+X", sel, false, [this] { cutSelection(); });
- menu.addItem (tr ("Copy") + "\tCtrl+C", sel, false, [this] { copySelection(); });
- menu.addItem (tr ("Paste insert") + "\tCtrl+V", clip && selection.empty(), false, [this] { paste (false); });
- menu.addItem (tr ("Paste replace"), clip && sel, false, [this] { paste (false); });
- menu.addItem (tr ("Paste mix"), clip && has, false, [this] { paste (true); });
- menu.addItem (envMode == EnvMode::mix ? tr ("Paste mix (envelope): apply") : tr ("Paste mix (envelope)"), clip && has, false, [this] { pasteMixWithEnvelope(); });
- menu.addItem (tr ("Paste mix (spectral)..."), clip && has, false, [this] {
- if (selection.empty())
- selection = { cursor, juce::jmin (doc.audio.frames(), cursor + ae::conform (clipboard(), doc.audio.numChannels(), doc.audio.sampleRate).frames()) };
- openEdisonTool (audiotools::Tool::pasteSpectral);
- });
- // Edison's "Paste stretch" / "Paste replace (drum)" (round 165l): the clipboard brought to the selection's length
- menu.addItem (tr ("Paste stretch"), clip && sel, false, [this] { pasteFitted (false); });
- menu.addItem (tr ("Paste replace (drum)"), clip && sel, false, [this] { pasteFitted (true); });
- menu.addSeparator();
- menu.addItem (tr ("Delete") + "\tDel", sel, false, [this] { deleteSelection(); });
- menu.addItem (tr ("Clear (silence)"), sel, false, [this] { edit (tr ("Silence"), [] (ae::Document& d, ae::Range r) { ae::clear (d, r); }, true); });
- menu.addItem (tr ("Trim (keep the selection)"), sel, false, [this] { trimSelection(); });
- // (right-click on the selection: issue #12)
- menu.addItem (tr ("Send the selection to a new Sampler channel"), sel, false, [this] { sendRangeToNewSampler (selection); });
- menu.addItem (tr ("Insert silence..."), has, false, [this] { showInsertSilence(); });
- menu.addItem (tr ("Delete the part after the loop"), has && doc.hasLoop(), false,
- [this] { edit (tr ("Delete after loop"), [] (ae::Document& d, ae::Range) { ae::deleteAfterLoop (d); }); });
- menu.addSeparator();
- menu.addItem (tr ("Select all") + "\tCtrl+A", has, false, [this] {
- selection = { 0, doc.audio.frames() };
- repaint();
- });
- menu.addItem (tr ("Deselect") + "\tEsc", sel, false, [this] {
- selection = {};
- repaint();
- });
- if (contextual)
- {
- menu.addSeparator();
- menu.addItem (tr ("Add marker") + "\tM", has, false, [this] { addMarkerAtCursor(); });
- menu.addItem (tr ("Add region"), sel, false, [this] { addRegionFromSelection(); });
- menu.addItem (tr ("Set loop"), sel, false, [this] { setLoopFromSelection(); });
- menu.addItem (tr ("Zoom on the selection"), sel, false, [this] { zoomTo (selection); });
- }
- return menu;
- }
- juce::PopupMenu AudioEditor::mainMenu()
- {
- const auto has = ! doc.audio.empty();
- juce::PopupMenu file;
- file.addItem (tr ("New (empty)"), [this] {
- stopPlayback();
- source = {};
- setDocument ({}, tr ("Empty"));
- });
- file.addItem (tr ("Open audio file..."), [this] { openFileDialog(); });
- juce::PopupMenu save;
- save.addItem (tr ("16-bit"), has, bits == ae::WavFormat::int16, [this] { saveAs (ae::WavFormat::int16); });
- save.addItem (tr ("24-bit"), has, bits == ae::WavFormat::int24, [this] { saveAs (ae::WavFormat::int24); });
- save.addItem (tr ("32-bit float"), has, bits == ae::WavFormat::float32, [this] { saveAs (ae::WavFormat::float32); });
- file.addSubMenu (tr ("Save as WAV"), save, has);
- file.addItem (tr ("Export regions as files..."), has && ! doc.markers.empty(), false, [this] { exportRegions(); });
- file.addSeparator();
- file.addItem (tr ("Send to the Playlist as an audio clip"), has, false, [this] { sendToPlaylist(); });
- file.addItem (tr ("Send to a new Sampler channel"), has, false, [this] { sendToNewSampler(); });
- juce::PopupMenu tools;
- using T = audiotools::Tool;
- const auto envOn = has && envMode != EnvMode::wave;
- const auto envAny = has && ae::hasEnvelopes (doc);
- tools.addSectionHeader (tr ("Envelope"));
- tools.addSubMenu (tr ("Edit"), envModeMenu(), has);
- tools.addItem (tr ("Cancel all envelopes"), envAny, false, [this] {
- doc.volumeEnvelope = doc.panEnvelope = doc.separationEnvelope = doc.mixEnvelope = doc.scratchEnvelope = {};
- if (envMode == EnvMode::mix || envMode == EnvMode::scratch)
- setEnvMode (EnvMode::wave);
- commit (tr ("Cancel all envelopes"));
- });
- tools.addItem (tr ("Add points at selection"), has && ! selection.empty(), false, [this] {
- const auto n = (double) juce::jmax<std::int64_t> (1, doc.audio.frames() - 1);
- const std::vector<double> xs { (double) selection.start / n, (double) selection.end / n };
- envelopeEdit (tr ("Add points at selection"), [xs] (ae::Envelope& e) { ae::addPointsAt (e, xs); });
- });
- tools.addItem (tr ("Add points at regions"), has && ! doc.markers.empty(), false, [this] {
- const auto n = (double) juce::jmax<std::int64_t> (1, doc.audio.frames() - 1);
- std::vector<double> xs;
- for (const auto& m : doc.markers)
- {
- xs.push_back ((double) m.start / n);
- if (m.isRegion())
- xs.push_back ((double) m.end / n);
- }
- envelopeEdit (tr ("Add points at regions"), [xs] (ae::Envelope& e) { ae::addPointsAt (e, xs); });
- });
- tools.addItem (tr ("Flip vertically"), envOn, false, [this] { envelopeEdit (tr ("Flip vertically"), [] (ae::Envelope& e) { ae::flipLevels (e); }); });
- tools.addItem (tr ("Scale levels..."), has, false, [this] { openEdisonTool (T::scaleLevels); });
- tools.addItem (tr ("Normalize levels"), envOn, false, [this] { envelopeEdit (tr ("Normalize levels"), [] (ae::Envelope& e) { ae::normalizeLevels (e); }); });
- tools.addItem (tr ("Decimate points..."), has, false, [this] { openEdisonTool (T::decimate); });
- tools.addItem (tr ("Filter..."), has, false, [this] { openEdisonTool (T::envFilter); });
- tools.addItem (tr ("Smooth up..."), has, false, [this] { openEdisonTool (T::smoothUp); });
- tools.addItem (tr ("Turn all points smooth"), envOn, false, [this] { envelopeEdit (tr ("Turn all points smooth"), [] (ae::Envelope& e) { ae::makePointsSmooth (e); }); });
- tools.addItem (tr ("Create sequence..."), has, false, [this] { openEdisonTool (T::createSequence); });
- tools.addSectionHeader (tr ("Amp"));
- tools.addItem (tr ("Mixdown amp envelopes"), envAny, false, [this] {
- stopPlayback();
- ae::mixdownEnvelopes (doc);
- setEnvMode (EnvMode::wave);
- commit (tr ("Mixdown amp envelopes"));
- });
- tools.addItem (tr ("Amp..."), has, false, [this] { showAmp(); });
- tools.addItem (tr ("Reverse polarity"), has, false, [this] { edit (tr ("Reverse polarity"), [] (ae::Document& d, ae::Range r) { ae::invert (d, r); }); });
- tools.addItem (tr ("Normalize"), has, false, [this] { edit (tr ("Normalize"), [] (ae::Document& d, ae::Range r) { ae::normalize (d, r); }); });
- tools.addItem (tr ("Normalize to..."), has, false, [this] { showNormalizeTo(); });
- tools.addItem (tr ("Lossy normalize"), has, false, [this] { edit (tr ("Lossy normalize"), [] (ae::Document& d, ae::Range r) { ae::lossyNormalize (d, r); }); });
- tools.addItem (tr ("Fade in"), has, false, [this] { fade (true); });
- tools.addItem (tr ("Fade out"), has, false, [this] { fade (false); });
- tools.addSubMenu (tr ("Fade curve"), curveMenu());
- tools.addItem (tr ("Declick in"), has, false, [this] { edit (tr ("Declick in"), [] (ae::Document& d, ae::Range r) { ae::declickIn (d, r); }); });
- tools.addItem (tr ("Declick out"), has, false, [this] { edit (tr ("Declick out"), [] (ae::Document& d, ae::Range r) { ae::declickOut (d, r); }); });
- tools.addSectionHeader (tr ("Waveform"));
- 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); }); });
- tools.addSectionHeader (tr ("Time"));
- tools.addItem (tr ("Reverse"), has, false, [this] { edit (tr ("Reverse"), [] (ae::Document& d, ae::Range r) { ae::reverse (d, r); }); });
- tools.addItem (tr ("Time stretch / pitch shift..."), has, false, [this] { openEdisonTool (T::stretch); });
- tools.addItem (tr ("Drum(loop) stretch..."), has, false, [this] { openEdisonTool (T::drumStretch); });
- tools.addItem (tr ("Claw machine..."), has, false, [this] { openEdisonTool (T::claw); });
- tools.addItem (envMode == EnvMode::scratch ? tr ("Scratch (envelope): apply") : tr ("Scratch (envelope)"), has, false, [this] { scratchWithEnvelope(); });
- tools.addItem (tr ("Resample..."), has, false, [this] { showResample(); });
- tools.addSectionHeader (tr ("Channels"));
- const auto stereo = doc.audio.numChannels() > 1;
- tools.addItem (tr ("Swap channels"), has && stereo, false, [this] { edit (tr ("Swap channels"), [] (ae::Document& d, ae::Range) { ae::swapChannels (d); }); });
- 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); }); });
- 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); }); });
- 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); }); });
- tools.addItem (tr ("Convert a mono signal to mono format"), has && stereo, false, [this] {
- stopPlayback();
- if (ae::monoIfMono (doc))
- commit (tr ("Convert to mono"));
- else
- setStatus (tr ("The left and right channels differ: the audio is really stereo"), false);
- });
- tools.addItem (tr ("Convert to stereo"), has && ! stereo, false, [this] { edit (tr ("Convert to stereo"), [] (ae::Document& d, ae::Range) { ae::toStereo (d); }); });
- tools.addSectionHeader (tr ("Synthesis"));
- tools.addItem (tr ("Generate noise"), true, false, [this] {
- stopPlayback();
- if (doc.audio.channels.empty())
- {
- doc.audio = ae::silence (2, 44100.0, 0);
- history.reset (doc, tr ("Empty").toStdString());
- }
- const auto at = selection.empty() ? cursor : selection.start;
- const auto length = selection.empty() ? (std::int64_t) doc.audio.sampleRate : selection.length();
- ae::generateNoise (doc, selection, 1.0f, (std::uint32_t) juce::Random::getSystemRandom().nextInt(), length);
- selection = { at, at + length };
- commit (tr ("Generate noise"));
- if (history.size() <= 2)
- zoomToFit();
- });
- tools.addSectionHeader (tr ("Scripting"));
- tools.addSubMenu (tr ("Run script"), scriptMenu(), ! scriptBusy);
- tools.addItem (lastScript.key.isEmpty() ? tr ("Edit last script") : tr ("Edit last script: {0}", { lastScript.name }), ! lastScript.key.isEmpty(), false,
- [this] { editLastScript(); });
- tools.addSectionHeader (tr ("Noise gating"));
- tools.addItem (tr ("Acquire noise threshold"), has && ! selection.empty(), false, [this] { acquireThreshold(); });
- tools.addItem (tr ("Gate noise"), has, false, [this] {
- const auto t = gateThreshold();
- edit (tr ("Gate noise"), [t] (ae::Document& d, ae::Range r) { ae::gateNoise (d, r, t); });
- });
- tools.addItem (tr ("Trim side noise"), has, false, [this] {
- const auto t = gateThreshold();
- edit (tr ("Trim side noise"), [t] (ae::Document& d, ae::Range r) { ae::trimSideNoise (d, r, t); });
- });
- tools.addItem (tr ("Trim all noise && slice up"), has, false, [this] {
- const auto t = gateThreshold();
- int n = 0;
- edit (tr ("Trim all noise & slice up"), [t, &n] (ae::Document& d, ae::Range r) { n = ae::trimNoiseAndSlice (d, r, t); });
- setStatus (tr ("{0} regions", { juce::String (n) }), false);
- });
- tools.addSectionHeader (tr ("Spectral"));
- tools.addItem (tr ("Convolution reverb..."), has, false, [this] { openEdisonTool (T::reverb); });
- tools.addItem (tr ("Blur..."), has, false, [this] { openEdisonTool (T::blur); });
- tools.addItem (tr ("Equalize..."), has, false, [this] { openEdisonTool (T::equalize); });
- tools.addItem (tr ("Acquire noise profile"), has && ! selection.empty(), false, [this] {
- noiseProfile = ae::acquireNoiseProfile (doc.audio, selection);
- setStatus (tr ("Noise profile acquired from the selection: Clean up (denoise) uses it"), false);
- });
- tools.addItem (tr ("Clean up (denoise)..."), has, false, [this] { openEdisonTool (T::denoise); });
- tools.addItem (tr ("Match spectrum..."), has, false, [this] { openEdisonTool (T::matchSpectrum); });
- tools.addItem (tr ("Vocal denoise/isolator..."), has, false, [this] { openEdisonTool (T::vocalDenoise); });
- tools.addItem (tr ("Deverb..."), has, false, [this] { openEdisonTool (T::deverb); });
- tools.addSectionHeader (tr ("Regions"));
- tools.addItem (tr ("Normalize all regions"), has, false, [this] { regionsTool (tr ("Normalize all regions"), [] (ae::Document& d) { return ae::normalizeRegions (d); }); });
- 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); }); });
- tools.addItem (tr ("Declick out all regions"), has, false, [this] { regionsTool (tr ("Declick out all regions"), [] (ae::Document& d) { return ae::declickRegions (d, false, true); }); });
- tools.addItem (tr ("Perfect all regions"), has, false, [this] { regionsTool (tr ("Perfect all regions"), [] (ae::Document& d) { return ae::perfectRegions (d); }); });
- tools.addItem (tr ("Tune loop..."), has, false, [this] { openEdisonTool (T::loopTuner); });
- tools.addSectionHeader (tr ("Analysis"));
- tools.addItem (tr ("Convert to score and dump to piano roll"), has && ! scoreBusy, false, [this] { convertToScore(); });
- juce::PopupMenu regions;
- regions.addItem (tr ("Add marker") + "\tM", has, false, [this] { addMarkerAtCursor(); });
- regions.addItem (tr ("Add region"), has && ! selection.empty(), false, [this] { addRegionFromSelection(); });
- regions.addItem (tr ("Set loop"), has && ! selection.empty(), false, [this] { setLoopFromSelection(); });
- regions.addItem (tr ("Remove loop"), doc.hasLoop(), false, [this] {
- ae::setLoop (doc, {});
- commit (tr ("Remove loop"));
- });
- regions.addItem (tr ("Delete markers in the selection"), has && ! doc.markers.empty(), false, [this] {
- if (ae::removeMarkers (doc, ae::orAll (doc, selection)) > 0)
- commit (tr ("Delete markers"));
- });
- regions.addSeparator();
- juce::PopupMenu slice;
- slice.addItem (tr ("Dull auto-slicing"), has, false, [this] { autoSlice (0.2f); });
- slice.addItem (tr ("Medium auto-slicing"), has, false, [this] { autoSlice (0.5f); });
- slice.addItem (tr ("Sharp auto-slicing"), has, false, [this] { autoSlice (0.85f); });
- slice.addSeparator();
- slice.addItem (tr ("Every beat (project tempo)"), has, false, [this] { gridSlice (1.0); });
- slice.addItem (tr ("Every 1/2 beat"), has, false, [this] { gridSlice (0.5); });
- slice.addItem (tr ("Every 1/4 beat"), has, false, [this] { gridSlice (0.25); });
- regions.addSubMenu (tr ("Auto-slice"), slice, has);
- juce::PopupMenu view;
- view.addItem (tr ("Waveform"), true, ! spectrumView, [this] { viewButton.setToggleState (false, juce::sendNotification); });
- view.addItem (tr ("Spectrogram") + "\tS", true, spectrumView, [this] { viewButton.setToggleState (true, juce::sendNotification); });
- juce::PopupMenu precision;
- for (int size : { 512, 1024, 2048, 4096, 8192 })
- precision.addItem (tr ("{0} bands", { juce::String (size / 2) }), true, fftSize == size, [this, size] {
- fftSize = size;
- repaint();
- });
- view.addSubMenu (tr ("Spectrum precision"), precision);
- view.addItem (tr ("Logarithmic frequency scale"), true, logFrequency, [this] {
- logFrequency = ! logFrequency;
- repaint();
- });
- juce::PopupMenu time;
- const std::pair<TimeFormat, const char*> formats[] = { { TimeFormat::automatic, TR_NOOP ("Auto") },
- { TimeFormat::seconds, TR_NOOP ("Minutes : seconds") },
- { TimeFormat::samples, TR_NOOP ("Samples") },
- { TimeFormat::bars, TR_NOOP ("Bar : beat : tick") } };
- for (const auto& [f, name] : formats)
- time.addItem (tr (name), true, timeFormat == f, [this, f = f] {
- timeFormat = f;
- repaint();
- });
- view.addSubMenu (tr ("Time format"), time);
- view.addSeparator();
- view.addItem (tr ("Zoom in") + "\t+", has, false, [this] { zoomAround ((float) waveArea.getCentreX(), 0.5); });
- view.addItem (tr ("Zoom out") + "\t-", has, false, [this] { zoomAround ((float) waveArea.getCentreX(), 2.0); });
- view.addItem (tr ("Zoom out full") + "\tF", has, false, [this] { zoomToFit(); });
- view.addItem (tr ("Zoom on the selection"), has && ! selection.empty(), false, [this] { zoomTo (selection); });
- view.addItem (tr ("Snap to zero crossings"), true, snapZero, [this] { snapButton.setToggleState (! snapZero, juce::sendNotification); });
- juce::PopupMenu menu;
- menu.addSubMenu (tr ("File"), file);
- menu.addSubMenu (tr ("Edit"), editMenu (false));
- menu.addSubMenu (tr ("Tools"), tools, has);
- menu.addSubMenu (tr ("Regions"), regions, has);
- menu.addSubMenu (tr ("View"), view);
- menu.addSubMenu (tr ("Record"), recordMenu());
- if (source.kind == Source::Kind::channel)
- {
- juce::PopupMenu warp;
- warp.addItem (tr ("Show warp markers"), has, warpMode, [this] { setWarpMode (! warpMode); });
- warp.addItem (tr ("Auto-warp"), has, false, [this] { autoWarp(); });
- warp.addItem (tr ("Remove the selected warp marker"), warpMode && warpSelected > 0, false, [this] { removeWarpMarker (warpSelected); });
- warp.addItem (tr ("Remove all warp markers"), has && warpMarkers().size() > 2, false, [this] {
- editWarp ([] (SamplerSettings& s, double) { warpedit::clearMarkers (s); });
- });
- menu.addSubMenu (tr ("Warp markers"), warp);
- }
- return menu;
- }
- juce::String windowKey (const Source& s)
- {
- switch (s.kind)
- {
- case Source::Kind::file: return "audioeditor:" + s.path;
- case Source::Kind::channel: return "audioeditor:channel:" + juce::String (s.index);
- case Source::Kind::insert: return "audioeditor:insert:" + juce::String (s.index);
- case Source::Kind::none: break;
- }
- return "audioeditor";
- }
- AudioEditor* openWindow (AudioEngine& engine, Source source)
- {
- auto editor = std::make_unique<AudioEditor> (engine, source);
- auto* raw = editor.get();
- if (auto* window = openToolWindow (std::move (editor), tr ("Audio editor"), windowKey (source)))
- {
- window->setResizable (true, false);
- window->setResizeLimits (720, 380, 4000, 3000);
- }
- return raw;
- }
- } // namespace
- void openAudioEditor (AudioEngine& engine)
- {
- openWindow (engine, {});
- }
- void openAudioEditor (AudioEngine& engine, const juce::File& file)
- {
- Source s { Source::Kind::file, -1, file.getFullPathName() };
- openWindow (engine, s)->loadFile (file);
- }
- void openAudioEditorForChannel (AudioEngine& engine, int channel, int clip)
- {
- const auto& song = engine.getSong();
- if (! juce::isPositiveAndBelow (channel, (int) song.channels.size()))
- return;
- const auto& c = song.channels[(std::size_t) channel];
- const auto path = juce::String::fromUTF8 (c.samplePath.c_str());
- auto* editor = openWindow (engine, { Source::Kind::channel, channel, path, clip });
- if (path.isNotEmpty())
- editor->loadFile (juce::File (path));
- }
- std::unique_ptr<juce::Component> makeAudioEditorPanel (AudioEngine& engine, int channel, int clip, bool showWarp)
- {
- const auto& song = engine.getSong();
- if (! juce::isPositiveAndBelow (channel, (int) song.channels.size()))
- return {};
- const auto path = juce::String::fromUTF8 (song.channels[(std::size_t) channel].samplePath.c_str());
- auto editor = std::make_unique<AudioEditor> (engine, Source { Source::Kind::channel, channel, path, clip });
- if (path.isNotEmpty())
- editor->loadFile (juce::File (path));
- if (showWarp)
- editor->setWarpModeForPanel (true);
- return editor;
- }
- void openAudioEditorRecording (AudioEngine& engine)
- {
- openWindow (engine, {})->recordInputWithSong();
- }
- void openAudioEditorForInsert (AudioEngine& engine, int insert)
- {
- auto* editor = openWindow (engine, { Source::Kind::insert, insert, {} });
- editor->setRecordSource (insert);
- }
- std::unique_ptr<juce::Component> makeAudioEditorForSnapshot (AudioEngine& engine, audioedit::Document doc, bool spectrum)
- {
- auto editor = std::make_unique<AudioEditor> (engine, Source {});
- const auto frames = doc.audio.frames();
- editor->setDocument (std::move (doc), tr ("Open"));
- editor->selectForSnapshot ({ frames / 4, frames / 2 }, spectrum);
- return editor;
- }
- std::unique_ptr<juce::Component> makeAudioToolPanelForSnapshot (juce::Component& editor, int tool, int envelopeMode)
- {
- auto* e = dynamic_cast<AudioEditor*> (&editor);
- if (e == nullptr || tool < 0 || tool > (int) audiotools::Tool::deverb)
- return {};
- e->setEnvModeForSnapshot (envelopeMode);
- return audiotools::makeToolPanel (*e, (audiotools::Tool) tool);
- }
- const char* audioToolNameForSnapshot (int tool)
- {
- if (tool < 0 || tool > (int) audiotools::Tool::deverb)
- return nullptr;
- return audiotools::toolTitle ((audiotools::Tool) tool);
- }
- void setAudioEditorEnvelopeModeForSnapshot (juce::Component& editor, int mode)
- {
- if (auto* e = dynamic_cast<AudioEditor*> (&editor))
- e->setEnvModeForSnapshot (mode);
- }
- juce::StringArray audioEditorMenuForSnapshot (juce::Component& component)
- {
- juce::StringArray lines;
- auto* editor = dynamic_cast<AudioEditor*> (&component);
- if (editor == nullptr)
- return lines;
- std::function<void (const juce::PopupMenu&, const juce::String&)> walk = [&] (const juce::PopupMenu& menu, const juce::String& prefix) {
- for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
- {
- const auto& item = it.getItem();
- if (item.isSeparator || item.text.isEmpty())
- continue;
- const auto text = prefix + item.text.upToFirstOccurrenceOf ("\t", false, false);
- if (item.subMenu != nullptr)
- walk (*item.subMenu, text + " > ");
- else if (! item.isSectionHeader)
- lines.add (text + (item.isEnabled ? "" : " (disabled)"));
- }
- };
- walk (editor->mainMenu(), {});
- return lines;
- }
- } // namespace lynx
|