| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527 |
- #include <juce_gui_basics/juce_gui_basics.h>
- #include "engine/FileSort.h"
- #include "platform/Paths.h"
- #include "core/PlaylistOps.h"
- #include "core/Comping.h"
- #include "core/Drumaxx.h"
- #include "core/PatternBlocks.h"
- #include "core/LoadTrace.h"
- #include "core/ProjectSafety.h"
- #include "core/Patcher.h"
- #include "core/Patcherize.h"
- #include "core/Performance.h"
- #include "core/VideoPlayer.h"
- #include "core/Effects.h"
- #include "core/MixSuite.h"
- #include "core/HardwareInsert.h"
- #include "core/EchoSuite.h"
- #include "core/LynxTune.h"
- #include "core/FlEffects.h"
- #include "core/FlpImport.h"
- #include "core/NoteEdit.h"
- #include "core/MaximusFx.h"
- #include "core/Harmor.h"
- #include "flp/Flp.h"
- #include "core/SynthPresets.h"
- #include "core/FlWrapper.h"
- #include "engine/AudioEngine.h"
- #include "engine/Metronome.h"
- #include "engine/AudioLogger.h"
- #include "engine/DllAsioDevice.h"
- #include "engine/PipeWireDevice.h"
- #include "platform/LinuxRealtime.h"
- #include "engine/Exporter.h"
- #include "engine/FlStudioExport.h"
- #include "engine/MidiFileIo.h"
- #include "engine/PluginHost.h"
- #include "engine/PluginSandbox.h"
- #include "engine/Bridge32Test.h"
- #include "engine/ProjectFile.h"
- #include "core/Sha256.h"
- #include "engine/SessionPack.h"
- #include "engine/LiveTest.h"
- #include "core/SessionIds.h"
- #include "core/SessionParts.h"
- #include "engine/SampleLibrary.h"
- #include "engine/Text.h"
- #include "platform/FileTypes.h"
- #include "platform/Package.h"
- #include "core/AlsImport.h"
- #include "ui/AlsExportDialog.h"
- #include "ui/GamepadInput.h"
- #include "ui/SettingsPages.h"
- #include "ui/OtherAppsExport.h"
- #include "ui/TimerWhileShowing.h"
- #include "ui/MixerBasicsCheck.h"
- #include "ui/VideoPlayerView.h"
- #include "ui/VideoMedia.h"
- #include "ui/VideoTracks.h"
- #include "ui/AdrWindow.h"
- #include "ui/PlaylistComponent.h"
- #include "ui/PatcherEditor.h"
- #include "ui/VisualEditors.h"
- #include "ui/FlExtraEditors.h"
- #include "ui/VisualGl.h"
- #include "ui/DanceView.h"
- #include "ui/PluginPresetMenu.h"
- #include "ui/PluginWindow.h"
- #include "ui/NativeChild.h"
- #include "ui/Workspace.h"
- #include "ui/PluginThumbs.h"
- #include "ui/ClipProperties.h"
- #include "ui/NewProjectDialog.h"
- #include "ui/PluginMonitorWindow.h"
- #include "ui/TouchKeyboard.h"
- #include "ui/AutomationUi.h"
- #include "ui/PluginSkin.h"
- #include "ui/ChannelSettings.h"
- #include "core/LynxBanks.h"
- #include "core/NativeEngines.h"
- #include "ui/ControllerEditors.h"
- #include "ui/NewtoneEditor.h"
- #include "core/NewtoneFx.h"
- #include "core/FormulaController.h"
- #include "core/MidiControls.h"
- #include "core/FlSynths.h"
- #include "core/SoundFont.h"
- #include "core/Sfz.h"
- #include "ui/Dialogs.h"
- #include "ui/FileChoosers.h"
- #include "ui/TrackIcons.h"
- #include "core/RackOps.h"
- #include "core/Layer.h"
- #include "core/XyController.h"
- #include "core/FlCurve.h"
- #include "core/ControlSurface.h"
- #include "core/VoltageController.h"
- #include "ui/Controllers164.h"
- #include "ui/ExportDialog.h"
- #include "ui/QuickAddPalette.h"
- #include "ui/I18n.h"
- #include "ui/MainComponent.h"
- #include "ui/MidiToolsPanel.h"
- #include "ui/FrameProbe.h"
- #include "ui/UiTrace.h"
- #include "core/MixerOps.h"
- #include "ui/QuickPick.h"
- #include "core/NoteTools.h"
- #include "engine/ProjectPackage.h"
- #include "ui/SetupWizard.h"
- #include "engine/FlStudio.h"
- #include "ui/HistoryPanel.h"
- #include "ui/MissingFilesDialog.h"
- #include "ui/SettingsDialog.h"
- #include "ui/PluginManager.h"
- #include "ui/ShortcutManager.h"
- #include "ui/NoteToolDialogs.h"
- #include "ui/EventEditor.h"
- #include "ui/AudioEditor.h"
- #include "ui/TempoTapper.h"
- #include "core/EventEdit.h"
- #include "core/FacetEq.h"
- #include "ui/FacetEqEditor.h"
- #include "core/RackRenderer.h"
- #include "ui/ProEditors.h"
- #include "ui/ParametricEqEditor.h"
- #include "ui/PluginEditors.h"
- #include "core/PluginLayout.h"
- #include "core/EffectPresets.h"
- #include "core/Vfx.h"
- #include "ui/Splash.h"
- #include "ui/Theme.h"
- #include "ui/ThemeSettings.h"
- #include "ui/WaveformView.h"
- #include "ui/WindowOwner.h"
- #include "ui/PluginKeysTest.h"
- #include "ui/Toolbar.h"
- #include "ui/ToolWindow.h"
- #include "platform/CrashGuard.h"
- #include "ui/CrashReporter.h"
- #include "ui/Updater.h"
- #include "ui/StemExtract.h"
- #include "ui/AudioToMidi.h"
- #include <atomic>
- #include <chrono>
- #include <cstdio>
- #include <cstdlib>
- #include <mutex>
- #include <thread>
- namespace
- {
- lynx::AudioEngine* crashEngine = nullptr;
- // Startup trace (REA round 116): with LYNX_TRACE_STARTUP set, the time of each startup step since the C++ runtime
- // started is written to %APPDATA%\LYNX\startup.log (the loader's own time before that is not included).
- struct StartupTrace
- {
- using clock = std::chrono::steady_clock;
- const clock::time_point t0 = clock::now(); // static initialisation: no JUCE yet, standard library only
- const bool on = std::getenv ("LYNX_TRACE_STARTUP") != nullptr;
- juce::String text;
- clock::time_point last = t0;
- double seconds() const { return std::chrono::duration<double> (clock::now() - t0).count(); } // since the process started
- void mark (const char* step)
- {
- if (! on)
- return;
- const auto now = clock::now();
- const auto ms = [] (clock::duration d) { return std::chrono::duration<double, std::milli> (d).count(); };
- text << juce::String (ms (now - t0), 1).paddedLeft (' ', 8) << " ms +" << juce::String (ms (now - last), 1).paddedLeft (' ', 7) << " " << step << "\n";
- last = now;
- lynx::platform::settingsFile ("startup.log").replaceWithText (text);
- }
- };
- StartupTrace startupTrace;
- void startupMarkHook (const char* step) { startupTrace.mark (step); }
- // Crashed: try to save the project and write the backtrace (like FL's "emergency save").
- void onCrash (void* exceptionPointers)
- {
- const auto folder = lynx::platform::settingsFile ("autosave");
- folder.createDirectory();
- const auto stamp = juce::Time::getCurrentTime().formatted ("%Y-%m-%d %H-%M-%S");
- // JUCE's backtrace (named frames only), then every frame of the faulting thread as module+offset (round 157a: a
- // release LYNX.exe has no symbols, so its own frames were missing from the file)
- folder.getChildFile ("crash " + stamp + ".txt").replaceWithText (juce::SystemStats::getStackBacktrace() + "\n--- frames (module+offset)\n"
- + juce::String::fromUTF8 (lynx::crashguard::exceptionBacktrace (exceptionPointers).c_str()));
- lynx::crashguard::note (("crashed: backtrace in autosave\\crash " + stamp + ".txt").toStdString());
- if (crashEngine != nullptr)
- {
- juce::String error;
- lynx::ProjectFile::save (crashEngine->getSong(), folder.getChildFile ("recovered " + stamp + lynx::ProjectFile::extension), error);
- }
- }
- juce::File sessionsFolder()
- {
- return lynx::PluginHost::settingsFolder().getChildFile ("sessions");
- }
- // Sessions of earlier runs whose process is gone without closing (a fail-fast, a crash, a forced end): each is appended
- // to %APPDATA%\LYNX\crash-history.log and its file removed. Returns the last step of the newest one ("" when none).
- juce::StringArray uncleanSteps; // the newest unclean session's steps (without their times)
- juce::String uncleanSessionText; // the newest unclean session's whole file (round 159: the crash report reads it)
- // What the newest unclean session tells (round 157a): the plugin whose editor was opening / shown when it ended, and
- // whether its crash file blames a graphics driver
- struct UncleanCause
- {
- juce::String editorPlugin; // the last steps were that plugin's editor
- bool gpuDriver = false; // the crash file's top frames are in a GPU driver / Direct3D / Direct2D module
- juce::String driverModule;
- };
- UncleanCause uncleanCause()
- {
- UncleanCause cause;
- juce::File crashFile;
- for (int i = uncleanSteps.size(); --i >= 0 && i >= uncleanSteps.size() - 4;)
- {
- const auto& step = uncleanSteps[i];
- if (step.startsWith ("crashed: backtrace in "))
- crashFile = lynx::platform::settingsFolder().getChildFile (step.fromFirstOccurrenceOf ("backtrace in ", false, false).replaceCharacter ('\\', '/'));
- for (const auto* prefix : { "opening the editor of ", "editor open: ", "editor shown: " })
- if (cause.editorPlugin.isEmpty() && step.startsWith (prefix))
- cause.editorPlugin = step.fromFirstOccurrenceOf (prefix, false, false).trim();
- if (step.startsWith ("closing the editor of ") || step.startsWith ("loaded plugin") || step.startsWith ("opening project"))
- break; // older steps than these did not end the session
- }
- // issue #32 (round 174a): a plugin whose editor already faulted in this session (caught, LYNX went on) is the
- // likely cause when the session then ended without a word: offer it a separate process too
- for (int i = uncleanSteps.size(); --i >= 0 && cause.editorPlugin.isEmpty();)
- if (const auto editor = lynx::crashreport::parseEditorCrashStep (uncleanSteps[i].toStdString()); ! editor.plugin.empty())
- cause.editorPlugin = juce::String::fromUTF8 (editor.plugin.c_str());
- if (crashFile.existsAsFile())
- {
- // the first frames after the crash handler's own (the "--- frames" part lists the faulting thread)
- auto text = crashFile.loadFileAsString();
- if (text.contains ("--- frames"))
- text = text.fromFirstOccurrenceOf ("--- frames", false, false);
- auto lines = juce::StringArray::fromLines (text);
- int looked = 0;
- for (const auto& line : lines)
- {
- const auto module = line.fromFirstOccurrenceOf (": ", false, false).upToFirstOccurrenceOf ("+", false, false).trim().toLowerCase();
- if (module.isEmpty() || ! module.endsWith (".dll"))
- continue;
- if (++looked > 12)
- break;
- for (const auto* driver : { "igd", "ig9icd", "ig7icd", "igxelp", "nvwgf2um", "nvoglv", "nvd3dum", "atidxx", "atio6axx", "amdxx", "aticfx",
- "d3d11.dll", "d3d10warp", "dxgi.dll", "d2d1.dll", "opengl32.dll", "dcomp.dll" })
- if (module.startsWith (driver))
- {
- cause.gpuDriver = true;
- cause.driverModule = module;
- break;
- }
- if (cause.gpuDriver)
- break;
- }
- }
- return cause;
- }
- juce::String collectUncleanSessions()
- {
- juce::String lastStep;
- juce::Time newest;
- for (const auto& file : sessionsFolder().findChildFiles (juce::File::findFiles, false, "session-*.txt"))
- {
- const auto text = file.loadFileAsString();
- juce::StringPairArray values;
- juce::StringArray steps;
- for (const auto& line : juce::StringArray::fromLines (text))
- {
- if (line.startsWith ("step="))
- steps.add (line.fromFirstOccurrenceOf ("=", false, false));
- else if (line.contains ("="))
- values.set (line.upToFirstOccurrenceOf ("=", false, false), line.fromFirstOccurrenceOf ("=", false, false));
- }
- const auto pid = (std::uint32_t) values["pid"].getLargeIntValue();
- const auto start = (std::uint64_t) values["start"].getLargeIntValue();
- if (pid == lynx::crashguard::processId() || lynx::crashguard::processRunning (pid, start))
- continue; // this run, or another LYNX window still open
- lynx::PluginHost::settingsFolder().getChildFile ("crash-history.log")
- .appendText (juce::Time::getCurrentTime().toISO8601 (true) + " previous session ended without closing\n" + text + "\n");
- file.deleteFile();
- if (const auto modified = file.getLastModificationTime(); lastStep.isEmpty() || modified > newest)
- {
- newest = modified;
- lastStep = steps.isEmpty() ? juce::String ("start-up") : steps[steps.size() - 1].fromFirstOccurrenceOf (" ", false, false);
- uncleanSessionText = text;
- uncleanSteps.clear();
- for (const auto& step : steps)
- uncleanSteps.add (step.fromFirstOccurrenceOf (" ", false, false));
- }
- }
- return lastStep;
- }
- } // namespace
- // --uiperf (round 173f, discussion #10): a mixer fader dragged up and down with the mouse while the pattern plays. A
- // high-resolution timer delivers 125 moves a second to the message thread through the window's own mouse path
- // (ComponentPeer::handleMouseEvent), at most one waiting at a time as Windows does with WM_MOUSEMOVE; every frame the
- // window paints tells whether it covered the fader. Measured: how long a move waited for the message thread, the time
- // from a move to the first frame that shows the fader after it (input → paint), and whether the value stays put when
- // the mouse is released.
- struct UiPerfDrag final : public std::enable_shared_from_this<UiPerfDrag>,
- private juce::HighResolutionTimer
- {
- ~UiPerfDrag() override { stopTimer(); }
- void start (juce::Component& windowIn, juce::Component& strips, juce::Rectangle<int> rail, lynx::AudioEngine* engineIn, int trackIn)
- {
- window = &windowIn;
- engine = engineIn;
- track = trackIn;
- railInWindow = window->getLocalArea (&strips, rail);
- watch = railInWindow.expanded (6, 40); // the cap, its tip above and the dB read-out below
- visible = strips.isShowing() && window->getLocalArea (&strips, strips.getLocalBounds()).contains (railInWindow.getCentre());
- const auto volume = engine->getSong().mixer[(std::size_t) track].volume;
- x = (float) railInWindow.getCentreX();
- startY = (float) railInWindow.getBottom() - volume * (float) railInWindow.getHeight(); // on the cap: no jump
- amplitude = 0.4f * (float) railInWindow.getHeight();
- centreY = juce::jlimit ((float) railInWindow.getY() + amplitude, (float) railInWindow.getBottom() - amplitude, startY);
- t0 = juce::Time::getMillisecondCounterHiRes();
- inject (x, startY, false);
- juce::ModifierKeys::currentModifiers = juce::ModifierKeys (juce::ModifierKeys::leftButtonModifier);
- inject (x, startY, true);
- active = true;
- startTimer (8);
- }
- // message thread
- void framePainted (double now, juce::Rectangle<int> area)
- {
- if (pending.empty() || ! area.intersects (watch))
- return;
- for (const auto t : pending)
- latencies.push_back (now - t);
- pending.clear();
- ++framesOverFader;
- }
- // the moves end; as in the reporter's clip, the song is stopped while the button is still down
- juce::String stop()
- {
- stopTimer();
- active = false;
- valueAtRelease = engine->getSong().mixer[(std::size_t) track].volume;
- engine->stop();
- juce::String text;
- text << " drag of insert " << track << "'s fader" << (visible ? "" : " (NOT VISIBLE)") << ": " << moves << " moves handled, " << dropped
- << " folded into the next (the message thread still busy with the previous one)\n"
- << " move waited for the message thread: " << describe (queueDelays) << "\n"
- << " input -> paint (move to the first frame over the fader): " << describe (latencies) << ", " << framesOverFader
- << " frames over the fader\n";
- return text;
- }
- juce::String release()
- {
- const auto now = engine->getSong().mixer[(std::size_t) track].volume;
- juce::ModifierKeys::currentModifiers = {};
- inject (x, lastY, false);
- return " song stopped, button still down: fader " + juce::String (now, 4) + " (" + juce::String (valueAtRelease, 4) + " at the last move) "
- + (std::abs (now - valueAtRelease) < 1.0e-4f ? "kept" : "CHANGED") + "\n";
- }
- juce::String released() const
- {
- const auto now = engine->getSong().mixer[(std::size_t) track].volume;
- return " after the release: fader " + juce::String (now, 4) + " (" + juce::String (valueAtRelease, 4) + " when released) "
- + (std::abs (now - valueAtRelease) < 1.0e-4f ? "kept" : "CHANGED") + "\n";
- }
- private:
- juce::Component* window = nullptr;
- lynx::AudioEngine* engine = nullptr;
- int track = 1;
- juce::Rectangle<int> railInWindow, watch;
- bool visible = false;
- float x = 0.0f, startY = 0.0f, centreY = 0.0f, amplitude = 0.0f, lastY = 0.0f;
- double t0 = 0.0;
- std::atomic<bool> active { false }, posted { false };
- std::atomic<int> dropped { 0 };
- int moves = 0, framesOverFader = 0;
- float valueAtRelease = 0.0f;
- std::vector<double> pending, latencies, queueDelays;
- static juce::String describe (std::vector<double> v)
- {
- if (v.empty())
- return "none";
- std::sort (v.begin(), v.end());
- const auto at = [&v] (double q) { return v[std::min (v.size() - 1, (std::size_t) (q * (double) v.size()))]; };
- return "p50 " + juce::String (at (0.5), 1) + " / p95 " + juce::String (at (0.95), 1) + " / p99 " + juce::String (at (0.99), 1) + " / max "
- + juce::String (v.back(), 1) + " ms";
- }
- void inject (float px, float py, bool down)
- {
- lastY = py;
- if (auto* peer = window != nullptr ? window->getPeer() : nullptr)
- {
- const auto local = peer->globalToLocal (window->localPointToGlobal (juce::Point<float> (px, py)));
- peer->handleMouseEvent (juce::MouseInputSource::InputSourceType::mouse, local,
- down ? juce::ModifierKeys (juce::ModifierKeys::leftButtonModifier) : juce::ModifierKeys(),
- juce::MouseInputSource::defaultPressure, juce::MouseInputSource::defaultOrientation,
- juce::Time::currentTimeMillis());
- }
- }
- void hiResTimerCallback() override
- {
- if (! active.load())
- return;
- if (posted.exchange (true))
- {
- ++dropped;
- return;
- }
- const auto postedAt = juce::Time::getMillisecondCounterHiRes();
- juce::MessageManager::callAsync ([self = shared_from_this(), postedAt] {
- self->posted = false;
- if (! self->active.load())
- return;
- const auto now = juce::Time::getMillisecondCounterHiRes();
- self->queueDelays.push_back (now - postedAt);
- // up and down ~1.3 times a second, like the reporter's hand
- const auto y = self->centreY + self->amplitude * (float) std::sin (2.0 * juce::MathConstants<double>::pi * 1.3 * (now - self->t0) / 1000.0);
- self->inject (self->x, y, true);
- self->pending.push_back (postedAt);
- ++self->moves;
- });
- }
- };
- class LynxApplication final : public juce::JUCEApplication
- {
- public:
- const juce::String getApplicationName() override { return JUCE_APPLICATION_NAME_STRING; }
- const juce::String getApplicationVersion() override { return JUCE_APPLICATION_VERSION_STRING; }
- // the plugin scan runs copies of LYNX as child processes
- bool moreThanOneInstanceAllowed() override { return true; }
- // A file handed to the running application. macOS does this for every Finder double-click, "Open With" and Dock drop,
- // also the one that starts LYNX (its argv has no file). On Windows and Linux a second start is a second process
- // (moreThanOneInstanceAllowed) with the file as an argument, so this is not called there. Only the first file of a
- // multiple selection opens: a project replaces the one before it. (D#92, round 180a)
- void anotherInstanceStarted (const juce::String& commandLine) override
- {
- const auto files = lynx::safety::filesInCommandLine (commandLine.toStdString());
- if (files.empty())
- return;
- const auto file = juce::File::getCurrentWorkingDirectory().getChildFile (juce::String::fromUTF8 (files.front().c_str()));
- if (! startupFileHandled) // still starting: openStartupFile takes it, nothing to ask about yet
- {
- fileToOpen = file;
- return;
- }
- if (mainWindow != nullptr)
- {
- mainWindow->toFront (true);
- mainWindow->getContent().openFileRequest (file);
- }
- }
- void initialise (const juce::String& commandLine) override
- {
- // round 166b: the copy of LYNX.exe that installs an update (ui/Updater.h) waits, installs, starts LYNX again
- if (commandLine.contains ("--apply-update") && lynx::updater::runApplyHelper (juce::StringArray::fromTokens (commandLine, true)))
- {
- updateHelper = true;
- quit();
- return;
- }
- // Windows, LYNX.exe in a folder with accents: run again from its ASCII short path (Waves editors crash otherwise)
- if (int code = 0; lynx::platform::relaunchFromAsciiPath (code))
- {
- relaunched = true;
- setApplicationReturnValue (code);
- quit();
- return;
- }
- // a crash in any mode (UI, command line) writes its backtrace to %APPDATA%\LYNX\autosave
- juce::SystemStats::setApplicationCrashHandler (onCrash);
- lynx::crashguard::hardenSignals(); // issue #115: stack overflows and SIGTERM / SIGHUP leave a trace (Linux / macOS)
- // SFZ instruments (round 167o): their FLAC / OGG / AIFF / MP3 samples through JUCE's readers
- lynx::sfz::setDecoder ([] (const std::string& path, lynx::sfz::Audio& out) {
- juce::AudioFormatManager formats;
- formats.registerBasicFormats();
- std::unique_ptr<juce::AudioFormatReader> reader (formats.createReaderFor (juce::File (juce::String::fromUTF8 (path.c_str()))));
- if (reader == nullptr || reader->lengthInSamples <= 0 || reader->lengthInSamples > (1 << 28) || reader->numChannels == 0)
- return false;
- const auto frames = (int) reader->lengthInSamples;
- juce::AudioBuffer<float> buffer ((int) std::min (2u, reader->numChannels), frames);
- if (! reader->read (&buffer, 0, frames, 0, true, buffer.getNumChannels() > 1))
- return false;
- out.channels.clear();
- for (int ch = 0; ch < buffer.getNumChannels(); ++ch)
- out.channels.emplace_back (buffer.getReadPointer (ch), buffer.getReadPointer (ch) + frames);
- out.sampleRate = reader->sampleRate;
- out.loopStart = out.loopEnd = -1;
- return true;
- });
- // child process of a sandboxed plugin: no window or audio of its own
- if (lynx::runPluginSandboxWorker (commandLine))
- {
- lynx::crashguard::quietCrashReports();
- sandboxChild = true;
- return;
- }
- const auto args = juce::StringArray::fromTokens (commandLine, true);
- // interface language: saved in %APPDATA%\LYNX\language.txt; --lang pt-BR overrides it for this run
- lynx::i18n::initialise (args);
- // interface font: saved in Settings › General; --uifont "Name" overrides it for this run
- const auto uiFontArg = args.indexOf ("--uifont");
- lookAndFeel.applyInterfaceFont (lynx::i18n::current(), uiFontArg >= 0 ? args[uiFontArg + 1].unquoted() : juce::String());
- if (args.contains ("--showcase"))
- {
- // LYNX's own demo project (README screenshots): --showcase output.lynx [pattern]
- const auto i = args.indexOf ("--showcase");
- runShowcase (args[i + 1].unquoted(), args[i + 2].getIntValue());
- return;
- }
- if (args.contains ("--sandboxtest"))
- {
- const auto i = args.indexOf ("--sandboxtest");
- runSandboxTest (args[i + 1].unquoted(), args[i + 2].unquoted());
- return;
- }
- if (args.contains ("--bridge32test"))
- {
- // LYNX.exe --bridge32test "LYNX Test Synth 32.dll" report.txt [--compare "LYNX Test Synth.dll"] (round 176a):
- // the 32-bit plugin bridge (engine/Bridge32Test.cpp)
- const auto i = args.indexOf ("--bridge32test");
- const auto compare = args.contains ("--compare") ? args[args.indexOf ("--compare") + 1].unquoted() : juce::String();
- setApplicationReturnValue (lynx::runBridge32Test (args[i + 1].unquoted(), args[i + 2].unquoted(), compare));
- quit();
- return;
- }
- if (args.contains ("--rtstress"))
- {
- // LYNX.exe --rtstress project.(flp|lynx) report.txt [seconds] [--buffer N] [--type "driver type"] [--device "output"]
- // [--no-window] [--record take.wav]: the real app (window, audio device) plays the project and reports the callbacks
- // that missed their deadline (REA round 87); --type/--device pick another driver for this run only (round 97);
- // --record also records the input during the run, like Rec + Play, and moves the take to take.wav (round 106)
- const auto i = args.indexOf ("--rtstress");
- const auto seconds = args[i + 3].getDoubleValue();
- const auto buffer = args.contains ("--buffer") ? args[args.indexOf ("--buffer") + 1].getIntValue() : 0;
- juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
- const auto option = [&args] (const char* name) { return args.contains (name) ? args[args.indexOf (name) + 1].unquoted() : juce::String(); };
- runRealtimeStress (juce::File (args[i + 1].unquoted()), juce::File (args[i + 2].unquoted()), seconds > 0.0 ? seconds : 30.0, buffer,
- option ("--type"), option ("--device"), option ("--record"));
- return;
- }
- if (args.contains ("--cliplooptest"))
- {
- // LYNX --cliplooptest report.txt [export.wav] (round 167q, issue #25: 0.1.21 drew the repeats of a stretched
- // pattern clip but played the pattern once). The real engine's device callback (a stand-in device, driven
- // block by block) plays a synth's 1-bar pattern in a 4-bar clip: every repeat must sound as bar 1, also
- // starting inside a repeat, after a jump mid-clip and in a loop region; the WAV export (written to
- // export.wav and read back) the same. With the LYNX extra off, bars 2-4 must be silent (FL's behaviour).
- const auto i = args.indexOf ("--cliplooptest");
- runClipLoopTest (juce::File (args[i + 1].unquoted()), args.size() > i + 2 && ! args[i + 2].startsWith ("--") ? juce::File (args[i + 2].unquoted()) : juce::File());
- return;
- }
- if (args.contains ("--countinrectest"))
- {
- // LYNX --countinrectest report.txt (round 170d, the Busy Works video: the chord on the downbeat after the
- // pre-count was lost). The real engine's device callback (a stand-in device: 48 kHz, blocks of 512, 256
- // samples of output latency) records a Song-mode take from bar 3 with a 1-bar count-in. Pass 1 finds where
- // the metronome's bar-3 click is heard; pass 2 plays MIDI notes stamped at the times they are heard around
- // it (a chord 15 ms early, a note in the count-in, one 3 ms after beat 2, one a bar for 6 bars) through
- // LYNX's MIDI input. Every note must land on the tick it was heard at (the chord on bar 3).
- const auto i = args.indexOf ("--countinrectest");
- runCountInRecordTest (juce::File (args[i + 1].unquoted()));
- return;
- }
- if (args.contains ("--bendrectest"))
- {
- // LYNX --bendrectest report.txt [song|pattern] (round 167a, issue #12): pitch bend recording end to end. A
- // controller's pitch wheel is injected into LYNX's MIDI input (as a device would send it) while recording
- // plays: a held note and a wheel sweep 0 → full up → full down → centre. The recorded lane (pattern mode) or
- // automation clip (song mode) of the channel's pitch bend must follow the sweep.
- const auto i = args.indexOf ("--bendrectest");
- const auto songMode = args.size() > i + 2 && args[i + 2] == "song";
- runBendRecordTest (juce::File (args[i + 1].unquoted()), songMode);
- return;
- }
- if (args.contains ("--rectest"))
- {
- // LYNX --rectest report.txt [seconds] [--type T] [--device D] [--input I] [--loop] [--buffer N]
- // (round 163): records a click track through a loopback (cable, interface loopback or PipeWire's
- // pw-loopback): pings the round trip, plays a click on every beat from an audio clip, records it on Insert 1,
- // stops, and checks every recorded click's song position on the Playlist against its beat (samples).
- // --loop: loop recording over bars 2-4 (take lanes). --punch: punch in/out on bars 3-4 with 1 bar of pre-roll
- // and 1 of post-roll (playback stops by itself after the post-roll).
- const auto i = args.indexOf ("--rectest");
- const auto option = [&args] (const char* name) { return args.contains (name) ? args[args.indexOf (name) + 1].unquoted() : juce::String(); };
- const auto seconds = args.size() > i + 2 && ! args[i + 2].startsWith ("--") ? args[i + 2].getDoubleValue() : 20.0;
- runRecordTest (juce::File (args[i + 1].unquoted()), seconds > 0.0 ? seconds : 20.0, option ("--type"), option ("--device"), option ("--input"),
- args.contains ("--loop") ? 1 : args.contains ("--punch") ? 2 : 0, option ("--pdc").getIntValue(), option ("--buffer").getIntValue());
- return;
- }
- if (args.contains ("--hwinserttest"))
- {
- // LYNX --hwinserttest report.txt [seconds] [--type T] [--device D] [--input I] [--buffer N] (round 164d): a
- // hardware insert through a loopback cable (output pair 1-2 -> input pair 1-2; the Master plays nowhere, so
- // the cable carries the send only). The same click track plays on two inserts: Insert 1 through the
- // hardware insert (panned left), Insert 2 dry (panned right). The insert's own ping measures the round
- // trip, PDC delays the dry path by it, and every click of the Master's left side must sit on the same
- // sample as the right side's.
- const auto i = args.indexOf ("--hwinserttest");
- const auto option = [&args] (const char* name) { return args.contains (name) ? args[args.indexOf (name) + 1].unquoted() : juce::String(); };
- const auto seconds = args.size() > i + 2 && ! args[i + 2].startsWith ("--") ? args[i + 2].getDoubleValue() : 10.0;
- // round 165c: --patcher puts the insert inside a Patcher on Insert 1; --bounce file.wav then exports the song in real
- // time through the device (Export › "Render through the hardware in real time") and offline, and compares them
- runHwInsertTest (juce::File (args[i + 1].unquoted()), seconds > 0.0 ? seconds : 10.0, option ("--type"), option ("--device"), option ("--input"),
- option ("--buffer").getIntValue(), args.contains ("--patcher"),
- args.contains ("--bounce") ? juce::File (option ("--bounce")) : juce::File());
- return;
- }
- if (args.contains ("--uiperf"))
- {
- // LYNX --uiperf project.(flp|lynx) report.txt: the heavy UI cases in the real window, every frame timed (round 161)
- const auto i = args.indexOf ("--uiperf");
- juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
- runUiPerf (juce::File (args[i + 1].unquoted()), juce::File (args[i + 2].unquoted()));
- return;
- }
- if (args.contains ("--cachetest"))
- {
- // LYNX --cachetest project.(flp|lynx) report.txt (round 174f): the Playlist's cached picture against exact
- // paints after zooms, scrolls and repaints, off screen (no window)
- const auto i = args.indexOf ("--cachetest");
- juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
- runCacheTest (juce::File (args[i + 1].unquoted()), juce::File (args[i + 2].unquoted()));
- return;
- }
- if (args.contains ("--timertest"))
- {
- // LYNX --timertest report.txt (round 174f): ui::TimerWhileShowing through hide / show / minimise (opens a small window)
- runTimerTest (juce::File (args[args.indexOf ("--timertest") + 1].unquoted()));
- return;
- }
- if (args.contains ("--livetest"))
- {
- // LYNX --livetest report.txt [--relay URL]: a live session of four peers over the relay (round 169b)
- setApplicationReturnValue (lynx::livetest::run (args));
- quit();
- return;
- }
- if (args.contains ("--selftest"))
- {
- const auto i = args.indexOf ("--selftest");
- runSelfTest (args[i + 1].unquoted(), args[i + 2].unquoted());
- return;
- }
- if (args.contains ("--scan-one"))
- {
- // child process of the plugin scan (see PluginHost::scan)
- const auto i = args.indexOf ("--scan-one");
- // no crash dialogs from the plugin being examined; and once the result is written, the process ends without
- // unloading it: a Waves shell crashed in its own teardown at exit (Intel GPU driver fail-fast, 0xC0000409),
- // which showed Windows' crash dialog and made the scan reject the whole shell (round 111)
- lynx::crashguard::quietCrashReports();
- lynx::PluginHost::scanOneFile (args[i + 1].unquoted(), args[i + 2].unquoted(), juce::File (args[i + 3].unquoted()));
- lynx::crashguard::exitNow (0);
- }
- if (args.contains ("--packageinfo"))
- {
- // round 165n: the Microsoft Store (MSIX) build's identity and folders (platform/Package.h); the release
- // workflow runs it inside the installed test package
- juce::File (args[args.indexOf ("--packageinfo") + 1].unquoted()).replaceWithText (lynx::platform::packageReport());
- quit();
- return;
- }
- if (args.contains ("--paths"))
- {
- // diagnostics: folders LYNX searches
- const auto programs = juce::File::getSpecialLocation (juce::File::globalApplicationsDirectory);
- juce::String report;
- report << "programs=" << programs.getFullPathName() << "\n";
- for (const auto& dir : programs.getChildFile ("Image-Line").findChildFiles (juce::File::findDirectories, false, "FL Studio*"))
- report << "fl=" << dir.getFullPathName() << " packs=" << (int) dir.getChildFile ("Data").getChildFile ("Patches").getChildFile ("Packs").isDirectory() << "\n";
- juce::File (args[args.indexOf ("--paths") + 1].unquoted()).replaceWithText (report);
- quit();
- return;
- }
- if (args.contains ("--fldb"))
- {
- // diagnostics: LYNX.exe --fldb report.txt [project.flp]: the FL Studio installation, its plugin database,
- // the suggested plugin folders and, for a project, how each of its plugins resolves (read-only)
- const auto i = args.indexOf ("--fldb");
- const auto fl = lynx::findFlStudio();
- lynx::PluginHost host (false);
- juce::String report;
- report << "install=" << fl.installDir.getFullPathName() << "\nuserdata=" << fl.userData.getFullPathName() << "\n";
- for (const auto& f : fl.vstFolders)
- report << "flvstfolder=" << f << "\n";
- report << "dbfiles=" << host.flPluginDatabaseFiles() << " entries=" << (int) host.flPluginDatabase().entries().size() << "\n";
- for (const auto& e : host.flPluginDatabase().entries())
- report << " entry: " << juce::String::fromUTF8 (e.name.c_str()) << " | " << juce::String::fromUTF8 (e.path.c_str()) << " | role=" << e.role << "\n";
- const auto suggested = host.suggestedFolders();
- for (int k = 0; k < suggested.getNumPaths(); ++k)
- report << "folder=" << suggested[k].getFullPathName() << "\n";
- if (const juce::File project (args[i + 2].unquoted()); project.existsAsFile())
- {
- juce::MemoryBlock data;
- project.loadFileAsData (data);
- try
- {
- for (const auto& use : lynx::flpForeignPlugins (flp::parseProject ({ static_cast<const std::uint8_t*> (data.getData()), data.getSize() })))
- {
- juce::String how;
- const auto d = host.findForeign (use.plugin, use.instrument, &how);
- const auto* entry = host.flPluginDatabase().match (use.plugin, use.instrument);
- report << "plugin: " << juce::String::fromUTF8 (use.plugin.name.c_str()) << " -> "
- << (d ? d->fileOrIdentifier + " (" + how + ")" : juce::String ("not known"))
- << (entry != nullptr ? " | fl db: " + juce::String::fromUTF8 (entry->path.c_str()) : juce::String()) << "\n";
- }
- const auto uses = lynx::flpForeignPlugins (flp::parseProject ({ static_cast<const std::uint8_t*> (data.getData()), data.getSize() }));
- const auto candidates = host.filesToScanFor (uses);
- report << "scan_candidates=" << candidates.joinIntoString (";") << "\n";
- if (args.contains ("--scan"))
- {
- // the targeted scan an open would run (child processes; the user's plugin list is not touched)
- report << "scanned_new=" << host.scanFiles (candidates, {}) << "\n";
- for (const auto& use : uses)
- {
- juce::String how;
- const auto d = host.findForeign (use.plugin, use.instrument, &how);
- report << "after_scan: " << juce::String::fromUTF8 (use.plugin.name.c_str()) << " -> "
- << (d ? d->fileOrIdentifier + " (" + how + ")" : juce::String ("not known")) << "\n";
- }
- }
- }
- catch (const flp::Error& e)
- {
- report << "error=" << e.what() << "\n";
- }
- }
- juce::File (args[i + 1].unquoted()).replaceWithText (report);
- quit();
- return;
- }
- if (args.contains ("--midisync-test"))
- {
- // LYNX --midisync-test report.txt ["output device"] ["input device"] (round 165f): MIDI clock timing
- const auto i = args.indexOf ("--midisync-test");
- const auto out = args.size() > i + 2 && ! args[i + 2].startsWith ("--") ? args[i + 2].unquoted() : juce::String();
- const auto in = args.size() > i + 3 && ! args[i + 3].startsWith ("--") ? args[i + 3].unquoted() : juce::String();
- juce::File (args[i + 1].unquoted()).replaceWithText (lynx::MidiSyncIo::selfTest (out, in));
- quit();
- return;
- }
- if (args.contains ("--devices") || args.contains ("--dispositivos")) // --dispositivos: legacy alias
- {
- // diagnostics: driver types and output devices JUCE offers (without opening any)
- juce::AudioDeviceManager manager;
- juce::String report;
- manager.getAvailableDeviceTypes();
- if (auto pipeWire = lynx::makePipeWireDeviceType()) // Linux: LYNX's own PipeWire client (round 161)
- manager.addAudioDeviceType (std::move (pipeWire));
- #if JUCE_LINUX
- report << lynx::describePipeWire() << "\n";
- #endif
- for (auto* type : manager.getAvailableDeviceTypes())
- {
- type->scanForDevices();
- report << "type=" << type->getTypeName() << "\n";
- for (const auto& name : type->getDeviceNames (false))
- report << " output=" << name << "\n";
- for (const auto& name : type->getDeviceNames (true))
- report << " input=" << name << "\n";
- }
- for (const auto& d : juce::MidiInput::getAvailableDevices())
- report << "midi-in=" << d.name << "\n";
- for (const auto& d : juce::MidiOutput::getAvailableDevices())
- report << "midi-out=" << d.name << "\n";
- const auto flag = args.contains ("--devices") ? args.indexOf ("--devices") : args.indexOf ("--dispositivos");
- juce::File (args[flag + 1].unquoted()).replaceWithText (report);
- quit();
- return;
- }
- if (args.contains ("--devicetest"))
- {
- // LYNX.exe --devicetest "type" "device" report.txt ["input device"] [--buffer N] [--roundtrip]: opens that output device (and, with the
- // 4th argument, an input: "*" = the same device / the driver's default input), receives 1 s of callbacks
- // writing silence, closes it and reports rate, block size, latency, callbacks and the input channels with
- // their peak level (driver check, no sound). --roundtrip: clicks out, found again on input 1 through a loopback
- // cable / PipeWire link: the round-trip latency (3 s)
- const auto i = args.indexOf ("--devicetest");
- const auto typeName = args[i + 1].unquoted(), deviceName = args[i + 2].unquoted();
- auto inputName = args.size() > i + 4 && ! args[i + 4].startsWith ("--") ? args[i + 4].unquoted() : juce::String();
- const auto wantInput = inputName.isNotEmpty();
- juce::String report;
- const juce::File reportFile (args[i + 3].unquoted());
- auto step = [&] (const juce::String& line) { report << line << "\n"; reportFile.replaceWithText (report); }; // progress survives a driver that ends the process
- step ("step=start");
- juce::AudioDeviceManager manager;
- manager.getAvailableDeviceTypes();
- if (auto pipeWire = lynx::makePipeWireDeviceType())
- manager.addAudioDeviceType (std::move (pipeWire));
- std::unique_ptr<juce::AudioIODevice> device;
- for (auto* type : manager.getAvailableDeviceTypes())
- if (type->getTypeName() == typeName)
- {
- type->scanForDevices();
- if (wantInput && type->hasSeparateInputsAndOutputs())
- {
- const auto inputs = type->getDeviceNames (true);
- if (inputName == "*" || ! inputs.contains (inputName))
- {
- const auto index = type->getDefaultDeviceIndex (true);
- inputName = juce::isPositiveAndBelow (index, inputs.size()) ? inputs[index] : juce::String();
- }
- for (const auto& n : inputs)
- step ("input_device=" + n);
- step ("input_chosen=" + inputName);
- }
- else if (wantInput)
- inputName = deviceName;
- step ("step=create");
- device.reset (type->createDevice (deviceName, type->hasSeparateInputsAndOutputs() ? inputName : juce::String()));
- step ("step=created");
- }
- struct Silence final : juce::AudioIODeviceCallback
- {
- std::atomic<int> calls { 0 }, inputs { 0 };
- std::array<std::atomic<float>, 64> peaks {};
- // --roundtrip (round 161): a click every quarter second on the outputs, found again on input 1 through a
- // loopback; the delays in samples
- bool roundtrip = false;
- int period = 12000;
- std::int64_t position = 0, lastClick = -1;
- std::vector<int> delays;
- void audioDeviceIOCallbackWithContext (const float* const* in, int numIn, float* const* out, int channels, int n,
- const juce::AudioIODeviceCallbackContext&) override
- {
- for (int c = 0; c < channels; ++c)
- if (out[c] != nullptr)
- juce::FloatVectorOperations::clear (out[c], n);
- if (roundtrip)
- {
- for (int i = 0; i < n; ++i)
- {
- if (numIn > 0 && in[0] != nullptr && lastClick >= 0 && std::abs (in[0][i]) > 0.5f)
- {
- if (delays.size() < delays.capacity())
- delays.push_back ((int) (position + i - lastClick));
- lastClick = -1;
- }
- if ((position + i) % period == 0 && position + i > 0)
- {
- for (int c = 0; c < channels; ++c)
- if (out[c] != nullptr)
- out[c][i] = 0.9f;
- lastClick = position + i;
- }
- }
- position += n;
- }
- inputs.store (numIn);
- for (int c = 0; c < juce::jmin (numIn, 64); ++c)
- if (in[c] != nullptr)
- {
- const auto range = juce::FloatVectorOperations::findMinAndMax (in[c], n);
- const auto peak = juce::jmax (std::abs (range.getStart()), std::abs (range.getEnd()));
- if (peak > peaks[(std::size_t) c].load())
- peaks[(std::size_t) c].store (peak);
- }
- ++calls;
- }
- void audioDeviceAboutToStart (juce::AudioIODevice*) override {}
- void audioDeviceStopped() override {}
- } silence;
- bool ok = false;
- if (device == nullptr)
- step ("error=device not found");
- else
- {
- step ("step=open");
- juce::BigInteger outputs;
- outputs.setRange (0, 2, true);
- const auto rates = device->getAvailableSampleRates();
- const auto rate = device->getCurrentSampleRate() > 0 ? device->getCurrentSampleRate()
- : rates.contains (48000.0) ? 48000.0 : rates.isEmpty() ? 44100.0 : rates[0];
- step ("rates=" + juce::String (rates.size()) + " chosen=" + juce::String (rate) + " default_block=" + juce::String (device->getDefaultBufferSize()));
- juce::BigInteger inputs;
- if (wantInput)
- {
- const auto names = device->getInputChannelNames();
- step ("input_channels=" + juce::String (names.size()));
- for (int c = 0; c < names.size(); ++c)
- step (" in" + juce::String (c + 1) + "=" + names[c]);
- inputs.setRange (0, juce::jmin (64, names.size()), true);
- }
- // --buffer N: ask for that block size (REA round 97 latency survey); default: the driver's default
- const auto wantedBlock = args.contains ("--buffer") ? args[args.indexOf ("--buffer") + 1].getIntValue() : 0;
- const auto error = device->open (inputs, outputs, rate, wantedBlock > 0 ? wantedBlock : device->getDefaultBufferSize());
- if (error.isNotEmpty())
- step ("error=" + error);
- else
- {
- step ("step=start_callbacks");
- silence.roundtrip = args.contains ("--roundtrip");
- silence.period = juce::jmax (1, (int) (rate / 4));
- silence.delays.reserve (64);
- device->start (&silence);
- juce::Thread::sleep (silence.roundtrip ? 3000 : 1000);
- device->stop();
- if (silence.roundtrip)
- {
- auto d = silence.delays;
- std::sort (d.begin(), d.end());
- report << "roundtrip_clicks=" << (int) d.size() << "\n";
- if (! d.empty())
- report << "roundtrip_samples=min " << d.front() << " median " << d[d.size() / 2] << " max " << d.back() << "\n"
- << "roundtrip_ms=" << juce::String (1000.0 * d[d.size() / 2] / device->getCurrentSampleRate(), 2) << "\n";
- }
- report << "rate=" << device->getCurrentSampleRate() << "\n"
- << "block=" << device->getCurrentBufferSizeSamples() << "\n"
- << "output_latency=" << device->getOutputLatencyInSamples() << "\n"
- << "callbacks=" << silence.calls.load() << "\n";
- if (wantInput)
- {
- report << "input_latency=" << device->getInputLatencyInSamples() << "\n"
- << "active_inputs=" << device->getActiveInputChannels().countNumberOfSetBits() << "\n"
- << "callback_inputs=" << silence.inputs.load() << "\n";
- for (int c = 0; c < juce::jmin (64, silence.inputs.load()); ++c)
- report << " peak_in" << (c + 1) << "=" << juce::Decibels::gainToDecibels (silence.peaks[(std::size_t) c].load(), -150.0f) << " dB\n";
- }
- ok = silence.calls.load() > 0 && (! wantInput || silence.inputs.load() > 0);
- device->close();
- }
- }
- step (juce::String ("result=") + (ok ? "OK" : "FAILED"));
- setApplicationReturnValue (ok ? 0 : 1);
- quit();
- return;
- }
- if (args.contains ("--scantest"))
- {
- // LYNX.exe --scantest folder report.txt: scan (in child processes) without touching the user's list
- const auto i = args.indexOf ("--scantest");
- lynx::PluginHost host (false);
- const auto found = host.scan (juce::FileSearchPath (args[i + 1].unquoted()), {});
- juce::String report;
- report << "found=" << found << "\n";
- for (const auto& t : host.getKnownPlugins().getTypes())
- report << " " << (t.isInstrument ? "instrument: " : "effect: ") << t.name << "\n";
- for (const auto& f : host.getKnownPlugins().getBlacklistedFiles())
- report << " blacklisted: " << f << "\n";
- juce::File (args[i + 2].unquoted()).replaceWithText (report);
- setApplicationReturnValue (found > 0 ? 0 : 1);
- quit();
- return;
- }
- if (args.contains ("--wrappermiditest"))
- {
- // LYNX.exe --wrappermiditest plugin.dll report.txt (round 181c), with LYNX_TEST_VST2_MIDILOG set: what a
- // hosted plugin receives after a wrapper MIDI option changes while it runs
- const auto i = args.indexOf ("--wrappermiditest");
- runWrapperMidiTest (args[i + 1].unquoted(), args[i + 2].unquoted());
- return;
- }
- if (args.contains ("--vst2test"))
- {
- const auto i = args.indexOf ("--vst2test");
- runVst2Test (args[i + 1].unquoted(), args[i + 2].unquoted());
- return;
- }
- if (args.contains ("--lv2scantest"))
- {
- runLv2ScanTest (args[args.indexOf ("--lv2scantest") + 1].unquoted());
- return;
- }
- if (args.contains ("--wrappertest"))
- {
- const auto i = args.indexOf ("--wrappertest");
- runWrapperTest (args[i + 1].unquoted(), args[i + 2].unquoted());
- return;
- }
- if (args.contains ("--plugintest"))
- {
- const auto i = args.indexOf ("--plugintest");
- // optional 3rd argument: the plugin's name inside a shell (e.g. "CLA-2A Stereo" in a WaveShell)
- const auto only = i + 3 < args.size() && ! args[i + 3].startsWith ("--") ? args[i + 3].unquoted() : juce::String();
- runPluginTest (args[i + 1].unquoted(), args[i + 2].unquoted(), only);
- return;
- }
- if (args.contains ("--claprestarttest"))
- {
- // LYNX.exe --claprestarttest "LYNX Test Restart.clap" report.txt (tools/testplugin/lynx_test_restart.c)
- const auto i = args.indexOf ("--claprestarttest");
- runClapRestartTest (args[i + 1].unquoted(), args[i + 2].unquoted());
- return;
- }
- if (args.contains ("--editortest"))
- {
- // LYNX.exe --editortest plugin.vst3 report.txt ["name"]: opens the plugin's own editor in a window for a few
- // seconds, then closes it (a plugin whose UI crashes the host ends the process before the report says OK)
- const auto i = args.indexOf ("--editortest");
- const auto only = i + 3 < args.size() && ! args[i + 3].startsWith ("--") ? args[i + 3].unquoted() : juce::String();
- runEditorTest (args[i + 1].unquoted(), args[i + 2].unquoted(), only);
- return;
- }
- if (args.contains ("--editorcrashtest"))
- {
- // LYNX.exe --editorcrashtest "LYNX Test Crash.clap" report.txt (issue #32, round 174a; Windows): the test
- // plugin's editor faults in its own window procedure (LYNX_TEST_CRASH=editor). LYNX must catch it, close
- // that editor, record the trace and keep running its message loop.
- const auto i = args.indexOf ("--editorcrashtest");
- runEditorCrashTest (args[i + 1].unquoted(), args[i + 2].unquoted());
- return;
- }
- if (args.contains ("--plugwintest"))
- {
- // LYNX --plugwintest plugin report.txt ["name"] [seconds]: round 162d. Puts the plugin in a channel (an
- // instrument) or on insert 1 (an effect) of an offline engine, opens its plugin window (wrapper header,
- // presets), checks a preset round trip, keeps the window `seconds` on screen (default 15: time for xdotool /
- // screenshots), then removes the plugin from the song and reports whether its window closed by itself.
- const auto i = args.indexOf ("--plugwintest");
- const auto only = i + 3 < args.size() && ! args[i + 3].startsWith ("--") && ! args[i + 3].containsOnly ("0123456789") ? args[i + 3].unquoted() : juce::String();
- auto seconds = 15;
- for (int k = i + 3; k < juce::jmin (args.size(), i + 5); ++k)
- if (args[k].containsOnly ("0123456789"))
- seconds = args[k].getIntValue();
- runPlugWinTest (args[i + 1].unquoted(), args[i + 2].unquoted(), only, seconds);
- return;
- }
- if (args.contains ("--fittest"))
- {
- // LYNX.exe --fittest report.txt [percent]: round 163 — at that UI zoom (default 150) a window taller than
- // the screen and a big resizable window that grows with a zoom change keep their title bar and close
- // button on the screen. The windows show for about two seconds.
- const auto i = args.indexOf ("--fittest");
- runFitTest (args[i + 1].unquoted(), i + 2 < args.size() ? args[i + 2].getIntValue() : 150);
- return;
- }
- if (args.contains ("--windowtest"))
- {
- // LYNX.exe --windowtest report.txt: opens the Quick-add palette, the Audio editor, a plugin-like window and a name dialog
- // over the main window and checks that each one stays in front, owned by the main window, with the
- // keyboard focus (issue #4). The windows appear on screen for a few seconds.
- runWindowTest (args[args.indexOf ("--windowtest") + 1].unquoted());
- return;
- }
- if (args.contains ("--pluginstyle")) // round 126: force one style for this run (glow, neon, hardware, vivid; auto = per plugin)
- {
- const auto i = args.indexOf ("--pluginstyle");
- if (i + 1 < args.size())
- {
- const auto name = args[i + 1].unquoted();
- lynx::skin::setForcedStyle (name.equalsIgnoreCase ("auto") ? -1 : (int) lynx::skin::styleFromName (name));
- }
- }
- if (args.contains ("--gfxprobe"))
- {
- // LYNX.exe --gfxprobe report.txt (round 170c, issue #11): renderer checks on this platform's native images —
- // text drawn with a gradient fill (a word with a space in it) and an empty path filled with a gradient must
- // stay inside their shapes. JUCE 8.0.4's CoreGraphics renderer (macOS) clipped to an empty glyph or path as
- // "no clip" and flooded the whole component (Facet EQ's blank pink window).
- const auto i = args.indexOf ("--gfxprobe");
- juce::File (args[i + 1].unquoted()).replaceWithText (lynx::skin::rendererProbeReport());
- quit();
- return;
- }
- if (args.contains ("--steppertest"))
- {
- // LYNX.exe --steppertest <report.txt>: round 170c (#14) — every value stepper of every generated effect editor
- // driven by synthetic input (arrows, click on the value, drag, wheel, trackpad); ends with result=OK / FAIL
- const auto i = args.indexOf ("--steppertest");
- juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
- juce::String report;
- int fails = 0, count = 0, skips = 0;
- {
- lynx::AudioEngine offline (false);
- auto kinds = lynx::plugui::flLayoutKinds();
- for (const auto own : lynx::plugui::ownLayoutKinds())
- kinds.push_back (own);
- // FL's Default preset when the installation has one (the state-backed controls need FL's state)
- const auto roots = lynx::findFlStudioRoots();
- const auto presets = juce::File (juce::String::fromUTF8 (roots.data.c_str())).getChildFile ("Patches/Plugin presets/Effects");
- for (const auto kind : kinds)
- {
- auto fx = lynx::makeEffectSlot (kind);
- for (const auto& plugin : lynx::flPluginsForEffect (kind))
- {
- juce::MemoryBlock data;
- const auto file = presets.getChildFile (juce::String::fromUTF8 (plugin.c_str())).getChildFile ("Default.fst");
- if (file.existsAsFile() && file.loadFileAsData (data))
- {
- const auto* bytes = static_cast<const std::uint8_t*> (data.getData());
- if (auto loaded = lynx::effectFromFlPreset (std::vector<std::uint8_t> (bytes, bytes + data.getSize()), 130.0, lynx::natives::flDataReader (lynx::flStudioAccess())); loaded && loaded->kind == kind)
- fx = *loaded;
- }
- break;
- }
- lynx::Song song;
- song.mixer.resize (2);
- song.mixer[0].name = "Master";
- song.mixer[1].name = "Insert 1";
- song.mixer[1].effects.push_back (fx);
- offline.setSong (std::move (song));
- offline.dispatchPendingMessages();
- const auto lines = lynx::stepperSelfTest (offline, 1, 0, (int) lynx::plugui::layoutFor (kind).pages.size());
- for (const auto& line : juce::StringArray::fromLines (lines))
- if (line.isNotEmpty())
- {
- ++count;
- fails += line.contains (": FAIL") ? 1 : 0;
- skips += line.contains (": SKIP") ? 1 : 0;
- }
- report << lines;
- juce::PopupMenu::dismissAllActiveMenus();
- offline.dispatchPendingMessages();
- }
- }
- report << "steppers=" << count << " failures=" << fails << " skipped=" << skips << "\nresult=" << (fails == 0 && count > 0 ? "OK" : "FAIL") << "\n";
- juce::File (args[i + 1].unquoted()).replaceWithText (report);
- quit();
- return;
- }
- if (args.contains ("--plugui"))
- {
- // LYNX.exe --plugui <folder>: the native effect editors at FL's size (one PNG per editor and page), each
- // loaded with the FL plugin's Default preset when the FL installation has one
- const auto i = args.indexOf ("--plugui");
- runPluginEditorSnapshots (args[i + 1].unquoted());
- return;
- }
- if (args.contains ("--parityshot"))
- {
- // LYNX.exe --parityshot <out.png> <effect name> [<params file>]: one built-in effect's editor with the given
- // parameters ("index value" lines, tools/fxrender --dump), its displays fed by the demo song — the LYNX side
- // of the third-party parity pictures (round tp172b)
- const auto i = args.indexOf ("--parityshot");
- runParityShot (args[i + 1].unquoted(), args[i + 2].unquoted(), i + 3 < args.size() ? args[i + 3].unquoted() : juce::String());
- if (parityShotFailed)
- setApplicationReturnValue (2);
- if (parityShow == nullptr)
- quit();
- return;
- }
- if (args.contains ("--design168rshot"))
- {
- // LYNX.exe --design168rshot <folder>: round 168r's editors (FL effects that had a generated page and LYNX's own
- // simple built-ins) at 100 % and 200 %, with their default settings and, when they have one, the first
- // preset of LYNX's own bank. "--design168rshot <folder> generated": the generated pages they had before
- const auto i = args.indexOf ("--design168rshot");
- if (i + 2 < args.size() && args[i + 2] == "generated")
- lynx::plugui::showGeneratedLayoutsOnly (true);
- runDesign168rShots (args[i + 1].unquoted());
- quit();
- return;
- }
- if (args.contains ("--eq166fshot"))
- {
- // LYNX.exe --eq166fshot <folder>: round 166f's pictures (issue #16) — Parametric EQ 2's spectrum and heatmap
- // (flat, a +12 dB band, a -12 dB band, Top position) and Facet EQ's comparative EQ (listening to the target,
- // its spectrum over the source's), each fed by the demo song rendered offline
- const auto i = args.indexOf ("--eq166fshot");
- runEq166fShots (args[i + 1].unquoted());
- quit();
- return;
- }
- if (args.contains ("--editorcpu"))
- {
- // LYNX.exe --editorcpu report.txt: opens built-in plugin editors one at a time in a small window (no audio
- // device: a silent, idle editor) and writes the process CPU each costs while idle and while its display
- // animates (demo signal) — round 122's check that an idle editor burns no CPU
- const auto i = args.indexOf ("--editorcpu");
- runEditorCpu (args[i + 1].unquoted());
- return;
- }
- if (args.contains ("--precomputeshot"))
- {
- // LYNX.exe --precomputeshot project.(flp|lynx) <prefix>: round 167h — <prefix>-precompute.png (channel 1's
- // Precomputed effects panel) and <prefix>-project.png (Options › Project with "Fast declick for cut groups")
- const auto i = args.indexOf ("--precomputeshot");
- juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
- lynx::AudioEngine shotEngine (false);
- const juce::File input (args[i + 1].unquoted());
- const auto prefix = args[i + 2].unquoted();
- juce::String error;
- bool ok = false;
- if (input.hasFileExtension ("flp"))
- ok = shotEngine.importFlpFile (input, error);
- else if (auto song = lynx::ProjectFile::load (input, error))
- shotEngine.setSong (std::move (*song)), ok = true;
- shotEngine.dispatchPendingMessages();
- auto shoot = [&] (std::unique_ptr<juce::Component> c, const juce::String& name) {
- if (c == nullptr)
- return false;
- if (c->getWidth() <= 0)
- c->setSize (520, 600);
- savePng (c->createComponentSnapshot (c->getLocalBounds()), prefix + name);
- return true;
- };
- ok = ok && shoot (lynx::makeChannelPrecomputePanel (shotEngine, 0), "-precompute.png");
- ok = ok && shoot (lynx::makeSettingsPanel (shotEngine, lynx::SettingsPage::project), "-project.png");
- setApplicationReturnValue (ok ? 0 : 1);
- quit();
- return;
- }
- if (args.contains ("--pluginthumbs"))
- {
- // LYNX.exe --pluginthumbs <folder> [key,key...]: the Plugin picker's pictures of LYNX's own plugins (round 171c,
- // ui/PluginThumbs.h), each editor drawn off-screen and kept as <folder>/<name>.png; the picker starts this in
- // the background when pictures are missing. One line per plugin on stdout.
- const auto i = args.indexOf ("--pluginthumbs");
- lynx::crashguard::quietCrashReports();
- juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
- juce::StringArray only;
- if (i + 2 < args.size() && ! args[i + 2].startsWith ("--"))
- only.addTokens (args[i + 2].unquoted(), ",", "");
- const auto t0 = juce::Time::getMillisecondCounterHiRes();
- const auto drawn = lynx::pluginthumbs::renderNative (juce::File (args[i + 1].unquoted()), only, [] (const juce::String& line) {
- std::printf ("%s\n", line.toRawUTF8());
- std::fflush (stdout);
- });
- std::printf ("drawn %d in %.0f ms\n", drawn, juce::Time::getMillisecondCounterHiRes() - t0);
- setApplicationReturnValue (0);
- quit();
- return;
- }
- if (args.contains ("--artshot"))
- {
- // LYNX.exe --artshot <folder> [before|after] [name,name...]: every editor with art of its own (round 170j/170k: the
- // Themed style; or only the named ones, e.g. "sakura,facet-eq") drawn off-screen at 100 % and 200 % as
- // <folder>/<plugin>-<before|after>-<scale>.png. "before" draws each in the style it had before the Themed style
- const auto i = args.indexOf ("--artshot");
- juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
- const auto mode = i + 2 < args.size() && ! args[i + 2].startsWith ("--") ? args[i + 2].unquoted() : juce::String ("after");
- if (i + 3 < args.size() && ! args[i + 3].startsWith ("--")) // [name,name...]: only these arts
- artOnly().addTokens (args[i + 3].unquoted(), ",", "");
- setApplicationReturnValue (runArtShots (juce::File (args[i + 1].unquoted()), mode == "before") ? 0 : 1);
- quit();
- return;
- }
- if (args.contains ("--artgui"))
- {
- // LYNX.exe --artgui <folder> [before|after|still] [name,name...]: the same editors in REAL windows on the desktop, one at a
- // time (always on top, no focus taken), each held while an outside script screenshots it (it writes
- // <folder>/<plugin>.ready with the window's bounds and waits up to 10 s for <folder>/<plugin>.done), then the
- // process CPU it costs over 6 s is written to <folder>/cpu-<mode>.txt. "still": Themed with the motion off
- const auto i = args.indexOf ("--artgui");
- juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
- const auto mode = i + 2 < args.size() && ! args[i + 2].startsWith ("--") ? args[i + 2].unquoted() : juce::String ("after");
- if (i + 3 < args.size() && ! args[i + 3].startsWith ("--")) // [name,name...]: only these arts
- artOnly().addTokens (args[i + 3].unquoted(), ",", "");
- runArtGui (juce::File (args[i + 1].unquoted()), mode);
- return;
- }
- if (args.contains ("--instrumentshot"))
- {
- // LYNX.exe --instrumentshot <folder> <engine,engine...|banks> [lynx|fl]: round 168n — the channel window of
- // each engine (its Plugin tab) at 100 %, 150 % and 200 %, as <folder>/<engine>-<source>-<scale>.png. Source
- // "lynx" starts from the engine's LYNX bank (what a PC without FL gets), "fl" from FL's Default preset.
- const auto i = args.indexOf ("--instrumentshot");
- juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
- const auto source = i + 3 < args.size() && ! args[i + 3].startsWith ("--") ? args[i + 3].unquoted() : juce::String ("lynx");
- setApplicationReturnValue (runInstrumentShots (juce::File (args[i + 1].unquoted()), args[i + 2].unquoted(), source) ? 0 : 1);
- quit();
- return;
- }
- if (args.contains ("--flextrashot"))
- {
- // LYNX.exe --flextrashot <folder>: pictures of the editors of round 165g (Big Clock, Tuner, HTML NoteBook, Mute 2, Scratcher, Transmitter) + round 167n Transporter
- const auto i = args.indexOf ("--flextrashot");
- juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
- lynx::AudioEngine shotEngine (false);
- const auto ok = lynx::runFlExtraShots (shotEngine, juce::File (args[i + 1].unquoted()));
- setApplicationReturnValue (ok ? 0 : 1);
- quit();
- return;
- }
- if (args.contains ("--visualtest"))
- {
- // LYNX.exe --visualtest <folder> [project.flp]: the visual plugins (round 164c) — the audio path's CPU, every
- // Wave Candy mode and Visualizer scene drawn from a test signal (PNG + the editor's CPU each), and the video
- // export of a project (default: FL's first ZGameEditor demo) with ffmpeg and as images. Writes report.txt.
- const auto i = args.indexOf ("--visualtest");
- juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
- const auto project = i + 2 < args.size() && ! args[i + 2].startsWith ("--") ? juce::File (args[i + 2].unquoted()) : juce::File();
- lynx::runVisualTest (juce::File (args[i + 1].unquoted()), project, [this] (bool ok) {
- setApplicationReturnValue (ok ? 0 : 1);
- quit();
- });
- return;
- }
- if (args.contains ("--menu-entry"))
- {
- // LYNX.AppImage --menu-entry on|off: puts the AppImage in the applications menu (and .lynx files on it) or
- // takes it out again, without opening a window; the same as the switch in Options › General (round 161)
- const auto i = args.indexOf ("--menu-entry");
- const auto on = args[i + 1].unquoted() != "off";
- const auto ok = lynx::runningAsAppImage() && lynx::setAppImageMenuEntry (on);
- std::fprintf (ok ? stdout : stderr, "%s\n", ok ? (on ? "LYNX SHARE added to the applications menu" : "LYNX SHARE removed from the applications menu")
- : "only the LYNX SHARE AppImage on Linux can do this");
- setApplicationReturnValue (ok ? 0 : 1);
- quit();
- return;
- }
- if (args.contains ("--send-test-report"))
- {
- // LYNX.exe --send-test-report out.txt [--dry]: builds a crash report marked "test" from the newest crash /
- // hang file and this computer's facts, writes its JSON to out.txt.json and (without --dry) sends it to
- // lynx-share.com (LYNX_CRASH_ENDPOINT overrides); out.txt gets "id=…" and "result=OK" or the error (round 159)
- const auto i = args.indexOf ("--send-test-report");
- const juce::File out (args[i + 1].unquoted());
- lynx::crashreporter::Session session;
- session.version = getApplicationVersion();
- for (const auto* pattern : { "crash *.txt", "hang *.txt" })
- {
- auto files = lynx::platform::settingsFile ("autosave").findChildFiles (juce::File::findFiles, false, pattern);
- lynx::filesort::byTime (files, lynx::filesort::By::modificationTime, true);
- if (! files.isEmpty())
- (juce::String (pattern).startsWith ("crash") ? session.crashFile : session.hangFile) = files[0];
- }
- session.steps = { "00:00:01 test report (LYNX.exe --send-test-report)", "00:00:02 opening project " + out.getFileName() };
- auto input = lynx::crashreporter::makeInput (session, session.crashFile.existsAsFile() ? "crash" : "manual", nullptr);
- input.test = true;
- const auto json = lynx::crashreporter::buildJson (input, false);
- out.withFileExtension (out.getFileExtension() + ".json").replaceWithText (json);
- const auto error = args.contains ("--dry") ? juce::String() : lynx::crashreporter::sendNow (json);
- out.replaceWithText ("id=" + juce::String::fromUTF8 (input.id.c_str()) + "\nendpoint=" + lynx::crashreporter::endpoint() + "\nbytes="
- + juce::String (json.getNumBytesAsUTF8()) + "\nresult=" + (error.isEmpty() ? juce::String ("OK") : error) + "\n");
- setApplicationReturnValue (error.isEmpty() ? 0 : 1);
- quit();
- return;
- }
- if (args.contains ("--symbolize"))
- {
- // LYNX.exe --symbolize "crash … .txt" out.txt: names the LYNX.exe+offset frames of a user's crash / hang file
- // (needs this build's LYNX.pdb next to LYNX.exe — the release's "LYNX-symbols" CI artifact; round 157a)
- const auto i = args.indexOf ("--symbolize");
- const auto text = juce::File (args[i + 1].unquoted()).loadFileAsString();
- juce::File (args[i + 2].unquoted()).replaceWithText (juce::String::fromUTF8 (lynx::crashguard::symbolizeOwnFrames (text.toStdString()).c_str()));
- quit();
- return;
- }
- if (args.contains ("--opentest"))
- {
- // LYNX.exe --opentest report.txt [--visible]: every built-in effect and instrument window opened as the mixer /
- // Channel rack open them, with default, extreme, random and old-project states; a watchdog fails the test on
- // a hang (round 157a: opening the Parametric EQ froze LYNX). Windows stay off-screen without --visible.
- const auto i = args.indexOf ("--opentest");
- runOpenTest (args[i + 1].unquoted(), args.contains ("--visible"), [this] (bool ok) {
- setApplicationReturnValue (ok ? 0 : 1);
- quit();
- });
- return;
- }
- if (args.contains ("--fxfuzz"))
- {
- // LYNX.exe --fxfuzz report.txt [rounds] [--drags]: every built-in effect in its editor, parameters swept (and
- // dragged with the mouse), audio rendered at several rates; a crash ends the process (round 111)
- const auto i = args.indexOf ("--fxfuzz");
- const auto rounds = args.size() > i + 2 ? juce::jmax (1, args[i + 2].getIntValue()) : 6;
- // --drags: also mouse drags over the editors (their menus may flash on screen: not for the selftest)
- const auto ok = runEffectFuzz (rounds, args[i + 1].unquoted(), args.contains ("--drags"));
- setApplicationReturnValue (ok ? 0 : 1);
- quit();
- return;
- }
- if (args.contains ("--controllershot"))
- {
- // LYNX.exe --controllershot prefix: the built-in controllers' editors (round 133) as PNGs
- const auto i = args.indexOf ("--controllershot");
- runControllerShot (args[i + 1].unquoted());
- quit();
- return;
- }
- if (args.contains ("--edisonshot"))
- {
- // LYNX.exe --edisonshot prefix [audio.wav]: the audio editor's Edison tool windows (round 165l) and the
- // editor before / after some of them, as PNGs (a synthetic drum loop without a file)
- const auto i = args.indexOf ("--edisonshot");
- runEdisonShot (args[i + 1].unquoted(), i + 2 < args.size() ? args[i + 2].unquoted() : juce::String());
- quit();
- return;
- }
- if (args.contains ("--danceshot"))
- {
- // LYNX.exe --danceshot prefix: LYNX Dance (round 165e) — every move as a contact sheet, the channel's editor,
- // and a demo project with two dance channels (for --snapshot)
- const auto i = args.indexOf ("--danceshot");
- runDanceShot (args[i + 1].unquoted());
- quit();
- return;
- }
- if (args.contains ("--videoshot") && args.indexOf ("--videoshot") + 2 < args.size())
- {
- // LYNX.exe --videoshot prefix video: the Video Player's editor (round 165g) at a few song positions, with
- // the user's ffmpeg, as PNGs + report.txt (frames decoded, the sound track)
- const auto i = args.indexOf ("--videoshot");
- runVideoShot (args[i + 1].unquoted(), args[i + 2].unquoted());
- return;
- }
- if (args.contains ("--videotrackshot") && args.indexOf ("--videotrackshot") + 2 < args.size())
- {
- // LYNX.exe --videotrackshot prefix video [video2]: round 174d — the Playlist with video tracks (filmstrips,
- // timecode row) and the video window at a few song positions, as PNGs + report.txt (the decoder, the
- // frame shown for each wanted time: frame accuracy, frames dropped)
- const auto i = args.indexOf ("--videotrackshot");
- runVideoTrackShot (args[i + 1].unquoted(), args[i + 2].unquoted(), i + 3 < args.size() ? args[i + 3].unquoted() : juce::String());
- return;
- }
- if (args.contains ("--vfxshot"))
- {
- // LYNX.exe --vfxshot prefix: the VFX note effects' editors (round 164b), on channels and in a Patcher, as PNGs
- const auto i = args.indexOf ("--vfxshot");
- runVfxShot (args[i + 1].unquoted());
- quit();
- return;
- }
- if (args.contains ("--patchershot"))
- {
- // LYNX.exe --patchershot prefix [project]: every Patcher's editor (round 141) as PNGs (a demo one without a project)
- const auto i = args.indexOf ("--patchershot");
- runPatcherShot (args[i + 1].unquoted(), i + 2 < args.size() ? args[i + 2].unquoted() : juce::String());
- quit();
- return;
- }
- if (args.contains ("--comp177shot"))
- {
- // LYNX.exe --comp177shot prefix project (round 177c): a project of loop takes in the maximised
- // Playlist as it opened; every group after "Comp these takes", with a swipe on the first; the track and record menus
- const auto i = args.indexOf ("--comp177shot");
- runComp177Shot (args[i + 1].unquoted(), args[i + 2].unquoted());
- quit();
- return;
- }
- if (args.contains ("--feat166shot"))
- {
- // LYNX.exe --feat166shot prefix [project]: round 166d (issue #14) — the Piano Roll with a scale, folded to
- // it, with one ghost channel, the ghost channels menu, and the Mixer filled to 500 inserts (its start and
- // its end, and the time a full repaint takes)
- const auto i = args.indexOf ("--feat166shot");
- runFeat166Shot (args[i + 1].unquoted(), i + 2 < args.size() ? args[i + 2].unquoted() : juce::String());
- quit();
- return;
- }
- if (args.contains ("--perfshot"))
- {
- // LYNX.exe --perfshot prefix project: the Playlist in Performance mode with a few clips launched and waiting,
- // then the project patcherized (every insert's effects, the first channels) saved as prefix-patcherized.lynx
- // for --patchershot (round 165m)
- const auto i = args.indexOf ("--perfshot");
- runPerfShot (args[i + 1].unquoted(), i + 2 < args.size() ? args[i + 2].unquoted() : juce::String());
- quit();
- return;
- }
- if (args.contains ("--gridshot"))
- {
- // LYNX.exe --gridshot prefix [project]: the Clip-launch workflow's layout off-screen, with a grid of sample
- // clips, some playing and waiting, at the size of LYNX_SNAPSHOT_SIZE (round 181a); with a project (.lynx,
- // .flp, .als), that project's grid instead (round 181c: a Live set's Session view as LYNX imports it)
- const auto i = args.indexOf ("--gridshot");
- const auto project = i + 2 < args.size() && ! args[i + 2].startsWith ("--") ? args[i + 2].unquoted() : juce::String();
- runGridShot (args[i + 1].unquoted(), project);
- quit();
- return;
- }
- if (args.contains ("--simpleshot"))
- {
- // LYNX.exe --simpleshot prefix: round 184a's Simple workflow off-screen — View › Layout style with each style
- // chosen, Settings › General (Pattern, then Simple selected) with its style list, the window in Pattern, then
- // Simple, then Pattern again, and how many Simple workflow objects existed before and after (0 before)
- const auto i = args.indexOf ("--simpleshot");
- runSimpleShot (args[i + 1].unquoted());
- quit();
- return;
- }
- if (args.contains ("--detailshot"))
- {
- // LYNX.exe --detailshot prefix: the Clip-launch workflow's detail view off-screen (round 183a): a track's chain
- // (instrument, effects, one off, one folded), its clip page, and Pattern workflow before / after, at
- // LYNX_SNAPSHOT_SIZE. Writes prefix-counts.txt with what the chain shows.
- const auto i = args.indexOf ("--detailshot");
- runDetailShot (args[i + 1].unquoted());
- quit();
- return;
- }
- if (args.contains ("--typeaheadtest"))
- {
- // LYNX.exe --typeaheadtest out.txt: issue #64 — a real popup menu (headings, a submenu) driven by key presses
- // through its window's peer, as the OS delivers them; writes what got the highlight and what was picked
- const auto i = args.indexOf ("--typeaheadtest");
- runTypeAheadTest (juce::File (args[i + 1].unquoted()));
- return;
- }
- if (args.contains ("--choosertest"))
- {
- // LYNX --choosertest out.txt file: issue #72 — opens LYNX's file chooser as the UI does (makeFileChooser +
- // launchChooser) and reports which dialog came up and what reached the callback. A built-in dialog is shot
- // (out.txt.png), `file` typed into it and confirmed; a native one (zenity / kdialog) is left to answer.
- const auto i = args.indexOf ("--choosertest");
- runChooserTest (juce::File (args[i + 1].unquoted()), juce::File (args[i + 2].unquoted()));
- return;
- }
- if (args.contains ("--snapshot"))
- {
- const auto i = args.indexOf ("--snapshot");
- runSnapshot (args[i + 1].unquoted(), args[i + 2].unquoted());
- return;
- }
- if (args.contains ("--stemsplit"))
- {
- // LYNX.exe --stemsplit input.wav folder: the stem separation of the clip menu, without the window
- const auto i = args.indexOf ("--stemsplit");
- lynx::AudioEngine loader (false);
- const auto error = lynx::extractStemsToFolder (loader, juce::File (args[i + 1].unquoted()), juce::File (args[i + 2].unquoted()));
- juce::File (args[i + 2].unquoted()).getSiblingFile ("stemsplit.txt").replaceWithText (error.isEmpty() ? "result=OK\n" : "result=FAIL " + error + "\n");
- setApplicationReturnValue (error.isEmpty() ? 0 : 1);
- quit();
- return;
- }
- if (args.contains ("--audio2midi"))
- {
- // LYNX.exe --audio2midi input.wav melody|harmony|drums notes.csv: the clip menu's Convert to MIDI, without the
- // window (round a2m189b's measurements)
- const auto i = args.indexOf ("--audio2midi");
- const auto mode = args[i + 2] == "drums" ? lynx::a2m::Mode::drums : args[i + 2] == "harmony" ? lynx::a2m::Mode::harmony : lynx::a2m::Mode::melody;
- lynx::AudioEngine loader (false);
- const juce::File csv (args[i + 3].unquoted());
- const auto error = lynx::convertFileToMidiCsv (loader, juce::File (args[i + 1].unquoted()), mode, csv);
- csv.getSiblingFile ("audio2midi.txt").replaceWithText (error.isEmpty() ? "result=OK\n" : "result=FAIL " + error + "\n");
- setApplicationReturnValue (error.isEmpty() ? 0 : 1);
- quit();
- return;
- }
- if (args.contains ("--stems"))
- {
- // LYNX.exe --stems project.(flp|als|lynx) base.wav: one WAV per insert that has sound (like "Export stems")
- const auto i = args.indexOf ("--stems");
- juce::String error, report;
- int written = 0;
- {
- lynx::AudioEngine loader (false);
- const juce::File input (args[i + 1].unquoted()), base (args[i + 2].unquoted());
- // an .flp or a Live set (.als) opens through the import, as File › Open does (round 182b)
- auto ok = input.hasFileExtension ("flp;als") ? loader.importFlpFile (input, error) : false;
- if (! input.hasFileExtension ("flp;als"))
- if (auto song = lynx::ProjectFile::load (input, error))
- {
- loader.setSong (std::move (*song));
- ok = true;
- }
- const auto& song = loader.getSong();
- for (int t = 1; ok && t < (int) song.mixer.size(); ++t)
- {
- if (std::none_of (song.channels.begin(), song.channels.end(), [t] (const lynx::ChannelDef& c) { return c.mixerTrack == t; }))
- continue;
- const auto file = base.getSiblingFile (base.getFileNameWithoutExtension() + " - " + juce::String (t) + ".wav");
- lynx::ExportSettings settings;
- lynx::ExportJob job (lynx::makeBounceSong (song, t), settings, file);
- if (job.run ({}, error))
- {
- ++written;
- report << file.getFileName() << " peak=" << job.getPeak() << "\n";
- }
- }
- }
- report << "stems=" << written << "\n";
- juce::File (args[i + 2].unquoted() + ".txt").replaceWithText (report);
- setApplicationReturnValue (written > 0 ? 0 : 1);
- quit();
- return;
- }
- // --export-als <in.lynx|.flp|.als> <folder> [--live11] [--reference] [--scan]: "<folder>/<name> Project/<name>.als" (round 175a)
- if (args.contains ("--export-als"))
- {
- const auto i = args.indexOf ("--export-als");
- runAlsExport (args[i + 1].unquoted(), args[i + 2].unquoted(), args.contains ("--live11"), args.contains ("--reference"));
- return;
- }
- // --gamepadshot <prefix> (round 184a, S16): the game controller's hints overlay and the MIDI settings page with
- // the option on, offscreen, plus the poller fed fake pad states ("<prefix>-gamepad.txt")
- if (args.contains ("--gamepadshot"))
- {
- runGamepadShot (args[args.indexOf ("--gamepadshot") + 1].unquoted());
- return;
- }
- // --export-bundle <in.lynx|.flp|.als> <folder> [--zip] [--no-mixdown] [--shot <prefix>] (round 184a, S9): File ›
- // Export › "For other apps..." without the window; the report goes to "<folder>/export-bundle.txt"
- if (args.contains ("--export-bundle"))
- {
- const auto i = args.indexOf ("--export-bundle");
- runBundleExport (args[i + 1].unquoted(), args[i + 2].unquoted(), args.contains ("--zip"), ! args.contains ("--no-mixdown"),
- args.contains ("--shot") ? args[args.indexOf ("--shot") + 1].unquoted() : juce::String());
- return;
- }
- if (args.contains ("--export-flp"))
- {
- const auto i = args.indexOf ("--export-flp");
- runFlExport (args[i + 1].unquoted(), args[i + 2].unquoted(), args.contains ("--substitute"));
- return;
- }
- if (args.contains ("--export"))
- {
- const auto i = args.indexOf ("--export");
- const auto insert = args.contains ("--insert") ? args[args.indexOf ("--insert") + 1].getIntValue() : 0;
- runExport (args[i + 1].unquoted(), args[i + 2].unquoted(), args.contains ("--pattern"), insert);
- return;
- }
- if (args.contains ("--render"))
- {
- const auto i = args.indexOf ("--render");
- runRender (args[i + 1].unquoted(), args[i + 2].unquoted(), args[i + 3].getDoubleValue());
- return;
- }
- // session breadcrumb: a fail-fast (no crash handler runs) still leaves the last steps behind (round 111)
- uncleanLastStep = collectUncleanSessions();
- sessionsFolder().createDirectory();
- lynx::crashguard::beginSession (
- sessionsFolder().getChildFile ("session-" + juce::String (lynx::crashguard::processId()) + ".txt").getFullPathName().toStdString(),
- ("LYNX session\nversion=" + getApplicationVersion() + "\npid=" + juce::String (lynx::crashguard::processId())
- + "\nstart=" + juce::String ((juce::int64) lynx::crashguard::processStartTime())
- + "\nstarted=" + juce::Time::getCurrentTime().toISO8601 (true) + "\n").toStdString());
- startHangWatch();
- // LYNX_PROFILE_MAIN=<file> (round 174f): the message thread sampled every millisecond, 5-second windows
- if (const auto profile = juce::SystemStats::getEnvironmentVariable ("LYNX_PROFILE_MAIN", {}); profile.isNotEmpty())
- lynx::crashguard::startMainProfiler (profile.toStdString());
- startupTrace.mark ("initialise (normal start)");
- if (startupTrace.on)
- lynx::startupMark = startupMarkHook;
- juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
- lynx::themeui::loadSaved(); // the user's theme (Options › Theme, round 162d)
- startupOptions = lynx::StartupOptions::load();
- lynx::registerFileTypes();
- startupTrace.mark ("options + file types");
- // Double-clicking a .lynx/.flp opens LYNX with the file as an argument; a path typed in a terminal may be relative
- // (D#92, round 180a: it was ignored, leaving the blank project with no message). A missing file gets "Could not open".
- if (args.size() > 0 && lynx::safety::isFileArgument (args[0].unquoted().toStdString()))
- fileToOpen = juce::File::getCurrentWorkingDirectory().getChildFile (args[0].unquoted());
- // LYNX_TEST_MODE=1 LYNX --open-event-test <ms> <file>: the file arrives the way macOS's Finder delivers it (a Linux
- // or Windows run can exercise that path): 0 ms = at once, before the window exists
- if (lynx::platform::testMode() && args[0] == "--open-event-test" && args.size() > 2)
- {
- const auto file = args[2].unquoted().quoted();
- if (args[1].getIntValue() == 0)
- anotherInstanceStarted (file);
- else
- juce::Timer::callAfterDelay (args[1].getIntValue(), [this, file] { anotherInstanceStarted (file); });
- }
- // LYNX --opentime project.(flp|lynx)|- report.txt [idle seconds] (round 165i): the normal start-up (splash, audio
- // device, window) opens the project, waits until it is loaded and LYNX has gone quiet, measures the idle CPU and
- // memory, writes the times and quits normally (a benchmark that killed LYNX left "closed unexpectedly" behind)
- if (args.contains ("--opentime"))
- {
- const auto i = args.indexOf ("--opentime");
- const auto project = args[i + 1].unquoted();
- fileToOpen = project != "-" && juce::File::isAbsolutePath (project) ? juce::File (project) : juce::File();
- openTimeReport = juce::File (args[i + 2].unquoted());
- if (args.size() > i + 3 && ! args[i + 3].startsWith ("--"))
- openTimeIdleSeconds = juce::jlimit (1, 120, args[i + 3].getIntValue());
- }
- if (! startupOptions.splash)
- {
- startEngine();
- createMainWindow();
- mainWindow->reveal();
- showUncleanNotice();
- startupTrace.mark ("window revealed");
- openStartupFile();
- startupTrace.mark ("startup file opened");
- startOpenTimeProbe();
- startUpdateCheck();
- juce::MessageManager::callAsync ([] { startupTrace.mark ("first message loop turn"); });
- return;
- }
- // the splash first, so it is on screen while the audio device opens; the main window is built
- // once the pepper has landed (the scene is still for a moment then) and shown when the splash ends
- splash = std::make_unique<lynx::SplashScreen>();
- startupTrace.mark ("splash made");
- splash->showOnDesktop();
- startupTrace.mark ("splash on the desktop");
- juce::Timer::callAfterDelay (40, [this] {
- startEngine();
- if (splash == nullptr) // quit meanwhile
- return;
- splash->setStatus (lynx::tr ("Loading the workspace..."));
- splash->startClock();
- // the minimum counts from the process start (the audio device took part of it already)
- splashDuration = lynx::SplashScreen::remainingDuration (startupTrace.seconds());
- splash->setBarDuration (splashDuration);
- juce::Timer::callAfterDelay (1050, [this] {
- if (splash == nullptr || engine == nullptr)
- return;
- createMainWindow();
- const auto wait = juce::jmax (0.0, splashDuration - splash->getElapsed());
- juce::Timer::callAfterDelay ((int) (wait * 1000.0), [this] {
- if (splash == nullptr || mainWindow == nullptr)
- return;
- mainWindow->reveal();
- startupTrace.mark ("window revealed (after the splash)");
- splash->toFront (false);
- splash->finish ([this] { splash = nullptr; });
- showUncleanNotice();
- openStartupFile();
- startupTrace.mark ("startup file opened");
- startOpenTimeProbe();
- startUpdateCheck();
- juce::MessageManager::callAsync ([] { startupTrace.mark ("first message loop turn"); });
- // first run: language, audio, plugin folders (FL Studio's included) and a background scan
- if (! lynx::setupWizardDone() && lynx::platform::testMode())
- lynx::platform::testModeLog ("setup wizard");
- else if (! lynx::setupWizardDone())
- mainWindow->showSetupWizard();
- });
- });
- });
- }
- void startEngine()
- {
- startupTrace.mark ("before the audio engine");
- engine = std::make_unique<lynx::AudioEngine>();
- lynx::videoview::install (*engine); // (Fruity Video Player channels: their sound tracks)
- startupTrace.mark ("audio engine + device");
- crashEngine = engine.get();
- lynx::crashreporter::watchAudioDevice (engine->getDeviceManager()); // (the session file names the device: crash reports)
- addDriverFileDeviceType();
- if (startupOptions.sound)
- {
- // Options › Theme › Startup sound (issue #12): the user's file, else (or when it can't be read) LYNX's own
- std::shared_ptr<const lynx::SampleData> sound;
- if (const auto& own = lynx::themeui::current().startupSound; ! own.empty() && juce::File (juce::String::fromUTF8 (own.c_str())).existsAsFile())
- sound = engine->getSampleLibrary().load (juce::String::fromUTF8 (own.c_str()));
- engine->previewSample (sound != nullptr ? sound : lynx::makeStartupSample());
- }
- startupTrace.mark ("startup sound");
- // a project given on the command line: its slow plugin modules (a Waves shell) start now, on their own
- // thread, while the splash and the main window come up (round 121)
- if (fileToOpen.hasFileExtension ("flp"))
- if (juce::MemoryBlock data; fileToOpen.loadFileAsData (data))
- try
- {
- engine->getPluginHost().startModulesFor (lynx::flpForeignPlugins (flp::parseProject ({ static_cast<const std::uint8_t*> (data.getData()), data.getSize() })));
- startupTrace.mark ("plugin modules started ahead");
- }
- catch (const flp::Error&)
- {
- }
- }
- void createMainWindow()
- {
- mainWindow = std::make_unique<MainWindow> ("LYNX SHARE", *engine); // the brand; getApplicationName() stays "LYNX" (an id: instance lock, X11 WM_CLASS, ALSA client)
- lynx::setMainWindowForOwnership (mainWindow.get());
- lynx::applyRenderingChoice (*mainWindow); // (GPU rendering off: GDI; round 157a)
- lynx::startRenderingWatch();
- startupTrace.mark ("main window built");
- }
- // the previous run ended without closing (see collectUncleanSessions): say so once, with its last step — and, as
- // Settings › General › "Crash reports" says (round 159), ask whether to send a report, send it unasked, or not
- void showUncleanNotice()
- {
- if (lynx::platform::testMode()) // LYNX_TEST_MODE: no prompt, no report sent (written to test-mode.log)
- {
- if (uncleanLastStep.isNotEmpty())
- lynx::platform::testModeLog ("\"closed unexpectedly\" notice (last step: " + uncleanLastStep + ")");
- return;
- }
- if (uncleanLastStep.isEmpty())
- {
- lynx::crashreporter::retryPending(); // (reports an earlier run could not send: once more)
- return;
- }
- auto message = lynx::tr ("The last session ended without closing normally. Last step: {0}. Backup copies of your project are in "
- "LYNX SHARE's autosave folder; details in crash-history.log.",
- { uncleanLastStep });
- uncleanLastStep.clear();
- const auto cause = uncleanCause();
- // round 157a: a plugin's editor was opening — it crashed (often in the graphics driver, inside the plugin's own
- // OpenGL window): offer to keep that plugin in its own process, where a crash takes only the plugin down
- juce::String separatePlugin;
- if (cause.editorPlugin.isNotEmpty() && ! lynx::pluginSandboxEnabled() && ! lynx::pluginAlwaysSeparate (cause.editorPlugin))
- separatePlugin = cause.editorPlugin;
- // LYNX's own drawing crashed in the graphics driver (Direct2D / Direct3D): draw with the CPU from now on
- else if (cause.gpuDriver && lynx::gpuRenderingEnabled())
- {
- lynx::setGpuRenderingEnabled (false);
- message << "\n\n"
- << lynx::tr ("The crash was in the graphics driver ({0}). LYNX SHARE now draws its windows without the GPU; you can turn GPU "
- "rendering back on in Options > General settings (after a driver update, for example).",
- { cause.driverModule });
- }
- // round 165e: the Visualizer's GPU view was drawing when the session ended (a driver crash, a hang, the machine
- // going down): the Visualizer draws with the 2D renderer from now on (its GPU button turns it back on)
- for (int i = uncleanSteps.size(); --i >= 0;)
- {
- if (uncleanSteps[i].contains (lynx::visualgl::stopNote))
- break;
- if (uncleanSteps[i].contains (lynx::visualgl::startNote))
- {
- if (lynx::visualgl::enabled())
- {
- lynx::visualgl::setEnabled (false);
- message << "\n\n"
- << lynx::tr ("The Visualizer was drawing with the GPU (OpenGL) when it happened. It now draws without the GPU; its GPU "
- "button turns it back on.");
- }
- break;
- }
- }
- const auto session = lynx::crashreporter::parseSession (uncleanSessionText);
- auto* devices = engine != nullptr ? &engine->getDeviceManager() : nullptr;
- const auto action = lynx::crashreport::actionFor (lynx::crashreporter::consent());
- lynx::crashreporter::retryPending();
- if (action == lynx::crashreport::Action::askUser)
- {
- if (separatePlugin.isNotEmpty())
- message << "\n\n"
- << lynx::tr ("It happened while the window of {0} was opening{1}.",
- { separatePlugin, cause.gpuDriver ? lynx::tr (" (in the graphics driver, {0})", { cause.driverModule }) : juce::String() });
- lynx::crashreporter::showStartupDialog (session, message, separatePlugin, [separatePlugin] { lynx::setPluginAlwaysSeparate (separatePlugin, true); },
- devices);
- return;
- }
- if (action == lynx::crashreport::Action::sendSilently)
- {
- const auto input = lynx::crashreporter::makeInput (session, session.kind(), devices);
- lynx::crashreporter::send (lynx::crashreporter::buildJson (input, false), juce::String::fromUTF8 (input.id.c_str()));
- message << "\n\n" << lynx::tr ("A crash report is being sent to help fix it (Options > General settings > Crash reports).");
- }
- if (separatePlugin.isNotEmpty())
- {
- juce::AlertWindow::showOkCancelBox (
- juce::MessageBoxIconType::WarningIcon, lynx::tr ("LYNX SHARE closed unexpectedly"),
- message + "\n\n"
- + lynx::tr ("It happened while the window of {0} was opening{1}. Run {0} in a separate process from now on? If it "
- "crashes again, only the plugin stops and LYNX SHARE keeps running (Plugin wrapper menu: \"Always run in a "
- "separate process\").",
- { separatePlugin, cause.gpuDriver ? lynx::tr (" (in the graphics driver, {0})", { cause.driverModule }) : juce::String() }),
- lynx::tr ("Run separately"), lynx::tr ("No"), nullptr,
- juce::ModalCallbackFunction::create ([separatePlugin] (int result) {
- if (result != 0)
- lynx::setPluginAlwaysSeparate (separatePlugin, true);
- }));
- return;
- }
- juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::WarningIcon, lynx::tr ("LYNX SHARE closed unexpectedly"), message);
- }
- // --opentime: after the start-up file was handed to the window
- void startOpenTimeProbe()
- {
- if (openTimeReport == juce::File())
- return;
- struct Probe final : juce::Timer
- {
- LynxApplication& app;
- juce::File report, project;
- int idleSeconds;
- int phase = 0; // 0 loading, 1 settling, 2 idle measurement
- double revealedS = 0.0, loadedS = -1.0, settledS = -1.0, cpuAtLoaded = 0.0;
- double lastCpu = 0.0, lastT = 0.0, quietSince = -1.0, idleCpu0 = 0.0, idleT0 = 0.0;
- Probe (LynxApplication& a, juce::File r, juce::File p, int idle)
- : app (a), report (std::move (r)), project (std::move (p)), idleSeconds (idle)
- {
- revealedS = startupTrace.seconds();
- startTimer (250);
- }
- bool loaded() const
- {
- if (project == juce::File())
- return true;
- return app.mainWindow != nullptr
- && app.mainWindow->getName().containsIgnoreCase (project.getFileNameWithoutExtension());
- }
- void finish (const juce::String& result)
- {
- stopTimer();
- const auto now = startupTrace.seconds();
- const auto cpu = lynx::processCpuSeconds();
- juce::String text;
- text << "project=" << (project == juce::File() ? juce::String ("-") : project.getFullPathName()) << "\n"
- << "window_s=" << juce::String (revealedS, 3) << "\n"
- << "loaded_s=" << juce::String (loadedS, 3) << "\n"
- << "settled_s=" << juce::String (settledS, 3) << "\n"
- << "cpu_at_loaded_s=" << juce::String (cpuAtLoaded, 3) << "\n"
- << "idle_s=" << juce::String (now - idleT0, 2) << "\n"
- << "idle_cpu_pct=" << juce::String (phase == 2 && now > idleT0 ? 100.0 * (cpu - idleCpu0) / (now - idleT0) : -1.0, 1) << "\n"
- << "working_set_mb=" << juce::String ((double) lynx::toolbar::PerformanceMeter::processMemoryBytes() / 1048576.0, 0) << "\n"
- << "cpu_total_s=" << juce::String (cpu, 3) << "\n"
- << "result=" << result << "\n";
- report.replaceWithText (text);
- app.setApplicationReturnValue (result == "OK" ? 0 : 1);
- app.quit();
- }
- void timerCallback() override
- {
- const auto now = startupTrace.seconds();
- const auto cpu = lynx::processCpuSeconds();
- if (phase == 0)
- {
- if (loaded())
- {
- loadedS = now;
- cpuAtLoaded = cpu;
- phase = 1;
- lastCpu = cpu;
- lastT = now;
- }
- else if (now - revealedS > 240.0)
- finish ("TIMEOUT loading");
- return;
- }
- if (phase == 1)
- {
- // quiet = under 10 % of one core for 1.5 s (the harness's rule), at most 30 s after loading
- const auto use = now > lastT ? 100.0 * (cpu - lastCpu) / (now - lastT) : 0.0;
- lastCpu = cpu;
- lastT = now;
- if (use < 10.0)
- {
- if (quietSince < 0.0)
- quietSince = now - 0.25;
- if (now - quietSince >= 1.5)
- settledS = quietSince;
- }
- else
- quietSince = -1.0;
- if (settledS >= 0.0 || now - loadedS > 30.0)
- {
- phase = 2;
- idleCpu0 = cpu;
- idleT0 = now;
- }
- return;
- }
- if (now - idleT0 >= (double) idleSeconds)
- finish ("OK");
- }
- };
- perf = std::make_unique<Probe> (*this, openTimeReport, fileToOpen, openTimeIdleSeconds);
- }
- // round 166b: the update check of a normal start (never in --opentime and the other command-line modes), a few
- // seconds after the window is up so it never competes with the start-up; and the result of an update just installed
- void startUpdateCheck()
- {
- if (openTimeReport != juce::File())
- return;
- lynx::updater::afterStart();
- juce::Timer::callAfterDelay (3000, [] { lynx::updater::startAutomaticCheck(); });
- }
- void openStartupFile()
- {
- startupFileHandled = true;
- if (fileToOpen != juce::File() && mainWindow != nullptr)
- mainWindow->openFile (fileToOpen);
- else if (mainWindow != nullptr && openTimeReport == juce::File())
- mainWindow->getContent().openStartupProject(); // issue #123 (FL's Startup project)
- }
- void shutdown() override
- {
- parityShow.reset(); // (LYNX_PARITYSHOT_SHOW's window, before the engine it shows)
- if (relaunched || updateHelper)
- return; // the copy that ran owns the session (its crash notes stay for the next start)
- lynx::crashguard::note ("closing");
- lynx::shutdownPluginSandboxWorker();
- splash = nullptr;
- lynx::shutdownStemExtraction(); // (a separation in flight stops before its window and the engine go)
- lynx::shutdownAudioToMidi(); // (the same for a conversion to MIDI)
- if (mainWindow != nullptr && mainWindow->isVisible())
- mainWindow->saveState();
- mainWindow = nullptr; // the UI goes before the engine
- lynx::updater::shutdown(); // (a check or download in flight stops)
- crashEngine = nullptr;
- engine = nullptr;
- juce::LookAndFeel::setDefaultLookAndFeel (nullptr);
- heartbeat.stopTimer();
- lynx::crashreporter::shutdown(); // (an upload in flight gets a moment, never long)
- lynx::crashguard::stopHangWatch();
- lynx::crashguard::stopMainProfiler();
- lynx::crashguard::endSession(); // a clean exit: no breadcrumb left behind
- // everything is saved and closed: a process that loaded third-party plugins ends here, before the DLLs' own
- // teardown runs (some crash in it at exit, round 111)
- if (sandboxChild || lynx::PluginHost::pluginsWereLoaded())
- lynx::crashguard::exitNow (getApplicationReturnValue());
- }
- void systemRequestedQuit() override
- {
- if (mainWindow != nullptr)
- mainWindow->confirmDiscard ([] { juce::JUCEApplication::quit(); });
- else
- quit();
- }
- private:
- // round 157a: a frozen UI (Windows' "not responding") writes the message thread's stack to autosave\hang <time>.txt
- // and a session step, so a freeze can be told apart from a crash and located. The timer is the heartbeat.
- struct Heartbeat final : juce::Timer
- {
- void timerCallback() override { lynx::crashguard::heartbeat(); }
- } heartbeat;
- void startHangWatch()
- {
- const auto folder = lynx::platform::settingsFile ("autosave");
- folder.createDirectory();
- // keep the newest hang files only
- auto old = folder.findChildFiles (juce::File::findFiles, false, "hang *.txt");
- lynx::filesort::byTime (old, lynx::filesort::By::modificationTime, true);
- for (int i = 20; i < old.size(); ++i)
- old.getReference (i).deleteFile();
- lynx::crashguard::startHangWatch (folder.getFullPathName().replaceCharacter ('\\', '/').toStdString());
- heartbeat.startTimerHz (5);
- }
- bool sandboxChild = false;
- bool relaunched = false; // relaunchFromAsciiPath ran LYNX from its short path: this process only waited
- bool updateHelper = false; // --apply-update (round 166b)
- juce::String uncleanLastStep; // last step of a previous run that ended without closing
- // LYNX_PROFILE_DIR=<folder> LYNX --lv2scantest report.txt (Linux, issue #85): the LV2 scan's promise, with real child
- // processes. A new PluginHost per step, as every start of LYNX has. The LV2 folders of the machine are read too.
- void runLv2ScanTest (const juce::String& reportPath)
- {
- juce::String report;
- auto ok = lynx::platform::profileOverride() != juce::File();
- #if JUCE_LINUX
- const auto folder = lynx::platform::profileOverride().getChildFile ("lv2-test");
- const juce::FileSearchPath paths (folder.getFullPathName());
- const auto check = [&] (const juce::String& name, bool passed) {
- report << name << "=" << (passed ? "ok" : "FAILED") << "\n";
- ok = ok && passed;
- };
- const auto install = [&] (const juce::String& name) {
- const auto bundle = folder.getChildFile (name + ".lv2");
- bundle.createDirectory();
- bundle.getChildFile ("manifest.ttl").replaceWithText ("@prefix lv2: <http://lv2plug.in/ns/lv2core#> .\n@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .\n"
- "<urn:lynx-test:" + name + "> a lv2:Plugin ; lv2:binary <" + name + ".so> ; rdfs:seeAlso <plugin.ttl> .\n");
- bundle.getChildFile ("plugin.ttl").replaceWithText ("@prefix doap: <http://usefulinc.com/ns/doap#> .\n<urn:lynx-test:" + name + "> doap:name \"" + name + "\" .\n");
- };
- auto date = juce::Time::getCurrentTime();
- const auto touch = [&] { // the next date, whatever the file system's date resolution
- date += juce::RelativeTime::seconds (2.0);
- folder.getChildFile ("a.lv2/plugin.ttl").setLastModificationTime (date);
- };
- const auto listed = [] (lynx::PluginHost& host, const juce::String& name) {
- for (const auto& d : host.getKnownPlugins().getTypes())
- if (d.fileOrIdentifier == "urn:lynx-test:" + name)
- return true;
- return false;
- };
- const auto step = [&] (const juce::String& name, int children, const std::function<void (lynx::PluginHost&)>& prepare = {}) {
- lynx::PluginHost host (true);
- if (prepare)
- prepare (host);
- host.scan (paths, {});
- check (name, host.scanChildrenStarted() == children && listed (host, "a"));
- };
- install ("a");
- step ("first_scan_one_child", 1);
- step ("nothing_changed_no_child", 0);
- touch();
- step ("ttl_updated", 1);
- install ("b");
- step ("bundle_installed", 1);
- step ("forget_file", 1, [] (lynx::PluginHost& host) { host.forgetFile ("urn:lynx-test:a"); });
- step ("forget_all", 1, [] (lynx::PluginHost& host) { host.forgetAll(); });
- lynx::platform::settingsFile ("plugins.xml").deleteFile();
- step ("list_lost", 1);
- step ("nothing_changed_again", 0);
- // cancelled while the child works: stopped at once, and nothing is taken for done
- touch();
- setenv ("LYNX_TEST_CRASH", "lv2-batch-hang", 1);
- {
- lynx::PluginHost host (true);
- const auto started = juce::Time::getMillisecondCounter();
- host.scan (paths, [] (float, const juce::String&) { return false; });
- check ("cancel_stops_the_child", host.scanChildrenStarted() == 1 && juce::Time::getMillisecondCounter() - started < 20000);
- }
- unsetenv ("LYNX_TEST_CRASH");
- step ("described_after_cancel", 1);
- // the child dies: plugin by plugin takes over (stopped after two of them: a machine may have hundreds)
- touch();
- setenv ("LYNX_TEST_CRASH", "lv2-batch", 1);
- {
- lynx::PluginHost host (true);
- host.scan (paths, [&host] (float, const juce::String&) { return host.scanChildrenStarted() < 3; });
- check ("crash_falls_back_plugin_by_plugin", host.scanChildrenStarted() == 3);
- auto blamed = false;
- for (const auto& file : host.getKnownPlugins().getBlacklistedFiles())
- blamed = blamed || file.startsWith ("lv2-folders:");
- check ("crash_blacklists_nothing", ! blamed);
- }
- unsetenv ("LYNX_TEST_CRASH");
- step ("described_after_crash", 1);
- #endif
- juce::File (reportPath).replaceWithText (report + "result=" + (ok ? "OK" : "FAILED") + "\n");
- setApplicationReturnValue (ok ? 0 : 1);
- quit();
- }
- // LYNX.exe --selftest report.txt: renders 2 s without a sound card and writes the result.
- // Exit code 0 = audio came out, 1 = silence.
- void runSelfTest (const juce::String& reportPath, const juce::String& demoProjectPath)
- {
- lynx::AudioEngine offline (false);
- const auto peak = offline.renderOffline (2.0, 48000.0);
- const auto audioOk = peak > 0.01f && peak < 10.0f;
- // project format round trip, with accents in the name
- auto original = lynx::Song::makeDefault();
- original.channels[0].name = "Bumbo ação";
- original.playlist.push_back ({ 0, 2, 3840, 1920, 960 });
- original.mode = lynx::PlayMode::song;
- original.mixer[3].effects.push_back (lynx::makeEffectSlot (lynx::EffectKind::delay));
- original.mixer[3].effects[0].params[1] = 0.25f;
- lynx::Automation automation;
- automation.name = "Pan";
- automation.target = { lynx::AutomationTargetKind::effectParam, 3, 0, 1 };
- automation.points = { { 0, 0.25f, 0.5f }, { 3840, 1.0f, 0.0f } };
- original.automations.push_back (automation);
- lynx::Clip automationClip;
- automationClip.kind = lynx::ClipKind::automation;
- automationClip.automation = 0;
- automationClip.track = 4;
- automationClip.length = 3840;
- original.playlist.push_back (automationClip);
- original.loopStart = 960;
- original.loopEnd = 7680;
- original.playlistTracks.resize (3);
- original.playlistTracks[2].colour = 0xFF2A6FDB; // a track colour (round 90)
- { // the clip grid (round 181a)
- lynx::launcher::setClip (original, 1, 2, { 0, 0, 0, 1920, 0 });
- auto& slot = *lynx::launcher::settingsAt (*original.clipGrid, 1, 2);
- slot.name = "Clip ação";
- slot.mode = lynx::LaunchMode::toggle;
- slot.quant = lynx::LaunchQuant::eighthTriplet;
- slot.legato = true;
- slot.loop = false;
- original.clipGrid->scenes[0].name = "Intro";
- original.clipGrid->globalQuant = lynx::LaunchQuant::bars2;
- }
- original.playlistTracks[2].grouped = true; // track groups and rack filter groups (round 104)
- original.playlistTracks[1].collapsed = true;
- original.channelGroups = { "Drums", "Keys" };
- original.channels[1].group = 1;
- juce::String error;
- if (demoProjectPath.isNotEmpty()) // sample project for checking the UI with --snapshot
- lynx::ProjectFile::save (original, juce::File (demoProjectPath), error);
- const auto reloaded = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (original), error);
- const auto projectOk = reloaded && reloaded->channels.size() == original.channels.size()
- && reloaded->channels[0].name == original.channels[0].name
- && reloaded->patterns[0].notes.size() == original.patterns[0].notes.size()
- && reloaded->patterns[0].notes[3].start == original.patterns[0].notes[3].start
- && reloaded->mode == lynx::PlayMode::song && reloaded->playlist.size() == 2
- && reloaded->clipGrid.has_value() && reloaded->clipGrid->globalQuant == lynx::LaunchQuant::bars2
- && reloaded->clipGrid->scenes.size() == 3 && reloaded->clipGrid->scenes[0].name == "Intro"
- && lynx::launcher::clipAt (*reloaded->clipGrid, 1, 2) != nullptr
- && [&reloaded] {
- auto grid = *reloaded->clipGrid;
- const auto* slot = lynx::launcher::settingsAt (grid, 1, 2);
- return slot != nullptr && slot->name == "Clip ação" && slot->mode == lynx::LaunchMode::toggle
- && slot->quant == lynx::LaunchQuant::eighthTriplet && slot->legato && ! slot->loop;
- }()
- && reloaded->playlist[1].kind == lynx::ClipKind::automation && reloaded->playlist[1].automation == 0
- && reloaded->automations.size() == 1 && reloaded->automations[0].target == automation.target
- && reloaded->automations[0].points.size() == 2 && reloaded->automations[0].points[0].tension == 0.5f
- && reloaded->automations[0].points[1].tick == 3840
- && reloaded->loopStart == 960 && reloaded->loopEnd == 7680
- && reloaded->playlistTracks.size() == 3 && reloaded->playlistTracks[2].colour == 0xFF2A6FDB
- && reloaded->playlistTracks[1].colour == 0
- && reloaded->playlistTracks[2].grouped && reloaded->playlistTracks[1].collapsed && ! reloaded->playlistTracks[1].grouped
- && reloaded->channelGroups == original.channelGroups && reloaded->channels[1].group == 1 && reloaded->channels[0].group == -1
- && reloaded->playlist[0].offset == 960 && reloaded->playlist[0].track == 2
- && reloaded->mixer[3].effects.size() == 1
- && reloaded->mixer[3].effects[0].kind == lynx::EffectKind::delay
- && reloaded->mixer[3].effects[0].params[1] == 0.25f;
- // round trip of the newer features: synth/sampler with modulation, EQs, utility, markers
- auto rich = lynx::Song::makeDefault();
- auto& synth = rich.channels[4].synth;
- synth.osc[1] = { lynx::Waveform::square, -1, 7.0f, 0.4f, 5, -0.25f };
- synth.filterType = 2;
- synth.mono = true;
- synth.portaBeats = 0.125f;
- synth.am = true;
- synth.filterEnv = { 3.0f, 0.01f, 0.02f, 0.3f, 0.25f, 0.4f };
- synth.lfo[lynx::lfoPitch] = { 0.5f, 0.25f, true, 1, 0.1f, 0.2f };
- auto& sampler = rich.channels[0].sampler;
- sampler.cutoff = 1200.0f;
- sampler.resonance = 0.3f;
- sampler.filterType = 1;
- sampler.pitchEnv = { -12.0f, 0.0f, 0.0f, 0.05f, 0.0f, 0.1f };
- sampler.lfo[lynx::lfoVolume] = { 0.5f, 0.5f, false, 2, 0.0f, 0.0f };
- rich.mixer[2].eq.gainDb = { 3.0f, -2.5f, 1.0f };
- rich.mixer[2].eq.hz[1] = 2200.0f;
- auto peqSlot = lynx::makeEffectSlot (lynx::EffectKind::parametricEq);
- peqSlot.params[(std::size_t) lynx::peq::param (2, 2)] = lynx::peq::gainValue (6.0);
- peqSlot.params[(std::size_t) (lynx::peq::slopeParam + 0)] = lynx::peq::slopeValue (3);
- rich.mixer[2].effects.push_back (peqSlot);
- auto utilitySlot = lynx::makeEffectSlot (lynx::EffectKind::utility);
- utilitySlot.params[1] = 0.2f;
- rich.mixer[2].effects.push_back (utilitySlot);
- auto vocodexSlot = lynx::makeEffectSlot (lynx::EffectKind::vocodex); // FL's raw state travels as base64
- for (int i = 0; i < 300; ++i)
- vocodexSlot.state.push_back ((std::uint8_t) (i * 37));
- vocodexSlot.sidechain = 1;
- vocodexSlot.sidechain2 = 2;
- rich.mixer[3].effects.push_back (vocodexSlot);
- rich.addMarker ({ 3840, "Refrão", 0, 4 });
- rich.addMarker ({ 7680, {}, 7, 8 });
- const auto richBack = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (rich), error);
- auto paramsClose = [] (const lynx::EffectParams& a, const lynx::EffectParams& b) {
- for (std::size_t i = 0; i < a.size(); ++i)
- if (std::abs (a[i] - b[i]) > 1.0e-3f)
- return false;
- return true;
- };
- const auto richOk = richBack && richBack->channels[4].synth == synth && richBack->channels[0].sampler == sampler
- && richBack->mixer[2].eq == rich.mixer[2].eq && richBack->mixer[2].effects.size() == 2
- && richBack->mixer[2].effects[0].kind == lynx::EffectKind::parametricEq
- && paramsClose (richBack->mixer[2].effects[0].params, peqSlot.params)
- && richBack->mixer[2].effects[1].kind == lynx::EffectKind::utility
- && paramsClose (richBack->mixer[2].effects[1].params, utilitySlot.params)
- && richBack->mixer[3].effects.size() == 1 && richBack->mixer[3].effects[0].kind == lynx::EffectKind::vocodex
- && richBack->mixer[3].effects[0].state == vocodexSlot.state && richBack->mixer[3].effects[0].sidechain2 == 2
- && richBack->markers() == rich.markers();
- // issue #96's per-plugin option: saved only when on; old projects (no field) read as off
- bool hostKeysOk = false;
- {
- auto song = lynx::Song::makeDefault();
- lynx::ChannelDef plugin;
- plugin.instrument = lynx::InstrumentKind::plugin;
- plugin.plugin.id = "x";
- song.channels.push_back (plugin);
- const auto channel = song.channels.size() - 1;
- const auto off = lynx::ProjectFile::toJson (song);
- song.channels[channel].plugin.allowHostKeys = true;
- song.channels[channel].plugin.hostKeysFirst = true;
- const auto on = lynx::ProjectFile::toJson (song);
- const auto offBack = lynx::ProjectFile::fromJson (off, error);
- const auto onBack = lynx::ProjectFile::fromJson (on, error);
- hostKeysOk = ! off.contains ("allowHostKeys") && on.contains ("allowHostKeys") && offBack && onBack
- && ! offBack->channels[channel].plugin.allowHostKeys && onBack->channels[channel].plugin.allowHostKeys
- && ! off.contains ("hostKeysFirst") && ! offBack->channels[channel].plugin.hostKeysFirst && onBack->channels[channel].plugin.hostKeysFirst;
- }
- // hardware output targets (REA round 156): saved only when set; old projects (no field) keep the defaults
- bool hwOutOk = false;
- {
- auto song = lynx::Song::makeDefault();
- const auto plain = lynx::ProjectFile::toJson (song);
- song.mixer[0].outputChannel = lynx::outputNone;
- song.mixer[1].outputChannel = 2;
- song.mixer[1].outputMode = lynx::OutputMode::monoRight;
- song.mixer[2].outputChannel = 6;
- song.mixer[3].outputChannel = 4;
- song.mixer[3].outputMode = lynx::OutputMode::monoSum;
- const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), error);
- const auto plainBack = lynx::ProjectFile::fromJson (plain, error);
- hwOutOk = back && back->mixer[0].outputChannel == lynx::outputNone && back->mixer[1].outputChannel == 2
- && back->mixer[1].outputMode == lynx::OutputMode::monoRight && back->mixer[2].outputChannel == 6
- && back->mixer[2].outputMode == lynx::OutputMode::stereo && back->mixer[3].outputMode == lynx::OutputMode::monoSum
- && back->mixer[4].outputChannel == lynx::outputDefault && ! plain.contains ("\"output\"") && plainBack
- && plainBack->mixer[0].outputChannel == lynx::outputDefault && plainBack->mixer[1].outputChannel == lynx::outputDefault;
- }
- // round 168j: FL's icons (channel / mixer track / playlist track), PDC Automatic / Compensate automations, Time
- // settings, scale highlighting and data folder — saved only when set, old projects load with FL's defaults
- bool flp168jOk = false;
- {
- auto song = lynx::Song::makeDefault();
- const auto plain = lynx::ProjectFile::toJson (song);
- song.channels[0].icon = 75;
- song.mixer[2].icon = 71;
- song.playlistTracks.resize (3);
- song.playlistTracks[2].icon = 30;
- song.autoPdc = false;
- song.compensateAutomations = false;
- song.timeSignatureMode = true;
- song.scaleHighlight = { 10, 5 };
- song.dataFolder = "D:\\Projects\\data";
- const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), error);
- const auto plainBack = lynx::ProjectFile::fromJson (plain, error);
- flp168jOk = back && back->channels[0].icon == 75 && back->mixer[2].icon == 71 && back->playlistTracks.size() >= 3
- && back->playlistTracks[2].icon == 30 && ! back->autoPdc && ! back->compensateAutomations && back->timeSignatureMode
- && back->scaleHighlight == song.scaleHighlight && back->dataFolder == song.dataFolder && plainBack && plainBack->autoPdc
- && plainBack->compensateAutomations && ! plainBack->timeSignatureMode && plainBack->scaleHighlight == lynx::Song::ScaleHighlight {}
- && plainBack->dataFolder.empty() && plainBack->channels[0].icon == 0 && ! plain.contains ("\"icon\"")
- && ! plain.contains ("autoPdc") && ! plain.contains ("scaleHighlight");
- }
- // round 180d: clip fades take FL's S curve; a project saved before that keeps its straight fades, also after another
- // save, and a clip made in it takes the S curve. FL's fade tensions and stretch mode and PITCH survive a save.
- // issue #122: playlist tracks linked to inserts (audio) and channels (instrument) survive save, load and save
- // again byte for byte (they were read before the mixer and fell back to Unassigned)
- bool trackModes122Ok = false;
- {
- auto song = lynx::Song::makeDefault();
- song.playlistTracks.resize (6);
- song.playlistTracks[1].mode = lynx::PlaylistTrackMode::audio;
- song.playlistTracks[1].mixerTrack = 3;
- song.playlistTracks[4].mode = lynx::PlaylistTrackMode::audio;
- song.playlistTracks[4].mixerTrack = (int) song.mixer.size() - 1;
- song.playlistTracks[5].mode = lynx::PlaylistTrackMode::instrument;
- song.playlistTracks[5].channel = 1;
- song.playlistTracks[5].mixerTrack = 2;
- const auto json = lynx::ProjectFile::toJson (song, false);
- const auto loaded = lynx::ProjectFile::fromJson (json, error);
- const auto again = loaded ? lynx::ProjectFile::toJson (*loaded, false) : juce::String();
- trackModes122Ok = loaded && json.contains ("playlistTrackModes") && again == json && loaded->playlistTracks.size() >= 6
- && loaded->playlistTracks[1].mode == lynx::PlaylistTrackMode::audio && loaded->playlistTracks[1].mixerTrack == 3
- && loaded->playlistTracks[4].mode == lynx::PlaylistTrackMode::audio
- && loaded->playlistTracks[4].mixerTrack == (int) song.mixer.size() - 1
- && loaded->playlistTracks[5].mode == lynx::PlaylistTrackMode::instrument && loaded->playlistTracks[5].channel == 1;
- }
- bool clipFades180dOk = false;
- {
- auto song = lynx::Song::makeDefault();
- lynx::Clip faded;
- faded.kind = lynx::ClipKind::audio;
- faded.channel = 0;
- faded.length = lynx::ppq * 8;
- faded.fadeIn = lynx::ppq;
- faded.fadeOutTension = -812.933f;
- faded.fadeOut = lynx::ppq * 2;
- lynx::Clip plainClip = faded;
- plainClip.fadeIn = plainClip.fadeOut = 0;
- plainClip.fadeOutTension = 0.0f;
- plainClip.start = lynx::ppq * 16;
- song.playlist = { faded, plainClip };
- song.channels[0].sampler.flStretchMode = 5;
- song.channels[0].sampler.flStretchPitch = 247;
- const auto json = lynx::ProjectFile::toJson (song);
- const auto current = lynx::ProjectFile::fromJson (json, error);
- const auto oldJson = json.replace ("\"clipFadesPerClip\"", "\"clipFadesOther\"");
- auto old = lynx::ProjectFile::fromJson (oldJson, error);
- auto resaved = old;
- if (resaved)
- {
- auto added = faded;
- added.start = lynx::ppq * 32;
- added.linearFades = 0;
- resaved->playlist.push_back (added);
- resaved = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (*resaved), error);
- }
- clipFades180dOk = current && old && resaved && json.contains ("clipFadesPerClip") && ! oldJson.contains ("clipFadesPerClip")
- && current->playlist.size() == 2 && ! current->playlist[0].linearFades
- && current->playlist[0].fadeOutTension == -812.933f && ! current->playlist[1].linearFades
- && current->channels[0].sampler.flStretchMode == 5 && current->channels[0].sampler.flStretchPitch == 247
- && old->playlist.size() == 2 && old->playlist[0].linearFades && ! old->playlist[1].linearFades
- && resaved->playlist.size() == 3 && resaved->playlist[0].linearFades && ! resaved->playlist[1].linearFades
- && ! resaved->playlist[2].linearFades && resaved->playlist[0].fadeOutTension == -812.933f;
- }
- // FL's legacy Pattern Blocks (round 170f): the option and every arrangement's blocks are saved; a project without
- // them has neither in its file and loads with the option off
- bool blocksOk = false;
- {
- auto song = lynx::Song::makeDefault();
- const auto plain = lynx::ProjectFile::toJson (song);
- song.patternBlocksOn = true;
- lynx::patternblocks::place (song, 0, 0);
- lynx::patternblocks::place (song, 0, 4 * 4 * lynx::ppq);
- song.addArrangement ("Second");
- lynx::patternblocks::place (song, 0, 2 * 4 * lynx::ppq);
- song.selectArrangement (0);
- const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), error);
- const auto plainBack = lynx::ProjectFile::fromJson (plain, error);
- blocksOk = back && back->patternBlocksOn && back->blocks == song.blocks && song.blocks.size() == 2
- && back->arrangements.size() == 2 && back->arrangements[1].blocks == song.arrangements[1].blocks
- && song.arrangements[1].blocks.size() == 1 && back->songLength() == song.songLength() && plainBack
- && ! plainBack->patternBlocksOn && plainBack->blocks.empty() && ! plain.contains ("blocks")
- && ! plain.contains ("patternBlocks");
- }
- // comping (round 177c): a comp's equal-power crossfades (Clip::fadeCurve) and the crossfade length are saved; a
- // project without them has neither in its file
- bool compOk = false;
- {
- auto song = lynx::Song::makeDefault();
- const auto plain = lynx::ProjectFile::toJson (song);
- lynx::ChannelDef take;
- take.instrument = lynx::InstrumentKind::audioClip;
- take.samplePath = "take.wav";
- song.channels.push_back (take);
- lynx::Clip a;
- a.kind = lynx::ClipKind::audio;
- a.channel = (int) song.channels.size() - 1;
- a.length = lynx::ppq;
- a.fadeOut = 20;
- a.fadeCurve = 2;
- auto b = a;
- b.start = lynx::ppq - 20;
- b.fadeOut = 0;
- b.fadeIn = 20;
- b.fadeCurve = 1;
- // round 180d's FL fade fields (indices 17..20) and the comp curve (index 21) on one clip, all kept
- auto c = a;
- c.start = 4 * lynx::ppq;
- c.fadeIn = 30;
- c.fadeInTension = -0.75f;
- c.fadeOutTension = 0.5f;
- c.linearFades = 2;
- c.flFadeFlags = 0x1234u;
- c.fadeCurve = 3;
- song.playlist = { a, b, c };
- song.compCrossfadeMs = 12.5f;
- song.playlistTracks.resize (2);
- song.playlistTracks[0].compTrack = true;
- song.playlistTracks[1].grouped = true;
- const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), error);
- const auto plainBack = lynx::ProjectFile::fromJson (plain, error);
- const auto* both = back && back->playlist.size() == 3 ? &back->playlist[2] : nullptr;
- compOk = back && back->playlist.size() == 3 && back->playlist[0].fadeCurve == 2 && back->playlist[1].fadeCurve == 1
- && both != nullptr && both->fadeCurve == 3 && both->fadeInTension == -0.75f && both->fadeOutTension == 0.5f
- && both->linearFades == 2 && both->flFadeFlags == 0x1234u && both->fadeIn == 30
- && back->playlist[1].fadeIn == 20 && back->compCrossfadeMs == 12.5f && back->playlistTracks[0].compTrack && ! back->playlistTracks[1].compTrack && plainBack
- && plainBack->compCrossfadeMs == lynx::Song::defaultCompCrossfadeMs && ! plain.contains ("compCrossfadeMs") && ! plain.contains ("playlistCompTracks");
- }
- // Misc › Mono / Porta / Slide on every generator (round 168l): kept in the file; a project saved before (an
- // imported engine's flags in its synth settings) gets them back, a Max polyphony of 1 is not Mono
- bool polyOk = false;
- {
- auto song = lynx::Song::makeDefault();
- lynx::ChannelDef osc;
- osc.instrument = lynx::InstrumentKind::threeosc;
- osc.misc.mono = osc.misc.porta = true;
- osc.misc.portaBeats = 0.25f;
- song.channels.push_back (osc);
- auto old = osc;
- old.misc = {};
- old.synth.mono = old.synth.porta = true;
- old.synth.portaBeats = 0.5f;
- song.channels.push_back (old);
- old.maxPolyphony = 1;
- song.channels.push_back (old);
- const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), error);
- const auto n = song.channels.size();
- polyOk = back && back->channels.size() == n && back->channels[n - 3].misc.mono && back->channels[n - 3].misc.porta
- && std::abs (back->channels[n - 3].misc.portaBeats - 0.25f) < 1e-6f && back->channels[n - 2].misc.mono
- && back->channels[n - 2].misc.porta && std::abs (back->channels[n - 2].misc.portaBeats - 0.5f) < 1e-6f
- && ! back->channels[n - 1].misc.mono && back->channels[n - 1].maxPolyphony == 1
- && ! back->channels[4].misc.mono; // (the LYNX Synth keeps its own flags)
- }
- // FL's track latency (REA round 165f-mixer): manual ms, bypass mode and master compensation saved only when set
- bool latencyOk = false;
- {
- auto song = lynx::Song::makeDefault();
- const auto plain = lynx::ProjectFile::toJson (song);
- song.mixer[1].latencyMs = -20.0f;
- song.mixer[2].latencyMs = 12.5f;
- song.mixer[2].latencyBypass = lynx::LatencyBypass::always;
- song.mixer[3].latencyBypass = lynx::LatencyBypass::whenRecordingOrStopped;
- song.mixer[3].compensateMasterLatency = false;
- const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), error);
- latencyOk = back && back->mixer[1].latencyMs == -20.0f && back->mixer[2].latencyMs == 12.5f
- && back->mixer[2].latencyBypass == lynx::LatencyBypass::always
- && back->mixer[3].latencyBypass == lynx::LatencyBypass::whenRecordingOrStopped && ! back->mixer[3].compensateMasterLatency
- && back->mixer[4].latencyMs == 0.0f && back->mixer[4].compensateMasterLatency
- && ! plain.contains ("latencyMs") && ! plain.contains ("latencyBypass") && ! plain.contains ("compensateMaster");
- }
- // LYNX substitutes (round 98): a missing plugin's slot plays a built-in equivalent and the project keeps the
- // original reference byte for byte (.flp record and LYNX plugin state)
- bool substituteOk = false;
- {
- auto song = lynx::Song::makeDefault();
- lynx::ForeignPlugin vv; // an .flp VST3 record (ValhallaVintageVerb's class ID), opaque state
- vv.format = lynx::ForeignPlugin::Format::vst3;
- const std::uint8_t cid[] = { 0x76, 0x54, 0x53, 0x56, 0x65, 0x65, 0x76, 0x33, 0x61, 0x6c, 0x68, 0x61, 0x6c, 0x6c, 0x61, 0x76 };
- std::copy (std::begin (cid), std::end (cid), vv.classId.begin());
- vv.hasClassId = true;
- vv.name = "ValhallaVintageVerb";
- vv.path = "C:\\x\\ValhallaVintageVerb.vst3";
- for (int i = 0; i < 777; ++i)
- vv.state.push_back ((std::uint8_t) (i * 13 + 1));
- lynx::EffectSlot fromFlp;
- fromFlp.kind = lynx::EffectKind::plugin;
- fromFlp.plugin.foreign = vv;
- lynx::EffectSlot fromLynx; // a LYNX reference whose plugin isn't installed here
- fromLynx.kind = lynx::EffectKind::plugin;
- fromLynx.plugin.id = "VST3-FabFilter Pro-Q 3-1a2b3c4d-5e6f7a8b";
- fromLynx.plugin.name = "FabFilter Pro-Q 3";
- fromLynx.plugin.state = "AAECAwQFBgcICQ==";
- const auto flpRef = fromFlp.plugin, lynxRef = fromLynx.plugin;
- song.mixer[1].effects = { fromFlp, fromLynx };
- const auto substitutesOn = lynx::pluginSubstitutesEnabled();
- const auto changed = offline.getPluginHost().applySubstitutes (song);
- auto& fx = song.mixer[1].effects;
- // only the LYNX reference is substituted here (an .flp record is the import's job); do the .flp one directly
- const auto flpSubstituted = lynx::substituteEffectSlot (fx[0], lynx::pluginIdentity (vv));
- const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), error);
- substituteOk = flpSubstituted && fx[0].kind == lynx::EffectKind::epochVerb
- && (! substitutesOn || (changed == 1 && fx[1].kind == lynx::EffectKind::facetEq && fx[1].substituteFor == lynxRef))
- && back && back->mixer[1].effects.size() == 2 && back->mixer[1].effects[0].kind == lynx::EffectKind::epochVerb
- && back->mixer[1].effects[0].substituteFor == flpRef && back->mixer[1].effects[0].substituteFor.foreign.state == vv.state
- && back->mixer[1].effects[1].kind == fx[1].kind && back->mixer[1].effects[1].substituteFor == fx[1].substituteFor;
- }
- // undo/redo
- offline.editSong ([] (lynx::Song& s) { s.bpm = 99.0; });
- offline.editSong ([] (lynx::Song& s) { s.bpm = 101.0; });
- offline.undo();
- const auto afterUndo = offline.getSong().bpm;
- offline.redo();
- const auto undoOk = afterUndo == 99.0 && offline.getSong().bpm == 101.0 && offline.canUndo() && ! offline.canRedo()
- && offline.isModified();
- // recording from the PC keyboard: a one-beat note lands in the pattern, in a single undo step
- // (Blend on: this checks that the take joins the pattern's notes; a new install starts with Blend off)
- const auto notesBefore = offline.getSong().patterns[0].notes.size();
- {
- auto o = offline.getRecordOptions();
- o.mode = lynx::RecordMode::overdub;
- offline.setRecordOptions (o);
- }
- offline.setRecording (true);
- offline.play();
- offline.getTransport().positionTicks.store (960.0);
- offline.sendLiveNote (2, 72, 0.9f, true, true);
- offline.getTransport().positionTicks.store (1920.0);
- offline.sendLiveNote (2, 72, 0.0f, false, true);
- offline.setRecording (false);
- offline.stop();
- const auto& recorded = offline.getSong().patterns[0].notes;
- const auto recordOk = recorded.size() == notesBefore + 1
- && std::any_of (recorded.begin(), recorded.end(), [] (const lynx::Note& n) {
- return n.key == 72 && n.channel == 2 && n.length == 960 && n.start >= 960 && n.start < 3840;
- });
- offline.undo();
- const auto recordUndoOk = offline.getSong().patterns[0].notes.size() == notesBefore;
- // FL's Tools › Cancel recording (round 187a): the pass's notes go, an edit made before it stays, recording turns
- // off and playback goes on; nothing to redo
- bool cancelRecordOk = false;
- {
- offline.editSong ([] (lynx::Song& s) { s.bpm = 123.0; });
- const auto notesThen = offline.getSong().patterns[0].notes.size();
- offline.setRecording (true);
- offline.play();
- offline.getTransport().positionTicks.store (960.0);
- offline.sendLiveNote (2, 74, 0.9f, true, true);
- offline.getTransport().positionTicks.store (1920.0);
- offline.sendLiveNote (2, 74, 0.0f, false, true);
- offline.sendLiveNote (2, 76, 0.9f, true, true); // (still held when the pass is cancelled)
- const auto cancelled = offline.cancelRecording();
- cancelRecordOk = cancelled && ! offline.isRecording() && offline.getTransport().playing.load()
- && offline.getSong().patterns[0].notes.size() == notesThen && offline.getSong().bpm == 123.0 && ! offline.canRedo()
- && ! offline.cancelRecording(); // (not recording: nothing to cancel)
- offline.sendLiveNote (2, 76, 0.0f, false, false);
- offline.stop();
- }
- // MIDI: exporting the pattern and importing it back gives the same notes
- bool midiOk = false;
- {
- auto source = lynx::Song::makeDefault();
- source.patterns[0].notes.push_back ({ 1000, 480, 4, 67, 0.5f });
- source.patterns[0].sortNotes();
- const auto midiFile = juce::File::getSpecialLocation (juce::File::tempDirectory).getChildFile ("lynx-selftest.mid");
- juce::String midiError;
- const auto saved = lynx::MidiFileIo::savePattern (source, 0, midiFile, midiError);
- const auto song = saved ? lynx::MidiFileIo::loadSong (midiFile, midiError) : std::nullopt;
- midiFile.deleteFile();
- if (song && song->patterns.size() == 1 && song->patterns[0].notes.size() == source.patterns[0].notes.size()
- && std::abs (song->bpm - source.bpm) < 0.01)
- {
- midiOk = true;
- const auto& a = source.patterns[0].notes;
- const auto& b = song->patterns[0].notes;
- for (std::size_t i = 0; i < a.size(); ++i)
- midiOk = midiOk && a[i].start == b[i].start && a[i].key == b[i].key && a[i].length == b[i].length;
- }
- }
- // project package (REA round 118): a project with a sample exported as .zip, extracted and opened again,
- // finds its sample inside the extracted folder
- bool packageOk = false;
- {
- const auto dir = juce::File::getSpecialLocation (juce::File::tempDirectory).getChildFile ("lynx-selftest-package");
- dir.deleteRecursively();
- dir.getChildFile ("src").createDirectory();
- const auto wav = dir.getChildFile ("src/hit.wav");
- {
- juce::WavAudioFormat format;
- juce::AudioBuffer<float> hit (1, 480);
- for (int i = 0; i < 480; ++i)
- hit.setSample (0, i, 0.5f * std::sin (0.1f * (float) i));
- std::unique_ptr<juce::OutputStream> out (wav.createOutputStream().release());
- if (auto* w = format.createWriterFor (out.get(), 48000.0, 1, 16, {}, 0))
- {
- out.release();
- std::unique_ptr<juce::AudioFormatWriter> writer (w);
- writer->writeFromAudioSampleBuffer (hit, 0, 480);
- }
- }
- auto source = lynx::Song::makeDefault();
- lynx::ChannelDef c;
- c.name = "Hit";
- c.instrument = lynx::InstrumentKind::sampler;
- c.samplePath = wav.getFullPathName().toStdString();
- source.channels.push_back (c);
- lynx::ProjectPackage::Result packed;
- juce::String packageError;
- const auto zip = dir.getChildFile ("Beat.zip");
- if (wav.existsAsFile() && lynx::ProjectPackage::exportZip (source, "Beat", zip, packed, packageError) && packed.files == 1)
- {
- const auto project = lynx::ProjectPackage::extractZip (zip, dir.getChildFile ("out"), packageError);
- const auto song = project.existsAsFile() ? lynx::ProjectFile::load (project, packageError) : std::nullopt;
- if (song && ! song->channels.empty())
- {
- const juce::File back (juce::String::fromUTF8 (song->channels.back().samplePath.c_str()));
- packageOk = back.existsAsFile() && back.isAChildOf (project.getParentDirectory()) && back.getSize() == wav.getSize();
- }
- }
- dir.deleteRecursively();
- }
- // D#92, round 180a: a non-ASCII folder and a dotted name save and load back; an unwritable place says so, and a
- // relative path resolves as the start-up argument does
- bool projectSaveOk = false;
- {
- const auto dir = juce::File::getSpecialLocation (juce::File::tempDirectory).getChildFile ("lynx-selftest-save180a");
- dir.deleteRecursively();
- const auto folder = dir.getChildFile (juce::String::fromUTF8 ("M\xc3\xbasica nova"));
- folder.createDirectory();
- const auto named = lynx::ProjectFile::withProjectExtension (folder.getChildFile (juce::String::fromUTF8 ("Can\xc3\xa7\xc3\xa3o.v2")));
- auto song = lynx::Song::makeDefault();
- lynx::Note note;
- note.length = 240;
- note.key = 64;
- song.patterns[0].notes.push_back (note);
- juce::String error, blockedError;
- const auto again = lynx::ProjectFile::save (song, named, error) ? lynx::ProjectFile::load (named, error) : std::nullopt;
- const auto blocker = dir.getChildFile ("a file");
- blocker.replaceWithText ("x");
- const auto cwd = juce::File::getCurrentWorkingDirectory();
- folder.setAsCurrentWorkingDirectory();
- const auto relative = juce::File::getCurrentWorkingDirectory().getChildFile (named.getFileName());
- cwd.setAsCurrentWorkingDirectory();
- projectSaveOk = named.getFileName().endsWith (".v2.lynx") && again && again->patterns[0].notes.size() == song.patterns[0].notes.size()
- && relative == named && ! lynx::ProjectFile::save (song, blocker.getChildFile ("x.lynx"), blockedError)
- && blockedError.isNotEmpty() && lynx::ProjectFile::withProjectExtension (named) == named;
- dir.deleteRecursively();
- }
- // Online Sessions (round 168a): a project sent as a .lynxpack (one sample used twice is stored once, the uids
- // survive), a stand-in rendered through an ExportJob, the guest's part sent back and merged by the host
- juce::String sessionResult = "ERROR";
- {
- const auto dir = juce::File::getSpecialLocation (juce::File::tempDirectory).getChildFile ("lynx-selftest-session");
- dir.deleteRecursively();
- dir.getChildFile ("src").createDirectory();
- const auto wav = dir.getChildFile ("src/hit.wav");
- {
- juce::WavAudioFormat format;
- juce::AudioBuffer<float> hit (1, 4800);
- for (int i = 0; i < 4800; ++i)
- hit.setSample (0, i, 0.5f * std::sin (0.05f * (float) i) * (1.0f - (float) i / 4800.0f));
- std::unique_ptr<juce::OutputStream> out (wav.createOutputStream().release());
- if (auto* w = format.createWriterFor (out.get(), 48000.0, 1, 16, {}, 0))
- {
- out.release();
- std::unique_ptr<juce::AudioFormatWriter> writer (w);
- writer->writeFromAudioSampleBuffer (hit, 0, 4800);
- }
- }
- auto host = lynx::Song::makeDefault();
- host.mode = lynx::PlayMode::song;
- const auto copyOfWav = dir.getChildFile ("src/hit copy.wav"); // the same bytes under another name: stored once
- wav.copyFileTo (copyOfWav);
- for (const auto& [name, file] : { std::pair<const char*, juce::File> { "Hit", wav }, { "Hit 2", copyOfWav } })
- {
- lynx::ChannelDef c;
- c.name = name;
- c.instrument = lynx::InstrumentKind::sampler;
- c.samplePath = file.getFullPathName().toStdString();
- host.channels.push_back (c);
- }
- const auto hitChannel = (int) host.channels.size() - 2;
- lynx::Note hitNote;
- hitNote.channel = hitChannel;
- hitNote.length = 480;
- host.patterns[0].notes.push_back (hitNote);
- host.playlist.push_back ({ 0, 0, 0, host.patterns[0].effectiveLength (host.beatsPerBar), 0 });
- lynx::uids::normalize (host);
- const auto* guest = lynx::parts::invite (host, "Host", "Ana", 0xFF3D9BE9, false);
- juce::String e;
- std::vector<lynx::sessionpack::Rendered> rendered;
- // (a sampler stands in for a plugin channel here: render() renders whatever it is given)
- const std::vector<lynx::sessionpack::RenderItem> items { { false, hitChannel, false, "Hit", "Test" } };
- const auto renderedOk = guest != nullptr && lynx::sessionpack::render (host, items, 44100.0, dir.getChildFile ("stems"), "Host", rendered, {}, e)
- && rendered.size() == 1 && rendered[0].standIns.size() == 2
- && juce::File (juce::String::fromUTF8 (rendered[0].standIns[0].path.c_str())).getSize() > 1000;
- if (renderedOk)
- lynx::sessionpack::apply (host, rendered);
- lynx::sessionpack::Manifest m;
- m.projectName = "Selftest";
- m.from = *host.session.find (lynx::session::hostTag);
- m.to = *host.session.find (2);
- lynx::sessionpack::WriteResult written;
- const auto pack = dir.getChildFile (juce::String ("Selftest") + lynx::sessionpack::extension);
- const auto packOk = renderedOk && lynx::sessionpack::write (lynx::parts::guestCopy (host, 2), m, offline.getPluginHost(), pack, written, e)
- && written.media == 3 && written.duplicates == 1; // the sample once (used twice), the stand-in pair
- auto opened = packOk ? lynx::sessionpack::open (pack, dir.getChildFile ("received"), e) : std::nullopt;
- bool openOk = false, mergeOk = false;
- if (opened && opened->corrupt.isEmpty())
- {
- const auto& g = opened->song;
- const juce::File sample (juce::String::fromUTF8 (g.channels[(std::size_t) hitChannel].samplePath.c_str()));
- openOk = g.session.me == 2 && g.projectId == host.projectId && g.channels[(std::size_t) hitChannel].uid == host.channels[(std::size_t) hitChannel].uid
- && sample.existsAsFile() && sample.isAChildOf (opened->folder) && g.channels[(std::size_t) hitChannel].standIns.size() == 2
- && juce::File (juce::String::fromUTF8 (g.channels[(std::size_t) hitChannel].standIns[1].path.c_str())).existsAsFile();
- // the guest adds a channel and a pattern of his own, sends his part back
- auto copy = g;
- lynx::ChannelDef mine;
- mine.name = "Ana's hit";
- mine.instrument = lynx::InstrumentKind::sampler;
- mine.samplePath = sample.getFullPathName().toStdString();
- copy.channels.push_back (mine);
- lynx::Pattern p;
- p.name = "Ana";
- lynx::Note note;
- note.channel = (int) copy.channels.size() - 1;
- note.length = 240;
- note.key = 64;
- p.notes.push_back (note);
- copy.patterns.push_back (p);
- lynx::uids::normalize (copy);
- // its uids survive a save and a load
- const auto saved = dir.getChildFile ("guest.lynx");
- auto reloaded = lynx::ProjectFile::save (copy, saved, e) ? lynx::ProjectFile::load (saved, e) : std::nullopt;
- lynx::sessionpack::Manifest back;
- back.part = true;
- back.from = *copy.session.self();
- const auto partFile = dir.getChildFile (juce::String ("Ana part") + lynx::sessionpack::extension);
- lynx::sessionpack::WriteResult partWritten;
- auto part = reloaded && reloaded->channels.back().uid == copy.channels.back().uid && lynx::uids::tagOf (reloaded->channels.back().uid) == 2
- ? lynx::sessionpack::write (lynx::parts::extract (*reloaded, 2), back, offline.getPluginHost(), partFile, partWritten, e)
- : false;
- auto partOpened = part ? lynx::sessionpack::open (partFile, dir.getChildFile ("parts"), e) : std::nullopt;
- if (partOpened && partOpened->manifest.part && lynx::sessionpack::adoptMedia (partOpened->song, dir.getChildFile ("Session media/Ana"), e))
- {
- const auto report = lynx::parts::merge (host, partOpened->song, 2);
- const auto& added = host.channels.back();
- mergeOk = report.ok && report.channels >= 1 && added.name == "Ana's hit" && lynx::uids::tagOf (added.uid) == 2
- && juce::File (juce::String::fromUTF8 (added.samplePath.c_str())).isAChildOf (dir.getChildFile ("Session media/Ana"))
- && host.channels[(std::size_t) hitChannel].name == "Hit";
- }
- }
- // a crafted package whose project points at a file elsewhere on this computer: opening it must not
- // reach that file, or merging would copy it into the project and the next package would send it on
- if (mergeOk)
- {
- const auto secret = dir.getChildFile ("secret.wav");
- wav.copyFileTo (secret);
- auto evil = lynx::Song::makeDefault();
- lynx::ChannelDef c;
- c.instrument = lynx::InstrumentKind::sampler;
- c.samplePath = secret.getFullPathName().toStdString();
- evil.channels.push_back (c);
- lynx::ChannelDef keys; // (FL Keys' zones are read by the engine but are not in the media list)
- keys.instrument = lynx::InstrumentKind::flkeys;
- keys.zones.push_back ({});
- keys.zones.back().path = c.samplePath;
- evil.channels.push_back (keys);
- lynx::ChannelDef patch; // (a Patcher's nodes are not in the media list either)
- patch.instrument = lynx::InstrumentKind::patcher;
- patch.patcher.nodes.resize (2);
- patch.patcher.nodes[0].generator = true;
- patch.patcher.nodes[0].channel = c;
- patch.patcher.nodes[1].effect.samplePath = c.samplePath;
- evil.channels.push_back (patch);
- evil.mixer[1].recordTo = dir.getChildFile ("overwritten.wav").getFullPathName().toStdString();
- const auto evilProject = dir.getChildFile ("evil.lynx");
- lynx::sessionpack::Manifest em;
- em.part = true;
- juce::ZipFile::Builder b;
- const auto json = lynx::sessionpack::manifestToJson (em);
- b.addEntry (new juce::MemoryInputStream (json.toRawUTF8(), json.getNumBytesAsUTF8(), true), 0, "manifest.json", {});
- const auto evilPack = dir.getChildFile (juce::String ("Evil") + lynx::sessionpack::extension);
- bool zipped = false;
- if (lynx::ProjectFile::save (evil, evilProject, e))
- {
- b.addFile (evilProject, 0, "project.lynx");
- juce::FileOutputStream out (evilPack);
- zipped = out.openedOk() && b.writeToStream (out, nullptr);
- }
- auto evilOpened = zipped ? lynx::sessionpack::open (evilPack, dir.getChildFile ("evil"), e) : std::nullopt;
- const auto media = dir.getChildFile ("Session media/Evil");
- mergeOk = evilOpened && lynx::sessionpack::adoptMedia (evilOpened->song, media, e)
- && std::none_of (evilOpened->song.channels.begin(), evilOpened->song.channels.end(), [&] (const lynx::ChannelDef& ch) {
- return juce::File (juce::String::fromUTF8 (ch.samplePath.c_str())) == secret
- || std::any_of (ch.zones.begin(), ch.zones.end(), [&] (const lynx::SampleZone& z) { return juce::File (juce::String::fromUTF8 (z.path.c_str())) == secret; });
- })
- && evilOpened->song.channels.back().patcher.nodes.size() == 2
- && juce::File (juce::String::fromUTF8 (evilOpened->song.channels.back().patcher.nodes[0].channel.samplePath.c_str())) != secret
- && juce::File (juce::String::fromUTF8 (evilOpened->song.channels.back().patcher.nodes[1].effect.samplePath.c_str())) != secret
- && evilOpened->song.mixer[1].recordTo.empty()
- && media.findChildFiles (juce::File::findFiles, true).isEmpty();
- if (! mergeOk && e.isEmpty())
- e = "a received package reached a file outside it";
- }
- // ... nor through its own folder: "..", Windows' dotted names (". ." climbs like ".." there), and a manifest
- // media entry outside the package (it must not even be read: "/dev/zero" would never end)
- if (mergeOk)
- {
- const auto secret = dir.getChildFile ("secret.wav");
- const auto folder = dir.getChildFile ("evil2").getChildFile ("Evil2"); // (where open() will unpack it)
- const auto climb = folder.getFullPathName() + "/media/../../../secret.wav";
- const auto dotted = folder.getFullPathName() + "/. ./.. ./secret.wav";
- auto evil = lynx::Song::makeDefault();
- for (const auto& path : { climb, dotted })
- {
- lynx::ChannelDef c;
- c.instrument = lynx::InstrumentKind::sampler;
- c.samplePath = path.toStdString();
- evil.channels.push_back (c);
- }
- juce::MemoryBlock secretBytes;
- secret.loadFileAsData (secretBytes);
- lynx::sessionpack::Manifest em;
- em.part = true;
- em.media.push_back ({ "sha256-" + juce::String (lynx::sha256Hex ((const std::uint8_t*) secretBytes.getData(), secretBytes.getSize())),
- "secret.wav", (juce::int64) secretBytes.getSize(), "../../secret.wav" });
- const auto evilProject = dir.getChildFile ("evil2.lynx");
- juce::ZipFile::Builder b;
- const auto json = lynx::sessionpack::manifestToJson (em);
- b.addEntry (new juce::MemoryInputStream (json.toRawUTF8(), json.getNumBytesAsUTF8(), true), 0, "manifest.json", {});
- const auto evilPack = dir.getChildFile (juce::String ("Evil2") + lynx::sessionpack::extension);
- bool zipped = false;
- if (lynx::ProjectFile::save (evil, evilProject, e))
- {
- b.addFile (evilProject, 0, "project.lynx");
- juce::FileOutputStream out (evilPack);
- zipped = out.openedOk() && b.writeToStream (out, nullptr);
- }
- auto evilOpened = zipped ? lynx::sessionpack::open (evilPack, dir.getChildFile ("evil2"), e) : std::nullopt;
- const auto media = dir.getChildFile ("Session media/Evil2");
- mergeOk = evilOpened && evilOpened->folder == folder && evilOpened->corrupt.contains ("secret.wav")
- && lynx::sessionpack::adoptMedia (evilOpened->song, media, e) && evilOpened->song.channels.size() >= 2
- && std::none_of (evilOpened->song.channels.begin(), evilOpened->song.channels.end(), [&] (const lynx::ChannelDef& ch) {
- const auto p = juce::String::fromUTF8 (ch.samplePath.c_str());
- return p == climb || p == dotted || (juce::File::isAbsolutePath (p) && juce::File (p) == secret);
- })
- && media.findChildFiles (juce::File::findFiles, true).isEmpty();
- if (! mergeOk && e.isEmpty())
- e = "a received package climbed out of its folder";
- }
- if (! packOk && e.isEmpty())
- e = "media " + juce::String (written.media) + ", duplicates " + juce::String (written.duplicates) + ", missing "
- + written.missing.joinIntoString (";");
- sessionResult = mergeOk ? juce::String ("OK")
- : "ERROR (" + juce::String (renderedOk ? packOk ? openOk ? "merge" : "open" : "pack" : "render") + (e.isEmpty() ? "" : ": " + e) + ")";
- dir.deleteRecursively();
- }
- // WavPack: a .wv from the FL packs (if installed) opens through the sample loader
- juce::String wavpack = "NO_FL";
- {
- const auto roots = lynx::findFlStudioRoots();
- const auto packs = juce::File (juce::String::fromUTF8 (roots.data.c_str())).getChildFile ("Patches/Packs");
- const auto found = packs.isDirectory() ? packs.findChildFiles (juce::File::findFiles, true, "*.wv") : juce::Array<juce::File> {};
- if (! found.isEmpty())
- {
- lynx::SampleLibrary library;
- const auto sample = library.load (found.getFirst().getFullPathName());
- float peakWv = 0.0f;
- if (sample != nullptr)
- for (std::size_t i = 0; i < sample->frames(); ++i)
- peakWv = std::max (peakWv, std::abs (sample->leftData()[i]));
- wavpack = sample != nullptr && sample->frames() > 0 && peakWv > 1e-4f ? "OK" : "ERROR";
- }
- }
- // every built-in effect's editor and engine with extreme settings (round 111): a crash or NaN output fails here
- const auto effectsOk = runEffectFuzz (4, {}); // (no mouse drags: nothing may open on screen)
- // FL's Patcher (round 141): a mixer slot and a generator channel with their graphs survive save / load, and the
- // generator one plays through the rack
- bool patcherOk = false;
- {
- auto song = lynx::Song::makeDefault();
- song.mixer.resize (4);
- auto slot = lynx::makeEffectSlot (lynx::EffectKind::patcher);
- lynx::PatchNode reverb, gain;
- reverb.effect = lynx::makeEffectSlot (lynx::EffectKind::utility); // (exact defaults: params are saved to 4 decimals)
- reverb.label = "Room";
- reverb.x = 120.5f;
- reverb.y = 40.0f;
- gain.effect = lynx::makeEffectSlot (lynx::EffectKind::utility);
- gain.effect.enabled = false;
- slot.patcher.nodes = { reverb, gain };
- lynx::PatchWire a, b, c, control;
- a.to = 0;
- b.from = 0, b.to = 1, b.gain = 0.5f;
- c.from = 1;
- control.kind = lynx::PatchWire::Kind::control, control.from = 0, control.to = 1, control.toPort = 0, control.curve = { 0.0f, 0.25f, 1.0f };
- slot.patcher.wires = { a, b, c, control };
- slot.patcher.outputTracks = { 3 };
- song.mixer[1].effects = { slot };
- lynx::ChannelDef ch;
- ch.name = "Patched";
- ch.instrument = lynx::InstrumentKind::patcher;
- lynx::PatchNode synth;
- synth.generator = true;
- synth.channel.instrument = lynx::InstrumentKind::synth;
- synth.channel.name = "Synth";
- ch.patcher.nodes = { synth };
- lynx::PatchWire notes, out;
- notes.kind = lynx::PatchWire::Kind::midi, notes.to = 0;
- out.from = 0;
- ch.patcher.wires = { notes, out };
- // round 162: the I/O nodes' MIDI pins and a MIDI Out node between them
- lynx::PatchNode midiOutNode;
- midiOutNode.generator = true;
- midiOutNode.channel.instrument = lynx::InstrumentKind::midiOut;
- lynx::midictl::writeMidiOut (midiOutNode.channel.pluginState, { 4, 0, 0, -1, -1 });
- ch.patcher.nodes.push_back (midiOutNode);
- lynx::PatchWire portIn, portOut;
- portIn.kind = portOut.kind = lynx::PatchWire::Kind::midi;
- portIn.fromPort = lynx::patchMidiPortPin (7), portIn.to = 1;
- portOut.from = 1, portOut.to = lynx::patchToHost, portOut.toPort = 9;
- ch.patcher.wires.push_back (portIn);
- ch.patcher.wires.push_back (portOut);
- ch.patcher.fromMidiPorts = { 2, 7 };
- ch.patcher.toMidiPorts = { 9, 11 };
- ch.patcher.fromNotesHidden = true;
- song.channels.push_back (ch);
- const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), error);
- patcherOk = back && back->mixer.size() >= 2 && back->mixer[1].effects.size() == 1
- && back->mixer[1].effects[0].kind == lynx::EffectKind::patcher && back->mixer[1].effects[0].patcher == slot.patcher
- && back->channels.back().instrument == lynx::InstrumentKind::patcher && back->channels.back().patcher.nodes.size() == 2
- && back->channels.back().patcher.fromMidiPorts == ch.patcher.fromMidiPorts
- && back->channels.back().patcher.toMidiPorts == ch.patcher.toMidiPorts && back->channels.back().patcher.fromNotesHidden
- && back->channels.back().patcher.nodes[1].channel.pluginState == midiOutNode.channel.pluginState
- && back->channels.back().patcher.nodes[0].generator
- && back->channels.back().patcher.nodes[0].channel.instrument == lynx::InstrumentKind::synth
- && back->channels.back().patcher.wires == ch.patcher.wires;
- }
- // FL engines in a native project (round 142, issue #5): every engine this PC can make survives save / load and
- // the instruments play through the rack
- juce::String nativesResult = "OK";
- int nativesMade = 0, nativesSilent = 0;
- {
- auto song = lynx::Song::makeDefault();
- song.channels.clear();
- song.patterns[0].notes.clear();
- song.mixer.resize (3);
- const auto& fl = lynx::flStudioAccess();
- for (const auto& e : lynx::natives::instrumentEngines())
- if (lynx::natives::available (e, fl))
- if (auto c = lynx::natives::makeChannel (e.kind, fl))
- {
- c->mixerTrack = 1;
- song.channels.push_back (*c);
- }
- for (const auto& e : lynx::natives::effectEngines())
- if (auto fx = lynx::natives::makeSlot (e.kind, fl))
- song.mixer[2].effects.push_back (*fx);
- nativesMade = (int) (song.channels.size() + song.mixer[2].effects.size());
- const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), error);
- auto same = back && back->channels.size() == song.channels.size() && back->mixer.size() >= 3
- && back->mixer[2].effects.size() == song.mixer[2].effects.size();
- for (std::size_t i = 0; same && i < song.channels.size(); ++i)
- {
- const auto& a = song.channels[i];
- const auto& b = back->channels[i];
- same = a.instrument == b.instrument && a.pluginState == b.pluginState && a.samplePath == b.samplePath && a.zones.size() == b.zones.size()
- && a.modelParams.size() == b.modelParams.size();
- if (! same)
- nativesResult = "ERROR channel " + juce::String::fromUTF8 (a.name.c_str());
- }
- for (std::size_t i = 0; same && i < song.mixer[2].effects.size(); ++i)
- {
- const auto& a = song.mixer[2].effects[i];
- const auto& b = back->mixer[2].effects[i];
- same = a.kind == b.kind && a.state == b.state;
- for (std::size_t p = 0; same && p < a.params.size(); ++p)
- same = std::abs (a.params[p] - b.params[p]) < 1.0e-3f;
- if (! same)
- nativesResult = juce::String ("ERROR effect ") + lynx::effectInfo (a.kind).name;
- }
- if (! back)
- nativesResult = "ERROR " + error;
- // each instrument plays a note alone. The Granulizer and Wave Traveller play the channel's sample, and a new
- // one has none (a PC without FL Studio, macOS / Linux: FL's presets are not there either), so they get a
- // generated one: a second of a 220 Hz tone (round 167m, PR #19: Wave Traveller was "SILENT 1" on macOS)
- const auto toneWav = juce::File::getSpecialLocation (juce::File::tempDirectory).getChildFile ("lynx-selftest-natives.wav");
- {
- juce::WavAudioFormat format;
- juce::AudioBuffer<float> tone (1, 48000);
- for (int i = 0; i < 48000; ++i)
- tone.setSample (0, i, 0.5f * std::sin (juce::MathConstants<float>::twoPi * 220.0f * (float) i / 48000.0f));
- toneWav.deleteFile();
- std::unique_ptr<juce::OutputStream> out (toneWav.createOutputStream().release());
- if (auto* w = format.createWriterFor (out.get(), 48000.0, 1, 16, {}, 0))
- {
- out.release();
- std::unique_ptr<juce::AudioFormatWriter> writer (w);
- writer->writeFromAudioSampleBuffer (tone, 0, 48000);
- }
- }
- juce::StringArray silentNames;
- for (std::size_t i = 0; same && i < song.channels.size(); ++i)
- {
- auto one = song;
- one.channels = { song.channels[i] };
- one.channels[0].mixerTrack = 1;
- const auto kind = song.channels[i].instrument;
- // A new Fruity Slicer has no sample and no slices, and FL's is silent then too (round 180c), so it is
- // not one of the engines that must sound here (Linux / macOS CI: "SILENT 1 [Fruity Slicer]", 0.1.25)
- if (kind == lynx::InstrumentKind::fruityslicer && one.channels[0].samplePath.empty())
- continue;
- if ((kind == lynx::InstrumentKind::granulizer || kind == lynx::InstrumentKind::wavetraveller) && one.channels[0].samplePath.empty())
- one.channels[0].samplePath = toneWav.getFullPathName().toStdString();
- one.mixer[2].effects.clear();
- // Drumaxx plays pad 1's key: FL's default kit has a pad at 48, LYNX's own bank kits (a PC without FL,
- // macOS / Linux; round 168p) start at 36 (round 169d: "SILENT 1 [Drumaxx]" on the Linux / macOS CI)
- auto key = 60;
- if (kind == lynx::InstrumentKind::drumaxx)
- {
- const auto padKey = lynx::drumaxxParam (one.channels[0].pluginState, 4);
- key = std::isfinite (padKey) && padKey >= 0.0f && padKey <= 127.0f ? (int) padKey : 48;
- }
- one.patterns[0].notes = { { 0, 1920, 0, key, 0.8f } };
- lynx::AudioEngine player (false);
- player.setSong (std::move (one));
- player.dispatchPendingMessages();
- if (! (player.renderOffline (1.0, 48000.0) > 1.0e-4f))
- {
- ++nativesSilent;
- silentNames.add (juce::String::fromUTF8 (song.channels[i].name.c_str()));
- }
- }
- toneWav.deleteFile();
- if (nativesSilent > 0 && nativesResult == "OK")
- nativesResult = "SILENT " + juce::String (nativesSilent) + " [" + silentNames.joinIntoString (", ") + "]";
- }
- const auto nativesOk = nativesResult == "OK";
- // The metronome as FL 2026 plays it (round 165z-a2): FL's five sounds from its install, the downbeat at
- // 0.9404 × the Tick two semitones up, into the Master ("---") by default; insert 2 as its track plays it through
- // insert 2 (muted: silent); never in an export
- juce::String metronomeResult = "OK";
- int metronomeFlSounds = 0;
- float metronomeMaster = 0.0f;
- {
- const auto& flData = lynx::flStudioAccess().roots.data;
- const auto sounds = lynx::Metronome::loadSounds (flData.empty() ? juce::File() : lynx::platform::localFile (flData));
- for (const auto& s : sounds)
- metronomeFlSounds += s.fromFl ? 1 : 0;
- auto renderClick = [] (int track, bool muteInsert, bool include) {
- auto song = lynx::Song::makeDefault();
- song.channels.clear();
- song.playlist.clear();
- for (auto& p : song.patterns)
- p.notes.clear();
- song.mixer[0].effects.clear(); // (the default Master limiter)
- song.mixer[2].muted = muteInsert;
- lynx::AudioEngine player (false);
- player.setSong (std::move (song));
- player.dispatchPendingMessages();
- auto& t = player.getTransport();
- t.metronome = true;
- t.metronomeSound = 1; // Tick
- t.metronomeTrack = track;
- lynx::AudioEngine::RenderOptions o;
- o.seconds = 0.25;
- o.sampleRate = 44100.0;
- o.pluginWarmUp = false;
- o.includeMetronome = include;
- return player.renderOffline (o);
- };
- metronomeMaster = renderClick (0, false, true);
- const auto insert = renderClick (2, false, true);
- const auto muted = renderClick (2, true, true);
- const auto exported = renderClick (0, false, false);
- // FL's Tick peaks at 1.0: its downbeat at most 0.9404 (the interpolation may land between peaks)
- const auto expectHigh = metronomeFlSounds == lynx::metronome::soundCount ? lynx::metronome::downbeatGain + 1.0e-3f : 1.0f;
- if (! (metronomeMaster > 0.5f && metronomeMaster < expectHigh))
- metronomeResult = "ERROR master " + juce::String (metronomeMaster, 4);
- else if (std::abs (insert - metronomeMaster) > 2.0e-3f)
- metronomeResult = "ERROR insert " + juce::String (insert, 4);
- else if (muted > 1.0e-4f)
- metronomeResult = "ERROR muted insert " + juce::String (muted, 4);
- else if (exported > 1.0e-4f)
- metronomeResult = "ERROR in export " + juce::String (exported, 4);
- }
- const auto metronomeOk = metronomeResult == "OK";
- // Settings › Audio "Driver settings…" with a fake driver panel (issue #13's crash, the panel's buffer kept)
- const auto driverPanel = lynx::AudioEngine::driverPanelSelfTest();
- // Online Sessions P2 (round 169b): live sessions without a network (the JSON round trip of every entity, replicas
- // through it, the invite code's keys)
- const auto liveResult = lynx::livetest::selfTest (&rich);
- // issue #67: every built-in effect's parameters, named and hidden (the Parametric EQ's FL law, processing, band
- // mask...), at odd values, through a project save and reload: the same floats back
- juce::String effectParamsResult = "OK";
- {
- auto song = lynx::Song::makeDefault();
- song.mixer.resize (1);
- for (int k = 0; k <= (int) lynx::lastEffectKind; ++k)
- {
- const auto kind = (lynx::EffectKind) k;
- if (kind == lynx::EffectKind::plugin || kind == lynx::EffectKind::parallel)
- continue;
- auto fx = lynx::makeEffectSlot (kind);
- for (std::size_t i = 0; i < fx.params.size(); ++i)
- {
- auto v = (float) ((double) ((i * 7919 + (std::size_t) k * 104729) % 65521) / 65521.0);
- fx.params[i] = v == fx.params[i] ? 1.0f - v : v;
- }
- if (kind == lynx::EffectKind::fruitySend) // ("Send to" is written over the insert span)
- fx.params[3] = 0.0f;
- song.mixer.emplace_back();
- song.mixer.back().name = "Insert " + std::to_string (song.mixer.size() - 1);
- song.mixer.back().effects.push_back (fx);
- }
- // round 171b's Patcher round trip (coordinator): the Frequency Splitter, Fruity Delay 3 and Peak Controller
- // nodes came back different (their FL defaults, e.g. the LFO speed 32750 / 65336, lost to 4 decimals)
- {
- auto patch = lynx::makeEffectSlot (lynx::EffectKind::patcher);
- for (const auto kind : { lynx::EffectKind::frequencySplitter, lynx::EffectKind::fruityDelay3, lynx::EffectKind::peakController,
- lynx::EffectKind::reverb, lynx::EffectKind::hardwareInsert })
- {
- lynx::PatchNode node;
- node.effect = lynx::natives::newEffect (kind, lynx::flStudioAccess()).value_or (lynx::makeEffectSlot (kind));
- if (kind == lynx::EffectKind::peakController)
- node.effect.params[7] = 32750.0f / 65336.0f;
- node.x = 200.0f, node.y = 60.0f * (float) patch.patcher.nodes.size();
- patch.patcher.nodes.push_back (node);
- }
- song.mixer.emplace_back();
- song.mixer.back().name = "Patcher";
- song.mixer.back().effects.push_back (patch);
- }
- juce::String why;
- const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), why);
- if (back && back->mixer.size() == song.mixer.size())
- {
- const auto& a = song.mixer.back().effects[0].patcher.nodes;
- const auto& b = back->mixer.back().effects[0].patcher.nodes;
- for (std::size_t n = 0; n < a.size(); ++n)
- if (n >= b.size() || ! (a[n].effect == b[n].effect))
- effectParamsResult = juce::String ("ERROR Patcher node ") + lynx::effectInfo (a[n].effect.kind).name;
- }
- if (! back || back->mixer.size() != song.mixer.size())
- effectParamsResult = "ERROR load " + why;
- else
- for (std::size_t t = 1; t + 1 < song.mixer.size() && effectParamsResult == "OK"; ++t)
- if (back->mixer[t].effects.size() != 1 || back->mixer[t].effects[0].params != song.mixer[t].effects[0].params)
- {
- effectParamsResult = juce::String ("ERROR ") + lynx::effectInfo (song.mixer[t].effects[0].kind).name;
- break;
- }
- }
- // round 170j: the Themed plugin style (its resolution with and without art; every art draws)
- const auto artResult = lynx::skin::artSelfTest();
- // round 177b: a plugin's sidechain bus gets the slot's sidechain (one-click sidechain)
- const auto sidechainResult = lynx::pluginSidechainSelfTest();
- // round 177b: automation lanes come back from a project (track, automation, height, folded)
- juce::String lanesResult = "OK";
- {
- auto song = lynx::Song::makeDefault();
- const auto lane = lynx::autolanes::addLane (song, 3, { lynx::AutomationTargetKind::mixerVolume, 1, 0, 0 }, "Vol", 0.4f);
- song.playlistTracks[3].lanes[0].height = 72;
- song.playlistTracks[3].lanesFolded = true;
- // (the same round's clip LFO and modulators ride along)
- auto& lfo = song.automations[(std::size_t) lane].lfo;
- lfo.on = true;
- lfo.level = -40;
- lfo.speed = 30000;
- lfo.flags = 1 | 4;
- lfo.phase = 123456789u;
- lfo.amp = { { 0, 0.5f, 0.0f }, { 960, 1.0f, 0.0f } };
- lynx::Modulator mod;
- mod.name = "LFO 1";
- mod.shape = lynx::ModShape::square;
- mod.sync = false;
- mod.hz = 2.5;
- mod.routes = { { { lynx::AutomationTargetKind::mixerPan, 1, 0, 0 }, -0.5f } };
- song.modulators.push_back (mod);
- juce::String why;
- const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), why);
- if (! back || back->playlistTracks.size() < 4 || ! (back->playlistTracks[3].lanes == song.playlistTracks[3].lanes)
- || ! back->playlistTracks[3].lanesFolded || back->automations.size() != song.automations.size()
- || ! (back->automations[(std::size_t) lane].points == song.automations[(std::size_t) lane].points)
- || ! (back->automations[(std::size_t) lane].lfo == lfo) || ! (back->modulators == song.modulators))
- lanesResult = "ERROR " + why;
- }
- const auto mixerBasics = lynx::mixerbasics::run();
- const auto ok = mixerBasics == "OK" && audioOk && projectOk && trackModes122Ok && richOk && hwOutOk && hostKeysOk && flp168jOk && clipFades180dOk && blocksOk && compOk && polyOk && latencyOk && substituteOk && patcherOk && nativesOk && undoOk && projectSaveOk && recordOk && recordUndoOk && cancelRecordOk && midiOk && packageOk
- && sessionResult == "OK" && liveResult.startsWith ("OK")
- && wavpack != "ERROR" && effectsOk && driverPanel == "OK" && metronomeOk && artResult == "OK" && effectParamsResult == "OK"
- && sidechainResult == "OK" && lanesResult == "OK";
- juce::String report;
- report << "connections=" << offline.getNumGraphConnections() << "\n"
- << "peak=" << peak << "\n"
- << "project=" << (projectOk ? "OK" : "ERROR " + error) << "\n"
- << "playlist_track_modes_roundtrip=" << (trackModes122Ok ? "OK" : "ERROR") << "\n"
- << "project_features=" << (richOk ? "OK" : "ERROR") << "\n"
- << "hardware_outputs=" << (hwOutOk ? "OK" : "ERROR") << "\n"
- << "plugin_host_keys_option=" << (hostKeysOk ? "OK" : "ERROR") << "\n"
- << "flp168j_fields=" << (flp168jOk ? "OK" : "ERROR") << "\n"
- << "clip_fades_180d=" << (clipFades180dOk ? "OK" : "ERROR") << "\n"
- << "pattern_blocks=" << (blocksOk ? "OK" : "ERROR") << "\n"
- << "comp_crossfades=" << (compOk ? "OK" : "ERROR") << "\n"
- << "channel_polyphony=" << (polyOk ? "OK" : "ERROR") << "\n"
- << "track_latency=" << (latencyOk ? "OK" : "ERROR") << "\n"
- << "plugin_substitutes=" << (substituteOk ? "OK" : "ERROR") << "\n"
- << "patcher=" << (patcherOk ? "OK" : "ERROR") << "\n"
- << "native_engines=" << nativesResult << " (" << nativesMade << " made)\n"
- << "undo=" << (undoOk ? "OK" : "ERROR") << "\n"
- << "mixer_basics=" << mixerBasics << "\n"
- << "recording=" << (recordOk && recordUndoOk ? "OK" : "ERROR") << "\n"
- << "cancel_recording=" << (cancelRecordOk ? "OK" : "ERROR") << "\n"
- << "midi=" << (midiOk ? "OK" : "ERROR") << "\n"
- << "package=" << (packageOk ? "OK" : "ERROR") << "\n"
- << "projectSave=" << (projectSaveOk ? "OK" : "ERROR") << "\n"
- << "online_session=" << sessionResult << "\n"
- << "live_session=" << liveResult << "\n"
- << "wavpack=" << wavpack << "\n"
- << "effects=" << (effectsOk ? "OK" : "NONFINITE") << "\n"
- << "effect_params_saved=" << effectParamsResult << "\n"
- << "driver_panel=" << driverPanel << "\n"
- << "plugin_art=" << artResult << "\n"
- << "plugin_sidechain=" << sidechainResult << "\n"
- << "lanes_saved=" << lanesResult << "\n"
- << "metronome=" << metronomeResult << " (FL sounds " << metronomeFlSounds << "/" << lynx::metronome::soundCount
- << ", downbeat peak " << juce::String (metronomeMaster, 4) << ")\n"
- << "result=" << (ok ? "OK" : "FAILED") << "\n";
- if (reportPath.isNotEmpty())
- juce::File (reportPath).replaceWithText (report);
- setApplicationReturnValue (ok ? 0 : 1);
- quit();
- }
- // Every built-in effect in its native editor: random / extreme parameters, mouse drags over the editor, the editor
- // painted, audio rendered at 44.1 / 48 / 96 kHz. Returns false when an effect output NaN / inf (muted by the
- // renderer's guard). The report lists each effect. Used by --fxfuzz and (a short run) by --selftest.
- bool runEffectFuzz (int rounds, const juce::String& reportPath, bool drags = false)
- {
- juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
- lynx::setNativeEditorDemo (true);
- juce::String report;
- auto allFinite = true;
- {
- lynx::AudioEngine offline (false);
- juce::Random random (111);
- const auto value = [&] { const auto r = random.nextInt (6); return r == 0 ? 0.0f : r == 1 ? 1.0f : random.nextFloat(); };
- for (int k = 0; k <= (int) lynx::lastEffectKind; ++k)
- {
- const auto kind = (lynx::EffectKind) k;
- if (! lynx::NativeEffectWindows::canOpen (kind) || kind == lynx::EffectKind::patcher) // (the Patcher's editor is a graph window)
- continue;
- const auto before = lynx::RackRenderer::nonFiniteEffectBlocks();
- const auto& info = lynx::effectInfo (kind);
- // (FL engines: a fresh instance as the menus make it, from the user's FL installation; round 142)
- auto fx = lynx::natives::newEffect (kind, lynx::flStudioAccess()).value_or (lynx::makeEffectSlot (kind));
- int dragged = 0; // parameter changes made by the mouse drags
- for (int round = 0; round < rounds; ++round)
- {
- if (round > 0)
- for (std::size_t p = 0; p < info.params.size(); ++p)
- fx.params[p] = round == 1 ? 0.0f : round == 2 ? 1.0f : value();
- auto song = lynx::Song::makeDefault(); // its demo beat feeds the effect
- song.mixer.resize (2);
- song.mixer[0].name = "Master";
- song.mixer[1].name = "Insert 1";
- song.mixer[1].effects.assign (1, fx);
- for (auto& channel : song.channels)
- channel.mixerTrack = 1;
- offline.setSong (std::move (song));
- offline.dispatchPendingMessages();
- const auto pages = juce::jmax (1, (int) lynx::plugui::layoutFor (kind).pages.size());
- for (int page = 0; page < pages; ++page)
- {
- auto editor = kind == lynx::EffectKind::facetEq ? lynx::makeFacetEqEditor (offline, 1, 0, false)
- : lynx::makeNativeEffectEditor (offline, 1, 0, 1.0f, page);
- if (editor == nullptr || editor->getWidth() <= 0 || editor->getHeight() <= 0)
- continue;
- juce::Image image (juce::Image::ARGB, editor->getWidth(), editor->getHeight(), true);
- const auto paint = [&] {
- juce::Graphics g (image);
- editor->paintEntireComponent (g, false);
- };
- paint();
- // drags from a grid of points, as a user moving every control (plain left button)
- if (round >= 3 && drags)
- {
- const auto source = juce::Desktop::getInstance().getMainMouseSource();
- const auto step = juce::jmax (12, juce::jmin (editor->getWidth(), editor->getHeight()) / 8);
- for (int y = step / 2; y < editor->getHeight(); y += step)
- for (int x = step / 2; x < editor->getWidth(); x += step)
- {
- auto* target = editor->getComponentAt (x, y);
- if (target == nullptr)
- continue;
- const auto at = target->getLocalPoint (editor.get(), juce::Point<float> ((float) x, (float) y));
- const auto now = juce::Time::getCurrentTime();
- const auto event = [&] (juce::Point<float> p, juce::ModifierKeys mods) {
- return juce::MouseEvent (source, p, mods, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, target, target, now, at, now, 1, false);
- };
- const auto down = juce::ModifierKeys (juce::ModifierKeys::leftButtonModifier);
- const juce::Component::SafePointer<juce::Component> alive (target);
- target->mouseDown (event (at, down));
- const auto dy = (float) (random.nextBool() ? 400 : -400), dx = (float) (random.nextInt (401) - 200);
- if (alive != nullptr)
- target->mouseDrag (event (at + juce::Point<float> (dx * 0.5f, dy * 0.5f), down));
- if (alive != nullptr)
- target->mouseDrag (event (at + juce::Point<float> (dx, dy), down));
- if (alive != nullptr)
- target->mouseUp (event (at + juce::Point<float> (dx, dy), juce::ModifierKeys()));
- juce::PopupMenu::dismissAllActiveMenus();
- offline.dispatchPendingMessages();
- }
- paint();
- }
- }
- for (const auto rate : { 44100.0, 48000.0, 96000.0 })
- offline.renderOffline (0.05, rate);
- if (round == 0 || round >= 3) // keep what the drags set for the next round
- if (offline.getSong().mixer.size() > 1 && ! offline.getSong().mixer[1].effects.empty())
- {
- const auto& now = offline.getSong().mixer[1].effects[0];
- for (std::size_t p = 0; p < fx.params.size(); ++p)
- dragged += now.params[p] != fx.params[p] ? 1 : 0;
- dragged += now.state != fx.state ? 1 : 0;
- fx = now;
- }
- }
- const auto broken = lynx::RackRenderer::nonFiniteEffectBlocks() - before;
- allFinite = allFinite && broken == 0;
- report << info.name << ": " << (broken == 0 ? juce::String ("OK") : "non-finite output in " + juce::String ((juce::int64) broken) + " blocks")
- << " (" << dragged << " changes by mouse)\n";
- if (reportPath.isNotEmpty())
- juce::File (reportPath).replaceWithText (report + "(running)\n"); // what was reached, if it crashes
- }
- }
- lynx::setNativeEditorDemo (false);
- juce::LookAndFeel::setDefaultLookAndFeel (nullptr);
- report << "result=" << (allFinite ? "OK" : "NONFINITE") << "\n";
- if (reportPath.isNotEmpty())
- juce::File (reportPath).replaceWithText (report);
- return allFinite;
- }
- // --opentest (round 157a): see the command line. Runs on the message loop (the editors' timers, animations and
- // native windows are real); one step per timer tick.
- void runOpenTest (const juce::String& reportPath, bool visible, std::function<void (bool)> done)
- {
- juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
- struct OpenTest final : juce::Timer
- {
- juce::String reportPath, report;
- bool visible = false, ok = true;
- std::function<void (bool)> done;
- std::unique_ptr<lynx::AudioEngine> engine;
- std::vector<std::pair<juce::String, std::function<void()>>> steps;
- std::size_t next = 0;
- std::atomic<std::int64_t> lastStep { 0 };
- std::atomic<bool> finished { false };
- std::thread watchdog;
- juce::String current;
- std::mutex currentLock;
- int opened = 0, painted = 0;
- // LYNX_OPENTEST_TIMEOUT (seconds): longer for sanitizer builds
- const std::int64_t timeoutMs = 1000 * juce::jmax (5, juce::SystemStats::getEnvironmentVariable ("LYNX_OPENTEST_TIMEOUT", "20").getIntValue());
- static std::int64_t now() { return (std::int64_t) juce::Time::getMillisecondCounter(); }
- void write (const juce::String& tail = {}) { juce::File (reportPath).replaceWithText (report + tail); }
- ~OpenTest() override
- {
- finished = true;
- if (watchdog.joinable())
- watchdog.join();
- }
- void start()
- {
- lastStep = now();
- // the UI hang watch runs during the whole test (5 s): a slow step leaves its stack next to the report
- const auto folder = juce::File (reportPath).getParentDirectory().getChildFile ("opentest-hang");
- folder.deleteRecursively();
- folder.createDirectory();
- lynx::crashguard::startHangWatch (folder.getFullPathName().replaceCharacter ('\\', '/').toStdString(), 5000);
- watchdog = std::thread ([this] {
- while (! finished)
- {
- std::this_thread::sleep_for (std::chrono::milliseconds (200));
- if (now() - lastStep.load() > timeoutMs)
- {
- juce::String at;
- {
- const std::lock_guard<std::mutex> l (currentLock);
- at = current;
- }
- juce::File (reportPath).replaceWithText (report + "HANG at " + at + " (no progress for " + juce::String (timeoutMs / 1000) + " s; stack in opentest-hang)\nresult=HANG\n");
- lynx::crashguard::exitNow (3);
- }
- }
- });
- startTimer (30);
- }
- // every LYNX window but none of the main one (there is none here): moved off-screen, painted once into an image
- void touchWindows (bool resize, bool large)
- {
- auto& desktop = juce::Desktop::getInstance();
- for (int i = desktop.getNumComponents(); --i >= 0;)
- if (auto* c = desktop.getComponent (i); c != nullptr && c->isVisible())
- {
- if (! visible && c->getScreenX() > -3000)
- c->setTopLeftPosition (-6000, -6000);
- if (resize)
- if (auto* w = dynamic_cast<juce::ResizableWindow*> (c))
- {
- const auto b = w->getBounds();
- w->setSize (large ? b.getWidth() * 2 : juce::jmax (40, b.getWidth() / 3), large ? b.getHeight() * 2 : juce::jmax (40, b.getHeight() / 3));
- }
- if (c->getWidth() > 0 && c->getHeight() > 0 && c->getWidth() < 8000 && c->getHeight() < 8000)
- {
- juce::Image image (juce::Image::ARGB, c->getWidth(), c->getHeight(), true);
- juce::Graphics g (image);
- c->paintEntireComponent (g, false);
- ++painted;
- // LYNX_OPENTEST_SHOTS=folder: each window as first painted (before the resizes), for a look
- if (const auto shots = juce::SystemStats::getEnvironmentVariable ("LYNX_OPENTEST_SHOTS", {}); shots.isNotEmpty() && ! resize)
- {
- juce::FileOutputStream out (juce::File (shots).getChildFile (juce::String (painted).paddedLeft ('0', 4) + ".png"));
- if (out.openedOk())
- {
- out.setPosition (0), out.truncate();
- juce::PNGImageFormat().writeImageToStream (c->createComponentSnapshot (c->getLocalBounds()), out);
- }
- }
- }
- }
- }
- void timerCallback() override
- {
- if (next >= steps.size())
- {
- stopTimer();
- lynx::NativeEffectWindows::closeAll();
- lynx::closeChannelSettings();
- // the UI hang watch itself: the message thread spins past the stall time; the watcher must write the stack
- {
- const auto before = lynx::crashguard::lastHangFile();
- for (const auto until = now() + 7000; now() < until;)
- lastStep = now(); // (busy: no heartbeat; the test's own watchdog stays quiet)
- for (const auto until = now() + 1500; now() < until && lynx::crashguard::lastHangFile() == before;)
- std::this_thread::sleep_for (std::chrono::milliseconds (20));
- lynx::crashguard::stopHangWatch();
- const juce::File hang (juce::String::fromUTF8 (lynx::crashguard::lastHangFile().c_str()));
- const auto text = hang.loadFileAsString();
- const auto frames = juce::StringArray::fromLines (text).size() - 2;
- #if JUCE_WINDOWS
- const auto hangOk = lynx::crashguard::lastHangFile() != before && hang.existsAsFile() && text.contains ("LYNX.exe+0x") && frames >= 3;
- #else
- const auto hangOk = lynx::crashguard::lastHangFile() != before && hang.existsAsFile() && frames >= 3;
- #endif
- report << "hang watch: " << (hangOk ? "OK" : "FAIL") << " (" << hang.getFileName() << ", " << frames << " lines"
- << (before.empty() ? juce::String() : "; a step stalled > 5 s earlier: " + juce::String::fromUTF8 (before.c_str())) << ")\n";
- ok = ok && hangOk;
- }
- report << "windows opened: " << opened << ", paints: " << painted << "\nresult=" << (ok ? "OK" : "FAIL") << "\n";
- write();
- finished = true;
- if (done)
- done (ok);
- return;
- }
- auto& [label, fn] = steps[next++];
- {
- const std::lock_guard<std::mutex> l (currentLock);
- current = label;
- }
- fn();
- lastStep = now();
- lynx::crashguard::heartbeat();
- }
- };
- auto* test = new OpenTest();
- test->reportPath = reportPath;
- test->visible = visible;
- test->engine = std::make_unique<lynx::AudioEngine> (false);
- test->done = [test, done] (bool ok) {
- juce::MessageManager::callAsync ([test, done, ok] {
- delete test;
- juce::LookAndFeel::setDefaultLookAndFeel (nullptr);
- done (ok);
- });
- };
- auto& engine = *test->engine;
- lynx::setNativeEditorDemo (true); // live displays animate without an audio device
- const auto songWith = [] (const lynx::EffectSlot& fx) {
- auto song = lynx::Song::makeDefault();
- song.mixer.resize (2);
- song.mixer[0].name = "Master";
- song.mixer[1].name = "Insert 1";
- song.mixer[1].effects.assign (1, fx);
- for (auto& channel : song.channels)
- channel.mixerTrack = 1;
- return song;
- };
- // an older project's slot: its parameter list cut to `count` and read back by the project reader (the
- // parameters a newer LYNX added after them take their defaults)
- const auto oldState = [songWith] (const lynx::EffectSlot& fx, std::size_t count) -> std::optional<lynx::Song> {
- auto json = juce::JSON::parse (lynx::ProjectFile::toJson (songWith (fx)));
- if (auto* mixer = json["mixer"].getArray(); mixer != nullptr && mixer->size() > 1)
- if (auto* effects = (*mixer)[1]["effects"].getArray(); effects != nullptr && ! effects->isEmpty())
- if (auto* params = (*effects)[0]["params"].getArray())
- params->removeRange ((int) count, params->size());
- juce::String error;
- return lynx::ProjectFile::fromJson (juce::JSON::toString (json), error);
- };
- auto& steps = test->steps;
- juce::Random random (157);
- for (int k = 0; k <= (int) lynx::lastEffectKind; ++k)
- {
- const auto kind = (lynx::EffectKind) k;
- if (! lynx::NativeEffectWindows::canOpen (kind) || kind == lynx::EffectKind::patcher)
- continue;
- const auto& info = lynx::effectInfo (kind);
- const auto base = lynx::natives::newEffect (kind, lynx::flStudioAccess()).value_or (lynx::makeEffectSlot (kind));
- const auto n = info.params.size();
- std::vector<std::pair<juce::String, std::function<std::optional<lynx::Song>()>>> variants;
- variants.push_back ({ "default", [=] { return std::optional<lynx::Song> (songWith (base)); } });
- for (const auto value : { 0.0f, 1.0f })
- variants.push_back ({ value == 0.0f ? "all 0" : "all 1", [=] {
- auto fx = base;
- for (std::size_t p = 0; p < n; ++p) fx.params[p] = value;
- return std::optional<lynx::Song> (songWith (fx));
- } });
- const auto seed = random.nextInt64();
- variants.push_back ({ "random", [=] {
- juce::Random r (seed);
- auto fx = base;
- for (std::size_t p = 0; p < n; ++p) fx.params[p] = r.nextFloat();
- return std::optional<lynx::Song> (songWith (fx));
- } });
- std::vector<std::size_t> cuts { n / 2 };
- for (const auto c : { (std::size_t) 90, (std::size_t) 114, (std::size_t) 128, (std::size_t) 160 }) // (Facet's 90 → 114 params; the 128 → 160 → 192 slot)
- if (c < n) cuts.push_back (c);
- for (const auto c : cuts)
- variants.push_back ({ "old project (" + juce::String ((int) c) + " of " + juce::String ((int) n) + " params)", [=] { return oldState (base, c); } });
- for (const auto& [variant, makeSong] : variants)
- {
- const auto label = juce::String::fromUTF8 (info.name) + " / " + variant;
- steps.push_back ({ label + ": open", [test, &engine, label, makeSong = makeSong] {
- auto song = makeSong();
- if (! song)
- {
- test->report << "FAIL " << label << ": project reader refused the state\n";
- test->ok = false;
- return;
- }
- engine.setSong (std::move (*song));
- engine.dispatchPendingMessages();
- lynx::NativeEffectWindows::open (engine, 1, 0);
- ++test->opened;
- test->touchWindows (false, false);
- } });
- steps.push_back ({ label + ": run", [test, &engine] {
- for (const auto rate : { 44100.0, 48000.0, 96000.0 })
- engine.renderOffline (0.03, rate);
- test->touchWindows (false, false);
- } });
- steps.push_back ({ label + ": small", [test] { test->touchWindows (true, false); } });
- steps.push_back ({ label + ": large", [test] { test->touchWindows (true, true); } });
- steps.push_back ({ label + ": close", [test, label] {
- lynx::NativeEffectWindows::closeAll();
- test->report << label << ": OK\n";
- test->write ("(running)\n");
- } });
- }
- }
- // instruments: the channel window the Channel rack opens (Patcher: its graph window, not here)
- for (int k = 0; k <= (int) lynx::InstrumentKind::soundfont; ++k)
- {
- const auto kind = (lynx::InstrumentKind) k;
- if (kind == lynx::InstrumentKind::plugin || kind == lynx::InstrumentKind::patcher)
- continue;
- for (const auto* variant : { "default", "old project (saved and read back)", "odd settings" })
- {
- if (juce::String (variant) == "odd settings" && kind != lynx::InstrumentKind::soundfont)
- continue;
- const auto label = "instrument " + juce::String (k) + " / " + variant;
- steps.push_back ({ label + ": open", [test, &engine, kind, label, variant = juce::String (variant), old = juce::String (variant) != "default"] {
- auto song = lynx::Song::makeDefault();
- auto channel = lynx::natives::makeChannel (kind, lynx::flStudioAccess());
- lynx::ChannelDef def;
- def.instrument = kind;
- def.name = "Test";
- song.channels.push_back (channel ? *channel : def);
- if (kind == lynx::InstrumentKind::soundfont && variant != "default")
- {
- // a real font when FL's is there; NaN / huge / truncated settings
- const auto& roots = lynx::flStudioAccess().roots;
- if (! roots.data.empty())
- song.channels.back().samplePath = (juce::File (juce::String::fromUTF8 (roots.data.c_str()))
- .getChildFile ("Patches/Soundfonts/STR_Ensemble.sf2"))
- .getFullPathName().toStdString();
- if (variant == "odd settings")
- song.channels.back().modelParams = { NAN, 1.0e9f, -1.0e9f, 0.5f, 7.0f };
- }
- if (old)
- {
- juce::String error;
- if (auto again = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), error))
- song = std::move (*again);
- }
- const auto index = (int) song.channels.size() - 1;
- engine.setSong (std::move (song));
- engine.dispatchPendingMessages();
- lynx::openChannelSettings (engine, index);
- ++test->opened;
- test->touchWindows (false, false);
- } });
- steps.push_back ({ label + ": run", [test, &engine] {
- engine.renderOffline (0.03, 48000.0);
- test->touchWindows (false, false);
- } });
- steps.push_back ({ label + ": small", [test] { test->touchWindows (true, false); } });
- steps.push_back ({ label + ": large", [test] { test->touchWindows (true, true); } });
- steps.push_back ({ label + ": close", [test, label] {
- lynx::closeChannelSettings();
- test->report << label << ": OK\n";
- test->write ("(running)\n");
- } });
- }
- }
- test->start();
- }
- void runPlugWinTest (const juce::String& pluginPath, const juce::String& reportPath, const juce::String& only, int seconds)
- {
- struct Test final : juce::Timer
- {
- juce::String reportPath, report;
- std::unique_ptr<lynx::AudioEngine> engine;
- bool instrument = false;
- int phase = 0, ticks = 0, seconds = 15, dockStep = 0;
- juce::uint32 phaseStartMs = 0; // (phase 1 counts real time: the timer's ticks ran faster than 20 Hz here)
- juce::AudioPluginInstance* instance = nullptr;
- juce::AudioProcessorParameter* checked = nullptr;
- std::unique_ptr<juce::DocumentWindow> mainWindow; // stands for LYNX's main window (window ownership)
- lynx::Workspace* workspace = nullptr; // LYNX_PLUGWIN_DOCK=1: the real main window's desktop (issue #116)
- int channelIndex = -1; // an instrument: its channel (added after the song's own channels)
- int stepMs = 3000; // dock mode: each state held that long (screenshots)
- bool keysDone = false;
- bool dockOk = true;
- std::function<void (bool)> done;
- // issue #116 (with LYNX_DOCKED_PLUGINS=1 and LYNX_PLUGWIN_DOCK=1), FL's f116 sequence for every floating
- // panel: the docked plugin window goes behind a clicked panel and comes back in front when clicked; a
- // panel called by its key comes in front too; Detached reopens it as a window of its own, which stays above
- // every panel clicked (it is owned by the main window).
- const std::array<lynx::workspace::Panel, 4> dockPanels { lynx::workspace::Panel::channelRack, lynx::workspace::Panel::playlist,
- lynx::workspace::Panel::pianoRoll, lynx::workspace::Panel::mixer };
- const int dockSteps = 2 * 4 + 5;
- void* panelHandle (lynx::workspace::Panel p) const { return workspace->getFrame (p).getWindowHandle(); }
- void dockCheck (int at)
- {
- using lynx::workspace::Panel;
- auto* main = mainWindow->getWindowHandle();
- auto* plug = lynx::PluginWindows::hostWindowHandle (*instance);
- auto expect = [this] (const juce::String& name, bool value) {
- step (name + "=" + juce::String ((int) value));
- dockOk = dockOk && value;
- };
- auto id = [] (Panel p) { return juce::String (lynx::workspace::panelId (p)); };
- if (at == 0)
- {
- expect ("docked", lynx::PluginWindows::isDocked (*instance));
- expect ("plugin_native_child", plug != nullptr && lynx::nativechild::parentOf (plug) == main);
- for (auto p : dockPanels)
- {
- auto* h = panelHandle (p);
- expect (id (p) + "_visible", workspace->isPanelVisible (p));
- expect (id (p) + "_native_child", h != nullptr && h != main && lynx::nativechild::parentOf (h) == main);
- expect ("plugin_above_" + id (p) + "_when_opened", lynx::nativechild::isAbove (plug, h));
- }
- expect ("browser_plain", ! workspace->isNativePanel (Panel::browser));
- }
- if (at < 2 * 4)
- {
- const auto p = dockPanels[at / 2];
- if (at % 2 == 0)
- {
- workspace->activate (p); // a click on the panel
- expect (id (p) + "_above_plugin_after_its_click", lynx::nativechild::isAbove (panelHandle (p), plug));
- // the plugin stays above the panels nobody clicked
- for (auto other : dockPanels)
- if (other != p)
- expect ("plugin_above_" + id (other) + "_after_" + id (p) + "_click", lynx::nativechild::isAbove (plug, panelHandle (other)));
- }
- else
- {
- lynx::PluginWindows::open ({}, *instance, {}); // (open again = a click on the plugin)
- expect ("plugin_above_" + id (p) + "_after_plugin_click", lynx::nativechild::isAbove (plug, panelHandle (p)));
- }
- return;
- }
- if (at == 8)
- {
- // a layout change elsewhere (a panel resized, the Browser shown) keeps the plugin in front; a panel
- // called by its key comes in front of it
- workspace->hide (Panel::browser);
- workspace->show (Panel::browser);
- for (auto p : dockPanels)
- expect ("plugin_above_" + id (p) + "_after_layout_change", lynx::nativechild::isAbove (plug, panelHandle (p)));
- workspace->show (Panel::mixer);
- expect ("mixer_above_plugin_after_show", lynx::nativechild::isAbove (panelHandle (Panel::mixer), plug));
- }
- else if (at == 9)
- lynx::PluginWindows::setDetached (*instance, true);
- else if (at == 10)
- {
- expect ("detached_reopened", lynx::PluginWindows::isOpen (*instance) && ! lynx::PluginWindows::isDocked (*instance));
- expect ("detached_owned_by_main", plug != nullptr && lynx::nativechild::ownerOf (plug) == main);
- expect ("detached_saved", find() == instance && engineRef() != nullptr && engineRef()->detached);
- for (auto p : dockPanels)
- workspace->activate (p);
- }
- else if (at == 11)
- {
- // (an owned top-level window: above the main window and so above all its child windows)
- expect ("detached_stays_above_clicked_panels", plug != nullptr && lynx::nativechild::ownerOf (plug) == main
- && lynx::nativechild::parentOf (plug) != main && lynx::PluginWindows::isOpen (*instance));
- lynx::PluginWindows::setDetached (*instance, false);
- }
- else
- {
- expect ("docked_again", lynx::PluginWindows::isDocked (*instance) && engineRef() != nullptr && ! engineRef()->detached);
- step (juce::String ("dock_result=") + (dockOk ? "OK" : "FAILED"));
- }
- }
- const lynx::PluginRef* engineRef() const
- {
- const auto& song = engine->getSong();
- if (instrument)
- return channelIndex < 0 || channelIndex >= (int) song.channels.size() ? nullptr : &song.channels[(size_t) channelIndex].plugin;
- return song.mixer.size() < 2 || song.mixer[1].effects.empty() ? nullptr : &song.mixer[1].effects[0].plugin;
- }
- void step (const juce::String& line)
- {
- report << line << "\n";
- juce::File (reportPath).replaceWithText (report);
- }
- juce::AudioPluginInstance* find()
- {
- if (instrument)
- {
- if (auto* p = dynamic_cast<lynx::PluginInstrument*> (engine->getChannelInstrument (channelIndex).get()))
- return &p->getInstance();
- }
- else if (auto* p = dynamic_cast<lynx::PluginEffect*> (engine->getEffect (1, 0).get()))
- return &p->getInstance();
- return nullptr;
- }
- void timerCallback() override
- {
- ++ticks;
- if (phase == 0) // waiting for the engine to host the plugin
- {
- instance = find();
- if (instance == nullptr)
- {
- if (ticks > 200)
- {
- step ("result=FAILED (not hosted)");
- stopTimer();
- done (false);
- }
- return;
- }
- step ("hosted=" + instance->getName() + " format=" + instance->getPluginDescription().pluginFormatName);
- step ("programs=" + juce::String (instance->getNumPrograms()));
- for (int p = 0; p < juce::jmin (5, instance->getNumPrograms()); ++p)
- step ("program" + juce::String (p) + "=" + instance->getProgramName (p));
- step ("save_formats=" + lynx::pluginpresetui::saveWildcard (*instance));
- // preset round trip: save, change the first parameter, load, compare
- juce::AudioProcessorParameter* param = nullptr;
- for (auto* candidate : instance->getParameters())
- if (candidate->isAutomatable() && ! candidate->isMetaParameter() && candidate != instance->getBypassParameter())
- {
- param = candidate;
- break;
- }
- if (param != nullptr)
- {
- step ("param=" + param->getName (64));
- checked = param;
- const auto file = lynx::pluginpresetui::folderFor (instance->getName()).getChildFile ("plugwintest.lynxpreset");
- juce::String error;
- const auto before = param->getValue();
- const auto saved = lynx::pluginpresetui::save (*instance, file, "plugwintest", error);
- param->setValueNotifyingHost (before > 0.5f ? 0.1f : 0.9f);
- const auto changed = param->getValue();
- const auto loaded = saved && lynx::pluginpresetui::load (*instance, file, error);
- step ("preset_roundtrip saved=" + juce::String ((int) saved) + " loaded=" + juce::String ((int) loaded) + " param0 before="
- + juce::String (before, 4) + " changed=" + juce::String (changed, 4) + " after=" + juce::String (param->getValue(), 4)
- + (error.isNotEmpty() ? " error=" + error : juce::String()));
- for (const auto* ext : { "fxp", "fxb", "vstpreset" })
- {
- juce::String e2;
- const auto f2 = file.withFileExtension (ext);
- const auto ok2 = lynx::pluginpresetui::save (*instance, f2, "plugwintest", e2) && lynx::pluginpresetui::load (*instance, f2, e2);
- step (juce::String ("preset_") + ext + "=" + juce::String ((int) ok2) + (e2.isNotEmpty() ? " (" + e2 + ")" : juce::String()));
- f2.deleteFile();
- }
- step ("browser_lists=" + juce::String (lynx::pluginpresetui::userPresets (instance->getName()).size()));
- }
- std::shared_ptr<void> owner = instrument ? std::shared_ptr<void> (engine->getChannelInstrument (channelIndex))
- : std::shared_ptr<void> (engine->getEffect (1, 0));
- lynx::PluginWindows::open (owner, *instance, instance->getName(),
- { engine.get(), [this] (lynx::Song& song) -> lynx::PluginRef* {
- if (instrument)
- return channelIndex < 0 || channelIndex >= (int) song.channels.size()
- ? nullptr : &song.channels[(size_t) channelIndex].plugin;
- return song.mixer.size() < 2 || song.mixer[1].effects.empty() ? nullptr : &song.mixer[1].effects[0].plugin;
- }, instrument });
- owner.reset();
- step ("window_open=" + juce::String ((int) lynx::PluginWindows::isOpen (*instance)));
- phase = 1;
- ticks = 0;
- phaseStartMs = juce::Time::getMillisecondCounter();
- return;
- }
- if (phase == 1 && ticks >= 30 && ! keysDone && juce::SystemStats::getEnvironmentVariable ("LYNX_PLUGWIN_KEYS", {}).isNotEmpty() && instance->getActiveEditor() != nullptr)
- keysDone = ! lynx::pluginKeysTestTick (*instance->getActiveEditor(),
- [this] (bool on) {
- engine->editSong ([this, on] (lynx::Song& song) {
- (instrument ? song.channels[(size_t) channelIndex].plugin : song.mixer[1].effects[0].plugin).hostKeysFirst = on;
- });
- },
- [this] (const juce::String& line) { step (line); });
- const auto elapsedMs = (int) (juce::Time::getMillisecondCounter() - phaseStartMs);
- if (phase == 1 && ticks == 20 && checked != nullptr)
- step ("param_after_1s=" + juce::String (checked->getValue(), 4));
- // (3 s apart: time for screenshots of each state)
- if (phase == 1 && workspace != nullptr && dockStep < dockSteps && elapsedMs >= (dockStep + 1) * stepMs)
- dockCheck (dockStep++);
- if (phase == 1 && elapsedMs >= seconds * 1000 && (workspace == nullptr || dockStep >= dockSteps)) // remove the plugin from the song
- {
- engine->editSong ([this] (lynx::Song& song) {
- if (instrument)
- {
- if (channelIndex >= 0 && channelIndex < (int) song.channels.size())
- song.channels.erase (song.channels.begin() + channelIndex);
- }
- else
- song.mixer[1].effects.clear();
- });
- step ("removed");
- phase = 2;
- ticks = 0;
- return;
- }
- if (phase == 2 && ticks >= 40)
- {
- const auto open = lynx::PluginWindows::isOpen (*instance);
- step ("window_open_after_remove=" + juce::String ((int) open));
- step (open || ! dockOk ? "result=FAILED" : "result=OK");
- stopTimer();
- lynx::PluginWindows::closeAll();
- done (! open && dockOk);
- }
- }
- };
- auto* test = new Test();
- test->reportPath = reportPath;
- test->seconds = seconds;
- test->done = [this, test] (bool ok) {
- setApplicationReturnValue (ok ? 0 : 1);
- juce::MessageManager::callAsync ([this, test] {
- lynx::setMainWindowForOwnership (nullptr);
- lynx::PluginWindows::setDockWorkspace (nullptr);
- test->workspace = nullptr;
- test->mainWindow = nullptr; // (dock mode: the main component with it, before the engine)
- test->engine = nullptr;
- delete test;
- quit();
- });
- };
- test->engine = std::make_unique<lynx::AudioEngine> (false);
- test->mainWindow = std::make_unique<juce::DocumentWindow> ("LYNX test main window", juce::Colours::darkgrey, 0);
- test->mainWindow->setBounds (20, 20, 300, 200);
- if (juce::SystemStats::getEnvironmentVariable ("LYNX_PLUGWIN_DOCK", {}) == "1" && lynx::nativechild::dockingEnabled())
- {
- // the real main window's contents (it docks plugin windows in its own desktop), so the panels are real
- juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
- auto* ui = new lynx::MainComponent (*test->engine, false);
- test->mainWindow->setUsingNativeTitleBar (true);
- test->mainWindow->setContentOwned (ui, false);
- test->mainWindow->setBounds (20, 20, 1500, 900);
- test->workspace = &ui->workspaceForTest();
- if (const auto ms = juce::SystemStats::getEnvironmentVariable ("LYNX_PLUGWIN_STEP_MS", {}).getIntValue(); ms > 0)
- test->stepMs = ms;
- }
- test->mainWindow->setVisible (true);
- lynx::setMainWindowForOwnership (test->mainWindow.get());
- if (test->workspace != nullptr)
- {
- using lynx::workspace::Panel;
- for (auto p : { Panel::playlist, Panel::mixer, Panel::pianoRoll, Panel::channelRack })
- test->workspace->show (p);
- test->step ("dock_test=2 rack_visible=" + juce::String ((int) test->workspace->isPanelVisible (Panel::channelRack)));
- }
- auto& host = test->engine->getPluginHost();
- test->step ("plugins_in_file=" + juce::String (host.addPluginFile (juce::File (pluginPath))));
- std::optional<juce::PluginDescription> chosen;
- for (const auto& type : host.getKnownPlugins().getTypes())
- if ((juce::File (type.fileOrIdentifier).getFileName() == juce::File (pluginPath).getFileName() || type.fileOrIdentifier == pluginPath)
- && (only.isEmpty() || type.name == only))
- {
- chosen = type;
- break;
- }
- if (! chosen)
- {
- test->step ("result=FAILED (no plugin)");
- test->done (false);
- return;
- }
- test->instrument = chosen->isInstrument;
- lynx::PluginRef ref;
- ref.separateProcess = juce::SystemStats::getEnvironmentVariable ("LYNX_PLUGWIN_SEPARATE", {}) == "1"; // (issue #96's other-process check)
- ref.id = chosen->createIdentifierString().toStdString();
- ref.name = chosen->name.toStdString();
- test->engine->editSong ([&] (lynx::Song& song) {
- if (test->instrument)
- {
- lynx::ChannelDef c;
- c.name = ref.name;
- c.instrument = lynx::InstrumentKind::plugin;
- c.plugin = ref;
- test->channelIndex = (int) song.channels.size();
- song.channels.push_back (c);
- }
- else
- {
- while (song.mixer.size() < 2)
- song.mixer.emplace_back();
- lynx::EffectSlot slot;
- slot.kind = lynx::EffectKind::plugin;
- slot.plugin = ref;
- song.mixer[1].effects.push_back (slot);
- }
- });
- test->step ("plugin=" + chosen->name + " instrument=" + juce::String ((int) test->instrument));
- test->startTimerHz (20);
- }
- void runEditorCrashTest (const juce::String& pluginPath, const juce::String& reportPath)
- {
- struct CrashTest final : juce::Timer
- {
- juce::String reportPath, report;
- std::unique_ptr<lynx::PluginHost> host;
- juce::AudioPluginInstance* plugin = nullptr;
- std::shared_ptr<juce::AudioPluginInstance> keep; // a window whose plugin nobody else holds is closed as orphaned
- std::function<void (bool)> done;
- int ticks = 0, crashesBefore = 0;
- void step (const juce::String& line)
- {
- report << line << "\n";
- juce::File (reportPath).replaceWithText (report); // at each step: a crash leaves the last one
- }
- void timerCallback() override
- {
- ++ticks;
- const auto crashes = lynx::PluginWindows::editorCrashCount() - crashesBefore;
- const auto open = lynx::PluginWindows::isOpen (*plugin);
- if ((crashes > 0 && ! open) || ticks >= 50) // 100 ms ticks: up to 5 s
- {
- stopTimer();
- step ("editor_crashes=" + juce::String (crashes) + " window_open=" + juce::String ((int) open) + " ticks=" + juce::String (ticks));
- bool traced = false;
- if (crashes > 0)
- {
- const auto last = lynx::PluginWindows::editorCrashes().back();
- traced = last.traceFile.existsAsFile() && last.traceFile.loadFileAsString().contains ("LYNX Test Crash");
- step ("plugin=" + last.plugin + " detail=" + last.detail + " trace=" + last.traceFile.getFileName() + " traced="
- + juce::String ((int) traced));
- last.traceFile.deleteFile();
- }
- // still alive: one more message through the loop after the fault
- juce::MessageManager::callAsync ([this, ok = crashes == 1 && ! open && traced] {
- step ("message_loop_after_fault=1");
- step (juce::String ("result=") + (ok ? "OK" : "FAILED"));
- done (ok);
- });
- }
- }
- };
- auto* test = new CrashTest();
- test->reportPath = reportPath;
- test->done = [this, test] (bool ok)
- {
- setApplicationReturnValue (ok ? 0 : 1);
- juce::MessageManager::callAsync ([this, test] { lynx::PluginWindows::closeAll(); delete test; quit(); });
- };
- #if ! JUCE_WINDOWS
- test->step ("result=SKIPPED (Windows only: on macOS / Linux a plugin fault is a signal, see docs/analise/REA_rodada174a.md)");
- test->done (true);
- return;
- #else
- _putenv_s ("LYNX_TEST_CRASH", "editor");
- test->host = std::make_unique<lynx::PluginHost> (false);
- test->step ("plugins_in_file=" + juce::String (test->host->addPluginFile (juce::File (pluginPath))));
- std::shared_ptr<juce::AudioPluginInstance> instance;
- for (const auto& type : test->host->getKnownPlugins().getTypes())
- {
- if (juce::File (type.fileOrIdentifier).getFileName() != juce::File (pluginPath).getFileName())
- continue;
- juce::String error;
- instance = std::shared_ptr<juce::AudioPluginInstance> (lynx::createRightInstance (test->host->getFormats(), type, 48000.0, 512, error).release());
- test->step ("plugin=" + type.name + (instance == nullptr ? " error=" + error : juce::String()));
- break;
- }
- if (instance == nullptr || ! instance->hasEditor())
- {
- test->step ("result=FAILED (no plugin with an editor)");
- test->done (false);
- return;
- }
- lynx::preparePlugin (*instance, 48000.0, 512);
- test->plugin = instance.get();
- test->keep = instance;
- test->crashesBefore = lynx::PluginWindows::editorCrashCount();
- lynx::PluginWindows::open (instance, *instance, instance->getName()); // (the window keeps the plugin alive)
- test->step ("window_open=" + juce::String ((int) lynx::PluginWindows::isOpen (*instance)));
- test->startTimer (100);
- #endif
- }
- void runEditorTest (const juce::String& pluginPath, const juce::String& reportPath, const juce::String& only)
- {
- struct EditorTest final : juce::Timer
- {
- juce::String reportPath, report;
- std::unique_ptr<lynx::PluginHost> host;
- std::unique_ptr<juce::AudioPluginInstance> plugin;
- std::unique_ptr<juce::DocumentWindow> window;
- std::function<void (bool)> done;
- void step (const juce::String& line)
- {
- report << line << "\n";
- juce::File (reportPath).replaceWithText (report); // written at each step: a crash leaves the last one
- }
- void timerCallback() override
- {
- stopTimer();
- window = nullptr;
- step ("step=closed");
- plugin = nullptr;
- step ("result=OK");
- done (true);
- }
- };
- auto* test = new EditorTest();
- test->reportPath = reportPath;
- test->done = [this, test] (bool ok)
- {
- setApplicationReturnValue (ok ? 0 : 1);
- juce::MessageManager::callAsync ([this, test] { delete test; quit(); });
- };
- test->host = std::make_unique<lynx::PluginHost> (false);
- test->step ("plugins_in_file=" + juce::String (test->host->addPluginFile (juce::File (pluginPath))));
- test->step ("exe=" + juce::File::getSpecialLocation (juce::File::currentExecutableFile).getFullPathName());
- for (const auto& type : test->host->getKnownPlugins().getTypes())
- {
- if (juce::File (type.fileOrIdentifier).getFileName() != juce::File (pluginPath).getFileName()
- || (only.isNotEmpty() && type.name != only))
- continue;
- juce::String error;
- test->plugin = lynx::createRightInstance (test->host->getFormats(), type, 48000.0, 512, error);
- test->step ("plugin=" + type.name + (test->plugin == nullptr ? " error=" + error : juce::String()));
- break;
- }
- if (test->plugin == nullptr)
- {
- test->step ("result=FAILED");
- test->done (false);
- return;
- }
- lynx::preparePlugin (*test->plugin, 48000.0, 512);
- test->step ("step=create_editor");
- test->window = std::make_unique<juce::DocumentWindow> (test->plugin->getName(), juce::Colours::black, juce::DocumentWindow::closeButton);
- test->window->setUsingNativeTitleBar (true);
- if (auto* editor = test->plugin->createEditorIfNeeded())
- test->window->setContentOwned (editor, true);
- else
- test->step ("no_editor");
- test->step ("step=show");
- test->window->centreWithSize (test->window->getWidth(), test->window->getHeight());
- test->window->setVisible (true);
- test->step ("step=shown");
- test->startTimer (4000);
- }
- void runFitTest (const juce::String& reportPath, int percent)
- {
- juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
- struct FitTest final : juce::Timer
- {
- juce::String path, report;
- bool ok = true;
- int step = 0, percent = 150;
- std::unique_ptr<juce::DocumentWindow> tall, big;
- std::function<void()> done;
- // `whole`: the window must fit entirely (a resizable one); else its title bar and close button must be on the screen
- void check (const juce::String& what, juce::Component& w, bool whole)
- {
- juce::BorderSize<int> frame;
- if (auto* peer = w.getPeer())
- if (const auto f = peer->getFrameSizeIfPresent())
- frame = *f;
- auto outer = frame.addedTo (w.getBounds());
- const auto* display = juce::Desktop::getInstance().getDisplays().getDisplayForRect (outer);
- const auto area = display != nullptr ? display->userArea : outer;
- #if JUCE_LINUX
- // round 164: a compositor that draws the frame itself (WSLg's Weston) reports its invisible shadow in
- // the frame (59 px on top, 38 around at 100%): only what is visible is checked, give or take 4 px
- const auto shadow = frame.getLeft() >= 16 ? frame.getLeft() : 0;
- outer = outer.reduced (shadow);
- const auto slack = shadow > 0 ? 4 : 0;
- #else
- const auto slack = 0;
- #endif
- const auto passed = outer.getY() >= area.getY() - slack && outer.getRight() <= area.getRight() + slack && outer.getX() >= area.getX() - slack
- && (! whole || outer.getBottom() <= area.getBottom() + 1 + slack);
- report << (passed ? "ok " : "FAIL ") << what << " window=" << outer.toString() << " (frame " << frame.getTop() << ","
- << frame.getLeft() << ") screen=" << area.toString() << "\n";
- ok = ok && passed;
- }
- void start()
- {
- report << "scale=" << percent << "%\n";
- juce::Desktop::getInstance().setGlobalScaleFactor ((float) percent / 100.0f);
- // a tool window taller than the screen, centred (its title bar would be above the screen)
- tall = std::make_unique<juce::DocumentWindow> ("LYNX fit test - tall", lynx::theme::colour::bg2, juce::DocumentWindow::closeButton);
- tall->setUsingNativeTitleBar (true);
- auto* content = new juce::Component();
- const auto area = juce::Desktop::getInstance().getDisplays().getPrimaryDisplay()->userArea;
- content->setSize (500, area.getHeight() + 200);
- tall->setContentOwned (content, true);
- tall->setCentrePosition (area.getCentre());
- tall->setVisible (true);
- lynx::keepAboveMainWindow (*tall);
- // LYNX_FITTEST_MS: how long each window stays (default 700 ms; longer to take screenshots of them)
- startTimer (juce::jlimit (300, 60000, juce::SystemStats::getEnvironmentVariable ("LYNX_FITTEST_MS", "700").getIntValue()));
- }
- void timerCallback() override
- {
- ++step;
- if (step == 1)
- {
- check ("tall tool window: title bar and close button on the screen", *tall, false);
- tall.reset();
- // round 164: a fixed-size LYNX tool window whose content is taller than the screen: it scrolls
- auto content = std::make_unique<juce::Component>();
- const auto screen = juce::Desktop::getInstance().getDisplays().getPrimaryDisplay()->userArea;
- content->setSize (520, screen.getHeight() + 300);
- lynx::openToolWindow (std::move (content), "LYNX fit test - fixed size", "fittest-fixed");
- return;
- }
- if (step == 2)
- {
- if (auto* w = lynx::findToolWindow ("fittest-fixed"))
- {
- check ("fixed-size tool window taller than the screen: fits (its content scrolls)", *w, true);
- const auto scrolls = w->getContentComponent() != nullptr && w->getContentComponent()->getNumChildComponents() > 0
- && dynamic_cast<juce::Viewport*> (w->getContentComponent()->getChildComponent (0)) != nullptr;
- report << (scrolls ? "ok " : "FAIL ") << "its content is in a scrolling viewport\n";
- ok = ok && scrolls;
- }
- else
- {
- report << "FAIL fixed-size tool window not found\n";
- ok = false;
- }
- lynx::closeAllToolWindows();
- // a resizable window that fits at 100%, then the zoom goes up (the main window's case)
- juce::Desktop::getInstance().setGlobalScaleFactor (1.0f);
- big = std::make_unique<juce::DocumentWindow> ("LYNX fit test - zoom", lynx::theme::colour::bg2, juce::DocumentWindow::allButtons);
- big->setUsingNativeTitleBar (true);
- big->setResizable (true, false);
- big->setResizeLimits (400, 300, 10000, 10000);
- const auto area = juce::Desktop::getInstance().getDisplays().getPrimaryDisplay()->userArea;
- big->setBounds (area.getX() + 40, area.getY() + 60, area.getWidth() * 9 / 10 - 40, area.getHeight() * 9 / 10 - 60);
- big->setVisible (true);
- return;
- }
- if (step == 3)
- {
- juce::Desktop::getInstance().setGlobalScaleFactor ((float) percent / 100.0f);
- juce::Timer::callAfterDelay (200, [] { lynx::fitAllWindowsOnScreen(); });
- return;
- }
- if (step == 4)
- {
- check ("resizable window after the zoom change: fits the screen", *big, true);
- big.reset();
- report << "result=" << (ok ? "OK" : "FAILED") << "\n";
- juce::File (path).replaceWithText (report);
- stopTimer();
- if (done)
- done();
- }
- }
- };
- static std::unique_ptr<FitTest> test;
- test = std::make_unique<FitTest>();
- test->path = reportPath;
- test->percent = juce::jlimit (50, 300, percent);
- test->done = [this] { juce::MessageManager::callAsync ([this] { test.reset(); quit(); }); };
- test->start();
- }
- void runWindowTest (const juce::String& reportPath)
- {
- juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
- struct WindowTest final : juce::Timer
- {
- juce::String reportPath, report;
- bool ok = true;
- int stepIndex = 0;
- std::unique_ptr<lynx::AudioEngine> engine;
- lynx::MainComponent* ui = nullptr;
- std::unique_ptr<juce::DocumentWindow> main, pluginLike;
- juce::TextEditor* pluginField = nullptr;
- std::unique_ptr<juce::AlertWindow> nameDialog;
- std::function<void()> done;
- void line (const juce::String& text)
- {
- report << text << "\n";
- juce::File (reportPath).replaceWithText (report);
- }
- void check (const juce::String& what, bool passed)
- {
- line ((passed ? "ok " : "FAIL ") + what);
- ok = ok && passed;
- }
- bool isAbove (juce::Component* w) { return w != nullptr && lynx::isAboveMainWindow (*w); }
- bool focusIn (juce::Component* w)
- {
- auto* f = juce::Component::getCurrentlyFocusedComponent();
- return w != nullptr && f != nullptr && (f == w || w->isParentOf (f));
- }
- void timerCallback() override
- {
- switch (stepIndex++)
- {
- case 0:
- line ("foreground=" + juce::String (juce::Process::isForegroundProcess() ? 1 : 0));
- ui->openQuickAddForTest();
- break;
- case 1:
- {
- auto* w = lynx::findToolWindow ("quickadd");
- check ("quick-add palette open", w != nullptr);
- check ("quick-add palette active", w != nullptr && w->isActiveWindow());
- check ("quick-add palette owned by the main window", w != nullptr && lynx::isOwnedByMainWindow (*w));
- check ("quick-add palette above the main window", isAbove (w));
- auto* f = juce::Component::getCurrentlyFocusedComponent();
- check ("quick-add search box has the keyboard focus", focusIn (w) && dynamic_cast<juce::TextEditor*> (f) != nullptr && f->hasKeyboardFocus (false) && w->isActiveWindow());
- lynx::closeAllToolWindows();
- lynx::openAudioEditor (*engine);
- break;
- }
- case 2:
- {
- auto* w = lynx::findToolWindow ("audioeditor");
- check ("audio editor open", w != nullptr);
- check ("audio editor active", w != nullptr && w->isActiveWindow());
- check ("audio editor owned by the main window", w != nullptr && lynx::isOwnedByMainWindow (*w));
- check ("audio editor above the main window", isAbove (w));
- lynx::forceForegroundForTest (*main); // the user clicks the main window
- break;
- }
- case 3:
- {
- auto* w = lynx::findToolWindow ("audioeditor");
- check ("audio editor stays above the main window after clicking it", isAbove (w));
- lynx::closeAllToolWindows();
- // a plugin editor's window: its own controls keep the keyboard focus
- pluginLike = std::make_unique<juce::DocumentWindow> ("Plugin", juce::Colours::black, juce::DocumentWindow::closeButton);
- pluginLike->setUsingNativeTitleBar (true);
- auto* field = new juce::TextEditor();
- field->setSize (300, 120);
- pluginLike->setContentOwned (field, true);
- pluginLike->centreWithSize (300, 120);
- pluginLike->setVisible (true);
- lynx::keepAboveMainWindow (*pluginLike);
- pluginLike->toFront (true);
- field->grabKeyboardFocus();
- pluginField = field;
- break;
- }
- case 4:
- check ("plugin window active", pluginLike->isActiveWindow());
- check ("plugin window keeps the keyboard focus", pluginField->hasKeyboardFocus (false) && pluginLike->isActiveWindow());
- check ("plugin window above the main window", isAbove (pluginLike.get()));
- pluginLike = nullptr;
- lynx::forceForegroundForTest (*main);
- juce::Component::unfocusAllComponents();
- break;
- case 5:
- check ("main window takes the keyboard focus back when it is active", ui->hasKeyboardFocus (true));
- // round 165q: a name dialog (F4's next empty pattern, Rename and color...) opens ready to type
- nameDialog = lynx::makeNameAndColourDialog ("Rename pattern", "Pattern 2", 0xff808080u);
- nameDialog->enterModalState (true, nullptr, false);
- lynx::keepAboveMainWindow (*nameDialog);
- break;
- case 6:
- {
- auto* f = juce::Component::getCurrentlyFocusedComponent();
- auto* field = dynamic_cast<juce::TextEditor*> (f);
- check ("name dialog: its text field has the keyboard focus", field != nullptr && focusIn (nameDialog.get()));
- if (field != nullptr)
- field->keyPressed (juce::KeyPress ('x', {}, 'x'));
- check ("name dialog: typing replaces the name", nameDialog->getTextEditorContents ("name") == "x");
- nameDialog->exitModalState (0);
- nameDialog = nullptr;
- line (ok ? "result=OK" : "result=FAILED");
- stopTimer();
- done();
- break;
- }
- default:
- break;
- }
- }
- };
- auto* test = new WindowTest();
- test->reportPath = reportPath;
- test->engine = std::make_unique<lynx::AudioEngine> (false);
- test->main = std::make_unique<juce::DocumentWindow> ("LYNX window test", lynx::theme::window, juce::DocumentWindow::allButtons);
- test->main->setUsingNativeTitleBar (true);
- test->ui = new lynx::MainComponent (*test->engine, false);
- test->main->setContentOwned (test->ui, true);
- test->main->setResizable (true, true);
- test->main->centreWithSize (1280, 760);
- test->main->setVisible (true);
- lynx::setMainWindowForOwnership (test->main.get());
- lynx::forceForegroundForTest (*test->main);
- test->main->toFront (true);
- test->done = [this, test] {
- setApplicationReturnValue (test->ok ? 0 : 1);
- juce::MessageManager::callAsync ([this, test] {
- lynx::closeAllToolWindows();
- lynx::setMainWindowForOwnership (nullptr);
- test->main = nullptr;
- delete test;
- quit();
- });
- };
- test->startTimer (1500);
- }
- // LYNX.exe --plugintest plugin.vst3 report.txt ["name"]: loads the plugin (or the one named in a shell), plays notes if it is an
- // instrument (and runs audio through it if it is an effect) and measures the audio.
- void runPluginTest (const juce::String& pluginPath, const juce::String& reportPath, const juce::String& only = {})
- {
- juce::String report;
- bool ok = false;
- {
- lynx::AudioEngine offline (false);
- auto& host = offline.getPluginHost();
- const auto added = host.addPluginFile (juce::File (pluginPath));
- report << "plugins_in_file=" << added << "\n";
- juce::PluginDescription instrument, effect;
- bool hasInstrument = false, hasEffect = false;
- for (const auto& type : host.getKnownPlugins().getTypes())
- {
- if (juce::File (type.fileOrIdentifier).getFileName() != juce::File (pluginPath).getFileName()
- || (only.isNotEmpty() && type.name != only))
- continue;
- report << " " << (type.isInstrument ? "instrument: " : "effect: ") << type.name << " (" << type.manufacturerName
- << ") in " << type.fileOrIdentifier << "\n";
- if (type.isInstrument && ! hasInstrument) { instrument = type; hasInstrument = true; }
- if (! type.isInstrument && ! hasEffect) { effect = type; hasEffect = true; }
- }
- auto song = lynx::Song::makeDefault();
- if (hasInstrument)
- {
- auto& c = song.channels[4]; // the "Synth" channel becomes the plugin
- c.instrument = lynx::InstrumentKind::plugin;
- c.plugin.id = instrument.createIdentifierString().toStdString();
- c.plugin.name = instrument.name.toStdString();
- c.volume = 1.0f;
- for (int i = 0; i < 4; ++i) // one chord per beat
- for (int key : { 60, 64, 67 })
- song.patterns[0].notes.push_back ({ (std::int64_t) i * lynx::ppq, lynx::ppq / 2, 4, key, 0.9f });
- song.patterns[0].sortNotes();
- }
- if (hasEffect)
- {
- lynx::EffectSlot slot;
- slot.kind = lynx::EffectKind::plugin;
- slot.plugin.id = effect.createIdentifierString().toStdString();
- slot.plugin.name = effect.name.toStdString();
- song.mixer[0].effects.push_back (slot);
- }
- const auto effectSlot = (int) song.mixer[0].effects.size() - 1; // (the default master may hold effects already)
- offline.setSong (song);
- // after a render: the rack (and its plugins) is built when the engine is prepared
- const auto peak = offline.renderOffline (3.0, 48000.0);
- const auto* loadedInstrument = dynamic_cast<lynx::PluginInstrument*> (offline.getChannelInstrument (4).get());
- const auto* loadedEffect = dynamic_cast<lynx::PluginEffect*> (offline.getEffect (0, effectSlot).get());
- report << "instrument_loaded=" << (loadedInstrument != nullptr ? "yes" : "no") << "\n"
- << "effect_loaded=" << (loadedEffect != nullptr ? "yes" : "no") << "\n";
- if (host.getLoadFailures().size() > 0) // why: the host's own message (license, missing file, load failure)
- report << "load_failures=" << host.getLoadFailures().joinIntoString (" | ") << "\n";
- report << "peak=" << peak << "\n";
- // plugins that crashed inside a call, were caught and switched off (round 111)
- report << "plugin_crashes=" << lynx::pluginCrashCount() << "\n";
- for (const auto& c : lynx::pluginCrashes())
- report << " crashed: " << c.plugin << " (" << lynx::crashguard::describe (c.code) << ")\n";
- offline.capturePluginStates();
- const auto stateSize = hasInstrument ? offline.getSong().channels[4].plugin.state.size() : (size_t) 0;
- report << "state_bytes_base64=" << (int) stateSize << "\n";
- ok = (hasInstrument || hasEffect) && (! hasInstrument || loadedInstrument != nullptr)
- && (! hasEffect || loadedEffect != nullptr) && peak > 0.001f && peak < 10.0f;
- }
- report << "result=" << (ok ? "OK" : "FAILED") << "\n";
- juce::File (reportPath).replaceWithText (report);
- setApplicationReturnValue (ok ? 0 : 1);
- quit();
- }
- // LYNX.exe --claprestarttest "LYNX Test Restart.clap" report.txt (tools/testplugin/lynx_test_restart.c, PR #29): a
- // CLAP effect on the Master that asks for a restart every 8 blocks while an export renders on a thread of its own
- // (the message thread is free to run the restarts, as with the Export window). The plugin aborts the process when
- // start / stop_processing run off the audio thread or activate / deactivate off the main thread (issue #46, as u-he
- // Presswerk does; an export at 44.1 kHz and prepare calls from the export's thread check the latter) and counts deactivations that
- // landed inside its process() call (must be none), the restarts must happen, and the delay compensation must end on
- // the latency the plugin reports after its last restart.
- void runClapRestartTest (const juce::String& pluginPath, const juce::String& reportPath)
- {
- struct Run
- {
- std::unique_ptr<lynx::AudioEngine> engine;
- juce::String report;
- int slot = -1;
- std::thread render;
- std::atomic<bool> done { false };
- double renderSeconds = 0.0;
- };
- auto run = std::make_shared<Run>();
- const auto counters = juce::File (reportPath).getSiblingFile (juce::File (reportPath).getFileNameWithoutExtension() + "-plugin.txt");
- counters.deleteFile();
- #if JUCE_WINDOWS
- _putenv_s ("LYNX_TEST_RESTART_REPORT", counters.getFullPathName().toRawUTF8());
- #else
- setenv ("LYNX_TEST_RESTART_REPORT", counters.getFullPathName().toRawUTF8(), 1);
- #endif
- const auto fail = [this, reportPath] (juce::String report) {
- report << "result=FAILED\n";
- juce::File (reportPath).replaceWithText (report);
- setApplicationReturnValue (1);
- quit();
- };
- run->engine = std::make_unique<lynx::AudioEngine> (false);
- auto& host = run->engine->getPluginHost();
- run->report << "plugins_in_file=" << host.addPluginFile (juce::File (pluginPath)) << "\n";
- std::optional<juce::PluginDescription> clap;
- for (const auto& type : host.getKnownPlugins().getTypes())
- if (type.pluginFormatName == "CLAP" && juce::File (type.fileOrIdentifier).getFileName() == juce::File (pluginPath).getFileName())
- clap = type;
- if (! clap)
- {
- fail (run->report + "no CLAP plugin in the file\n");
- return;
- }
- auto song = lynx::Song::makeDefault();
- lynx::EffectSlot slot;
- slot.kind = lynx::EffectKind::plugin;
- slot.plugin.id = clap->createIdentifierString().toStdString();
- slot.plugin.name = clap->name.toStdString();
- slot.smartDisable = false; // (processed every block, as with music playing: the export itself is silent)
- song.mixer[0].effects = { slot }; // alone on the Master: the delay compensation is the plugin's latency
- run->slot = (int) song.mixer[0].effects.size() - 1;
- run->engine->setSong (song);
- run->engine->renderOffline (0.1, 48000.0); // builds the rack (and the plugin) on the message thread
- if (dynamic_cast<lynx::PluginEffect*> (run->engine->getEffect (0, run->slot).get()) == nullptr)
- {
- fail (run->report + "effect_loaded=no\n");
- return;
- }
- auto effect = std::dynamic_pointer_cast<lynx::PluginEffect> (run->engine->getEffect (0, run->slot));
- run->render = std::thread ([run, effect] {
- const auto start = juce::Time::getMillisecondCounterHiRes();
- run->engine->renderOffline (30.0, 48000.0);
- run->renderSeconds = (juce::Time::getMillisecondCounterHiRes() - start) * 0.001;
- // issue #46: an export at another rate / block size prepares the plugin from the export's thread; the
- // plugin aborts unless activate / deactivate reach the main thread
- auto& instance = effect->getInstance();
- instance.prepareToPlay (44100.0, 1024);
- instance.releaseResources();
- instance.prepareToPlay (48000.0, 512);
- run->engine->renderOffline (3.0, 44100.0); // (the engine rebuilds its rack at that rate)
- run->done = true;
- });
- // after the render: a second for the restarts still queued and the engine's timer (the new PDC plan)
- auto finish = std::make_shared<std::function<void()>>();
- *finish = [this, run, counters, reportPath, fail, finish] {
- if (! run->done)
- {
- juce::Timer::callAfterDelay (50, *finish);
- return;
- }
- run->render.join();
- juce::Timer::callAfterDelay (1000, [this, run, counters, reportPath, fail] {
- auto report = run->report;
- int pluginLatency = -1;
- if (const auto effect = run->engine->getEffect (0, run->slot)) // (not held past the engine's reset)
- pluginLatency = effect->latencySamples();
- const auto pdc = run->engine->getLatencySamples();
- report << "render_seconds=" << juce::String (run->renderSeconds, 2) << "\n"
- << "plugin_latency=" << pluginLatency << "\npdc_total=" << pdc << "\n"
- << "plugin_crashes=" << lynx::pluginCrashCount() << "\n";
- run->engine.reset(); // destroys the plugin: it writes its counters
- // one line per plugin instance (the engine may have made more than one): none may have been
- // deactivated inside process(), and the one that rendered must have restarted
- int overlapped = 0, inactive = 0, requests = 0, activations = 0, lines = 0, wrongThread = 0, misordered = 0, unstopped = 0;
- bool otherRate = false;
- for (const auto& line : juce::StringArray::fromLines (counters.loadFileAsString()))
- {
- juce::StringPairArray values;
- for (const auto& token : juce::StringArray::fromTokens (line, " ", ""))
- if (token.contains ("="))
- values.set (token.upToFirstOccurrenceOf ("=", false, false), token.fromFirstOccurrenceOf ("=", false, false));
- if (values.size() == 0)
- continue;
- ++lines;
- report << "instance: " << line << "\n";
- overlapped += values["overlapped"].getIntValue();
- inactive += values["inactive_blocks"].getIntValue();
- // issue #46: activate / deactivate on the main thread, start / stop_processing on the audio thread
- // (the plugin aborts the process otherwise, as u-he's do), in order, every start stopped
- wrongThread += values["wrong_thread"].getIntValue();
- misordered += values["misordered"].getIntValue();
- unstopped += values["starts"].getIntValue() - values["stops"].getIntValue();
- otherRate = otherRate || values["last_rate"].getIntValue() == 44100;
- if (values["requests"].getIntValue() > requests)
- {
- requests = values["requests"].getIntValue();
- activations = values["activations"].getIntValue();
- }
- }
- report << "wrong_thread=" << wrongThread << "\nmisordered=" << misordered << "\nunstopped=" << unstopped
- << "\nactivated_at_44100=" << (otherRate ? "yes" : "no") << "\n";
- const auto ok = lines > 0 && requests > 0 && activations > requests / 2 && overlapped == 0 && inactive == 0
- && wrongThread == 0 && misordered == 0 && unstopped == 0 && otherRate
- && pluginLatency > 0 && pdc == pluginLatency && lynx::pluginCrashCount() == 0;
- if (! ok)
- {
- fail (report);
- return;
- }
- report << "result=OK\n";
- juce::File (reportPath).replaceWithText (report);
- setApplicationReturnValue (0);
- quit();
- });
- };
- juce::Timer::callAfterDelay (50, *finish);
- }
- // LYNX.exe --vst2test "LYNX Test Synth.dll" report.txt (tools/testplugin/lynx_test_vst2.c): LYNX's own VST2 host.
- // Scans the DLL, imports it the way an .flp holds it (Fruity Wrapper VST2 state with a chunk, REA_rodada89 §2),
- // renders with two saved gains (the level must follow the restored state) and checks the plugin saw the song tempo.
- void runVst2Test (const juce::String& pluginPath, const juce::String& reportPath)
- {
- juce::String report;
- bool ok = false;
- {
- lynx::AudioEngine offline (false);
- auto& host = offline.getPluginHost();
- report << "plugins_in_file=" << host.addPluginFile (juce::File (pluginPath)) << "\n";
- std::optional<juce::PluginDescription> vst2;
- for (const auto& type : host.getKnownPlugins().getTypes())
- if (type.pluginFormatName == "VST")
- vst2 = type;
- auto render = [&] (float gain, float& tempoSeen, int& adopted) {
- lynx::FlVst2State state;
- state.flags = 8;
- state.chunk = { 'L', 'X', 'V', '2', 0, 0, 0, 0 };
- std::memcpy (state.chunk.data() + 4, &gain, 4);
- auto song = lynx::Song::makeDefault();
- song.bpm = 137.0;
- auto& f = song.channels[4].plugin.foreign;
- f.format = lynx::ForeignPlugin::Format::vst2;
- f.vst2Id = (std::uint32_t) vst2->uniqueId;
- f.name = "Some other name"; // found by the VST2 ID
- f.state = lynx::writeFlVst2State (state);
- song.channels[4].volume = 1.0f;
- song.patterns[0].notes.clear();
- song.patterns[0].notes.push_back ({ 0, 4 * lynx::ppq, 4, 69, 1.0f });
- for (std::size_t c = 0; c < song.channels.size(); ++c)
- if (c != 4)
- song.channels[c].muted = true;
- adopted = host.adoptFlPlugins (song);
- offline.setSong (song);
- const auto peak = offline.renderOffline (1.0, 48000.0);
- offline.capturePluginStates();
- juce::MemoryBlock saved;
- saved.fromBase64Encoding (juce::String (offline.getSong().channels[4].plugin.state));
- lynx::FlVst2State back;
- tempoSeen = 0.0f;
- if (lynx::parseFlVst2State (std::vector<std::uint8_t> ((const std::uint8_t*) saved.getData(), (const std::uint8_t*) saved.getData() + saved.getSize()), back)
- && back.chunk.size() >= 12)
- std::memcpy (&tempoSeen, back.chunk.data() + 8, 4);
- return peak;
- };
- if (vst2)
- {
- report << "plugin=" << vst2->name << " id=" << vst2->uniqueId << " instrument=" << (int) vst2->isInstrument << "\n";
- float tempoA = 0, tempoB = 0;
- int adoptedA = 0, adoptedB = 0;
- const auto quiet = render (0.1f, tempoA, adoptedA);
- const auto loud = render (0.4f, tempoB, adoptedB);
- report << "adopted=" << adoptedA << "," << adoptedB << " peak_gain_0.1=" << quiet << " peak_gain_0.4=" << loud
- << " tempo_seen=" << tempoB * 1000.0f << "\n";
- ok = adoptedA == 1 && adoptedB == 1 && quiet > 0.01f && std::abs (loud / quiet - 4.0f) < 0.2f
- && std::abs (tempoB * 1000.0f - 137.0f) < 0.01f;
- }
- }
- report << "result=" << (ok ? "OK" : "FAILED") << "\n";
- juce::File (reportPath).replaceWithText (report);
- setApplicationReturnValue (ok ? 0 : 1);
- quit();
- }
- // Round 181c: a wrapper MIDI option changed on a running plugin must act like the same option on a new one. For each
- // option: a control engine whose plugin is created with the option set (proves the test can see it), then an engine
- // whose plugin is already running when the option changes through editSong, as the wrapper page does it. What the
- // plugin received comes from the test plugin's own log. The running instance must also stay the same one.
- void runWrapperMidiTest (const juce::String& pluginPath, const juce::String& reportPath)
- {
- juce::String report;
- auto ok = true;
- const juce::File logFile (juce::SystemStats::getEnvironmentVariable ("LYNX_TEST_VST2_MIDILOG", {}));
- struct Event { juce::String instance; int status, data1, data2; };
- auto take = [&] {
- std::vector<Event> out;
- juce::StringArray lines;
- logFile.readLines (lines);
- for (const auto& line : lines)
- {
- const auto p = juce::StringArray::fromTokens (line, " ", {});
- if (p.size() == 4)
- out.push_back ({ p[0], p[1].getIntValue(), p[2].getIntValue(), p[3].getIntValue() });
- }
- logFile.deleteFile();
- return out;
- };
- auto count = [] (const std::vector<Event>& events, int status, int data1, int data2) {
- int n = 0;
- for (const auto& e : events)
- n += (e.status & 0xF0) == status && (data1 < 0 || e.data1 == data1) && (data2 < 0 || e.data2 == data2) ? 1 : 0;
- return n;
- };
- struct Option
- {
- const char* name;
- std::function<void (lynx::PluginRef&)> before, change;
- std::function<juce::String (const std::vector<Event>&)> seen;
- };
- const Option options[] = {
- { "Send note release velocity off", {}, [] (lynx::PluginRef& r) { r.releaseVelocity = false; },
- [&] (const std::vector<Event>& e) { return "offs_with_release_32=" + juce::String (count (e, 0x80, 69, 32)) + " offs_at_0=" + juce::String (count (e, 0x80, 69, 0)); } },
- { "Send pitch bend range on", {}, [] (lynx::PluginRef& r) { r.sendBendRange = true; },
- [&] (const std::vector<Event>& e) { return "rpn_range_12=" + juce::String (count (e, 0xB0, 6, 12)); } },
- { "Pitch bend range 24", [] (lynx::PluginRef& r) { r.sendBendRange = true; }, [] (lynx::PluginRef& r) { r.bendRange = 24; },
- [&] (const std::vector<Event>& e) { return "rpn_range_24=" + juce::String (count (e, 0xB0, 6, 24)); } },
- { "Send MOD X as polyphonic aftertouch on", {}, [] (lynx::PluginRef& r) { r.modXAftertouch = true; },
- [&] (const std::vector<Event>& e) { return "aftertouch=" + juce::String (count (e, 0xA0, 69, -1)); } },
- { "Send All Notes Off when playback stops off", {}, [] (lynx::PluginRef& r) { r.allNotesOffOnStop = false; },
- [&] (const std::vector<Event>& e) { return "cc123=" + juce::String (count (e, 0xB0, 123, -1)); } },
- };
- // each phase has its own engine: an engine keeps the running instance across setSong, so one engine would
- // carry the control's plugin into the "before" phase
- lynx::AudioEngine scanner (false);
- auto& host = scanner.getPluginHost();
- report << "plugins_in_file=" << host.addPluginFile (juce::File (pluginPath)) << "\n";
- std::optional<juce::PluginDescription> vst2;
- for (const auto& type : host.getKnownPlugins().getTypes())
- if (type.pluginFormatName == "VST")
- vst2 = type;
- if (! vst2 || logFile.getFullPathName().isEmpty())
- ok = false;
- else
- for (const auto& option : options)
- {
- auto makeSong = [&] (bool changed) {
- auto song = lynx::Song::makeDefault();
- auto& channel = song.channels[0];
- channel.instrument = lynx::InstrumentKind::plugin;
- channel.plugin = {};
- channel.plugin.id = vst2->createIdentifierString().toStdString();
- channel.plugin.name = vst2->name.toStdString();
- if (option.before)
- option.before (channel.plugin);
- if (changed)
- option.change (channel.plugin);
- song.patterns[0].notes.clear();
- lynx::Note note;
- note.start = 0;
- note.length = lynx::ppq;
- note.channel = 0;
- note.key = 69;
- note.velocity = 1.0f;
- note.release = 0.25f; // 32 of 127
- note.modX = 0.75f;
- song.patterns[0].notes.push_back (note);
- for (std::size_t c = 1; c < song.channels.size(); ++c)
- song.channels[c].muted = true;
- return song;
- };
- // a block of the song, then a note held across "playback stopped", as the options act on either
- auto play = [&] (lynx::AudioEngine& engine) {
- logFile.deleteFile();
- engine.renderOffline (1.0, 48000.0);
- if (auto instrument = engine.getChannelInstrument (0))
- {
- instrument->noteOn (60, 1.0f);
- instrument->transportStopped();
- }
- engine.renderOffline (0.1, 48000.0);
- return take();
- };
- auto newEngine = [&] {
- auto engine = std::make_unique<lynx::AudioEngine> (false);
- engine->getPluginHost().addPluginFile (juce::File (pluginPath));
- return engine;
- };
- std::vector<Event> control;
- {
- auto engine = newEngine();
- engine->setSong (makeSong (true));
- control = play (*engine);
- }
- auto engine = newEngine();
- engine->setSong (makeSong (false));
- const auto before = play (*engine);
- const auto instrumentBefore = engine->getChannelInstrument (0).get();
- engine->capturePluginStates(); // as the wrapper page does
- engine->editSong ([&] (lynx::Song& song) { option.change (song.channels[0].plugin); });
- const auto after = play (*engine);
- const auto sameInstance = engine->getChannelInstrument (0).get() == instrumentBefore;
- // the counts differ between phases (how many blocks the note spans, how many instances the phase made):
- // what matters is whether each kind of event is there at all
- auto shape = [] (const juce::String& seen) {
- juce::String out;
- for (const auto& token : juce::StringArray::fromTokens (seen, " ", {}))
- out << token.upToFirstOccurrenceOf ("=", false, false) << (token.fromFirstOccurrenceOf ("=", false, false).getIntValue() > 0 ? "=yes " : "=no ");
- return out;
- };
- auto instances = [] (const std::vector<Event>& events) {
- std::set<juce::String> made;
- for (const auto& e : events)
- made.insert (e.instance);
- return (int) made.size();
- };
- const auto a = option.seen (control) + " instances=" + juce::String (instances (control)),
- b = option.seen (before) + " instances=" + juce::String (instances (before)),
- c = option.seen (after) + " instances=" + juce::String (instances (after));
- const auto visible = shape (option.seen (control)) != shape (option.seen (before));
- const auto works = shape (option.seen (after)) == shape (option.seen (control));
- report << option.name << ": control " << a << " | before " << b << " | after the change " << c << " | same_instance=" << (int) sameInstance
- << " | test_sees_the_option=" << (int) visible << " | " << (! visible ? "NOT PROVEN" : works ? "acts on the plugin" : "DEAD until re-created") << "\n";
- ok = ok && visible && works;
- }
- report << "result=" << (ok ? "OK" : "FAILED") << "\n";
- juce::File (reportPath).replaceWithText (report);
- setApplicationReturnValue (ok ? 0 : 1);
- quit();
- }
- // LYNX.exe --wrappertest plugin.vst3 report.txt: builds a VST3 state the way FL's Fruity
- // Wrapper stores it (REA_rodada5 §3.2), runs it through the import (adoptFlPlugins) and checks
- // that the plugin comes back with the changed parameter.
- void runWrapperTest (const juce::String& pluginPath, const juce::String& reportPath)
- {
- juce::String report;
- bool ok = false;
- {
- lynx::AudioEngine offline (false);
- auto& host = offline.getPluginHost();
- host.addPluginFile (juce::File (pluginPath));
- const juce::PluginDescription* vst3 = nullptr;
- const auto types = host.getKnownPlugins().getTypes(); // copy: the pointer below points into it
- for (const auto& type : types)
- if (type.pluginFormatName == "VST3" && type.isInstrument)
- vst3 = &type;
- if (vst3 != nullptr)
- {
- juce::String error;
- auto plugin = host.getFormats().createPluginInstance (*vst3, 48000.0, 512, error);
- auto* parameter = plugin != nullptr && ! plugin->getParameters().isEmpty() ? plugin->getParameters()[0] : nullptr;
- if (parameter != nullptr)
- {
- const auto target = parameter->getValue() > 0.5f ? 0.13f : 0.87f;
- parameter->setValueNotifyingHost (target);
- juce::MemoryBlock juceState;
- plugin->getStateInformation (juceState);
- report << "parameter=" << parameter->getName (64) << " target=" << target << "\n";
- // JUCE state -> FL container: u32 1 + records 1 (flags), 3 (component), 2 (controller)
- std::vector<std::uint8_t> flState;
- auto put32 = [&] (std::uint32_t v) { for (int b = 0; b < 4; ++b) flState.push_back ((std::uint8_t) (v >> (8 * b))); };
- auto record = [&] (std::uint32_t id, const juce::MemoryBlock& data) {
- put32 (id);
- put32 ((std::uint32_t) data.getSize());
- put32 (0);
- flState.insert (flState.end(), (const std::uint8_t*) data.getData(), (const std::uint8_t*) data.getData() + data.getSize());
- };
- put32 (1);
- record (1, juce::MemoryBlock (64, true));
- // record 4 (REA_rodada22 §2.3): slots 0/1 hold the ParamIDs of parameters 2 and 0, so FL's
- // automations k = 0, 1, 2 mean positions 2, 0 and 1 (the first parameter without a slot)
- juce::MemoryBlock slots;
- const auto paramId = [&] (int i) {
- const auto* hosted = dynamic_cast<const juce::HostedAudioProcessorParameter*> (plugin->getParameters()[i]);
- return hosted != nullptr ? (std::uint32_t) hosted->getParameterID().getLargeIntValue() : 0u;
- };
- const bool reorder = plugin->getParameters().size() >= 3;
- if (reorder)
- {
- for (auto v : { 2u, paramId (2), paramId (0) })
- slots.append (&v, 4);
- report << "slot_param_ids=" << (juce::int64) paramId (2) << "," << (juce::int64) paramId (0) << "\n";
- }
- if (auto xml = juce::AudioProcessor::getXmlFromBinary (juceState.getData(), (int) juceState.getSize()))
- for (auto [tag, id] : { std::pair { "IComponent", 3u }, { "IEditController", 2u } })
- if (auto* child = xml->getChildByName (tag))
- {
- juce::MemoryBlock data;
- data.fromBase64Encoding (child->getAllSubText());
- record (id, data);
- report << tag << "_bytes=" << (int) data.getSize() << "\n";
- }
- if (reorder)
- record (4, slots);
- plugin.reset();
- auto song = lynx::Song::makeDefault();
- auto& f = song.channels[4].plugin.foreign;
- f.format = lynx::ForeignPlugin::Format::vst3;
- f.name = vst3->name.toStdString(); // no class ID: find it by name (fallback)
- f.state = flState;
- {
- std::vector<std::uint8_t> comp, ctrl;
- report << "split=" << (int) lynx::splitFlVst3State (flState, comp, ctrl) << " component=" << (int) comp.size()
- << " saved_slots=" << (int) lynx::flVst3ParamSlots (flState).size() << "\n";
- }
- for (int k = 0; k < 3; ++k)
- {
- lynx::Automation a;
- a.target = { lynx::AutomationTargetKind::channelParam, 4, 0, k };
- song.automations.push_back (a);
- }
- const auto adopted = host.adoptFlPlugins (song);
- report << "adopted=" << adopted << "\n";
- juce::String mapped;
- for (const auto& a : song.automations)
- if (a.target.kind == lynx::AutomationTargetKind::channelParam && a.target.index == 4)
- mapped << (mapped.isEmpty() ? "" : ",") << a.target.param;
- report << "slot_positions=" << mapped << "\n";
- const auto slotsOk = ! reorder || mapped == "2,0,1";
- offline.setSong (song);
- if (auto* loaded = dynamic_cast<lynx::PluginInstrument*> (offline.getChannelInstrument (4).get()))
- {
- const auto value = loaded->getInstance().getParameters()[0]->getValue();
- report << "restored_value=" << value << "\n";
- ok = adopted == 1 && std::abs (value - target) < 0.02f && slotsOk;
- }
- }
- }
- }
- report << "result=" << (ok ? "OK" : "FAILED") << "\n";
- juce::File (reportPath).replaceWithText (report);
- setApplicationReturnValue (ok ? 0 : 1);
- quit();
- }
- void runShowcase (const juce::String& outputPath, int currentPattern)
- {
- using namespace lynx;
- Song song;
- song.bpm = 124.0;
- song.mixer = Song::defaultMixer();
- const auto presets = synthPresets();
- auto preset = [&] (const char* name) {
- for (const auto& [n, sset] : presets)
- if (n == name)
- return sset;
- return SynthSettings {};
- };
- auto channel = [&] (const char* name, InstrumentKind kind, float volume, int track, std::uint32_t colour) {
- ChannelDef c;
- c.name = name;
- c.instrument = kind;
- c.volume = volume;
- c.mixerTrack = track;
- c.colour = colour;
- song.channels.push_back (c);
- return (int) song.channels.size() - 1;
- };
- const auto kick = channel ("Kick", InstrumentKind::kick, 0.9f, 1, 0xffd9534f);
- const auto clap = channel ("Clap", InstrumentKind::clap, 0.75f, 2, 0xfff0ad4e);
- const auto hat = channel ("Hat", InstrumentKind::hat, 0.6f, 3, 0xfff7d774);
- const auto snare = channel ("Snare", InstrumentKind::snare, 0.7f, 4, 0xffe8835a);
- const auto bass = channel ("Reese Bass", InstrumentKind::synth, 0.8f, 5, 0xff5bc0de);
- song.channels[(std::size_t) bass].synth = preset ("Reese Bass"); // preset name as defined in core/SynthPresets
- const auto pad = channel ("Pad", InstrumentKind::synth, 0.7f, 6, 0xff9b7fd6);
- song.channels[(std::size_t) pad].synth = preset ("Pad");
- const auto pluck = channel ("Pluck", InstrumentKind::synth, 0.72f, 7, 0xff5cb85c);
- song.channels[(std::size_t) pluck].synth = preset ("Pluck");
- const auto lead = channel ("Supersaw", InstrumentKind::synth, 0.6f, 8, 0xff4fc3a1);
- song.channels[(std::size_t) lead].synth = preset ("Supersaw");
- auto addPattern = [&] (const char* name, std::uint32_t colour) {
- auto& p = song.patterns.emplace_back();
- p.name = name;
- p.colour = colour;
- return (int) song.patterns.size() - 1;
- };
- auto note = [&] (int pattern, int ch, double beat, double beats, int key, float velocity = 0.8f) {
- Note n;
- n.channel = ch;
- n.start = (std::int64_t) (beat * ppq);
- n.length = (std::int64_t) (beats * ppq);
- n.key = key;
- n.velocity = velocity;
- song.patterns[(std::size_t) pattern].notes.push_back (n);
- };
- const auto beat = addPattern ("Beat", 0xffd9534f);
- for (int s = 0; s < 16; s += 4)
- song.patterns[(std::size_t) beat].toggleStep (kick, s);
- for (int s : { 4, 12 })
- song.patterns[(std::size_t) beat].toggleStep (clap, s);
- for (int s = 2; s < 16; s += 4)
- song.patterns[(std::size_t) beat].toggleStep (hat, s);
- for (int s : { 7, 15 })
- song.patterns[(std::size_t) beat].toggleStep (snare, s);
- const auto groove = addPattern ("Groove", 0xfff0ad4e);
- for (int s = 0; s < 16; ++s)
- song.patterns[(std::size_t) groove].toggleStep (hat, s);
- for (int s : { 4, 12 })
- song.patterns[(std::size_t) groove].toggleStep (clap, s);
- // Am – F – C – G, one bar each
- const int roots[4] = { 45, 41, 48, 43 };
- const int chords[4][3] = { { 57, 60, 64 }, { 53, 57, 60 }, { 55, 60, 64 }, { 55, 59, 62 } };
- const auto bassline = addPattern ("Bass", 0xff5bc0de);
- for (int bar = 0; bar < 4; ++bar)
- for (int e = 0; e < 8; ++e)
- if (e != 3)
- note (bassline, bass, bar * 4 + e * 0.5, 0.4, roots[bar] - 12 + (e == 6 ? 12 : 0), e % 2 == 0 ? 0.9f : 0.65f);
- const auto chordsPattern = addPattern ("Chords", 0xff9b7fd6);
- for (int bar = 0; bar < 4; ++bar)
- for (int k = 0; k < 3; ++k)
- note (chordsPattern, pad, bar * 4, 3.9, chords[bar][k], 0.7f);
- const auto melody = addPattern ("Melody", 0xff5cb85c);
- const int line[] = { 69, 72, 76, 74, 72, 69, 67, 69, 65, 69, 72, 74, 72, 69, 67, 64,
- 72, 76, 79, 76, 74, 72, 74, 76, 71, 74, 79, 78, 76, 74, 71, 67 };
- for (int k = 0; k < 32; ++k)
- if (k % 8 != 7)
- note (melody, pluck, k * 0.5, k % 4 == 3 ? 0.9 : 0.4, line[k], k % 2 == 0 ? 0.85f : 0.65f);
- const auto hook = addPattern ("Hook", 0xff4fc3a1);
- for (int bar = 0; bar < 4; ++bar)
- for (int k = 0; k < 3; ++k)
- note (hook, lead, bar * 4 + k * 1.5, k == 2 ? 1.0 : 1.4, chords[bar][2] + 12 - k * 3, 0.8f);
- // Playlist: intro, verse, drop, breakdown, final drop
- song.playlistTracks = { { "Drums" }, { "Groove" }, { "Bass" }, { "Chords" }, { "Melody" }, { "Hook" }, { "Automation" } };
- const auto bar = (std::int64_t) ppq * 4;
- auto clip = [&] (int pattern, int track, int fromBar, int bars) {
- const auto length = song.patterns[(std::size_t) pattern].effectiveLength (song.beatsPerBar);
- for (int b = fromBar; b < fromBar + bars;)
- {
- Clip c;
- c.pattern = pattern;
- c.track = track;
- c.start = b * bar;
- c.length = length;
- song.playlist.push_back (c);
- b += (int) std::max<std::int64_t> (1, length / bar);
- }
- };
- clip (chordsPattern, 3, 0, 8);
- clip (melody, 4, 4, 4);
- clip (beat, 0, 8, 16);
- clip (groove, 1, 12, 12);
- clip (bassline, 2, 8, 8);
- clip (melody, 4, 8, 8);
- clip (chordsPattern, 3, 16, 4);
- clip (bassline, 2, 20, 4);
- clip (hook, 5, 20, 4);
- clip (melody, 4, 20, 4);
- song.addMarker ({ 0, "Intro" });
- song.addMarker ({ 8 * bar, "Drop" });
- song.addMarker ({ 16 * bar, "Breakdown" });
- song.addMarker ({ 20 * bar, "Final" });
- // automation: the pad volume opens up during the intro
- Automation a;
- a.name = "Pad Volume";
- a.target = { AutomationTargetKind::mixerVolume, 6, 0, 0 };
- a.points = { { 0, 0.15f, 0.4f }, { 8 * bar, 0.8f, 0.0f } };
- song.automations.push_back (a);
- Clip ac;
- ac.kind = ClipKind::automation;
- ac.automation = 0;
- ac.track = 6;
- ac.start = 0;
- ac.length = 8 * bar;
- song.playlist.push_back (ac);
- // mixer: names, colours and effects (bass compressor sidechained to the kick)
- const char* names[] = { "Master", "Kick", "Clap", "Hat", "Snare", "Bass", "Pad", "Pluck", "Lead" };
- for (int t = 0; t < 9; ++t)
- {
- song.mixer[(std::size_t) t].name = names[t];
- if (t > 0)
- song.mixer[(std::size_t) t].colour = song.channels[(std::size_t) t - 1].colour;
- }
- auto fx = [&] (int track, EffectKind kind) -> EffectSlot& {
- song.mixer[(std::size_t) track].effects.push_back (makeEffectSlot (kind));
- return song.mixer[(std::size_t) track].effects.back();
- };
- {
- // kick EQ: cut below 30 Hz, weight at 60 Hz, remove the "boxiness" at 350 Hz, brightness at 4 kHz
- auto& eq = fx (1, EffectKind::parametricEq);
- auto band = [&] (int b, peq::BandType type, double hz, double db, double q) {
- eq.params[(std::size_t) peq::param (b, 0)] = peq::typeValue (type);
- eq.params[(std::size_t) peq::param (b, 1)] = peq::hzValue (hz);
- eq.params[(std::size_t) peq::param (b, 2)] = peq::gainValue (db);
- eq.params[(std::size_t) peq::param (b, 3)] = peq::qValue (q);
- };
- band (0, peq::BandType::lowCut, 30.0, 0.0, 0.7);
- band (1, peq::BandType::peak, 62.0, 5.0, 1.2);
- band (2, peq::BandType::peak, 350.0, -6.0, 2.0);
- band (3, peq::BandType::peak, 4200.0, 3.5, 1.5);
- band (4, peq::BandType::highCut, 14000.0, 0.0, 0.7);
- for (int b = 5; b < peq::bands; ++b)
- eq.params[(std::size_t) peq::param (b, 0)] = peq::typeValue (peq::BandType::off);
- }
- fx (1, EffectKind::distortion).mix = 0.3f;
- auto& comp = fx (5, EffectKind::compressor);
- comp.params[0] = 0.55f;
- comp.params[1] = 0.8f;
- comp.sidechain = 1;
- fx (5, EffectKind::parametricEq);
- fx (6, EffectKind::chorus);
- fx (6, EffectKind::reverb);
- fx (7, EffectKind::delay);
- fx (7, EffectKind::reverb).mix = 0.4f;
- fx (8, EffectKind::effector);
- fx (8, EffectKind::delay);
- fx (0, EffectKind::parametricEq);
- auto& limiter = fx (0, EffectKind::limiter);
- limiter.params = { 11.7f / 12.0f, 0.1f, 0.5f };
- song.mixer[1].volume = 0.78f;
- song.mixer[5].volume = 0.72f;
- song.mixer[6].volume = 0.6f;
- song.mixer[6].pan = -0.2f;
- song.mixer[7].pan = 0.25f;
- song.mode = PlayMode::song;
- song.currentPattern = std::clamp (currentPattern, 0, (int) song.patterns.size() - 1);
- juce::String error;
- const auto ok = ProjectFile::save (song, juce::File (outputPath), error);
- setApplicationReturnValue (ok ? 0 : 1);
- quit();
- }
- // LYNX.exe --sandboxtest plugin.vst3 report.txt: opens the instrument in a separate process, plays a
- // note, changes a parameter, checks the state (back in an in-process plugin) and makes the child hang
- // to check that LYNX keeps going (silence, without waiting longer than the timeout).
- // --sandboxtest: plays an instrument (a note) or an effect (a 440 Hz tone through it); render() adds into l / r
- struct TestVoice
- {
- explicit TestVoice (std::unique_ptr<juce::AudioPluginInstance> p)
- {
- if (p->acceptsMidi() && p->getTotalNumInputChannels() == 0)
- instrument = std::make_unique<lynx::PluginInstrument> (std::move (p), 512);
- else
- effect = std::move (p);
- }
- void noteOn()
- {
- if (instrument != nullptr)
- instrument->noteOn (60, 0.9f);
- }
- void render (float* l, float* r, int n, float gainLeft, float gainRight)
- {
- if (instrument != nullptr)
- {
- instrument->render (l, r, n, gainLeft, gainRight);
- return;
- }
- const auto channels = juce::jmax (2, effect->getTotalNumInputChannels(), effect->getTotalNumOutputChannels());
- juce::AudioBuffer<float> block (channels, 512);
- juce::MidiBuffer midi;
- for (int done = 0; done < n; done += 512)
- {
- const auto k = juce::jmin (512, n - done);
- block.setSize (channels, k, false, false, true);
- for (int i = 0; i < k; ++i)
- {
- const auto v = 0.25f * (float) std::sin (phase);
- phase += 2.0 * juce::MathConstants<double>::pi * 440.0 / 48000.0;
- for (int c = 0; c < channels; ++c)
- block.setSample (c, i, v);
- }
- effect->processBlock (block, midi);
- for (int i = 0; i < k; ++i)
- {
- l[done + i] += gainLeft * block.getSample (0, i);
- r[done + i] += gainRight * block.getSample (1, i);
- }
- }
- }
- std::unique_ptr<lynx::PluginInstrument> instrument;
- std::unique_ptr<juce::AudioPluginInstance> effect;
- double phase = 0.0;
- };
- void runSandboxTest (const juce::String& pluginPath, const juce::String& reportPath)
- {
- juce::String report;
- bool ok = false;
- lynx::setPluginSandboxAlerts (false);
- const juce::File log (reportPath + ".log");
- auto step = [&] (const char* what) { log.appendText (juce::String (what) + "\n"); };
- log.deleteFile();
- {
- lynx::PluginHost host (false);
- host.addPluginFile (juce::File (pluginPath));
- const auto types = host.getKnownPlugins().getTypes(); // getTypes() returns a copy
- // the file's instrument, else its first effect (round 161: effects too, e.g. a Windows effect through yabridge)
- const juce::PluginDescription* instrument = nullptr;
- for (const auto& type : types)
- if (type.isInstrument)
- instrument = &type;
- for (const auto& type : types)
- if (instrument == nullptr && ! type.isInstrument)
- instrument = &type;
- step ("host");
- juce::String error;
- auto remote = instrument != nullptr ? lynx::createSandboxedPlugin (*instrument, 48000.0, 512, {}, error) : nullptr;
- report << "opened=" << (remote != nullptr ? 1 : 0) << " error=" << error << "\n";
- step ("created");
- if (remote != nullptr)
- {
- auto& proxy = *remote;
- TestVoice voice (std::move (remote));
- std::vector<float> l (48000), r (48000);
- auto peakOf = [&] {
- float peak = 0.0f;
- for (std::size_t k = 0; k < l.size(); ++k)
- peak = std::max ({ peak, std::abs (l[k]), std::abs (r[k]) });
- return peak;
- };
- const auto start = juce::Time::getMillisecondCounterHiRes();
- voice.noteOn();
- voice.render (l.data(), r.data(), 48000, 1.0f, 1.0f);
- const auto renderMs = juce::Time::getMillisecondCounterHiRes() - start;
- const auto peak = peakOf();
- step ("played");
- if (juce::JUCEApplication::getCommandLineParameters().contains ("--expect-crash"))
- {
- // a plugin that crashes while playing (round 161 test plugin): LYNX notices, mutes it and keeps running
- const auto dead = lynx::isSandboxedPluginDead (proxy);
- std::fill (l.begin(), l.end(), 0.0f);
- std::fill (r.begin(), r.end(), 0.0f);
- voice.render (l.data(), r.data(), 4096, 1.0f, 1.0f);
- report << "peak=" << peak << " render_1s_ms=" << renderMs << " dead=" << (dead ? 1 : 0) << " peak_after=" << peakOf() << "\n";
- ok = dead && peak > 1e-4f && renderMs < 2000.0 && peakOf() == 0.0f;
- report << "result=" << (ok ? "OK" : "FAILED") << "\n";
- juce::File (reportPath).replaceWithText (report);
- setApplicationReturnValue (ok ? 0 : 1);
- quit();
- return;
- }
- report << "plugin=" << proxy.getName() << (instrument->isInstrument ? " (instrument)" : " (effect)") << " parameters="
- << proxy.getParameters().size() << " peak=" << peak << " render_1s_ms=" << renderMs << "\n";
- if (juce::JUCEApplication::getCommandLineParameters().contains ("--editor") && proxy.hasEditor())
- {
- // the plugin's own window, opened by the child process (4 s on screen); the child must stay responsive
- std::unique_ptr<juce::AudioProcessorEditor> editor (proxy.createEditorIfNeeded());
- juce::Thread::sleep (4000);
- juce::MemoryBlock state;
- const auto t0 = juce::Time::getMillisecondCounterHiRes();
- proxy.getStateInformation (state);
- report << "editor_shown=1 state_with_editor_ms=" << (juce::Time::getMillisecondCounterHiRes() - t0) << " dead=" << (lynx::isSandboxedPluginDead (proxy) ? 1 : 0) << "\n";
- editor.reset();
- }
- // parameter -> state -> in-process plugin
- bool stateOk = false;
- if (! proxy.getParameters().isEmpty())
- {
- auto* p = proxy.getParameters()[0];
- const auto target = p->getValue() > 0.5f ? 0.13f : 0.87f;
- p->setValue (target);
- std::fill (l.begin(), l.end(), 0.0f);
- voice.render (l.data(), r.data(), 512, 1.0f, 1.0f); // carries the change to the child
- juce::MemoryBlock state;
- proxy.getStateInformation (state);
- if (auto local = host.getFormats().createPluginInstance (*instrument, 48000.0, 512, error))
- {
- local->setStateInformation (state.getData(), (int) state.getSize());
- const auto back = local->getParameters()[0]->getValue();
- // the same steps without the sandbox: some plugins quantise the value or keep it out of their state
- auto control = target;
- if (auto a = host.getFormats().createPluginInstance (*instrument, 48000.0, 512, error))
- {
- a->enableAllBuses();
- a->prepareToPlay (48000.0, 512);
- a->getParameters()[0]->setValue (target);
- juce::AudioBuffer<float> block (juce::jmax (2, a->getTotalNumInputChannels(), a->getTotalNumOutputChannels()), 512);
- block.clear();
- juce::MidiBuffer none;
- a->processBlock (block, none);
- juce::MemoryBlock direct;
- a->getStateInformation (direct);
- if (auto b = host.getFormats().createPluginInstance (*instrument, 48000.0, 512, error))
- {
- b->setStateInformation (direct.getData(), (int) direct.getSize());
- control = b->getParameters()[0]->getValue();
- }
- a->releaseResources();
- }
- report << "state_bytes=" << (int) state.getSize() << " target=" << target << " in_process=" << back << " in_process_control=" << control << "\n";
- stateOk = std::abs (back - control) < 0.02f;
- }
- }
- step ("state");
- // hung child: the block returns in ~0.5 s, muted, and the plugin is marked dead
- lynx::hangSandboxedPluginForTest (proxy);
- juce::Thread::sleep (200);
- std::fill (l.begin(), l.end(), 1.0f);
- std::fill (r.begin(), r.end(), 1.0f);
- const auto hangStart = juce::Time::getMillisecondCounterHiRes();
- voice.render (l.data(), r.data(), 4096, 0.0f, 0.0f);
- std::fill (l.begin(), l.end(), 0.0f);
- std::fill (r.begin(), r.end(), 0.0f);
- voice.render (l.data(), r.data(), 4096, 1.0f, 1.0f);
- const auto hangMs = juce::Time::getMillisecondCounterHiRes() - hangStart;
- const auto dead = lynx::isSandboxedPluginDead (proxy);
- const auto hangPeak = peakOf();
- report << "hung_ms=" << hangMs << " dead=" << (dead ? 1 : 0) << " peak_after=" << hangPeak << "\n";
- // crashed child (round 161): a second instance aborts; LYNX notices, mutes it and keeps running
- bool crashOk = false;
- if (auto second = lynx::createSandboxedPlugin (*instrument, 48000.0, 512, {}, error))
- {
- auto& proxy2 = *second;
- TestVoice voice2 (std::move (second));
- voice2.noteOn();
- voice2.render (l.data(), r.data(), 512, 1.0f, 1.0f);
- lynx::crashSandboxedPluginForTest (proxy2);
- const auto crashStart = juce::Time::getMillisecondCounterHiRes();
- while (! lynx::isSandboxedPluginDead (proxy2) && juce::Time::getMillisecondCounterHiRes() - crashStart < 5000.0)
- {
- voice2.render (l.data(), r.data(), 512, 1.0f, 1.0f);
- juce::Thread::sleep (5);
- }
- const auto crashMs = juce::Time::getMillisecondCounterHiRes() - crashStart;
- std::fill (l.begin(), l.end(), 0.0f);
- std::fill (r.begin(), r.end(), 0.0f);
- voice2.render (l.data(), r.data(), 4096, 1.0f, 1.0f);
- const auto crashDead = lynx::isSandboxedPluginDead (proxy2);
- report << "crash_ms=" << crashMs << " crash_dead=" << (crashDead ? 1 : 0) << " crash_peak_after=" << peakOf() << "\n";
- crashOk = crashDead && crashMs < 3000.0;
- }
- step ("crash");
- ok = peak > 1e-4f && stateOk && dead && hangMs < 1500.0 && hangPeak == 0.0f && crashOk;
- }
- }
- report << "result=" << (ok ? "OK" : "FAILED") << "\n";
- juce::File (reportPath).replaceWithText (report);
- setApplicationReturnValue (ok ? 0 : 1);
- quit();
- }
- // --timertest (round 174f): a view's polling timer follows the view and its parents, and survives a minimised window
- void runTimerTest (const juce::File& report)
- {
- struct Ticks final : juce::Timer
- {
- void timerCallback() override {}
- } timer;
- juce::Component top, parent, view;
- parent.addChildComponent (view);
- top.addChildComponent (parent);
- top.setSize (320, 200);
- lynx::ui::TimerWhileShowing watch (view, timer, 30);
- juce::String text;
- auto failures = 0;
- auto expect = [&] (const char* step, bool running) {
- const auto ok = timer.isTimerRunning() == running;
- failures += ok ? 0 : 1;
- text << step << ": timer " << (timer.isTimerRunning() ? "running" : "stopped") << (ok ? "" : " FAIL") << "\n";
- };
- expect ("never shown", false);
- view.setVisible (true);
- parent.setVisible (true);
- expect ("view and parent visible, not on the desktop", false);
- top.addToDesktop (juce::ComponentPeer::windowHasTitleBar);
- top.setVisible (true);
- expect ("window shown", true);
- parent.setVisible (false);
- expect ("parent hidden", false);
- parent.setVisible (true);
- expect ("parent shown", true);
- view.setVisible (false);
- expect ("view hidden", false);
- top.getPeer()->setMinimised (true);
- view.setVisible (true);
- expect ("view shown while minimised", true);
- top.getPeer()->setMinimised (false);
- expect ("window restored", true);
- top.setVisible (false);
- expect ("window hidden", false);
- top.setVisible (true);
- expect ("window shown again", true);
- top.removeFromDesktop();
- text << "failures: " << failures << "\nresult=" << (failures == 0 ? "OK" : "FAIL") << "\n";
- report.replaceWithText (text);
- setApplicationReturnValue (failures == 0 ? 0 : 1);
- quit();
- }
- // --cachetest (round 174f): PlaylistComponent::cacheSelfTest on the project, the Playlist off screen at 1466 x 930
- void runCacheTest (const juce::File& project, const juce::File& report)
- {
- engine = std::make_unique<lynx::AudioEngine>();
- juce::String error;
- auto ok = false;
- if (project.hasFileExtension ("flp"))
- ok = engine->importFlpFile (project, error);
- else if (auto song = lynx::ProjectFile::load (project, error))
- {
- engine->setSong (std::move (*song));
- ok = true;
- }
- juce::String text = "project: " + project.getFullPathName() + "\n";
- if (ok)
- {
- auto playlist = std::make_unique<lynx::PlaylistComponent> (*engine);
- playlist->setBounds (0, 0, 1466, 930);
- playlist->setVisible (true);
- text << playlist->cacheSelfTest ([] { lynx::ui::WaveformCache::getInstance()->waitUntilIdle (60000); }, report.getParentDirectory());
- }
- else
- text << "result=ERROR " << error << "\n";
- report.replaceWithText (text);
- setApplicationReturnValue (ok && text.contains ("result=OK") ? 0 : 1);
- quit();
- }
- // --uiperf (round 161): opens the project in the normal window, plays it, and drives the heavy UI cases of round 151
- // through the window's own event path — the default layout, the Mixer maximised (meters while playing, then
- // scrolled), the Playlist maximised (scroll down, scroll sideways, zoom in and out) and the Channel rack scrolled.
- // Every frame is painted right after its event (ComponentPeer::performAnyPendingRepaintsNow) and timed; the report
- // has, per case, the time to show it and the frames' mean / p95 / max, how many took longer than 16 ms, and the
- // process CPU. The same on every OS, so Linux (X11, XWayland) and Windows numbers can be put side by side.
- void runUiPerf (const juce::File& project, const juce::File& report)
- {
- if (const auto profile = juce::SystemStats::getEnvironmentVariable ("LYNX_PROFILE_MAIN", {}); profile.isNotEmpty())
- lynx::crashguard::startMainProfiler (profile.toStdString()); // (stopped in shutdown)
- startupOptions = lynx::StartupOptions::load();
- engine = std::make_unique<lynx::AudioEngine>();
- lynx::videoview::install (*engine); // (Fruity Video Player channels: their sound tracks)
- crashEngine = engine.get();
- createMainWindow();
- mainWindow->reveal();
- // LYNX_UIPERF_SIZE=WxH, LYNX_UIPERF_SCALE=<percent> (round 179a): a large window, a HiDPI desktop's scale
- if (const auto scale = juce::SystemStats::getEnvironmentVariable ("LYNX_UIPERF_SCALE", {}).getIntValue(); scale > 0)
- juce::Desktop::getInstance().setGlobalScaleFactor ((float) scale / 100.0f);
- if (const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_UIPERF_SIZE", {}), "x", ""); size.size() == 2)
- mainWindow->setBounds (0, 0, size[0].getIntValue(), size[1].getIntValue());
- juce::String error;
- auto ok = false;
- const auto loadStart = juce::Time::getMillisecondCounterHiRes();
- if (project.hasFileExtension ("flp"))
- ok = engine->importFlpFile (project, error);
- else if (auto song = lynx::ProjectFile::load (project, error))
- {
- engine->setSong (std::move (*song));
- ok = true;
- }
- const auto loadMs = juce::Time::getMillisecondCounterHiRes() - loadStart;
- if (! ok)
- {
- report.replaceWithText ("project: " + project.getFullPathName() + "\nresult=ERROR " + error + "\n");
- setApplicationReturnValue (1);
- quit();
- return;
- }
- // LYNX_UIPERF_MUTE=1: the Master fader down (the meters of the inserts still move): a run on a desktop someone uses
- if (juce::SystemStats::getEnvironmentVariable ("LYNX_UIPERF_MUTE", {}) == "1")
- engine->editSong ([] (lynx::Song& s) { if (! s.mixer.empty()) s.mixer[0].volume = 0.0f; }, false);
- struct Step
- {
- juce::String name;
- std::function<void()> setup;
- std::function<void (int)> action; // per frame; none: the step watches the window for `frames` ms
- int frames;
- std::function<juce::String()> finish = {}; // round 173f: after the step, its own lines for the report
- };
- struct UiPerf final : juce::Timer
- {
- LynxApplication& app;
- juce::File report;
- juce::String text;
- std::vector<Step> steps;
- std::size_t step = 0;
- int frame = -1;
- std::vector<double> times, rendered; // whole frames (event + paint + blit, when this timer paints) / the window's paints
- std::vector<double> frames; // round 173f: the time of every frame the window painted (ui/FrameProbe.h)
- double setupMs = 0.0, wallStart = 0.0;
- double cpuStart = 0.0; // process CPU seconds (std::clock is wall time on Windows)
- double messageCpuStart = 0.0; // the message thread's CPU seconds
- double audioLoadSum = 0.0; // the device's CPU use (AudioDeviceManager::getCpuUsage), summed per tick
- int audioLoadTicks = 0;
- UiPerf (LynxApplication& a, juce::File r) : app (a), report (std::move (r)) {}
- juce::ComponentPeer* peer() const { return app.mainWindow != nullptr ? app.mainWindow->getPeer() : nullptr; }
- double paintNow() const
- {
- const auto t0 = juce::Time::getMillisecondCounterHiRes();
- if (auto* p = peer())
- p->performAnyPendingRepaintsNow();
- return juce::Time::getMillisecondCounterHiRes() - t0;
- }
- void timerCallback() override
- {
- if (step >= steps.size())
- {
- stopTimer();
- finish();
- return;
- }
- auto& s = steps[step];
- if (frame < 0)
- {
- const auto t0 = juce::Time::getMillisecondCounterHiRes();
- if (s.setup)
- s.setup();
- paintNow();
- setupMs = juce::Time::getMillisecondCounterHiRes() - t0;
- times.clear();
- rendered.clear();
- frames.clear();
- wallStart = juce::Time::getMillisecondCounterHiRes();
- cpuStart = lynx::processCpuSeconds();
- messageCpuStart = lynx::threadCpuSeconds();
- audioLoadSum = 0.0;
- audioLoadTicks = 0;
- frame = 0;
- return;
- }
- audioLoadSum += app.engine->getDeviceManager().getCpuUsage();
- ++audioLoadTicks;
- if (s.action)
- s.action (frame);
- if (const auto ms = paintNow(); ms > 0.25) // (nothing to paint: not a frame)
- times.push_back (ms);
- ++frame;
- if (s.action ? frame < s.frames : juce::Time::getMillisecondCounterHiRes() - wallStart < (double) s.frames)
- return;
- const auto wall = juce::Time::getMillisecondCounterHiRes() - wallStart;
- const auto cpu = 1000.0 * (lynx::processCpuSeconds() - cpuStart);
- const auto messageCpu = 1000.0 * (lynx::threadCpuSeconds() - messageCpuStart);
- text << s.name << ": show " << juce::String (setupMs, 1) << " ms\n"
- << " painted frames: " << stats (rendered) << "\n"
- << " timed here (event + paint + blit): " << stats (times)
- << "\n window frames (probe): " << lynx::ui::FrameStats::of (frames, wall).describe()
- << "\n CPU " << juce::String (wall > 0.0 ? 100.0 * cpu / wall : 0.0, 0) << "% (process, " << juce::String (wall / 1000.0, 1) << " s), message thread "
- << juce::String (wall > 0.0 ? 100.0 * messageCpu / wall : 0.0, 1) << "%, audio device "
- << juce::String (audioLoadTicks > 0 ? 100.0 * audioLoadSum / audioLoadTicks : 0.0, 1) << "%\n";
- if (s.finish)
- text << s.finish();
- juce::File (report).replaceWithText (text);
- ++step;
- frame = -1;
- }
- static juce::String stats (std::vector<double> sorted)
- {
- std::sort (sorted.begin(), sorted.end());
- const auto at = [&sorted] (double q) { return sorted.empty() ? 0.0 : sorted[(std::size_t) juce::jlimit (0, (int) sorted.size() - 1, (int) (q * (double) sorted.size()))]; };
- double sum = 0.0;
- int over = 0;
- for (auto t : sorted)
- {
- sum += t;
- over += t > 16.0 ? 1 : 0;
- }
- return juce::String ((int) sorted.size()) + ", mean " + juce::String (sorted.empty() ? 0.0 : sum / (double) sorted.size(), 1)
- + " ms, p95 " + juce::String (at (0.95), 1) + " ms, max " + juce::String (sorted.empty() ? 0.0 : sorted.back(), 1)
- + " ms, >16 ms " + juce::String (over);
- }
- void finish()
- {
- // the cost of asking where the mouse is (X11: a round trip to the display server)
- const auto q0 = juce::Time::getMillisecondCounterHiRes();
- for (int i = 0; i < 100; ++i)
- juce::ignoreUnused (juce::Desktop::getInstance().getMainMouseSource().getScreenPosition());
- text << "mouse position query: " << juce::String ((juce::Time::getMillisecondCounterHiRes() - q0) / 100.0, 3) << " ms\n";
- app.mainWindow->onFrame = nullptr;
- app.mainWindow->watchFrames ({});
- app.engine->stop();
- text << "result=OK\n";
- report.replaceWithText (text);
- app.setApplicationReturnValue (0);
- app.quit();
- }
- };
- auto* ui = &mainWindow->getContent();
- auto wheelAt = [this] (juce::Component& target, float dx, float dy, juce::ModifierKeys mods) {
- auto* peer = mainWindow->getPeer();
- if (peer == nullptr || ! target.isShowing())
- return;
- juce::ModifierKeys::currentModifiers = mods;
- const auto local = peer->globalToLocal (target.localPointToGlobal (target.getLocalBounds().getCentre()).toFloat());
- juce::MouseWheelDetails wheel { dx, dy, false, false, false };
- peer->handleMouseWheel (juce::MouseInputSource::InputSourceType::mouse, local, juce::Time::currentTimeMillis(), wheel);
- juce::ModifierKeys::currentModifiers = {};
- };
- auto run = std::make_unique<UiPerf> (*this, report);
- mainWindow->onFrame = [r = run.get()] (double ms) { if (r->frame >= 0) r->rendered.push_back (ms); };
- // round 173f: every frame the window paints; a fader drag's moves count as shown when a frame covers the fader
- auto drag = std::make_shared<UiPerfDrag>();
- mainWindow->watchFrames ([r = run.get(), drag] (double now, juce::Rectangle<int> area) {
- if (r->frame >= 0)
- r->frames.push_back (now);
- drag->framePainted (now, area);
- });
- run->text << "project: " << project.getFullPathName() << "\n"
- << "LYNX " << getApplicationVersion() << ", " << juce::SystemStats::getOperatingSystemName() << ", "
- << juce::SystemStats::getCpuModel() << ", window " << mainWindow->getWidth() << "x" << mainWindow->getHeight()
- << ", scale " << juce::String (juce::Desktop::getInstance().getDisplays().getPrimaryDisplay() != nullptr
- ? juce::Desktop::getInstance().getDisplays().getPrimaryDisplay()->scale : 1.0, 2)
- << ", audio device " << (engine->getDeviceManager().getCurrentAudioDevice() != nullptr ? engine->getDeviceManager().getCurrentAudioDevice()->getName() : juce::String ("none")) << "\n"
- << "load " << juce::String (loadMs / 1000.0, 2) << " s\n";
- const auto none = juce::ModifierKeys();
- // discussion #10 (round 173f): the reporter's screen — the Channel Rack and the Mixer open, the pattern playing —
- // watched as it is, then insert 3's fader dragged up and down with the mouse (125 moves a second through the
- // window's own mouse path, the frames painted as the window paints them)
- const auto dragTrack = engine->getSong().mixer.size() > 3 ? 3 : 1;
- run->steps.push_back ({ "rack + mixer, pattern playing", [this, ui] {
- ui->showPanelsForSnapshot ({ lynx::workspace::Panel::channelRack, lynx::workspace::Panel::mixer });
- engine->getTransport().songMode = false;
- engine->rewind();
- engine->play();
- }, {}, 4000 });
- run->steps.push_back ({ "fader drag by mouse, rack + mixer, pattern playing", [this, ui, drag, dragTrack] {
- auto& strips = ui->getMixerForSnapshot().getStripsForSnapshot();
- const auto rail = strips.faderRailForSnapshot (dragTrack);
- drag->start (*mainWindow, strips, rail, engine.get(), dragTrack);
- }, {}, 3000, [drag] { return drag->stop(); } });
- run->steps.push_back ({ "song stopped during the drag", {}, {}, 500, [drag] { return drag->release(); } });
- run->steps.push_back ({ "after the drag (released)", {}, {}, 600, [drag] { return drag->released(); } });
- run->steps.push_back ({ "desktop, playing", [this, ui] { ui->showDesktopForSnapshot (false); engine->rewind(); engine->play(); }, {}, 3000 });
- run->steps.push_back ({ "mixer maximised, playing", [ui] { ui->selectTabForSnapshot (3); }, {}, 3000 });
- // round 177a: only the meters move, so the strips' picture must stay valid, also with a folded group's tab and VCA
- // strips on screen (their levels are drawn over the picture, like the inserts' meters)
- run->steps.push_back ({ "mixer meters over the picture, playing", [this, ui] {
- ui->selectTabForSnapshot (3);
- engine->getTransport().songMode = false;
- engine->rewind();
- engine->play();
- ui->getMixerForSnapshot().getStripsForSnapshot().cacheCountersForPerf();
- }, {}, 6000, [this, ui, report] {
- const auto [spoiled, refills] = ui->getMixerForSnapshot().getStripsForSnapshot().cacheCountersForPerf();
- if (juce::FileOutputStream out (report.withFileExtension ("png")); out.openedOk())
- {
- out.setPosition (0);
- out.truncate();
- juce::PNGImageFormat().writeImageToStream (mainWindow->createComponentSnapshot (mainWindow->getLocalBounds()), out);
- }
- return juce::String (" mixer picture: spoiled ") + juce::String (spoiled) + " times, drawn again " + juce::String (refills) + " times\n";
- } });
- run->steps.push_back ({ "mixer scroll", {}, [wheelAt, ui, none] (int f) { wheelAt (ui->getMixerForSnapshot(), 0.0f, f < 30 ? -0.25f : 0.25f, none); }, 60 });
- // a fader dragged while the song plays (round 171c, discussion #10): 4 mouse moves per frame on insert 1's fader,
- // through the old path (a whole snapshot per move) and through editLevels
- auto faderMove = [this] (bool levels, int f) {
- for (int k = 0; k < 4; ++k)
- {
- const auto v = 0.5f + 0.3f * std::sin ((float) (f * 4 + k) * 0.05f);
- const auto edit = [v] (lynx::Song& s) { if (s.mixer.size() > 1) s.mixer[1].volume = v; };
- if (levels)
- engine->editLevels (edit, false); // (no undo step: in a real drag only the press saves one)
- else
- engine->editSong (edit, false);
- }
- };
- run->steps.push_back ({ "mixer fader drag, playing, rebuild per move (before 171c)", {}, [faderMove] (int f) { faderMove (false, f); }, 60 });
- run->steps.push_back ({ "mixer fader drag, playing, live levels (171c)", {}, [faderMove, this] (int f) { faderMove (true, f); if (f == 59) engine->flushLevels(); }, 60 });
- // F8's Plugin picker (round 171c): opening it (the "show" time = building it + its first paint), its pictures
- // loading while it stays open, pointing at the tiles, then closing it
- run->steps.push_back ({ "plugin picker open (F8)", [ui] { ui->togglePluginPickerForSnapshot(); }, {}, 2500 });
- run->steps.push_back ({ "plugin picker, pointing at tiles", {}, [ui] (int f) {
- // (round 175b: the picker is its own window)
- if (auto* picker = ui->pluginPickerForSnapshot(); picker != nullptr && picker->getPeer() != nullptr)
- {
- const auto p = picker->localPointToGlobal (juce::Point<int> (60 + (f * 37) % juce::jmax (1, picker->getWidth() - 120),
- 90 + (f * 53) % juce::jmax (1, picker->getHeight() - 200)));
- const auto local = picker->getPeer()->globalToLocal (p.toFloat());
- picker->getPeer()->handleMouseEvent (juce::MouseInputSource::InputSourceType::mouse, local, {}, 0.0f, 0.0f,
- juce::Time::currentTimeMillis());
- }
- }, 60 });
- run->steps.push_back ({ "plugin picker close", [ui] { ui->togglePluginPickerForSnapshot(); }, {}, 300 });
- run->steps.push_back ({ "playlist maximised, playing", [ui] { ui->selectTabForSnapshot (2); }, {}, 3000 });
- run->steps.push_back ({ "playlist scroll down/up", [this] { engine->stop(); },
- [wheelAt, ui, none] (int f) { wheelAt (ui->getPlaylistForSnapshot(), 0.0f, f < 40 ? -0.15f : 0.15f, none); }, 80 });
- run->steps.push_back ({ "playlist scroll sideways", {},
- [wheelAt, ui, none] (int f) { wheelAt (ui->getPlaylistForSnapshot(), f < 40 ? -0.15f : 0.15f, 0.0f, none); }, 80 });
- // round 174f: Ctrl+wheel zoom, a notch every third frame (~20 a second), three in then three out, as dupmon drives it
- run->steps.push_back ({ "playlist zoom (Ctrl+wheel)", {},
- [wheelAt, ui] (int f) {
- if (f % 3 == 0)
- wheelAt (ui->getPlaylistForSnapshot(), 0.0f, (f / 9) % 2 == 0 ? 0.15f : -0.15f, juce::ModifierKeys (juce::ModifierKeys::ctrlModifier));
- }, 120 });
- run->steps.push_back ({ "playlist after the zoom (settles)", {}, {}, 500 });
- run->steps.push_back ({ "whole window repainted", {}, [this] (int) { mainWindow->repaint(); }, 40 });
- run->steps.push_back ({ "channel rack scroll", [ui] { ui->selectTabForSnapshot (0); },
- [wheelAt, ui, none] (int f) { wheelAt (ui->getRackViewportForSnapshot(), 0.0f, f < 30 ? -0.25f : 0.25f, none); }, 60 });
- // LYNX_UIPERF_ONLY=text: only the steps whose name has that text
- if (const auto only = juce::SystemStats::getEnvironmentVariable ("LYNX_UIPERF_ONLY", {}); only.isNotEmpty())
- run->steps.erase (std::remove_if (run->steps.begin(), run->steps.end(), [&only] (const auto& s) { return ! juce::String (s.name).contains (only); }), run->steps.end());
- // let the window draw the project first
- perf = std::move (run);
- juce::Timer::callAfterDelay (1500, [this] { if (perf != nullptr) perf->startTimer (16); });
- }
- // --rtstress: opens the project in the normal window with the saved audio device, plays it from the start for
- // `seconds` and writes the real-time statistics (deadline misses, late device calls, load histogram, heaviest units)
- // --rtstress --backuptest N (round 177d): while the project plays, a device's MIDI clock (10/s) and active sensing
- // (3/s) arrive, and the project counts as changed. N > 0 also forces a backup every N seconds on top of the timed ones.
- // The report tells how many backups were written, when, and what the MIDI counters did.
- struct BackupTest final : juce::Timer
- {
- lynx::AudioEngine* engine = nullptr;
- lynx::MainComponent* ui = nullptr;
- double everyMs = 0.0, startMs = 0.0, lastForcedMs = 0.0, longestCallMs = 0.0;
- int ticks = 0, forced = 0;
- std::uint64_t seenOver = 0, seenNear = 0;
- juce::String misses; // each callback over (or near) its deadline: how long after the last forced backup
- void timerCallback() override
- {
- engine->injectMidiInput (juce::MidiMessage (0xf8));
- if (++ticks % 3 == 0)
- engine->injectMidiInput (juce::MidiMessage (0xfe));
- const auto now = juce::Time::getMillisecondCounterHiRes();
- const auto s = engine->getRtStats().snapshot();
- if (s.overBudget != seenOver || s.nearBudget != seenNear)
- {
- misses << " +" << juce::String ((now - lastForcedMs) / 1000.0, 1) << " s after the last forced backup (or the start): over +"
- << (juce::int64) (s.overBudget - seenOver) << ", near +" << (juce::int64) (s.nearBudget - seenNear) << "\n";
- seenOver = s.overBudget;
- seenNear = s.nearBudget;
- }
- if (everyMs > 0.0 && now - lastForcedMs >= everyMs)
- {
- lastForcedMs = now;
- ++forced;
- ui->backupNowForTest();
- longestCallMs = juce::jmax (longestCallMs, juce::Time::getMillisecondCounterHiRes() - now);
- }
- }
- };
- std::unique_ptr<BackupTest> backupTest;
- void startBackupTest()
- {
- const auto& cli = juce::JUCEApplication::getCommandLineParameterArray();
- const auto at = cli.indexOf ("--backuptest");
- auto* ui = mainWindow != nullptr ? dynamic_cast<lynx::MainComponent*> (mainWindow->getContentComponent()) : nullptr;
- if (at < 0 || ui == nullptr)
- return;
- backupTest = std::make_unique<BackupTest>();
- backupTest->engine = engine.get();
- backupTest->ui = ui;
- backupTest->everyMs = cli[at + 1].getDoubleValue() * 1000.0;
- backupTest->startMs = backupTest->lastForcedMs = juce::Time::getMillisecondCounterHiRes();
- // (the project counts as changed, so a backup has something to write; the Master's fader is down, so a long run
- // makes no sound: everything else is processed as usual)
- engine->editSong ([] (lynx::Song& s) {
- if (! s.mixer.empty())
- s.mixer[0].volume = 0.0f;
- });
- backupTest->startTimer (100);
- }
- juce::String finishBackupTest()
- {
- if (backupTest == nullptr)
- return {};
- backupTest->stopTimer();
- juce::String text;
- const auto played = engine->getMidiPlayed();
- text << " backup test: MIDI light count " << (int) engine->getMidiActivity() << ", played count " << (int) played << " (clock and active sensing only)\n";
- text << " backup test: " << backupTest->forced << " forced, longest forced call on the message thread "
- << juce::String (backupTest->longestCallMs, 1) << " ms\n";
- if (backupTest->misses.isNotEmpty())
- text << " backup test: callbacks over or near the deadline (seen within 100 ms):\n" << backupTest->misses;
- auto files = lynx::autosaveFolder().findChildFiles (juce::File::findFiles, false, "*.lynx");
- text << " backup test: " << files.size() << " file(s) in the backup folder:\n";
- for (const auto& f : files)
- text << " " << juce::String ((f.getLastModificationTime().toMilliseconds() - juce::Time::getCurrentTime().toMilliseconds()) / 1000) << " s before the end: "
- << f.getFileName() << " (" << f.getSize() << " bytes)\n";
- engine->injectMidiInput (juce::MidiMessage::noteOn (1, 60, (juce::uint8) 1));
- engine->injectMidiInput (juce::MidiMessage::noteOff (1, 60));
- text << " backup test: after a played note, played count " << (int) engine->getMidiPlayed() << "\n";
- backupTest.reset();
- return text;
- }
- void runRealtimeStress (const juce::File& project, const juce::File& report, double seconds, int bufferSize,
- const juce::String& deviceType, const juce::String& deviceName, const juce::String& recordTo = {})
- {
- startupOptions = lynx::StartupOptions::load();
- engine = std::make_unique<lynx::AudioEngine>();
- lynx::videoview::install (*engine); // (Fruity Video Player channels: their sound tracks)
- crashEngine = engine.get();
- // the user's saved device stays as it was: this run's choices are undone before quitting
- savedDeviceState = engine->getDeviceManager().createStateXml();
- auto& devices = engine->getDeviceManager();
- const auto driverFile = addDriverFileDeviceType();
- const auto type = deviceType.isEmpty() && driverFile ? juce::String (lynx::dllAsioTypeName) : deviceType;
- if (type.isNotEmpty() && devices.getCurrentAudioDeviceType() != type)
- devices.setCurrentAudioDeviceType (type, true);
- if (bufferSize > 0 || deviceName.isNotEmpty())
- {
- auto setup = devices.getAudioDeviceSetup();
- if (bufferSize > 0)
- setup.bufferSize = bufferSize;
- if (deviceName.isNotEmpty())
- setup.outputDeviceName = deviceName;
- const auto error = devices.setAudioDeviceSetup (setup, true);
- if (error.isNotEmpty())
- report.replaceWithText ("device error: " + error + "\n");
- }
- createMainWindow();
- if (! juce::JUCEApplication::getCommandLineParameters().contains ("--no-window")) // --no-window: is it the UI?
- mainWindow->reveal();
- juce::String error;
- auto ok = false;
- const auto loadStart = juce::Time::getMillisecondCounterHiRes();
- if (project.hasFileExtension ("flp"))
- ok = engine->importFlpFile (project, error);
- else if (auto song = lynx::ProjectFile::load (project, error))
- {
- engine->setSong (std::move (*song));
- ok = true;
- }
- const auto loadMs = juce::Time::getMillisecondCounterHiRes() - loadStart;
- if (! ok)
- {
- report.replaceWithText ("project: " + project.getFullPathName() + "\nresult=ERROR " + error + "\n");
- restoreSavedDeviceState();
- setApplicationReturnValue (1);
- quit();
- return;
- }
- if (recordTo.isNotEmpty())
- engine->setAudioRecordingArmed (true); // opens the input of the driver
- // let the window draw the project, then play from the start with fresh statistics
- juce::Timer::callAfterDelay (1500, [this, project, report, seconds, loadMs, recordTo] {
- if (engine == nullptr)
- return;
- engine->stop();
- engine->rewind();
- engine->getRtStats().reset();
- engine->takeUiPulse();
- if (recordTo.isNotEmpty())
- engine->setRecording (true);
- // --log folder: the audio logger records what the Master plays during the run (realtime vs export checks)
- const auto& cli = juce::JUCEApplication::getCommandLineParameterArray();
- if (const auto at = cli.indexOf ("--log"); at >= 0 && at + 1 < cli.size())
- engine->getAudioLogger().start (juce::File (cli[at + 1].unquoted()), engine->getDeviceManager().getCurrentAudioDevice() != nullptr
- ? engine->getDeviceManager().getCurrentAudioDevice()->getCurrentSampleRate() : 44100.0);
- engine->play();
- startBackupTest();
- juce::Timer::callAfterDelay ((int) (seconds * 1000.0), [this, project, report, seconds, loadMs, recordTo] {
- if (engine == nullptr)
- return;
- const auto backupReport = finishBackupTest();
- engine->stop();
- juce::String recording;
- if (engine->getAudioLogger().isLogging())
- {
- recording << " logged: " << engine->getAudioLogger().currentFile().getFullPathName() << "\n";
- engine->getAudioLogger().stop();
- }
- if (recordTo.isNotEmpty())
- recording = finishStressTake (juce::File (recordTo), seconds);
- const auto& cli = juce::JUCEApplication::getCommandLineParameterArray();
- const auto s = engine->getRtStats().snapshot();
- juce::String text;
- text << "project: " << project.getFullPathName() << "\n"
- << "LYNX " << getApplicationVersion() << ", " << juce::SystemStats::getOperatingSystemName() << ", "
- << juce::SystemStats::getNumCpus() << " logical CPUs (" << juce::SystemStats::getNumPhysicalCpus() << " cores), "
- << juce::SystemStats::getCpuModel() << "\n"
- << "load " << juce::String (loadMs / 1000.0, 1) << " s, played " << juce::String (seconds, 0) << " s\n"
- << engine->describeRealtime();
- const auto pulse = engine->takeUiPulse();
- text << " UI: the 30 Hz engine timer ran " << pulse.calls << " times (" << juce::String (pulse.calls / seconds, 1)
- << "/s), longest gap " << juce::String (pulse.maxGapMs, 0) << " ms" << (mainWindow == nullptr || ! mainWindow->isVisible() ? " (window hidden)" : "") << "\n";
- text << " load histogram (share of the deadline: callbacks):";
- for (std::size_t b = 0; b < s.histogram.size(); ++b)
- if (s.histogram[b] > 0)
- text << " " << (int) (b * 10) << (b + 1 == s.histogram.size() ? juce::String ("+") : "-" + juce::String ((int) (b * 10 + 10))) << "%:" << (juce::int64) s.histogram[b];
- text << "\n";
- text << recording << backupReport;
- // --settingsshot file.png (round 161): Options > Audio settings of this run's device, as a picture
- if (const auto at = cli.indexOf ("--settingsshot"); at >= 0 && at + 1 < cli.size())
- {
- auto page = lynx::makeSettingsPanel (*engine, lynx::SettingsPage::audio);
- juce::Image image (juce::Image::ARGB, page->getWidth(), page->getHeight(), true);
- {
- juce::Graphics g (image);
- g.fillAll (lynx::theme::panel);
- page->paintEntireComponent (g, false);
- }
- const juce::File shot (cli[at + 1].unquoted());
- shot.deleteFile();
- if (auto out = shot.createOutputStream())
- juce::PNGImageFormat().writeImageToStream (image, *out);
- }
- text << "result=" << (s.callbacks == 0 ? "ERROR no audio callbacks" : s.overBudget == 0 && s.lateCalls == 0 ? "OK" : "GLITCHES") << "\n";
- report.replaceWithText (text);
- restoreSavedDeviceState();
- setApplicationReturnValue (s.callbacks == 0 ? 1 : 0);
- quit();
- });
- });
- }
- // --bendrectest (round 167a): see the command line above
- void runBendRecordTest (const juce::File& report, bool songMode)
- {
- engine = std::make_unique<lynx::AudioEngine>();
- auto text = std::make_shared<juce::String>();
- auto step = [report, text] (const juce::String& line) { *text << line << "\n"; report.replaceWithText (*text); };
- auto finish = [this] (int code) {
- setApplicationReturnValue (code);
- quit();
- };
- auto* device = engine->getDeviceManager().getCurrentAudioDevice();
- if (device == nullptr)
- {
- step ("result=ERROR no audio device");
- finish (1);
- return;
- }
- step ("device=" + device->getTypeName() + " | " + device->getName() + " | mode " + (songMode ? "song" : "pattern"));
- auto song = lynx::Song::makeDefault();
- song.bpm = 120.0;
- song.mode = songMode ? lynx::PlayMode::song : lynx::PlayMode::pattern;
- engine->setSong (std::move (song));
- auto o = engine->getRecordOptions();
- o.mode = lynx::RecordMode::overdub;
- o.recordNotes = true;
- o.recordAutomation = true;
- o.countInBars = 0;
- o.waitForInput = false;
- o.quantiseAutomation = false;
- o.punchLoopRegion = false;
- o.preRollBars = o.postRollBars = 0;
- engine->setRecordOptions (o);
- engine->stop();
- engine->rewind();
- engine->setRecording (true);
- engine->startPlayback();
- // 2 s of wheel at ~100 messages a second: 0 → +1 (0.5 s), +1 → −1 (1 s), −1 → 0 (0.5 s)
- auto sent = std::make_shared<std::vector<std::pair<double, float>>>();
- auto t0 = std::make_shared<double> (juce::Time::getMillisecondCounterHiRes());
- engine->injectMidiInput (juce::MidiMessage::noteOn (1, 60, (juce::uint8) 100));
- auto tick = std::make_shared<std::function<void()>>();
- *tick = [this, sent, t0, tick, step, finish, songMode] {
- if (engine == nullptr)
- return;
- const auto ms = juce::Time::getMillisecondCounterHiRes() - *t0;
- if (ms < 2000.0)
- {
- const auto x = ms / 1000.0;
- const auto v = (float) (x < 0.5 ? x * 2.0 : x < 1.5 ? 1.0 - (x - 0.5) * 2.0 : -1.0 + (x - 1.5) * 2.0);
- const auto wheel = juce::jlimit (0, 16383, 8192 + juce::roundToInt (v * 8191.0f));
- engine->injectMidiInput (juce::MidiMessage::pitchWheel (1, wheel));
- sent->push_back ({ ms, (float) (wheel - 8192) / 8192.0f });
- juce::Timer::callAfterDelay (10, *tick);
- return;
- }
- engine->injectMidiInput (juce::MidiMessage::pitchWheel (1, 8192));
- engine->injectMidiInput (juce::MidiMessage::noteOff (1, 60));
- juce::Timer::callAfterDelay (400, [this, sent, step, finish, songMode] {
- if (engine == nullptr)
- return;
- engine->stop();
- juce::Timer::callAfterDelay (600, [this, sent, step, finish, songMode] {
- if (engine == nullptr)
- return;
- engine->setRecording (false);
- const auto& s = engine->getSong();
- // the channel's pitch bend (MIDI channel 1), recorded as a lane or a clip
- std::vector<std::pair<std::int64_t, float>> got;
- juce::String where = "nothing";
- for (const auto& a : s.automations)
- if (a.target.kind == lynx::AutomationTargetKind::channelParam && lynx::midictl::isPitchBend (a.target.param))
- {
- where = "automation clip \"" + juce::String (a.name) + "\"";
- for (const auto& pt : a.points)
- got.push_back ({ pt.tick, pt.value });
- }
- for (const auto& p : s.patterns)
- for (const auto& lane : p.events)
- if (lane.target.kind == lynx::AutomationTargetKind::channelParam && lynx::midictl::isPitchBend (lane.target.param))
- {
- where = "pattern \"" + juce::String (p.name) + "\" event lane";
- for (const auto& e : lane.events)
- got.push_back ({ e.tick, e.value });
- }
- int notes = 0;
- for (const auto& p : s.patterns)
- notes += (int) p.notes.size();
- float lo = 1.0f, hi = 0.0f;
- for (const auto& [t, v] : got)
- lo = std::min (lo, v), hi = std::max (hi, v);
- // ticks: in order, spread over the ~2 s sweep (8 beats of 96 ticks at 120 bpm ≈ 4 beats)
- const auto span = got.empty() ? 0 : got.back().first - got.front().first;
- const auto sorted = std::is_sorted (got.begin(), got.end(), [] (const auto& a, const auto& b) { return a.first < b.first; });
- step ("sent=" + juce::String ((int) sent->size()) + " wheel messages over 2 s");
- step ("recorded=" + juce::String ((int) got.size()) + " points in " + where + ", value " + juce::String (lo, 3) + " .. "
- + juce::String (hi, 3) + " (0.5 = centre), ticks " + juce::String (span) + " apart, " + (sorted ? "in order" : "OUT OF ORDER")
- + ", notes " + juce::String (notes));
- if (! got.empty())
- step ("last=" + juce::String (got.back().second, 3));
- // song mode: a clip over the take, ending back at the centre. Pattern mode: the take loops the 1-bar pattern
- // (4.6 beats of take), so the lane spans the bar and the last wheel message (the centre) lands inside it
- const auto centred = std::any_of (got.begin(), got.end(), [] (const auto& p) { return std::abs (p.second - 0.5f) < 0.02f; });
- const auto ok = got.size() >= 20 && hi > 0.97f && lo < 0.03f && sorted && notes >= 1
- && (songMode ? span > lynx::ppq * 3 && span < lynx::ppq * 6 && std::abs (got.back().second - 0.5f) < 0.02f
- : span > lynx::ppq * 2 && span <= lynx::ppq * 4 && centred);
- step (ok ? "result=OK" : "result=FAILED");
- finish (ok ? 0 : 1);
- });
- });
- };
- juce::Timer::callAfterDelay (300, *tick);
- }
- // --countinrectest (round 170d): see the command line above.
- void runCountInRecordTest (const juce::File& report)
- {
- engine = std::make_unique<lynx::AudioEngine>();
- engine->getDeviceManager().closeAudioDevice(); // the engine's callback is driven by hand below
- struct StandIn final : juce::AudioIODevice
- {
- StandIn() : juce::AudioIODevice ("countin", "test") {}
- juce::StringArray getOutputChannelNames() override { return { "L", "R" }; }
- juce::StringArray getInputChannelNames() override { return {}; }
- juce::Array<double> getAvailableSampleRates() override { return { 48000.0 }; }
- juce::Array<int> getAvailableBufferSizes() override { return { 512 }; }
- int getDefaultBufferSize() override { return 512; }
- juce::String open (const juce::BigInteger&, const juce::BigInteger&, double, int) override { return {}; }
- void close() override {}
- bool isOpen() override { return true; }
- void start (juce::AudioIODeviceCallback*) override {}
- void stop() override {}
- bool isPlaying() override { return true; }
- juce::String getLastError() override { return {}; }
- int getCurrentBufferSizeSamples() override { return 512; }
- double getCurrentSampleRate() override { return 48000.0; }
- int getCurrentBitDepth() override { return 32; }
- juce::BigInteger getActiveOutputChannels() const override
- {
- juce::BigInteger b;
- b.setRange (0, 2, true);
- return b;
- }
- juce::BigInteger getActiveInputChannels() const override { return {}; }
- int getOutputLatencyInSamples() override { return 256; }
- int getInputLatencyInSamples() override { return 0; }
- };
- auto device = std::make_shared<StandIn>();
- auto text = std::make_shared<juce::String>();
- auto step = [report, text] (const juce::String& line) { *text << line << "\n"; report.replaceWithText (*text); };
- auto finish = [this] (int code) {
- setApplicationReturnValue (code);
- quit();
- };
- constexpr std::int64_t bar = 4 * lynx::ppq; // 120 BPM, 4/4
- lynx::Song song; // (as --cliplooptest: one synth channel on insert 1, an empty pattern)
- song.bpm = 120.0;
- song.mixer = lynx::Song::defaultMixer (2);
- song.channels.resize (1);
- song.channels[0].mixerTrack = 1;
- song.patterns.emplace_back();
- song.mode = lynx::PlayMode::song;
- song.currentPattern = 0;
- engine->setSong (song);
- engine->getTransport().metronome.store (true);
- auto o = engine->getRecordOptions();
- o.mode = lynx::RecordMode::overdub;
- o.countInBars = 1;
- o.catchWindow = lynx::ppq / 4;
- o.compensateOutput = true;
- o.recordNotes = true;
- o.recordAudio = false;
- o.recordAutomation = false;
- o.waitForInput = false;
- o.quantise = 0;
- o.placeSongClip = true;
- o.recordingMarkers = false;
- o.punchLoopRegion = false;
- o.preRollBars = o.postRollBars = 0;
- engine->setRecordOptions (o);
- engine->deviceCallback().audioDeviceAboutToStart (device.get());
- step ("stand-in device: 48 kHz, blocks of 512, output latency 256 samples; Song mode, 120 BPM, take from bar 3, count-in 1 bar");
- // an event heard at output sample `heard` (counted from the first block after Play), sent as MIDI input
- struct Event
- {
- std::int64_t heard;
- juce::MidiMessage message;
- };
- struct Pass
- {
- std::vector<float> out;
- std::vector<Event> events;
- std::int64_t playingAt = -1; // the first sample of the block the song started in
- int block = 0, blocks = 0;
- std::function<void()> done;
- };
- constexpr int n = 512;
- constexpr double rate = 48000.0;
- // one pass: the take recorded from bar 3, `blocks` blocks driven by hand, 8 at a time between the engine's timer
- // ticks (the take is committed there); then stopped and its results left to the timer
- auto runPass = std::make_shared<std::function<void (std::shared_ptr<Pass>)>>();
- *runPass = [this] (std::shared_ptr<Pass> pass) {
- auto& cb = engine->deviceCallback();
- std::vector<float> l (n), r (n);
- float* outs[] = { l.data(), r.data() };
- juce::AudioIODeviceCallbackContext context;
- if (pass->block == 0)
- {
- engine->stop();
- engine->seek ((double) (2 * bar));
- cb.audioDeviceIOCallbackWithContext (nullptr, 0, outs, 2, n, context); // (the seek, stopped)
- engine->setRecording (true);
- engine->startPlayback(); // the count-in starts
- }
- for (int k = 0; k < 8 && pass->block < pass->blocks; ++k, ++pass->block)
- {
- // the events heard in this block: stamped the way the engine's clock maps time to heard samples
- const auto blockStart = (std::int64_t) pass->block * n;
- const auto clock = engine->liveClock();
- const auto compMs = 1000.0 * (n + 256) / rate;
- for (auto& e : pass->events)
- if (e.heard >= blockStart && e.heard < blockStart + n)
- {
- auto m = e.message;
- m.setTimeStamp ((clock.timeMs + compMs + (double) (e.heard - blockStart) * 1000.0 / rate) * 0.001);
- engine->injectMidiInput (m);
- }
- cb.audioDeviceIOCallbackWithContext (nullptr, 0, outs, 2, n, context);
- pass->out.insert (pass->out.end(), l.begin(), l.end());
- if (pass->playingAt < 0 && engine->getTransport().playing.load())
- pass->playingAt = blockStart;
- }
- };
- // (the recursion through the message loop; written out so each step lets the engine's timer run)
- auto drive = std::make_shared<std::function<void (std::shared_ptr<Pass>)>>();
- *drive = [this, runPass, drive, device] (std::shared_ptr<Pass> pass) { // (the stand-in lives while the passes run)
- if (engine == nullptr)
- return;
- (*runPass) (pass);
- if (pass->block < pass->blocks)
- {
- juce::Timer::callAfterDelay (40, [pass, drive] { (*drive) (pass); });
- return;
- }
- engine->stop();
- juce::Timer::callAfterDelay (300, [this, pass] {
- if (engine == nullptr)
- return;
- engine->setRecording (false);
- juce::Timer::callAfterDelay (200, [pass] { pass->done(); });
- });
- };
- auto onsets = [] (const std::vector<float>& out) {
- std::vector<std::int64_t> at;
- std::int64_t last = -100000;
- for (std::size_t i = 0; i < out.size(); ++i)
- if (std::abs (out[i]) > 0.02f && (std::int64_t) i - last > 4000)
- {
- at.push_back ((std::int64_t) i);
- last = (std::int64_t) i;
- }
- else if (std::abs (out[i]) > 0.02f)
- last = (std::int64_t) i;
- return at;
- };
- // the graph is (re)built on the message thread: start once it has settled
- juce::Timer::callAfterDelay (1500, [this, step, finish, drive, onsets] {
- if (engine == nullptr)
- return;
- auto first = std::make_shared<Pass>();
- first->blocks = (int) (rate * 18.0 / n); // count-in + 8 bars
- first->done = [this, first, step, finish, drive, onsets] {
- const auto clicks = onsets (first->out);
- juce::String list;
- for (std::size_t i = 0; i < std::min<std::size_t> (clicks.size(), 8); ++i)
- list << clicks[i] << " ";
- step ("pass 1: clicks heard at samples " + list + "…, the song started in the block at " + juce::String (first->playingAt));
- // the bar-3 downbeat: the click at the block the song started in
- std::int64_t down = -1;
- for (auto c : clicks)
- if (std::abs (c - first->playingAt) < n)
- down = c;
- if (down < 0 || engine->getSong().patterns[0].notes.size() != 0)
- {
- step ("result=FAILED no downbeat click found (or notes recorded without input)");
- finish (1);
- return;
- }
- const auto ms = [down] (double t) { return down + (std::int64_t) std::llround (t * rate / 1000.0); };
- auto second = std::make_shared<Pass>();
- second->blocks = first->blocks;
- auto add = [&second] (std::int64_t at, int key, bool on) {
- second->events.push_back ({ at, on ? juce::MidiMessage::noteOn (1, key, (juce::uint8) 100) : juce::MidiMessage::noteOff (1, key) });
- };
- for (int key : { 60, 64, 67 }) // the chord, 15 ms early, held half a second
- {
- add (ms (-15.0), key, true);
- add (ms (500.0), key, false);
- }
- add (ms (-1500.0), 62, true); // beat 2 of the count-in bar (bar 2)
- add (ms (-1250.0), 62, false);
- add (ms (503.0), 77, true); // 3 ms after beat 2
- add (ms (603.0), 77, false);
- for (int b = 1; b <= 6; ++b) // a note a bar ("it stopped after two bars")
- {
- add (ms (b * 2000.0), 70 + b, true);
- add (ms (b * 2000.0 + 250.0), 70 + b, false);
- }
- second->done = [this, step, finish] {
- const auto& s = engine->getSong();
- const auto& p = s.patterns[0];
- const lynx::Clip* clip = nullptr;
- for (const auto& c : s.playlist)
- if (c.kind == lynx::ClipKind::pattern && c.pattern == 0)
- clip = &c;
- const auto origin = clip != nullptr ? clip->start - clip->offset : -1;
- step ("pass 2: " + juce::String ((int) p.notes.size()) + " notes recorded, clip at " + juce::String (clip != nullptr ? clip->start : -1));
- auto ok = clip != nullptr && origin == bar && p.notes.size() == 11;
- // where each one was heard (song ticks): 0.5 ms = ~1 tick
- const std::vector<std::pair<int, double>> want = { { 60, 2.0 * bar }, { 64, 2.0 * bar }, { 67, 2.0 * bar },
- { 62, 2.0 * bar - 3 * lynx::ppq }, { 77, 2.0 * bar + lynx::ppq + 3.0 * 1.92 },
- { 71, 3.0 * bar }, { 72, 4.0 * bar }, { 73, 5.0 * bar },
- { 74, 6.0 * bar }, { 75, 7.0 * bar }, { 76, 8.0 * bar } };
- for (const auto& [key, tick] : want)
- {
- const lynx::Note* found = nullptr;
- for (const auto& note : p.notes)
- if (note.key == key)
- found = ¬e;
- const auto at = found != nullptr ? (double) (origin + found->start) : -1.0;
- const auto good = found != nullptr && std::abs (at - tick) <= 2.0;
- ok = ok && good;
- step ("key " + juce::String (key) + ": heard at tick " + juce::String (tick, 2) + ", recorded at " + juce::String (at, 0)
- + (good ? " ok" : " WRONG"));
- }
- const auto* chord = [&p] () -> const lynx::Note* {
- for (const auto& note : p.notes)
- if (note.key == 60)
- return ¬e;
- return nullptr;
- }();
- if (chord != nullptr)
- step ("chord length " + juce::String (chord->length) + " ticks (caught 15 ms early, released 500 ms after bar 3: 960)");
- step (ok ? "result=OK" : "result=FAILED");
- finish (ok ? 0 : 1);
- };
- (*drive) (second);
- };
- (*drive) (first);
- });
- }
- // --cliplooptest (round 167q): see the command line above.
- void runClipLoopTest (const juce::File& report, const juce::File& wavFile)
- {
- engine = std::make_unique<lynx::AudioEngine>();
- engine->getDeviceManager().closeAudioDevice(); // the engine's callback is driven by hand below
- struct StandIn final : juce::AudioIODevice
- {
- StandIn() : juce::AudioIODevice ("cliploop", "test") {}
- juce::StringArray getOutputChannelNames() override { return { "L", "R" }; }
- juce::StringArray getInputChannelNames() override { return {}; }
- juce::Array<double> getAvailableSampleRates() override { return { 48000.0 }; }
- juce::Array<int> getAvailableBufferSizes() override { return { 512 }; }
- int getDefaultBufferSize() override { return 512; }
- juce::String open (const juce::BigInteger&, const juce::BigInteger&, double, int) override { return {}; }
- void close() override {}
- bool isOpen() override { return true; }
- void start (juce::AudioIODeviceCallback*) override {}
- void stop() override {}
- bool isPlaying() override { return true; }
- juce::String getLastError() override { return {}; }
- int getCurrentBufferSizeSamples() override { return 512; }
- double getCurrentSampleRate() override { return 48000.0; }
- int getCurrentBitDepth() override { return 32; }
- juce::BigInteger getActiveOutputChannels() const override
- {
- juce::BigInteger b;
- b.setRange (0, 2, true);
- return b;
- }
- juce::BigInteger getActiveInputChannels() const override { return {}; }
- int getOutputLatencyInSamples() override { return 0; }
- int getInputLatencyInSamples() override { return 0; }
- };
- auto device = std::make_shared<StandIn>();
- auto text = std::make_shared<juce::String>();
- auto step = [report, text] (const juce::String& line) { *text << line << "\n"; report.replaceWithText (*text); };
- constexpr int bar = 96000, beat = bar / 4; // 120 BPM, 48 kHz
- const auto ppq = (double) lynx::ppq;
- lynx::Song song;
- song.bpm = 120.0;
- song.mixer = lynx::Song::defaultMixer (2);
- song.channels.resize (1); // the synth of a new channel: deterministic
- song.channels[0].mixerTrack = 1;
- auto& pattern = song.patterns.emplace_back(); // 1 bar: C5 on beat 0, C6 on beat 2
- for (auto [b, key] : { std::pair { 0, 60 }, std::pair { 2, 72 } })
- {
- lynx::Note n;
- n.start = b * lynx::ppq;
- n.length = lynx::ppq / 4;
- n.key = key;
- pattern.notes.push_back (n);
- }
- lynx::Clip clip;
- clip.pattern = 0;
- clip.length = 16 * lynx::ppq; // stretched to 4 bars
- song.playlist.push_back (clip);
- song.mode = lynx::PlayMode::song;
- {
- // the Windows GUI check's project: the same song with a 1-bar clip, to stretch with the mouse
- auto gui = song;
- gui.playlist[0].length = 4 * lynx::ppq;
- juce::String error;
- lynx::ProjectFile::save (gui, report.getSiblingFile ("cliploop-gui.lynx"), error);
- }
- engine->setSong (song);
- auto& callback = engine->deviceCallback();
- callback.audioDeviceAboutToStart (device.get());
- step ("song=1-bar synth pattern, clip stretched to 4 bars, 120 BPM, 48 kHz, blocks of 512");
- // the graph is (re)built on the message thread: the scenarios run once it has settled
- juce::Timer::callAfterDelay (1500, [this, device, step, wavFile, ppq] {
- if (engine == nullptr)
- return;
- auto& cb = engine->deviceCallback();
- // plays `samples` from tick `from` through the device callback; `between` runs after each block (block index)
- auto play = [this, &cb] (double from, int samples, const std::function<void (int)>& between = {}) {
- engine->stop();
- engine->seek (from);
- std::vector<float> l (512), r (512), out;
- float* outs[] = { l.data(), r.data() };
- juce::AudioIODeviceCallbackContext context;
- cb.audioDeviceIOCallbackWithContext (nullptr, 0, outs, 2, 512, context); // (the seek, stopped)
- engine->play();
- for (int k = 0; (int) out.size() < samples; ++k)
- {
- cb.audioDeviceIOCallbackWithContext (nullptr, 0, outs, 2, 512, context);
- out.insert (out.end(), l.begin(), l.end());
- if (between)
- between (k);
- }
- engine->stop();
- for (int k = 0; k < 400; ++k) // the tails of the scenario die out
- cb.audioDeviceIOCallbackWithContext (nullptr, 0, outs, 2, 512, context);
- out.resize ((std::size_t) samples);
- return out;
- };
- auto rms = [] (const std::vector<float>& x, int from, int count) {
- double sum = 0.0;
- for (int i = from; i < from + count && i < (int) x.size(); ++i)
- sum += (double) x[(std::size_t) i] * x[(std::size_t) i];
- return std::sqrt (sum / juce::jmax (1, count));
- };
- auto diff = [] (const std::vector<float>& a, int aFrom, const std::vector<float>& b, int bFrom, int count) {
- double m = 0.0;
- for (int i = 0; i < count && aFrom + i < (int) a.size() && bFrom + i < (int) b.size(); ++i)
- m = juce::jmax (m, (double) std::abs (a[(std::size_t) (aFrom + i)] - b[(std::size_t) (bFrom + i)]));
- return m;
- };
- auto num = [] (double v) { return juce::String (v, 6); };
- bool ok = true;
- auto check = [&ok, step] (bool good, const juce::String& what) {
- ok = ok && good;
- step ((good ? "ok " : "FAIL ") + what);
- };
- lynx::setStretchedClipsLoop (true);
- const auto a = play (0.0, 4 * bar);
- const auto bar1 = rms (a, 0, bar);
- check (bar1 > 0.01, "play from the start: bar 1 RMS " + num (bar1));
- for (int k = 1; k < 4; ++k)
- {
- const auto rk = rms (a, k * bar, bar), d = diff (a, k * bar, a, 0, bar);
- check (std::abs (rk / bar1 - 1.0) < 1.0e-3 && d < 1.0e-4,
- "bar " + juce::String (k + 1) + " RMS " + num (rk) + " (x" + num (rk / bar1) + " of bar 1), max |bar - bar 1| " + juce::String (d, 9));
- }
- {
- const auto x = play (10 * ppq, bar + bar / 2);
- const auto d = juce::jmax (diff (x, 0, a, 2 * beat, bar / 2), diff (x, bar / 2, a, 0, bar));
- check (rms (x, 0, bar / 2) > 0.01 && d < 1.0e-4,
- "start inside a repeat (bar 3, beat 3): RMS " + num (rms (x, 0, (int) x.size())) + ", max diff vs bar 1 " + juce::String (d, 9));
- }
- {
- // a seek while playing, after 6.99 beats, to bar 4 beat 3 (a ruler click)
- const auto jumpBlock = 7 * beat / 512 - 1;
- const auto x = play (0.0, 2 * bar, [this, jumpBlock, ppq] (int k) {
- if (k == jumpBlock)
- engine->seek (14 * ppq);
- });
- // (the best of 0-2 samples late: anything but 0 fails)
- const auto at = (jumpBlock + 1) * 512;
- int lag = 0;
- auto d = 1.0e9;
- for (int l = 0; l <= 2; ++l)
- if (const auto dl = diff (x, at + l, a, 2 * beat, beat - 2); dl < d)
- d = dl, lag = l;
- d = lag == 0 ? d : 1.0;
- const auto ratio = rms (x, at, beat) / rms (a, 2 * beat, beat);
- check (std::abs (ratio - 1.0) < 1.0e-3 && d < 1.0e-4,
- "jump mid-clip to bar 4 beat 3: RMS " + num (rms (x, at, beat)) + " (x" + num (ratio) + " of bar 1 beat 3), max diff "
- + juce::String (d, 9) + " (" + juce::String (lag) + " sample(s) late)");
- }
- {
- engine->editSong ([ppq] (lynx::Song& s) {
- s.loopStart = (std::int64_t) (4 * ppq);
- s.loopEnd = (std::int64_t) (12 * ppq);
- }, false);
- const auto x = play (0.0, 7 * bar);
- double d = 0.0;
- juce::String lags;
- for (int k = 1; k < 7; ++k) // (the best of 0-2 samples late after a wrap, as after a jump)
- {
- auto best = 1.0e9;
- int lag = 0;
- for (int l = 0; l <= 2; ++l)
- if (const auto dl = diff (x, k * bar + l, a, 0, bar - 2); dl < best)
- best = dl, lag = l;
- d = juce::jmax (d, lag == 0 ? best : 1.0); // a sample gained at a wrap fails (round 167q loopwrap)
- lags << (k > 1 ? "," : "") << lag;
- }
- const auto r = rms (x, bar, 6 * bar);
- check (std::abs (r / bar1 - 1.0) < 1.0e-3 && d < 1.0e-4,
- "loop region bars 2-3, played 3 times: RMS " + num (r) + " (x" + num (r / bar1) + "), max diff of each bar vs bar 1 " + juce::String (d, 9)
- + " (samples late, bars 2-7: " + lags + ")");
- engine->editSong ([] (lynx::Song& s) { s.loopStart = s.loopEnd = 0; }, false);
- }
- {
- // 100 wraps of a 1-bar loop region (bar 2): every pass on its sample, none gained (round 167q loopwrap: each
- // wrap used to play one sample more)
- engine->editSong ([ppq] (lynx::Song& s) {
- s.loopStart = (std::int64_t) (4 * ppq);
- s.loopEnd = (std::int64_t) (8 * ppq);
- }, false);
- const auto x = play (0.0, 101 * bar);
- double d = 0.0;
- int worst = 0;
- for (int k = 1; k <= 100; ++k)
- if (const auto dk = diff (x, k * bar, a, 0, bar); dk > d)
- d = dk, worst = k + 1;
- check (d < 1.0e-4, "loop region bar 2, 100 wraps: max diff of every pass vs bar 1 " + juce::String (d, 9)
- + (d < 1.0e-4 ? juce::String() : " (worst: bar " + juce::String (worst) + ")"));
- engine->editSong ([] (lynx::Song& s) { s.loopStart = s.loopEnd = 0; }, false);
- }
- lynx::setStretchedClipsLoop (false);
- {
- const auto x = play (0.0, 4 * bar);
- const auto r = juce::jmax (rms (x, bar, bar), juce::jmax (rms (x, 2 * bar, bar), rms (x, 3 * bar, bar)));
- check (diff (x, 0, a, 0, bar) < 1.0e-4 && r < 1.0e-5, "option off (FL): bar 1 the same, bars 2-4 RMS at most " + juce::String (r, 9));
- }
- lynx::setStretchedClipsLoop (true);
- cb.audioDeviceStopped();
- // the export: a WAV of the 4 bars, read back from the file
- if (wavFile != juce::File())
- {
- for (const auto loops : { true, false })
- {
- lynx::setStretchedClipsLoop (loops);
- const auto file = loops ? wavFile : wavFile.getSiblingFile (wavFile.getFileNameWithoutExtension() + "-off.wav");
- file.deleteFile();
- {
- juce::WavAudioFormat wav;
- std::unique_ptr<juce::AudioFormatWriter> writer (wav.createWriterFor (file.createOutputStream().release(), 48000.0, 2, 32, {}, 0));
- engine->stop();
- engine->seek (0.0);
- lynx::AudioEngine::RenderOptions o;
- o.seconds = 8.0;
- o.sampleRate = 48000.0;
- o.output = writer.get();
- engine->renderOffline (o);
- }
- juce::WavAudioFormat wav;
- std::unique_ptr<juce::AudioFormatReader> reader (wav.createReaderFor (file.createInputStream().release(), true));
- std::vector<float> x;
- if (reader != nullptr)
- {
- juce::AudioBuffer<float> buffer (2, (int) reader->lengthInSamples);
- reader->read (&buffer, 0, (int) reader->lengthInSamples, 0, true, true);
- x.assign (buffer.getReadPointer (0), buffer.getReadPointer (0) + buffer.getNumSamples());
- }
- const auto b1 = rms (x, 0, bar);
- juce::String line = juce::String (loops ? "export" : "export, option off") + " (" + file.getFileName() + ", " + juce::String ((int) x.size()) + " samples): bar 1 RMS " + num (b1);
- bool good = x.size() >= (std::size_t) 4 * bar && b1 > 0.01;
- for (int k = 1; k < 4; ++k)
- {
- const auto rk = rms (x, k * bar, bar);
- line << ", bar " << (k + 1) << " " << num (rk);
- good = good && (loops ? std::abs (rk / b1 - 1.0) < 1.0e-3 && diff (x, k * bar, x, 0, bar) < 1.0e-4 : rk < 1.0e-5);
- }
- if (loops)
- line << ", max |bar - bar 1| " << juce::String (juce::jmax (diff (x, bar, x, 0, bar), juce::jmax (diff (x, 2 * bar, x, 0, bar), diff (x, 3 * bar, x, 0, bar))), 9);
- check (good, line);
- }
- lynx::setStretchedClipsLoop (true);
- }
- step (ok ? "result=OK" : "result=FAILED");
- setApplicationReturnValue (ok ? 0 : 1);
- quit();
- });
- }
- // --rectest (round 163): see the command line above. Writes report lines step by step (a driver that ends the
- // process leaves what was done).
- void runRecordTest (const juce::File& report, double seconds, const juce::String& deviceType, const juce::String& deviceName,
- const juce::String& inputName, int mode, int pdcSamples, int bufferSize)
- {
- engine = std::make_unique<lynx::AudioEngine>();
- lynx::videoview::install (*engine); // (Fruity Video Player channels: their sound tracks)
- savedDeviceState = engine->getDeviceManager().createStateXml();
- auto text = std::make_shared<juce::String>();
- auto step = [report, text] (const juce::String& line) { *text << line << "\n"; report.replaceWithText (*text); };
- auto finish = [this, step] (int code) {
- restoreSavedDeviceState();
- setApplicationReturnValue (code);
- quit();
- };
- auto& devices = engine->getDeviceManager();
- if (deviceType.isNotEmpty() && devices.getCurrentAudioDeviceType() != deviceType)
- devices.setCurrentAudioDeviceType (deviceType, true);
- {
- auto setup = devices.getAudioDeviceSetup();
- if (deviceName.isNotEmpty())
- setup.outputDeviceName = deviceName;
- if (bufferSize > 0)
- setup.bufferSize = bufferSize;
- if (const auto error = devices.setAudioDeviceSetup (setup, true); error.isNotEmpty())
- step ("device_error=" + error);
- }
- if (const auto r = engine->openAudioInput (inputName.isNotEmpty() ? inputName : deviceName); r.issue != lynx::AudioEngine::InputIssue::none)
- step ("input_error=" + juce::String ((int) r.issue) + " " + r.detail);
- // takes go next to the report, not into the user's recordings folder
- engine->setRecordingTarget (report.getSiblingFile (report.getFileNameWithoutExtension() + "-takes"), {});
- auto* device = devices.getCurrentAudioDevice();
- if (device == nullptr || engine->getInputChannelNames().empty())
- {
- step ("result=ERROR no device / no input");
- finish (1);
- return;
- }
- const auto rate = device->getCurrentSampleRate();
- step ("device=" + device->getTypeName() + " | " + device->getName() + " | " + juce::String (rate) + " Hz | block " + juce::String (device->getCurrentBufferSizeSamples())
- + " | driver latency in " + juce::String (device->getInputLatencyInSamples()) + " out " + juce::String (device->getOutputLatencyInSamples()));
- // a click (the ping's pulse) on every beat at 120 bpm: beat k at sample k * rate / 2
- const auto beats = (int) std::ceil (seconds * 2.0) + 8;
- const auto clickFile = report.getSiblingFile (report.getFileNameWithoutExtension() + "-clicks.wav");
- {
- lynx::takes::WavTakeWriter w;
- w.open (clickFile.getFullPathName().toStdString(), rate, 1, lynx::takes::SampleFormat::float32);
- const auto total = (juce::int64) std::llround ((double) beats * rate / 2.0);
- std::vector<float> block (4096);
- for (juce::int64 at = 0; at < total; at += (juce::int64) block.size())
- {
- std::fill (block.begin(), block.end(), 0.0f);
- for (int k = 0; k < (int) block.size(); ++k)
- {
- const auto f = at + k;
- const auto beat = (juce::int64) std::floor ((double) f / (rate / 2.0));
- const auto rel = f - (juce::int64) std::llround ((double) beat * rate / 2.0);
- static constexpr float shape[] { 0.25f, 0.75f, 1.0f, 0.75f, 0.25f };
- if (rel >= 0 && rel < 5)
- block[(std::size_t) k] = 0.5f * shape[rel];
- }
- const float* d[] { block.data() };
- w.write (d, (int) std::min<juce::int64> ((juce::int64) block.size(), total - at));
- }
- w.close();
- }
- lynx::Song song = lynx::Song::makeDefault();
- song.bpm = 120.0;
- song.mode = lynx::PlayMode::song;
- song.playlist.clear();
- lynx::ChannelDef c;
- c.name = "Clicks";
- c.instrument = lynx::InstrumentKind::audioClip;
- c.samplePath = clickFile.getFullPathName().toStdString();
- c.mixerTrack = 0;
- c.volume = 1.0f;
- song.channels.push_back (c);
- lynx::Clip clip;
- clip.kind = lynx::ClipKind::audio;
- clip.channel = (int) song.channels.size() - 1;
- clip.track = 0;
- clip.start = 0;
- clip.length = (std::int64_t) beats * lynx::ppq;
- song.playlist.push_back (clip);
- if (mode == 1) // loop recording, bars 2-4
- {
- song.loopStart = 4 * lynx::ppq;
- song.loopEnd = 16 * lynx::ppq;
- }
- else if (mode == 2) // punch in/out, bars 3-4
- {
- song.loopStart = 8 * lynx::ppq;
- song.loopEnd = 16 * lynx::ppq;
- }
- if (song.mixer.size() > 1)
- {
- song.mixer[1].name = "Loop In";
- song.mixer[1].monitor = lynx::InputMonitor::off; // (the loopback must not hear itself)
- }
- engine->setSong (std::move (song));
- engine->setInsertInput (1, 0, false);
- juce::ignoreUnused (pdcSamples);
- // 1) the ping
- if (const auto error = engine->startLatencyPing(); error.isNotEmpty())
- step ("ping_error=" + error);
- juce::Timer::callAfterDelay (3500, [this, step, finish, seconds, rate, report, mode] {
- if (engine == nullptr)
- return;
- if (engine->isPinging())
- engine->cancelLatencyPing();
- const auto r = engine->finishLatencyPing();
- step ("ping=" + juce::String (r.ok ? "ok" : "FAILED " + juce::String (r.problem)) + " samples " + juce::String (r.samples) + " spread " + juce::String (r.spread)
- + " found " + juce::String (r.found) + "/" + juce::String (r.sent) + " peak " + juce::String (juce::Decibels::gainToDecibels (r.peak, -150.0f), 1) + " dB");
- const auto l = engine->currentLatency();
- step ("compensation=" + juce::String (l.total()) + " (round trip " + juce::String (l.roundTrip()) + ", manual " + juce::String (l.manual) + ", pdc " + juce::String (l.pdc) + ")");
- // 2) record
- engine->setInsertArmed (1, true);
- auto o = engine->getRecordOptions();
- o.recordAudio = true;
- o.countInBars = 0;
- o.waitForInput = false;
- o.punchLoopRegion = mode == 2;
- o.preRollBars = mode == 2 ? 1 : 0;
- o.postRollBars = mode == 2 ? 1 : 0;
- // (round 177c: LYNX_RECTEST_BLEND_OFF=1: Blend off; LYNX_RECTEST_LAST_PASS=1: "only the last pass plays")
- o.mode = juce::SystemStats::getEnvironmentVariable ("LYNX_RECTEST_BLEND_OFF", {}) == "1" ? lynx::RecordMode::replace
- : lynx::RecordMode::overdub;
- o.lastLoopPassPlays = juce::SystemStats::getEnvironmentVariable ("LYNX_RECTEST_LAST_PASS", {}) == "1";
- engine->setRecordOptions (o);
- engine->stop();
- engine->rewind();
- engine->setRecording (true);
- juce::Timer::callAfterDelay (300, [this, step, finish, seconds, rate, report, mode] {
- if (engine == nullptr)
- return;
- engine->startPlayback(); // (as the Play button: pre-roll / punch)
- juce::Timer::callAfterDelay ((int) (seconds * 1000.0), [this, step, finish, seconds, rate, report, mode] {
- if (engine == nullptr)
- return;
- if (mode == 2)
- step (juce::String ("stopped_by_post_roll=") + (engine->getTransport().playing.load() ? "no" : "yes"));
- engine->stop();
- juce::Timer::callAfterDelay (500, [this, step, finish, seconds, rate, report, mode] {
- if (engine == nullptr)
- return;
- engine->setRecording (false);
- const auto& s = engine->getSong();
- const auto tps = 120.0 * lynx::ppq / (60.0 * rate);
- int take = -1;
- for (int ch = 0; ch < (int) s.channels.size(); ++ch)
- if (s.channels[(std::size_t) ch].instrument == lynx::InstrumentKind::audioClip && s.channels[(std::size_t) ch].name != "Clicks")
- take = ch;
- if (take < 0)
- {
- step ("result=ERROR no take (" + engine->getLastRecordingError() + ")");
- finish (1);
- return;
- }
- std::vector<std::vector<float>> audio;
- double takeRate = 0.0;
- const auto& path = s.channels[(std::size_t) take].samplePath;
- lynx::takes::readWav (path, audio, &takeRate);
- const auto frames = audio.empty() ? (juce::int64) 0 : (juce::int64) audio[0].size();
- step ("take=" + juce::String::fromUTF8 (path.c_str()) + " frames " + juce::String (frames) + " (" + juce::String ((double) frames / rate, 3)
- + " s of " + juce::String (seconds, 1) + " s played) lost " + juce::String (engine->getLostRecordingFrames()));
- // the clicks in the file (peaks above -12 dBFS, one per 1/8 s at most)
- std::vector<juce::int64> peaks;
- if (! audio.empty())
- for (juce::int64 f = 1; f + 1 < frames; ++f)
- {
- const auto x = std::abs (audio[0][(std::size_t) f]);
- if (x > 0.25f && x >= std::abs (audio[0][(std::size_t) f - 1]) && x > std::abs (audio[0][(std::size_t) f + 1])
- && (peaks.empty() || f - peaks.back() > (juce::int64) (rate / 8)))
- peaks.push_back (f);
- }
- // every clip of the take: each click inside it against the nearest beat
- int clips = 0, checked = 0, muted = 0;
- double worst = 0.0, sum = 0.0;
- for (const auto& c : s.playlist)
- {
- if (c.kind != lynx::ClipKind::audio || c.channel != take)
- continue;
- ++clips;
- muted += c.muted ? 1 : 0;
- const auto skip = ((double) c.offset + (double) c.offsetFraction) / tps; // file samples before the clip start
- for (const auto f : peaks)
- {
- const auto intoClip = (double) f - skip;
- if (intoClip < 0.0 || intoClip * tps >= (double) c.length)
- continue;
- const auto songTick = (double) c.start + intoClip * tps - 2.0 * tps; // (the pulse's peak is its 3rd sample)
- const auto beat = std::round (songTick / lynx::ppq) * lynx::ppq;
- const auto error = (songTick - beat) / tps;
- worst = std::max (worst, std::abs (error));
- sum += error;
- ++checked;
- }
- step ("clip track " + juce::String (c.track) + " start " + juce::String ((juce::int64) c.start) + " length " + juce::String ((juce::int64) c.length)
- + " offset " + juce::String ((juce::int64) c.offset) + juce::String (c.offsetFraction >= 0.0f ? "+" : "") + juce::String (c.offsetFraction, 4)
- + (c.muted ? " (muted lane)" : ""));
- }
- step ("clicks_in_file=" + juce::String ((int) peaks.size()) + " checked=" + juce::String (checked) + " clips=" + juce::String (clips)
- + " muted_lanes=" + juce::String (muted));
- step ("placement_error_samples=max " + juce::String (worst, 3) + " mean " + juce::String (checked > 0 ? sum / checked : 0.0, 3));
- auto ok = checked > 0 && worst <= 1.0 && engine->getLostRecordingFrames() == 0;
- if (mode == 2) // one clip, exactly the punch range, its 8 beats
- {
- const auto& sp = engine->getSong();
- bool exact = false;
- for (const auto& c : sp.playlist)
- if (c.kind == lynx::ClipKind::audio && c.channel == take)
- exact = c.start == sp.loopStart && c.start + c.length == sp.loopEnd;
- step (juce::String ("punch_clip_matches_range=") + (exact ? "yes" : "no"));
- ok = ok && clips == 1 && exact && checked == 8;
- }
- report.getSiblingFile (report.getFileNameWithoutExtension() + "-project.lynx").replaceWithText (lynx::ProjectFile::toJson (engine->getSong()));
- step (juce::String ("result=") + (ok ? "OK" : "FAILED"));
- finish (ok ? 0 : 1);
- });
- });
- });
- });
- }
- // --hwinserttest (round 164d): see the command line above.
- void runHwInsertTest (const juce::File& report, double seconds, const juce::String& deviceType, const juce::String& deviceName,
- const juce::String& inputName, int bufferSize, bool inPatcher = false, juce::File bounceFile = {})
- {
- engine = std::make_unique<lynx::AudioEngine>();
- lynx::videoview::install (*engine); // (Fruity Video Player channels: their sound tracks)
- savedDeviceState = engine->getDeviceManager().createStateXml();
- auto text = std::make_shared<juce::String>();
- auto step = [report, text] (const juce::String& line) { *text << line << "\n"; report.replaceWithText (*text); };
- auto finish = [this] (int code) {
- if (engine != nullptr)
- engine->getMeters().capture.setSource (lynx::AudioCapture::off);
- restoreSavedDeviceState();
- setApplicationReturnValue (code);
- quit();
- };
- auto& devices = engine->getDeviceManager();
- if (deviceType.isNotEmpty() && devices.getCurrentAudioDeviceType() != deviceType)
- devices.setCurrentAudioDeviceType (deviceType, true);
- {
- auto setup = devices.getAudioDeviceSetup();
- if (deviceName.isNotEmpty())
- setup.outputDeviceName = deviceName;
- if (bufferSize > 0)
- setup.bufferSize = bufferSize;
- if (const auto error = devices.setAudioDeviceSetup (setup, true); error.isNotEmpty())
- step ("device_error=" + error);
- }
- if (const auto r = engine->openAudioInput (inputName.isNotEmpty() ? inputName : deviceName); r.issue != lynx::AudioEngine::InputIssue::none)
- step ("input_error=" + juce::String ((int) r.issue) + " " + r.detail);
- auto* device = devices.getCurrentAudioDevice();
- if (device == nullptr || engine->getInputChannelNames().empty())
- {
- step ("result=ERROR no device / no input");
- finish (1);
- return;
- }
- const auto rate = device->getCurrentSampleRate();
- step ("device=" + device->getTypeName() + " | " + device->getName() + " | " + juce::String (rate) + " Hz | block " + juce::String (device->getCurrentBufferSizeSamples()));
- // the click track: the ping's pulse on every beat at 120 bpm
- const auto beats = (int) std::ceil (seconds * 2.0) + 8;
- const auto clickFile = report.getSiblingFile (report.getFileNameWithoutExtension() + "-clicks.wav");
- {
- lynx::takes::WavTakeWriter w;
- w.open (clickFile.getFullPathName().toStdString(), rate, 1, lynx::takes::SampleFormat::float32);
- const auto total = (juce::int64) std::llround ((double) beats * rate / 2.0);
- std::vector<float> block (4096);
- for (juce::int64 at = 0; at < total; at += (juce::int64) block.size())
- {
- std::fill (block.begin(), block.end(), 0.0f);
- for (int k = 0; k < (int) block.size(); ++k)
- {
- const auto f = at + k;
- const auto beat = (juce::int64) std::floor ((double) f / (rate / 2.0));
- const auto rel = f - (juce::int64) std::llround ((double) beat * rate / 2.0);
- static constexpr float shape[] { 0.25f, 0.75f, 1.0f, 0.75f, 0.25f };
- if (rel >= 0 && rel < 5)
- block[(std::size_t) k] = 0.5f * shape[rel];
- }
- const float* d[] { block.data() };
- w.write (d, (int) std::min<juce::int64> ((juce::int64) block.size(), total - at));
- }
- w.close();
- }
- lynx::Song song = lynx::Song::makeDefault();
- song.bpm = 120.0;
- song.mode = lynx::PlayMode::song;
- song.playlist.clear();
- song.channels.clear();
- for (int k = 0; k < 2; ++k)
- {
- lynx::ChannelDef c;
- c.name = k == 0 ? "Wet" : "Dry";
- c.instrument = lynx::InstrumentKind::audioClip;
- c.samplePath = clickFile.getFullPathName().toStdString();
- c.mixerTrack = k + 1;
- c.volume = 1.0f;
- song.channels.push_back (c);
- lynx::Clip clip;
- clip.kind = lynx::ClipKind::audio;
- clip.channel = k;
- clip.track = k;
- clip.start = 0;
- clip.length = (std::int64_t) beats * lynx::ppq;
- song.playlist.push_back (clip);
- }
- song.mixer[0].outputChannel = lynx::outputNone; // (the cable carries the send only)
- for (auto& fx : song.mixer[0].effects) // (no Master effects: the default limiter's PDC would hide nothing, but keep it plain)
- fx.enabled = false;
- song.mixer[1].pan = -1.0f;
- song.mixer[2].pan = 1.0f;
- auto hw = lynx::makeEffectSlot (lynx::EffectKind::hardwareInsert);
- hw.params[lynx::hwinsert::output] = lynx::hwinsert::channelValue (0);
- hw.params[lynx::hwinsert::input] = lynx::hwinsert::channelValue (0);
- hw.params[lynx::hwinsert::inputStereo] = 1.0f;
- song.mixer[1].effects.clear();
- lynx::AudioEngine::HardwareInsertRef ref { false, 1, 0, {} };
- if (inPatcher) // (round 165c) From LYNX -> Hardware Insert -> To LYNX
- {
- auto slot = lynx::makeEffectSlot (lynx::EffectKind::patcher);
- lynx::PatchNode node;
- node.effect = hw;
- slot.patcher.nodes = { node };
- lynx::PatchWire in, out;
- in.from = lynx::patchFromHost;
- in.to = 0;
- out.from = 0;
- out.to = lynx::patchToHost;
- slot.patcher.wires = { in, out };
- song.mixer[1].effects.push_back (slot);
- ref.nodes = { 0 };
- }
- else
- song.mixer[1].effects.push_back (hw);
- engine->setSong (std::move (song));
- step (juce::String ("insert=") + (inPatcher ? "inside a Patcher on Insert 1" : "Insert 1 slot 1"));
- const auto meter = [this, ref] (int output) {
- const auto fx = engine->runningHardwareInsert (ref);
- return fx != nullptr ? fx->controlOutput (output) : 0.0f;
- };
- // 1) the insert's ping (as its Ping button: a momentary value flipped)
- juce::Timer::callAfterDelay (500, [this, report, step, finish, seconds, rate, meter, ref, inPatcher, bounceFile] {
- if (engine == nullptr)
- return;
- engine->pingHardwareInserts ({ ref });
- juce::Timer::callAfterDelay (3500, [this, report, step, finish, seconds, rate, meter, ref, inPatcher, bounceFile] {
- if (engine == nullptr)
- return;
- // (round 165c) the engine makes a ping's result the slot's round trip with the device setup it belongs to; the
- // new round trip rebuilds the insert (its latency), so the result is read from the slot
- const auto* slot = lynx::AudioEngine::locateHardwareInsert (const_cast<lynx::Song&> (engine->getSong()), ref);
- const auto samples = slot != nullptr ? lynx::hwinsert::roundTripOf (slot->params[lynx::hwinsert::roundTrip]) : 0;
- const auto setup = slot != nullptr ? lynx::hwinsert::measuredSetup (*slot) : std::string();
- const auto state = meter (lynx::hwinsert::pingState);
- const auto ok = samples > 0 && setup == engine->currentSetupKey();
- step ("ping_round_trip=" + juce::String (samples) + " measured_setup=" + juce::String (setup) + (ok ? " (ok)" : " (FAILED)")
- + " live_ping_state=" + juce::String (state, 3) + " status_flags=" + juce::String (juce::roundToInt (meter (lynx::hwinsert::status) * 16.0f)));
- if (! ok)
- {
- step ("result=FAILED ping");
- finish (1);
- return;
- }
- // a stale setup is noticed: another setup key on the slot gives the notice, the real one none
- step ("stale_now=" + juce::String ((int) engine->staleHardwareInserts().size()));
- // 2) play, capturing the Master
- juce::Timer::callAfterDelay (500, [this, report, step, finish, seconds, rate, samples, ref, inPatcher, bounceFile] {
- if (engine == nullptr)
- return;
- step ("pdc_total=" + juce::String (engine->getLatencySamples()) + " (expected " + juce::String (samples) + ")");
- // saved in the project: the slot comes back the same (routing, round trip), and its latency with it — also an
- // odd round trip (12345 samples: the project keeps it to the sample)
- if (! inPatcher)
- {
- auto odd = engine->getSong();
- odd.mixer[1].effects[0].params[lynx::hwinsert::roundTrip] = lynx::hwinsert::roundTripValue (12345);
- juce::String error;
- auto same = true;
- for (const auto* song : { &engine->getSong(), (const lynx::Song*) &odd })
- {
- const auto file = report.getSiblingFile (report.getFileNameWithoutExtension() + (song == &odd ? "-odd.lynx" : ".lynx"));
- const auto saved = lynx::ProjectFile::save (*song, file, error);
- const auto loaded = saved ? lynx::ProjectFile::load (file, error) : std::nullopt;
- same = same && loaded && loaded->mixer.size() > 1 && ! loaded->mixer[1].effects.empty()
- && loaded->mixer[1].effects[0].kind == lynx::EffectKind::hardwareInsert
- && loaded->mixer[1].effects[0].params == song->mixer[1].effects[0].params
- && lynx::makeEffect (loaded->mixer[1].effects[0])->latencySamples() == (song == &odd ? 12345 : samples);
- }
- const auto file = report.getSiblingFile (report.getFileNameWithoutExtension() + ".lynx");
- step (juce::String ("project_round_trip=") + (same ? "same" : "DIFFERENT " + error) + " (" + file.getFileName() + ")");
- if (! same)
- {
- step ("result=FAILED project");
- finish (1);
- return;
- }
- }
- auto left = std::make_shared<std::vector<float>>(), right = std::make_shared<std::vector<float>>();
- engine->stop();
- engine->rewind();
- engine->getMeters().capture.setSource (0);
- engine->play();
- auto pulls = std::make_shared<int> ((int) (seconds * 5.0));
- auto pull = std::make_shared<std::function<void()>>();
- *pull = [this, report, step, finish, seconds, rate, samples, left, right, pulls, pull, ref, inPatcher, bounceFile] {
- if (engine == nullptr)
- return;
- engine->getMeters().capture.pull (*left, *right);
- if (*pulls == 10) // the insert's editor while it plays (next to the report)
- for (const auto scale : { 1.0f, 1.5f })
- {
- auto editor = inPatcher ? lynx::makeNodeEffectEditor (
- *engine, [ref] (lynx::Song& s) { return lynx::AudioEngine::locateHardwareInsert (s, ref); },
- [this, ref] { return engine->runningHardwareInsert (ref); }, "Insert 1 (Patcher)", scale)
- : lynx::makeNativeEffectEditor (*engine, 1, 0, scale, 0);
- juce::Image image (juce::Image::ARGB, editor->getWidth(), editor->getHeight(), true);
- {
- juce::Graphics g (image);
- g.fillAll (lynx::theme::panel);
- editor->paintEntireComponent (g, false);
- }
- const auto file = report.getSiblingFile (report.getFileNameWithoutExtension() + (scale > 1.0f ? "-editor150.png" : "-editor.png"));
- file.deleteFile();
- juce::PNGImageFormat png;
- if (auto stream = file.createOutputStream())
- png.writeImageToStream (image, *stream);
- }
- if (--*pulls > 0)
- {
- juce::Timer::callAfterDelay (200, *pull);
- return;
- }
- engine->stop();
- const auto dropped = engine->getMeters().capture.droppedFrames();
- engine->getMeters().capture.setSource (lynx::AudioCapture::off);
- // the clicks of each side (peaks above -12 dBFS, one per 1/8 s at most)
- auto peaksOf = [rate] (const std::vector<float>& x) {
- std::vector<juce::int64> peaks;
- for (std::size_t f = 1; f + 1 < x.size(); ++f)
- if (std::abs (x[f]) > 0.25f && std::abs (x[f]) >= std::abs (x[f - 1]) && std::abs (x[f]) > std::abs (x[f + 1])
- && (peaks.empty() || (juce::int64) f - peaks.back() > (juce::int64) (rate / 8)))
- peaks.push_back ((juce::int64) f);
- return peaks;
- };
- const auto wet = peaksOf (*left), dry = peaksOf (*right);
- int pairs = 0;
- juce::int64 worst = 0;
- double gainSum = 0.0, residual = 0.0, energy = 0.0;
- for (const auto w : wet)
- {
- auto best = std::min_element (dry.begin(), dry.end(), [w] (juce::int64 a, juce::int64 b) { return std::abs (a - w) < std::abs (b - w); });
- if (best == dry.end() || std::abs (*best - w) > (juce::int64) (rate / 8))
- continue;
- ++pairs;
- worst = std::max (worst, std::abs (*best - w));
- gainSum += (*left)[(std::size_t) w] / (*right)[(std::size_t) *best];
- }
- const auto gain = pairs > 0 ? gainSum / pairs : 1.0;
- // dry clicks with no wet click beside them (a dropout of the cable / device), listed
- juce::String unmatched;
- for (const auto d : dry)
- if (std::none_of (wet.begin(), wet.end(), [d, rate] (juce::int64 w) { return std::abs (w - d) <= (juce::int64) (rate / 8); }))
- unmatched << " " << (juce::int64) d << " (" << juce::String ((*left)[(std::size_t) d], 3) << ")";
- if (unmatched.isNotEmpty())
- step ("dry_clicks_without_wet=" + unmatched);
- // the null test: left − gain · right around each click (both sides aligned → only the cable's colour remains)
- for (const auto w : wet)
- for (juce::int64 f = std::max<juce::int64> (0, w - 16); f < std::min<juce::int64> ((juce::int64) left->size(), w + 16); ++f)
- {
- const auto d = (double) (*left)[(std::size_t) f] - gain * (double) (*right)[(std::size_t) f];
- residual += d * d;
- energy += (double) (*left)[(std::size_t) f] * (*left)[(std::size_t) f];
- }
- const auto nullDb = energy > 0.0 ? 10.0 * std::log10 (std::max (1e-30, residual / energy)) : 0.0;
- step ("captured=" + juce::String ((int) left->size()) + " frames dropped=" + juce::String (dropped) + " wet_clicks=" + juce::String ((int) wet.size())
- + " dry_clicks=" + juce::String ((int) dry.size()) + " pairs=" + juce::String (pairs));
- step ("alignment_error_samples=max " + juce::String ((int) worst) + " cable_gain=" + juce::String (gain, 4) + " null_residual_db=" + juce::String (nullDb, 1));
- auto* dev = engine->getDeviceManager().getCurrentAudioDevice();
- const auto xruns = dev != nullptr ? dev->getXRunCount() : -1;
- step ("device_xruns=" + juce::String (xruns) + " (a dropout loses what was on the cable then: its clicks are excused)");
- const auto excused = xruns > 0 ? 2 * xruns : 0;
- const auto ok = pairs >= (int) (seconds * 2.0) - 2 - excused && worst == 0 && dropped == 0 && engine->getLatencySamples() == samples;
- step (juce::String ("result=") + (ok ? "OK" : "FAILED"));
- // (round 165c) then the re-ping notice after a buffer size change
- auto then = [this, ref, step, finish] (int code) {
- if (code != 0)
- finish (code);
- else
- runRepingCheck (ref, step, finish);
- };
- if (! ok)
- {
- finish (1);
- return;
- }
- if (bounceFile == juce::File())
- then (0);
- else
- runBounceCheck (bounceFile, step, then);
- };
- juce::Timer::callAfterDelay (200, *pull);
- });
- });
- });
- }
- // --hwinserttest --bounce (round 165c): Export › "Render through the hardware in real time" of the test song next to
- // the offline export of the same song. Through the loopback cable (gain 1) the return is the send delayed by the
- // pinged round trip, so the real-time file must equal the offline one (which passes the dry signal at that delay)
- // to float rounding, with the wet clicks (left) on the dry clicks' samples (right).
- // --hwinserttest (round 165c): the buffer size changes (another round trip on the device): the engine notices the
- // insert measured for the old setup (the app's "Ping now?" prompt), "Ping now" measures it again for the new one
- void runRepingCheck (lynx::AudioEngine::HardwareInsertRef ref, std::function<void (const juce::String&)> step, std::function<void (int)> finish)
- {
- auto& devices = engine->getDeviceManager();
- auto setup = devices.getAudioDeviceSetup();
- const auto before = setup.bufferSize;
- setup.bufferSize = before == 512 ? 256 : 512;
- if (const auto error = devices.setAudioDeviceSetup (setup, true); error.isNotEmpty())
- step ("reping_device_error=" + error);
- engine->takeHardwareInsertNotice(); // (whatever was pending before the change)
- juce::Timer::callAfterDelay (1500, [this, ref, step, finish, before] {
- if (engine == nullptr)
- return;
- auto* device = engine->getDeviceManager().getCurrentAudioDevice();
- const auto block = device != nullptr ? device->getCurrentBufferSizeSamples() : 0;
- const auto notice = engine->takeHardwareInsertNotice();
- step ("reping_buffer=" + juce::String (before) + "->" + juce::String (block) + " notice=" + juce::String ((int) notice.size())
- + " stale=" + juce::String ((int) engine->staleHardwareInserts().size()));
- if (notice.size() != 1 || ! (notice[0] == ref))
- {
- step ("result_reping=FAILED (no notice)");
- finish (1);
- return;
- }
- engine->pingHardwareInserts (notice); // ("Ping now")
- juce::Timer::callAfterDelay (3500, [this, ref, step, finish, block] {
- if (engine == nullptr)
- return;
- const auto* slot = lynx::AudioEngine::locateHardwareInsert (const_cast<lynx::Song&> (engine->getSong()), ref);
- const auto samples = slot != nullptr ? lynx::hwinsert::roundTripOf (slot->params[lynx::hwinsert::roundTrip]) : 0;
- const auto stale = (int) engine->staleHardwareInserts().size();
- step ("reping_round_trip=" + juce::String (samples) + " pdc_total=" + juce::String (engine->getLatencySamples()) + " stale=" + juce::String (stale));
- const auto ok = stale == 0 && samples > 0 && engine->getLatencySamples() == samples;
- step (juce::String ("result_reping=") + (ok ? "OK" : "FAILED") + " (device block " + juce::String (block) + ")");
- finish (ok ? 0 : 1);
- });
- });
- }
- void runBounceCheck (const juce::File& bounceFile, std::function<void (const juce::String&)> step, std::function<void (int)> finish)
- {
- // the Export window as the user sees it with the real-time option ticked (next to the report)
- lynx::showExportDialog (*engine, bounceFile.getParentDirectory(), "bounce", 0);
- for (int k = 0; k < juce::TopLevelWindow::getNumTopLevelWindows(); ++k)
- if (auto* w = juce::TopLevelWindow::getTopLevelWindow (k))
- {
- std::function<juce::ToggleButton* (juce::Component&)> find = [&find] (juce::Component& c) -> juce::ToggleButton* {
- if (auto* t = dynamic_cast<juce::ToggleButton*> (&c); t != nullptr && t->getButtonText() == lynx::tr ("Render through the hardware in real time"))
- return t;
- for (auto* child : c.getChildren())
- if (auto* t = find (*child))
- return t;
- return nullptr;
- };
- if (auto* toggle = find (*w))
- {
- step (juce::String ("export_option_visible=") + (toggle->isVisible() ? "yes" : "NO"));
- toggle->setToggleState (true, juce::sendNotificationSync); // (calls its onClick, as a click)
- auto* c = dynamic_cast<juce::DocumentWindow*> (w) != nullptr ? static_cast<juce::DocumentWindow*> (w)->getContentComponent() : w;
- if (c != nullptr)
- {
- const auto file = bounceFile.getSiblingFile (bounceFile.getFileNameWithoutExtension() + "-export.png");
- file.deleteFile();
- juce::FileOutputStream out (file);
- juce::PNGImageFormat png;
- if (out.openedOk())
- png.writeImageToStream (c->createComponentSnapshot (c->getLocalBounds()), out);
- }
- delete w;
- break;
- }
- }
- lynx::exportopts::Options o;
- o.format = lynx::exportopts::Format::wav;
- o.wavBits = 32;
- o.dither = lynx::exportopts::DitherMode::none;
- o.tail = lynx::exportopts::TailMode::cut;
- o.range = lynx::exportopts::Range::song;
- o.trimPdc = true;
- o.hqAllPlugins = false;
- o.pluginWarmUp = false;
- const auto offlineFile = bounceFile.getSiblingFile (bounceFile.getFileNameWithoutExtension() + "-offline.wav");
- auto realtimeJob = std::make_shared<lynx::ExportJob> (*engine, o, bounceFile);
- o.sampleRate = engine->getTransport().sampleRate.load();
- auto offlineJob = std::make_shared<lynx::ExportJob> (engine->getSong(), o, offlineFile);
- struct Shared
- {
- std::atomic<int> done { 0 };
- bool okRealtime = false, okOffline = false;
- juce::String errorRealtime, errorOffline;
- double lastProgress = 0.0;
- double started = juce::Time::getMillisecondCounterHiRes();
- };
- auto shared = std::make_shared<Shared>();
- // (the jobs stay owned by the message thread's poll below: they are destroyed there)
- juce::Thread::launch ([rt = realtimeJob.get(), off = offlineJob.get(), shared] {
- shared->okRealtime = rt->run ([shared] (double p) { shared->lastProgress = p; return true; }, shared->errorRealtime);
- shared->okOffline = off->run ({}, shared->errorOffline);
- shared->done.store (1);
- });
- auto poll = std::make_shared<std::function<void()>>();
- *poll = [this, poll, shared, realtimeJob, offlineJob, bounceFile, offlineFile, step, finish] {
- if (shared->done.load() == 0)
- {
- juce::Timer::callAfterDelay (100, *poll);
- return;
- }
- const auto seconds = (juce::Time::getMillisecondCounterHiRes() - shared->started) / 1000.0;
- step ("bounce_realtime=" + juce::String (shared->okRealtime ? "ok" : "FAILED " + shared->errorRealtime) + " offline="
- + juce::String (shared->okOffline ? "ok" : "FAILED " + shared->errorOffline) + " took=" + juce::String (seconds, 1) + " s (music "
- + juce::String (realtimeJob->getMusicSeconds(), 1) + " s)" + (realtimeJob->getNotice().isNotEmpty() ? " notice=" + realtimeJob->getNotice() : juce::String()));
- juce::AudioFormatManager formats;
- formats.registerBasicFormats();
- std::unique_ptr<juce::AudioFormatReader> a (formats.createReaderFor (bounceFile)), b (formats.createReaderFor (offlineFile));
- if (! shared->okRealtime || ! shared->okOffline || a == nullptr || b == nullptr)
- {
- step ("result=FAILED bounce");
- finish (1);
- return;
- }
- const auto frames = (int) std::min (a->lengthInSamples, b->lengthInSamples);
- juce::AudioBuffer<float> x (2, frames), y (2, frames);
- a->read (&x, 0, frames, 0, true, true);
- b->read (&y, 0, frames, 0, true, true);
- double residual = 0.0, energy = 0.0, wetDry = 0.0;
- for (int ch = 0; ch < 2; ++ch)
- for (int i = 0; i < frames; ++i)
- {
- const double d = x.getSample (ch, i) - y.getSample (ch, i);
- residual += d * d;
- energy += (double) y.getSample (ch, i) * y.getSample (ch, i);
- }
- for (int i = 0; i < frames; ++i) // the wet side against the dry side of the real-time file
- wetDry += std::pow ((double) x.getSample (0, i) - x.getSample (1, i), 2.0);
- const auto db = [energy] (double r) { return energy > 0.0 ? 10.0 * std::log10 (std::max (1e-30, r / energy)) : 0.0; };
- step ("bounce_frames=" + juce::String ((juce::int64) a->lengthInSamples) + " offline_frames=" + juce::String ((juce::int64) b->lengthInSamples)
- + " rate=" + juce::String (a->sampleRate) + " bounce_vs_offline_db=" + juce::String (db (residual), 1)
- + " wet_vs_dry_db=" + juce::String (db (2.0 * wetDry), 1) + " peak=" + juce::String (realtimeJob->getPeak(), 3));
- const auto ok = std::abs (a->lengthInSamples - b->lengthInSamples) <= 1 && db (residual) < -100.0 && realtimeJob->getPeak() > 0.1f;
- step (juce::String ("result_bounce=") + (ok ? "OK" : "FAILED"));
- finish (ok ? 0 : 1);
- };
- juce::Timer::callAfterDelay (100, *poll);
- }
- // --rtstress --record: stops recording (the take becomes a clip of the song, as in the app), moves the take's WAV to
- // `target` and describes it: length against the time played, channels, peak, the latencies the driver reported.
- juce::String finishStressTake (const juce::File& target, double seconds)
- {
- juce::String text;
- auto* device = engine->getDeviceManager().getCurrentAudioDevice();
- text << " recording: input " << (device != nullptr ? device->getActiveInputChannels().countNumberOfSetBits() : 0) << " channel(s)";
- if (device != nullptr)
- text << ", input latency " << device->getInputLatencyInSamples() << " + output latency " << device->getOutputLatencyInSamples() << " samples";
- engine->setRecording (false); // closes the take: a clip of the song
- juce::File take;
- for (const auto& c : engine->getSong().channels)
- if (c.instrument == lynx::InstrumentKind::audioClip)
- take = juce::File (juce::String::fromUTF8 (c.samplePath.c_str()));
- if (! take.existsAsFile())
- return text + "\n recording: no take (" + engine->getLastRecordingError() + ")\n";
- target.deleteFile();
- if (! take.moveFileTo (target))
- take.copyFileTo (target);
- juce::AudioFormatManager formats;
- formats.registerBasicFormats();
- if (std::unique_ptr<juce::AudioFormatReader> reader (formats.createReaderFor (target)); reader != nullptr)
- {
- juce::AudioBuffer<float> audio ((int) reader->numChannels, (int) reader->lengthInSamples);
- reader->read (&audio, 0, (int) reader->lengthInSamples, 0, true, true);
- const auto peak = audio.getMagnitude (0, audio.getNumSamples());
- const auto length = (double) reader->lengthInSamples / reader->sampleRate;
- text << "\n recording: take " << juce::String (length, 3) << " s of " << juce::String (seconds, 0) << " s played, "
- << (int) reader->numChannels << " ch @ " << (int) reader->sampleRate << " Hz, peak "
- << juce::String (juce::Decibels::gainToDecibels (peak, -150.0f), 1) << " dBFS -> " << target.getFullPathName() << "\n";
- }
- else
- text << "\n recording: take unreadable (" << target.getFullPathName() << ")\n";
- return text;
- }
- // LYNX.exe --render project.(flp|lynx) output.wav [seconds]
- // Exports the current pattern to 24-bit WAV (for an imported .flp, the one with the most notes).
- void runRender (const juce::String& inputPath, const juce::String& outputPath, double seconds)
- {
- lynx::AudioEngine offline (false);
- const juce::File input (inputPath);
- juce::String error, report;
- bool ok = false;
- if (input.hasFileExtension ("flp;als;flm;songtmpl"))
- ok = offline.importFlpFile (input, error);
- else if (auto song = lynx::ProjectFile::load (input, error))
- {
- offline.setSong (std::move (*song));
- ok = true;
- }
- int samplers = 0, samplersLoaded = 0;
- if (ok)
- {
- for (const auto& c : offline.getSong().channels)
- if (c.instrument == lynx::InstrumentKind::sampler || c.instrument == lynx::InstrumentKind::audioClip)
- {
- ++samplers;
- samplersLoaded += offline.getSampleLibrary().load (juce::String::fromUTF8 (c.samplePath.c_str())) != nullptr;
- }
- const juce::File output (outputPath);
- output.deleteFile();
- juce::WavAudioFormat wav;
- std::unique_ptr<juce::AudioFormatWriter> writer (
- wav.createWriterFor (output.createOutputStream().release(), 44100.0, 2, 24, {}, 0));
- if (writer == nullptr)
- {
- ok = false;
- error = lynx::utf8 ("could not create ") + outputPath;
- }
- else
- {
- const auto peak = offline.renderOffline (seconds > 0.0 ? seconds : 10.0, 44100.0, writer.get());
- report << "peak=" << peak << "\n";
- ok = peak > 0.001f;
- }
- }
- report << "samples=" << samplersLoaded << "/" << samplers << "\n"
- << "result=" << (ok ? "OK" : "ERROR " + error) << "\n";
- juce::File (outputPath + ".txt").replaceWithText (report);
- setApplicationReturnValue (ok ? 0 : 1);
- quit();
- }
- // LYNX.exe --export-flp project.(lynx|flp|als) output.(flp|zip) [--substitute] (round 171e): File › Export › FL Studio
- // project without the window (option A unless --substitute; the renders next to a .flp in "<name> audio"); the
- // report goes to output.txt
- void runAlsExport (const juce::String& inputPath, const juce::String& folderPath, bool live11, bool reference)
- {
- juce::String error;
- juce::StringArray notes;
- juce::File als;
- {
- lynx::AudioEngine loader (false);
- const juce::File input (inputPath);
- bool ok = false;
- // --scan: the targeted plugin scan an open runs first (child processes), so the set's plugins load
- if (juce::JUCEApplication::getCommandLineParameterArray().contains ("--scan") && input.hasFileExtension ("flp;als;flm;songtmpl"))
- {
- juce::MemoryBlock data;
- if (input.loadFileAsData (data))
- {
- const std::vector<std::uint8_t> bytes (static_cast<const std::uint8_t*> (data.getData()),
- static_cast<const std::uint8_t*> (data.getData()) + data.getSize());
- try
- {
- const auto uses = input.hasFileExtension ("als") ? lynx::alsForeignPlugins (bytes)
- : lynx::flpForeignPlugins (flp::parseProject ({ bytes.data(), bytes.size() }));
- loader.getPluginHost().scanFiles (loader.getPluginHost().filesToScanFor (uses), {});
- }
- catch (const std::exception&)
- {
- }
- }
- }
- if (input.hasFileExtension ("flp;als;flm;songtmpl"))
- ok = loader.importFlpFile (input, error);
- else if (auto song = lynx::ProjectFile::load (input, error))
- {
- loader.setSong (std::move (*song));
- ok = true;
- }
- if (ok)
- {
- loader.capturePluginStates();
- const juce::File folder (folderPath);
- folder.createDirectory();
- als = lynx::writeAlsProject (loader.getSong(), &loader.getPluginHost(), live11 ? lynx::AlsVersion::live11 : lynx::AlsVersion::live12, ! reference, folder,
- input.getFileNameWithoutExtension(), notes, error);
- }
- }
- juce::String report;
- report << (als != juce::File() ? "ok " + als.getFullPathName() : "error=" + error) << "\n" << notes.joinIntoString ("\n") << "\n";
- juce::File (folderPath).getChildFile ("export-als.txt").replaceWithText (report);
- setApplicationReturnValue (als != juce::File() ? 0 : 1);
- quit();
- }
- void runGamepadShot (const juce::String& prefix)
- {
- juce::String report;
- int failures = 0;
- {
- lynx::AudioEngine engine (false);
- auto hints = lynx::makeGamepadHints();
- savePng (hints->createComponentSnapshot (hints->getLocalBounds()), prefix + "-hints.png");
- auto prefs = engine.getMidiPrefs();
- prefs.gamepad = true;
- engine.setMidiPrefs (prefs, false);
- auto page = lynx::makeMidiPage (engine, {}, false);
- page->setSize (760, 1400);
- savePng (page->createComponentSnapshot (page->getLocalBounds()), prefix + "-settings.png");
- // the poller with fake states: what the handler gets
- using namespace lynx::gamepad;
- std::vector<std::string> got;
- lynx::GamepadInput input ([&got] (const Changes& c, const State&, double dt) {
- for (int i = 0; i < c.pressedCount; ++i)
- got.push_back (std::string ("press ") + buttonName (c.pressed[(std::size_t) i]));
- for (int i = 0; i < c.releasedCount; ++i)
- got.push_back (std::string ("release ") + buttonName (c.released[(std::size_t) i]));
- for (int i = 0; i < c.controllerCount; ++i)
- got.push_back ("cc " + std::to_string (c.controller[(std::size_t) i]) + "=" + std::to_string (c.value[(std::size_t) i]));
- if (c.connectedChanged)
- got.push_back ("connected changed");
- got.push_back ("dt " + std::to_string ((int) std::lround (dt * 1000)));
- });
- State pad;
- pad.connected = true;
- input.inject (pad, 1.0 / 60.0);
- pad.buttons = mask (Button::a);
- pad.rightTrigger = 255;
- input.inject (pad, 1.0 / 60.0);
- pad.buttons = 0;
- input.inject (pad, 1.0 / 60.0);
- const std::vector<std::string> expected { "connected changed", "dt 17", "press A", "cc 102=127", "cc 21=127", "dt 17",
- "release A", "cc 102=0", "dt 17" };
- for (const auto& line : got)
- report << line << "\n";
- if (got != expected)
- {
- ++failures;
- report << "FAILED: the poller's changes differ from the expected ones\n";
- }
- report << "xinput " << (input.available() ? "loaded" : "not available") << "\n";
- }
- report << (failures == 0 ? "gamepad OK" : "gamepad FAILED") << "\n";
- juce::File (prefix + "-gamepad.txt").replaceWithText (report);
- setApplicationReturnValue (failures == 0 ? 0 : 1);
- quit();
- }
- void runBundleExport (const juce::String& inputPath, const juce::String& folderPath, bool zip, bool mixdown, const juce::String& shotPrefix)
- {
- juce::String error;
- bool ok = false;
- lynx::otherapps::Result result;
- {
- lynx::AudioEngine loader (false);
- const juce::File input (inputPath);
- if (input.hasFileExtension ("flp;als"))
- ok = loader.importFlpFile (input, error);
- else if (auto song = lynx::ProjectFile::load (input, error))
- {
- loader.setSong (std::move (*song));
- ok = true;
- }
- if (ok)
- {
- loader.capturePluginStates();
- lynx::otherapps::Context context;
- context.host = &loader.getPluginHost();
- context.flOptions = lynx::flstudio::optionsFor (context.host, lynx::flpexport::LynxOnly::renderAudio, loader.getSong());
- context.render = [] (const lynx::Song& s, const lynx::exportopts::Options& o, const juce::File& file,
- const std::function<bool (double)>& progress, juce::String& err) {
- lynx::ExportJob job (s, o, file);
- return job.run (progress, err);
- };
- context.onMessageThread = [] (std::function<void()> f) { f(); };
- lynx::exportbundle::Options options;
- options.zip = zip;
- options.mixdown = mixdown;
- const auto name = input.getFileNameWithoutExtension();
- const auto shot = [&shotPrefix] (juce::Component& c, const juce::String& suffix) {
- if (shotPrefix.isNotEmpty())
- savePng (c.createComponentSnapshot (c.getLocalBounds()), shotPrefix + suffix);
- };
- if (auto panel = lynx::makeOtherAppsExportPanel (loader, name))
- shot (*panel, "-panel.png");
- ok = lynx::otherapps::write (loader.getSong(), name, options, juce::File (folderPath), context, result);
- if (auto report = lynx::makeOtherAppsReportPanel (result.folder, result.written, result.failed))
- shot (*report, "-report.png");
- }
- }
- juce::String report;
- report << (ok ? "ok " + result.folder.getFullPathName() : "error=" + error) << "\n";
- for (const auto& w : result.written)
- report << "written " << w << "\n";
- for (const auto& f : result.failed)
- report << "failed " << f << "\n";
- juce::File (folderPath).getChildFile ("export-bundle.txt").replaceWithText (report);
- setApplicationReturnValue (ok && result.failed.isEmpty() ? 0 : 1);
- quit();
- }
- void runFlExport (const juce::String& inputPath, const juce::String& outputPath, bool substitute)
- {
- juce::String error;
- bool ok = false;
- lynx::flstudio::Written written;
- {
- lynx::AudioEngine loader (false);
- const juce::File input (inputPath);
- // a Live set opens through the same import as an .flp (as File › Open does, and --export-als accepts an .flp)
- if (input.hasFileExtension ("flp;als"))
- ok = loader.importFlpFile (input, error);
- else if (auto song = lynx::ProjectFile::load (input, error))
- {
- loader.setSong (std::move (*song));
- ok = true;
- }
- if (ok)
- {
- const juce::File output (outputPath);
- const auto zip = output.hasFileExtension ("zip");
- const auto mode = substitute ? lynx::flpexport::LynxOnly::substitute : lynx::flpexport::LynxOnly::renderAudio;
- loader.capturePluginStates();
- auto options = lynx::flstudio::optionsFor (&loader.getPluginHost(), mode, loader.getSong());
- // --flp-ppq N: the file's PPQ (tests; default: 96 when the notes and clips fit it)
- if (const auto args = juce::JUCEApplication::getCommandLineParameterArray(); args.contains ("--flp-ppq"))
- options.ppq = juce::jlimit (0, 960, args[args.indexOf ("--flp-ppq") + 1].getIntValue());
- const auto renderDir = zip ? juce::File::getSpecialLocation (juce::File::tempDirectory).getNonexistentChildFile ("LYNX FL export", {}, false)
- : output.getSiblingFile (output.getFileNameWithoutExtension() + " audio");
- ok = lynx::flstudio::exportProject (loader.getSong(), options, output, zip, renderDir, 44100.0,
- [] (const lynx::Song& s, const lynx::ExportSettings& settings, const juce::File& wav,
- const std::function<bool (double)>& progress, juce::String& err) {
- lynx::ExportJob job (s, settings, wav);
- return job.run (progress, err);
- },
- {}, written, error);
- if (zip)
- renderDir.deleteRecursively();
- }
- }
- juce::String report;
- report << (ok ? "ok" : "error=" + error) << "\n"
- << "exact=" << (int) written.report.exact.size() << " rendered=" << (int) written.report.rendered.size()
- << " substituted=" << (int) written.report.substituted.size() << " dropped=" << (int) written.report.dropped.size()
- << " samples=" << written.samples << "\n\n"
- << lynx::flstudio::reportText (written) << "\n";
- juce::File (outputPath + ".txt").replaceWithText (report);
- setApplicationReturnValue (ok ? 0 : 1);
- quit();
- }
- // LYNX.exe --export project.(flp|als|lynx) output.(wav|flac|ogg|mp3) [--pattern] [--insert N] [--rate N]
- // Same path as "Export" in the UI: the whole song (or the current pattern) with its tail.
- void runExport (const juce::String& inputPath, const juce::String& outputPath, bool patternOnly, int insert)
- {
- juce::String error, report;
- bool ok = false;
- const auto started = juce::Time::getMillisecondCounterHiRes();
- lynx::loadtrace::begin (inputPath.toStdString()); // phase times (round 112): report lines + load.log
- {
- lynx::AudioEngine loader (false);
- const juce::File input (inputPath);
- // --find-plugins: first the targeted scan opening the project in the app runs (its plugins not known yet)
- if (input.hasFileExtension ("flp") && juce::JUCEApplication::getCommandLineParameters().contains ("--find-plugins"))
- {
- juce::MemoryBlock data;
- if (input.loadFileAsData (data))
- try
- {
- const auto uses = lynx::flpForeignPlugins (flp::parseProject ({ static_cast<const std::uint8_t*> (data.getData()), data.getSize() }));
- auto& host = loader.getPluginHost();
- const auto listed = std::chrono::steady_clock::now();
- const auto files = host.filesToScanFor (uses);
- lynx::loadtrace::add ("plugin_scan_list", lynx::loadtrace::msSince (listed));
- report << "scanned=" << files.joinIntoString (";") << "\n";
- const auto scanned = std::chrono::steady_clock::now();
- host.scanFiles (files, {});
- lynx::loadtrace::add ("plugin_scan", lynx::loadtrace::msSince (scanned), files.size());
- }
- catch (const flp::Error&)
- {
- }
- }
- if (input.hasFileExtension ("flp;als")) // a Live set opens through the same import (round 182b)
- ok = loader.importFlpFile (input, error);
- else if (auto song = lynx::ProjectFile::load (input, error))
- {
- loader.setSong (std::move (*song));
- ok = true;
- }
- if (ok)
- {
- const juce::File output (outputPath);
- lynx::ExportSettings settings;
- settings.wholeSong = ! patternOnly;
- settings.format = output.hasFileExtension ("flac") ? lynx::ExportSettings::Format::flac24
- : output.hasFileExtension ("ogg") ? lynx::ExportSettings::Format::ogg
- : lynx::ExportSettings::Format::wav24;
- // --insert N: only that insert's output (what "Render to audio" records)
- if (juce::JUCEApplication::getCommandLineParameters().contains ("--no-effects")
- || juce::JUCEApplication::getCommandLineParameters().contains ("--sem-efeitos")) // performance diagnostics; --sem-efeitos: legacy alias
- loader.editSong ([] (lynx::Song& s) {
- for (auto& t : s.mixer)
- t.effects.clear();
- }, false);
- if (juce::JUCEApplication::getCommandLineParameters().contains ("--no-automation")
- || juce::JUCEApplication::getCommandLineParameters().contains ("--sem-automacao")) // --sem-automacao: legacy alias
- loader.editSong ([] (lynx::Song& s) { s.automations.clear(); }, false);
- const auto loaded = juce::Time::getMillisecondCounterHiRes();
- // .mp3: the Export window's MP3 (320 kbps); everything else as before
- auto options = settings.toOptions();
- // --save-tempo: FL's "Tempo information" (acid chunk) on (round 167l: compare with FL's AcidBox render; --export)
- if (juce::JUCEApplication::getCommandLineParameters().contains ("--save-tempo"))
- options.saveTempo = true;
- // --no-warmup: the export's plugin warm-up off (round 155: compare the start of the file)
- if (juce::JUCEApplication::getCommandLineParameters().contains ("--no-warmup"))
- options.pluginWarmUp = false;
- // --rate N: render at another sample rate (round 157b: samples resampled as at a 48 kHz device)
- if (const auto args = juce::JUCEApplication::getCommandLineParameterArray(); args.contains ("--rate"))
- if (const auto rate = args[args.indexOf ("--rate") + 1].getDoubleValue(); rate >= 8000.0 && rate <= 384000.0)
- options.sampleRate = rate;
- if (output.hasFileExtension ("mp3"))
- {
- options.format = lynx::exportopts::Format::mp3;
- options.mp3Kbps = 320;
- }
- lynx::ExportJob job (insert > 0 ? lynx::makeBounceSong (loader.getSong(), insert) : loader.getSong(), options, output);
- job.setExtraData (true);
- const auto prepared = juce::Time::getMillisecondCounterHiRes();
- lynx::loadtrace::end();
- int lastPercent = -1;
- ok = job.run ([&lastPercent] (double p) {
- lastPercent = (int) (p * 100.0);
- return true;
- }, error);
- auto joined = [] (const std::map<std::string, int>& items) {
- juce::StringArray names;
- for (const auto& [name, count] : items)
- names.add (juce::String::fromUTF8 (name.c_str()) + "x" + juce::String (count));
- return names.joinIntoString (", ");
- };
- const auto& importReport = loader.getImportReport();
- report << "converted=" << joined (importReport.converted) << "\n"
- << "approximated=" << joined (importReport.approximated) << "\n"
- << "unsupported=" << joined (importReport.unsupported) << "\n"
- << "dropped_effects=" << joined (importReport.droppedEffects) << "\n"
- << "partial_effects=" << joined (importReport.partialEffects) << "\n"
- << "missing_samples=" << importReport.missingSamples << "\n";
- // third-party plugins: how each was found, or what plays in its place (diagnostics for level differences)
- for (const auto& line : loader.getMatchedPlugins())
- report << "plugin_found=" << line << "\n";
- for (const auto& m : loader.getMissingPluginDetails())
- report << "plugin_missing=" << juce::String::fromUTF8 (m.name.c_str()) << " -> "
- << juce::String::fromUTF8 (m.replacement.c_str()).replace ("{0}", juce::String::fromUTF8 (m.replacementArg.c_str())) << "\n";
- {
- const auto& song = loader.getSong();
- for (std::size_t t = 0; t < song.mixer.size(); ++t)
- {
- const auto& track = song.mixer[t];
- if (track.effects.empty() && track.sends.empty())
- continue;
- report << "insert " << (int) t << " vol=" << juce::String (track.volume / lynx::unityFader, 3)
- << (track.muted ? " muted" : "") << (track.toMaster ? "" : " noMaster");
- for (const auto& s : track.sends)
- report << " send>" << s.target << "@" << juce::String (s.level, 3);
- report << " |";
- for (const auto& fx : track.effects)
- report << " [" << (fx.kind == lynx::EffectKind::plugin ? juce::String::fromUTF8 (fx.plugin.name.c_str())
- : juce::String::fromUTF8 (lynx::effectInfo (fx.kind).name))
- << (fx.isSubstitute() ? " (substitute)" : "") << (fx.enabled ? "" : " off")
- << (fx.mix < 0.999f ? " mix=" + juce::String (fx.mix, 2) : juce::String()) << "]";
- report << "\n";
- }
- }
- report << juce::String (lynx::loadtrace::reportLines());
- lynx::PluginHost::settingsFolder().getChildFile ("load.log").replaceWithText (juce::String (lynx::loadtrace::table()));
- report << "open_ms=" << juce::roundToInt (loaded - started) << "\n"
- << "prepare_ms=" << juce::roundToInt (prepared - loaded) << "\n"
- << "render_ms=" << juce::roundToInt (juce::Time::getMillisecondCounterHiRes() - prepared) << "\n"
- << "graph_ms=" << juce::roundToInt (job.getEngine().getLastRenderStats().graphMs) << "\n"
- << "write_ms=" << juce::roundToInt (job.getEngine().getLastRenderStats().writeMs) << "\n"
- << "warmup_blocks=" << job.getEngine().getLastRenderStats().warmUp.blocks << "\n"
- << "warmup_ms=" << juce::roundToInt (job.getEngine().getLastRenderStats().warmUp.wallSeconds * 1000.0) << "\n"
- << "warmup_changes=" << job.getEngine().getLastRenderStats().warmUp.signatureChanges << "\n"
- << "warmup_timed_out=" << (job.getEngine().getLastRenderStats().warmUp.timedOut ? 1 : 0) << "\n"
- << "pdc_trim=" << job.getEngine().getLastRenderStats().trimmedSamples << "\n"
- << "song_seconds=" << job.getMusicSeconds() << "\n"
- << "peak=" << job.getPeak() << "\n"
- << "final_progress=" << lastPercent << "\n"
- << "bytes=" << output.getSize() << "\n";
- ok = ok && job.getPeak() > 0.001f;
- }
- }
- report << "result=" << (ok ? "OK" : "ERROR " + error) << "\n";
- juce::File (outputPath + ".txt").replaceWithText (report);
- setApplicationReturnValue (ok ? 0 : 1);
- quit();
- }
- // LYNX.exe --snapshot prefix [project]: draws the window off-screen and writes
- // prefix-rack.png, -pianoroll.png and -playlist.png (to check the UI without touching the screen).
- // --editorcpu: one editor after another; each phase runs 2 s to settle and 8 s measured
- struct EditorCpuRun final : juce::Timer
- {
- struct Case { lynx::EffectKind kind; const char* name; int type; bool demo; }; // type 0 native, 1 display-first, 2 Facet EQ
- std::vector<Case> cases;
- std::size_t at = 0;
- int phase = 0;
- double t0 = 0.0, c0 = 0.0;
- juce::String report;
- juce::File out;
- std::unique_ptr<lynx::AudioEngine> engine;
- std::unique_ptr<juce::DocumentWindow> window;
- std::function<void()> done;
- void start()
- {
- engine = std::make_unique<lynx::AudioEngine> (false);
- report << "editor\tmode\tcpu % of one core\n";
- open();
- startTimer (250);
- }
- void open()
- {
- window.reset();
- if (at >= cases.size()) { out.replaceWithText (report); stopTimer(); if (done) done(); return; }
- const auto& c = cases[at];
- lynx::Song song;
- song.mixer.resize (2);
- song.mixer[0].name = "Master";
- song.mixer[1].name = "Insert 1";
- song.mixer[1].effects.push_back (lynx::makeEffectSlot (c.kind));
- engine->setSong (std::move (song));
- engine->dispatchPendingMessages();
- lynx::setNativeEditorDemo (c.demo);
- auto editor = c.type == 1 ? lynx::makeProEditor (*engine, 1, 0, c.demo) : c.type == 2 ? lynx::makeFacetEqEditor (*engine, 1, 0, c.demo)
- : lynx::makeNativeEffectEditor (*engine, 1, 0, 1.0f, 0);
- window = std::make_unique<juce::DocumentWindow> (juce::String ("LYNX editor CPU - ") + c.name, lynx::theme::colour::bg1, 0);
- window->setUsingNativeTitleBar (true);
- window->setContentOwned (editor.release(), true);
- const auto area = juce::Desktop::getInstance().getDisplays().getPrimaryDisplay()->userArea;
- window->setTopLeftPosition (area.getRight() - window->getWidth() - 8, area.getBottom() - window->getHeight() - 8);
- window->setVisible (true);
- phase = 0;
- t0 = juce::Time::getMillisecondCounterHiRes();
- }
- void timerCallback() override
- {
- const auto now = juce::Time::getMillisecondCounterHiRes();
- if (phase == 0 && now - t0 > 2000.0) { phase = 1; t0 = now; c0 = lynx::processCpuSeconds(); return; }
- if (phase == 1 && now - t0 > 8000.0)
- {
- const auto cpu = (lynx::processCpuSeconds() - c0) / ((now - t0) * 0.001) * 100.0;
- const auto& c = cases[at];
- report << c.name << "\t" << (c.demo ? "animating" : "idle") << "\t" << juce::String (cpu, 2) << "\n";
- ++at;
- open();
- }
- }
- };
- std::unique_ptr<EditorCpuRun> editorCpu;
- void runEditorCpu (const juce::String& path)
- {
- juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
- editorCpu = std::make_unique<EditorCpuRun>();
- editorCpu->out = juce::File (path);
- using K = lynx::EffectKind;
- for (const auto demo : { false, true })
- for (const auto& c : std::vector<EditorCpuRun::Case> { { K::facetEq, "Facet EQ", 2, demo }, { K::crestCompressor, "Crest Compressor", 1, demo },
- { K::apexLimiter, "Apex Limiter", 1, demo }, { K::prismMultiband, "Prism Multiband", 1, demo },
- { K::epochVerb, "Epoch Verb", 0, demo }, { K::glowLeveler, "Glow Leveler", 0, demo },
- { K::fruityLimiter, "Fruity Limiter", 0, demo }, { K::lynxTune, "LYNX Tune", 0, demo } })
- editorCpu->cases.push_back (c);
- editorCpu->done = [this] { juce::MessageManager::callAsync ([this] { editorCpu.reset(); quit(); }); };
- editorCpu->start();
- }
- struct ParityShow
- {
- std::unique_ptr<lynx::AudioEngine> engine;
- std::unique_ptr<juce::Component> editor;
- std::unique_ptr<juce::DocumentWindow> window;
- ~ParityShow() { window.reset(); editor.reset(); engine.reset(); }
- };
- std::shared_ptr<ParityShow> parityShow;
- bool parityShotFailed = false; // --parityshot: the effect name matched no built-in effect
- void runParityShot (const juce::String& path, const juce::String& effectName, const juce::String& paramsFile)
- {
- juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
- int kindIndex = -1;
- for (int k = 0; k <= (int) lynx::lastEffectKind; ++k)
- if (juce::String::fromUTF8 (lynx::effectInfo ((lynx::EffectKind) k).name).equalsIgnoreCase (effectName))
- kindIndex = k;
- if (kindIndex < 0)
- {
- // round tp172b7: say so and fail (a silent exit 0 hid a split effect name in a launch script)
- std::fprintf (stderr, "unknown effect: %s\n", effectName.toRawUTF8());
- std::fflush (stderr);
- parityShotFailed = true;
- return;
- }
- const auto kind = (lynx::EffectKind) kindIndex;
- auto fx = lynx::makeEffectSlot (kind);
- if (paramsFile.isNotEmpty())
- for (const auto& line : juce::StringArray::fromLines (juce::File (paramsFile).loadFileAsString()))
- {
- const auto t = juce::StringArray::fromTokens (line, " \t", "");
- const auto index = t.size() >= 2 ? t[0].getIntValue() : -1;
- if (index >= 0 && index < lynx::maxEffectParams)
- fx.params[(std::size_t) index] = t[1].getFloatValue();
- }
- auto offlineOwner = std::make_unique<lynx::AudioEngine> (false); // (kept alive by LYNX_PARITYSHOT_SHOW's window)
- auto& offline = *offlineOwner;
- auto song = lynx::Song::makeDefault();
- song.mixer.resize (2);
- song.mixer[0].name = "Master";
- song.mixer[1].name = "Insert 1";
- song.mixer[1].effects.assign (1, fx);
- for (auto& c : song.channels)
- c.mixerTrack = 1;
- offline.setSong (std::move (song));
- offline.dispatchPendingMessages();
- const bool facet = kind == lynx::EffectKind::facetEq;
- // round tp172b4: the originals are pictured idle (nothing playing), so the display-first editors are too: no demo
- // history unless LYNX_PARITYSHOT_DEMO=1 asks for the running display
- const bool demoDisplay = juce::SystemStats::getEnvironmentVariable ("LYNX_PARITYSHOT_DEMO", {}) == "1";
- // (Ember in its Classic voicing: the Classic panel, as the mixer opens it)
- const bool pro = lynx::ProEditorWindows::handles (kind)
- && ! (kind == lynx::EffectKind::ember && fx.params[(std::size_t) lynx::mixsuite::ember::voicing] > 0.5f);
- auto editor = facet ? lynx::makeFacetEqEditor (offline, 1, 0, false)
- : pro ? lynx::makeProEditor (offline, 1, 0, demoDisplay) : lynx::makeNativeEffectEditor (offline, 1, 0, 1.0f, 0);
- if (editor == nullptr)
- return;
- if (! pro) // the demo song through the effect, the editor ticked 30 times a second of audio as its timer would
- {
- lynx::AudioEngine::RenderOptions o;
- o.seconds = 3.0;
- o.sampleRate = 48000.0;
- o.pluginWarmUp = false;
- int sinceTick = 0;
- o.capture = [&] (const float*, const float*, int n) {
- sinceTick += n;
- if (sinceTick < 1600) return;
- sinceTick = 0;
- if (facet) lynx::tickFacetEqEditor (*editor);
- else lynx::tickNativeEffectEditor (*editor);
- };
- offline.renderOffline (o);
- }
- // round tp172b5: LYNX_PARITYSHOT_CLICKS drives the editor before the picture (the originals' pictures have their
- // panels open), tokens in order: "x,y" a click, then the pointer leaves; "h:x,y" the pointer rests there (a hover);
- // "d:x,y,x2,y2" a drag from there to there, the button still down in the picture
- for (const auto& token : juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_PARITYSHOT_CLICKS", {}), " ", ""))
- {
- const auto hover = token.startsWith ("h:"), drag = token.startsWith ("d:");
- const auto xy = juce::StringArray::fromTokens (hover || drag ? token.substring (2) : token, ",", "");
- if (xy.size() < (drag ? 4 : 2))
- continue;
- const juce::Point<int> at (xy[0].getIntValue(), xy[1].getIntValue());
- editor->setVisible (true); // (getComponentAt finds nothing in a hidden component; it never goes on screen)
- auto* target = editor->getComponentAt (at);
- if (target == nullptr)
- continue;
- const auto local = target->getLocalPoint (editor.get(), at).toFloat();
- const auto now = juce::Time::getCurrentTime();
- auto source = juce::Desktop::getInstance().getMainMouseSource();
- const juce::ModifierKeys left (juce::ModifierKeys::leftButtonModifier);
- const auto event = [&] (juce::Point<float> p, juce::ModifierKeys mods, bool dragged) {
- return juce::MouseEvent (source, p, mods, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, target, target, now, local, now, 1, dragged);
- };
- target->mouseMove (event (local, {}, false));
- if (hover)
- continue;
- target->mouseDown (event (local, left, false));
- if (drag)
- {
- const auto end = target->getLocalPoint (editor.get(), juce::Point<int> (xy[2].getIntValue(), xy[3].getIntValue())).toFloat();
- target->mouseDrag (event (end, left, true));
- continue;
- }
- target->mouseUp (event (local, {}, false));
- target->mouseExit (event ({ -1000.0f, -1000.0f }, {}, false));
- }
- // round tp172b6: LYNX_PARITYSHOT_SHOW=1 puts the same editor in a real window and keeps it open (for a guarded GUI check
- // of its pop-up menus, which the offscreen picture cannot hold); closing the window quits
- if (juce::SystemStats::getEnvironmentVariable ("LYNX_PARITYSHOT_SHOW", {}) == "1")
- {
- struct ShowWindow final : juce::DocumentWindow
- {
- ShowWindow() : juce::DocumentWindow ("LYNX parity check", juce::Colours::black, juce::DocumentWindow::closeButton) {}
- void closeButtonPressed() override { juce::JUCEApplication::getInstance()->systemRequestedQuit(); }
- };
- parityShow = std::make_shared<ParityShow>();
- parityShow->engine = std::move (offlineOwner);
- parityShow->editor = std::move (editor);
- auto window = std::make_unique<ShowWindow>();
- window->setUsingNativeTitleBar (true);
- window->setContentNonOwned (parityShow->editor.get(), true);
- window->setTopLeftPosition (80, 80);
- window->setVisible (true);
- parityShow->window = std::move (window);
- return;
- }
- juce::Image image (juce::Image::ARGB, editor->getWidth(), editor->getHeight(), true);
- {
- juce::Graphics g (image);
- g.fillAll (lynx::theme::panel);
- editor->paintEntireComponent (g, false);
- }
- const juce::File file (path);
- file.deleteFile();
- juce::PNGImageFormat png;
- if (auto stream = file.createOutputStream())
- png.writeImageToStream (image, *stream);
- }
- void runEq166fShots (const juce::String& folder)
- {
- juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
- const juce::File out (folder);
- out.createDirectory();
- lynx::AudioEngine offline (false);
- auto save = [&] (juce::Component& editor, const juce::String& name) {
- juce::Image image (juce::Image::ARGB, editor.getWidth(), editor.getHeight(), true);
- {
- juce::Graphics g (image);
- g.fillAll (lynx::theme::panel);
- editor.paintEntireComponent (g, false);
- }
- const auto f = out.getChildFile (name);
- f.deleteFile();
- juce::PNGImageFormat png;
- if (auto stream = f.createOutputStream())
- png.writeImageToStream (image, *stream);
- };
- // a song whose demo beat plays into insert 1 (the source) and, for Facet's target, its other half into insert 2
- auto songWith = [] (const lynx::EffectSlot& fx, bool split) {
- auto song = lynx::Song::makeDefault();
- song.mixer.resize (3);
- song.mixer[0].name = "Master";
- song.mixer[1].name = "Vocal";
- song.mixer[2].name = "Reference mix";
- song.mixer[1].effects.assign (1, fx);
- for (std::size_t c = 0; c < song.channels.size(); ++c)
- song.channels[c].mixerTrack = split && c % 2 == 1 ? 2 : 1;
- return song;
- };
- auto feed = [&] (juce::Component& editor, bool facet, int frames) {
- // one continuous render of the song, the editor ticked 30 times a second of audio, as its timer would
- lynx::AudioEngine::RenderOptions o;
- o.seconds = frames / 30.0;
- o.sampleRate = 48000.0;
- o.pluginWarmUp = false;
- int sinceTick = 0;
- o.capture = [&] (const float*, const float*, int n) {
- sinceTick += n;
- if (sinceTick < 1600) return;
- sinceTick = 0;
- if (facet) lynx::tickFacetEqEditor (editor);
- else lynx::tickNativeEffectEditor (editor);
- };
- offline.renderOffline (o);
- if (facet) lynx::tickFacetEqEditor (editor);
- else lynx::tickNativeEffectEditor (editor);
- };
- // Parametric EQ 2: spectrum + heatmap (Full), flat / band 4 +12 dB / band 4 -12 dB, then the Top position
- auto& display = lynx::peqview::displaySettings();
- const auto kept = display;
- display.spectrum = display.heatmap = true;
- display.position = 0;
- for (const auto& [gain, name] : { std::pair { 0.0, "peq2-heatmap-flat.png" }, { 12.0, "peq2-heatmap-boost.png" }, { -12.0, "peq2-heatmap-cut.png" },
- { 0.0, "peq2-heatmap-top.png" } })
- {
- auto eq = lynx::makeEffectSlot (lynx::EffectKind::parametricEq);
- eq.params[(std::size_t) lynx::peq::param (3, 2)] = lynx::peq::gainValue (gain);
- eq.params[(std::size_t) lynx::peq::param (3, 1)] = lynx::peq::hzValue (900.0);
- display.position = juce::String (name).contains ("top") ? 1 : 0;
- offline.setSong (songWith (eq, false));
- offline.dispatchPendingMessages();
- auto editor = lynx::makeNativeEffectEditor (offline, 1, 0, 1.25f, 0);
- feed (*editor, false, 120);
- save (*editor, name);
- }
- display = kept;
- // Facet EQ's comparative EQ: listening to the target (insert 2) with its spectrum over the source's
- {
- using namespace lynx::facet;
- auto eq = lynx::makeEffectSlot (lynx::EffectKind::facetEq);
- eq.params[(std::size_t) param (0, 0)] = shapeValue (Shape::bell);
- eq.params[(std::size_t) param (0, 1)] = hzValue (250.0);
- eq.params[(std::size_t) param (0, 2)] = gainValue (-4.0);
- eq.params[(std::size_t) param (1, 0)] = shapeValue (Shape::highShelf);
- eq.params[(std::size_t) param (1, 1)] = hzValue (6000.0);
- eq.params[(std::size_t) param (1, 2)] = gainValue (3.0);
- eq.params[(std::size_t) analyzerParam] = analyzerValue (Analyzer::both);
- eq.sidechain = 2;
- for (const auto& [l, name] : { std::pair { Listen::target, "facet-compare-target.png" }, { Listen::eq, "facet-compare-eq.png" } })
- {
- eq.params[(std::size_t) listenParam] = listenValue (l);
- offline.setSong (songWith (eq, true));
- offline.dispatchPendingMessages();
- auto editor = lynx::makeFacetEqEditor (offline, 1, 0, false);
- feed (*editor, true, 90);
- save (*editor, name);
- }
- }
- }
- void runDesign168rShots (const juce::String& folder)
- {
- juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
- const juce::File out (folder);
- out.createDirectory();
- lynx::AudioEngine offline (false);
- using K = lynx::EffectKind;
- for (const auto kind : { K::pitchCorrect, K::lovePhilter, K::peakController, K::spreader, K::fruityFastLP, K::flFrequencyShifter,
- K::flLowLifter, K::distructor, K::flBassBoost, K::flDelay1, K::fl7BandEq, K::flCenter, K::flPhaseInverter,
- K::eq, K::delay, K::reverb, K::limiter, K::filter, K::distortion, K::chorus, K::utility, K::lofi,
- K::crossover, K::pitchShift, K::freqShift, K::rhythmGain, K::volumeGate })
- {
- const auto& bank = lynx::presets::factory (kind);
- // Love Philter / Distructor play FL's state: their second picture is FL's default preset (when installed)
- std::optional<lynx::EffectSlot> flPreset;
- if (kind == K::lovePhilter || kind == K::distructor)
- {
- const auto roots = lynx::findFlStudioRoots();
- const auto file = juce::File (juce::String::fromUTF8 (roots.data.c_str()))
- .getChildFile ("Patches/Plugin presets/Effects")
- .getChildFile (kind == K::lovePhilter ? "Fruity Love Philter/Default.fst" : "Distructor/Default.fst");
- juce::MemoryBlock bytes;
- if (file.loadFileAsData (bytes))
- flPreset = lynx::effectFromFlPreset (std::vector<std::uint8_t> ((const std::uint8_t*) bytes.getData(),
- (const std::uint8_t*) bytes.getData() + bytes.getSize()));
- }
- for (int pass = 0; pass < (bank.empty() && ! flPreset ? 1 : 2); ++pass)
- {
- auto fx = lynx::makeEffectSlot (kind);
- if (pass == 1 && flPreset)
- fx = *flPreset;
- else if (pass == 1)
- {
- fx.params = lynx::presets::apply (kind, bank.front(), 120.0);
- fx.presetName = bank.front().name;
- }
- lynx::Song song;
- song.mixer.resize (2);
- song.mixer[0].name = "Master";
- song.mixer[1].name = "Insert 1";
- song.mixer[1].effects.push_back (fx);
- offline.setSong (std::move (song));
- offline.dispatchPendingMessages();
- const auto pages = juce::jmax (1, (int) lynx::plugui::layoutFor (kind).pages.size());
- for (const auto scale : { 1.0f, 2.0f })
- for (int page = 0; page < pages; ++page)
- {
- auto editor = lynx::makeNativeEffectEditor (offline, 1, 0, scale, page);
- if (editor == nullptr)
- continue;
- juce::Image image (juce::Image::ARGB, juce::jmax (1, editor->getWidth()), juce::jmax (1, editor->getHeight()), true);
- {
- juce::Graphics g (image);
- g.fillAll (lynx::theme::panel);
- editor->paintEntireComponent (g, false);
- }
- // (FL's "Frequency Shifter" and LYNX's "Frequency shifter" differ only in case: FL editors get "FL ")
- const auto file = out.getChildFile ((lynx::plugui::hasFlLayout (kind) ? "FL " : "")
- + juce::String (lynx::effectInfo (kind).name).replaceCharacters ("/\\:", "---")
- + (pass == 1 ? "-preset" : "") + (page > 0 ? "-p" + juce::String (page + 1) : juce::String())
- + (scale > 1.5f ? "-200" : "-100") + ".png");
- file.deleteFile();
- juce::PNGImageFormat png;
- if (auto stream = file.createOutputStream())
- png.writeImageToStream (image, *stream);
- }
- }
- }
- }
- bool runInstrumentShots (const juce::File& folder, const juce::String& which, const juce::String& source)
- {
- folder.createDirectory();
- auto key = [] (juce::String n) { return n.toLowerCase().removeCharacters (" -!._"); };
- juce::StringArray wanted;
- wanted.addTokens (which, ",", "");
- auto ok = true;
- struct Shot
- {
- juce::String name;
- std::optional<lynx::ChannelDef> channel;
- };
- std::vector<Shot> shots;
- for (const auto& e : lynx::natives::instrumentEngines())
- {
- const auto name = key (e.name);
- const auto banked = which == "banks" && lynx::banks::hasBank (e.kind);
- if (! banked && ! wanted.contains (name))
- continue;
- auto channel = source == "fl" ? lynx::natives::makeChannel (e.kind, lynx::flStudioAccess())
- : lynx::banks::defaultChannel (e.kind, e.name);
- if (! channel)
- {
- std::fprintf (stderr, "%s: no %s channel\n", e.name, source.toRawUTF8());
- ok = false;
- continue;
- }
- shots.push_back ({ name, std::move (channel) });
- }
- // Autogun (round 169h): not in the Add menus (no preset files); FL's own render-test channel, either source
- if (wanted.contains ("autogun"))
- {
- if (auto channel = lynx::natives::autogunShotChannel (lynx::flStudioAccess()))
- shots.push_back ({ "autogun", std::move (channel) });
- else
- {
- std::fprintf (stderr, "Autogun: no channel (FL Studio's Render tests\\Autogun.flp)\n");
- ok = false;
- }
- }
- for (auto& shot : shots)
- {
- const auto& name = shot.name;
- auto& channel = shot.channel;
- lynx::AudioEngine offline (false);
- lynx::Song song;
- song.mixer = lynx::Song::defaultMixer (2);
- song.channels.push_back (*channel);
- song.patterns.emplace_back();
- {
- juce::String error; // the project too, so an older build can picture the same channel (--snapshot)
- lynx::ProjectFile::save (song, folder.getChildFile (name + "-" + source + ".lynx"), error);
- }
- offline.setSong (std::move (song));
- offline.dispatchPendingMessages();
- auto frame = lynx::makeChannelFrame (offline, 0, 0);
- if (frame == nullptr || frame->getWidth() <= 0)
- {
- ok = false;
- continue;
- }
- for (const auto scale : { 1.0f, 1.5f, 2.0f })
- {
- const auto file = folder.getChildFile (name + "-" + source + "-" + juce::String (juce::roundToInt (scale * 100)) + ".png");
- savePng (frame->createComponentSnapshot (frame->getLocalBounds(), true, scale), file.getFullPathName());
- std::printf ("%s %dx%d\n", file.getFullPathName().toRawUTF8(), frame->getWidth(), frame->getHeight());
- }
- // round 169h: the layout's other pages (Toxic's MIDI / Seq …), one shot each at 1.5×
- for (int page = 1; page < lynx::showChannelLayoutPage (*frame, -1); ++page)
- {
- lynx::showChannelLayoutPage (*frame, page);
- const auto file = folder.getChildFile (name + "-" + source + "-page" + juce::String (page) + "-150.png");
- savePng (frame->createComponentSnapshot (frame->getLocalBounds(), true, 1.5f), file.getFullPathName());
- std::printf ("%s\n", file.getFullPathName().toRawUTF8());
- }
- }
- return ok;
- }
- // --- round 170j: the pilot editors with their own art -------------------------------------------------
- struct ArtPilot
- {
- std::string file; // the art's name as a file name: "toxic-biohazard"
- bool instrument;
- lynx::InstrumentKind instrumentKind;
- lynx::EffectKind effectKind;
- lynx::skin::Style before; // the automatic style it had before the Themed style
- };
- static juce::StringArray& artOnly() // --artshot / --artgui: only these (file names), all when empty
- {
- static juce::StringArray only;
- return only;
- }
- // every plugin with art of its own (round 170j/170k): generators first, then effects; built from the art
- // registries, so a new theme is shot without touching this list
- static const std::vector<ArtPilot>& artPilots()
- {
- using I = lynx::InstrumentKind;
- using E = lynx::EffectKind;
- static const std::vector<ArtPilot> list = [] {
- std::vector<ArtPilot> all;
- auto slug = [] (lynx::skin::Art a) {
- return juce::String (lynx::skin::artName (a)).toLowerCase().replaceCharacters (" ", "-").removeCharacters ("!.()'").toStdString();
- };
- for (const auto& e : lynx::natives::instrumentEngines()) // (the engines' order first)
- if (const auto a = lynx::skin::artForInstrument (e.kind); a != lynx::skin::Art::none)
- all.push_back ({ slug (a), true, e.kind, E::reverb, lynx::skin::Style::neon });
- for (int k = 0; k <= (int) I::wavetraveller; ++k) // then every other kind with art (DrumSynth, Autogun, Wasp...)
- if (const auto a = lynx::skin::artForInstrument ((I) k); a != lynx::skin::Art::none)
- all.push_back ({ slug (a), true, (I) k, E::reverb, lynx::skin::Style::neon });
- for (int k = 0; k <= (int) lynx::lastEffectKind; ++k)
- if (const auto a = lynx::skin::artForEffect ((E) k); a != lynx::skin::Art::none)
- all.push_back ({ slug (a), false, I::synth, (E) k, lynx::skin::plainStyleFor (k) });
- std::vector<ArtPilot> kept;
- for (auto& p : all)
- if (artOnly().isEmpty() || artOnly().contains (juce::String (p.file)))
- if (std::none_of (kept.begin(), kept.end(), [&] (const ArtPilot& q) { return q.file == p.file; }))
- kept.push_back (p);
- return kept;
- }();
- return list;
- }
- // the song and the editor of a pilot (an instrument: the channel window on its Plugin tab)
- static std::unique_ptr<juce::Component> makeArtPilot (lynx::AudioEngine& engine, const ArtPilot& p)
- {
- lynx::Song song;
- song.mixer = lynx::Song::defaultMixer (2);
- if (p.instrument)
- {
- for (const auto& e : lynx::natives::instrumentEngines())
- if (e.kind == p.instrumentKind)
- {
- auto channel = lynx::natives::makeChannel (e.kind, lynx::flStudioAccess());
- if (! channel) channel = lynx::banks::defaultChannel (e.kind, e.name);
- if (! channel) return nullptr;
- song.channels.push_back (*channel);
- break;
- }
- if (song.channels.empty()) // a kind without an engine entry: its LYNX default, else an empty channel of that kind
- {
- const std::string name = lynx::skin::artName (lynx::skin::artForInstrument (p.instrumentKind));
- auto channel = lynx::banks::defaultChannel (p.instrumentKind, name);
- if (! channel)
- {
- channel = lynx::ChannelDef {};
- channel->instrument = p.instrumentKind;
- channel->name = name;
- }
- song.channels.push_back (*channel);
- }
- song.patterns.emplace_back();
- }
- else
- {
- song.mixer[1].effects.push_back (lynx::makeEffectSlot (p.effectKind));
- }
- engine.setSong (std::move (song));
- engine.dispatchPendingMessages();
- if (p.instrument) return lynx::makeChannelFrame (engine, 0, 0);
- if (p.effectKind == lynx::EffectKind::facetEq) return lynx::makeFacetEqEditor (engine, 1, 0, true);
- if (lynx::ProEditorWindows::handles (p.effectKind)) return lynx::makeProEditor (engine, 1, 0, true); // display-first editors, demo signal
- return lynx::makeNativeEffectEditor (engine, 1, 0, 1.0f, 0);
- }
- // "before": the style each pilot had (forced for its run); "after": automatic (the pilots are Themed)
- static void artPilotStyle (const ArtPilot& p, const juce::String& mode)
- {
- lynx::skin::setForcedStyle (mode == "before" ? (int) p.before : -1);
- lynx::skin::setArtMotion (mode != "still");
- }
- bool runArtShots (const juce::File& folder, bool before)
- {
- folder.createDirectory();
- auto ok = true;
- juce::String titles ("editor\tsize\twidth\tname width at the style's size\tbox\tsize used\tlines\tresult\n");
- for (const auto& p : artPilots())
- {
- artPilotStyle (p, before ? "before" : "after");
- lynx::AudioEngine offline (false);
- auto editor = makeArtPilot (offline, p);
- if (editor == nullptr || editor->getWidth() <= 0)
- {
- std::fprintf (stderr, "%s: no editor\n", p.file.c_str());
- ok = false;
- continue;
- }
- if (p.effectKind == lynx::EffectKind::facetEq) lynx::tickFacetEqEditor (*editor);
- // round 170k2: titles.tsv, how the header's name fitted (its width at the style's size, the box, the size used)
- auto fit = [&] (const juce::String& at) {
- const auto f = lynx::skin::lastTitleFit();
- if (f.have <= 0.0f) return; // no plugin header drawn (a generator's channel window)
- titles << juce::String (p.file) << "\t" << at << "\t" << editor->getWidth() << "\t" << juce::String (f.need, 1) << "\t" << juce::String (f.have, 1)
- << "\t" << juce::String (f.size, 1) << "\t" << f.lines << "\t" << (f.clipped ? "ELLIPSIS" : "full") << "\n";
- };
- for (const auto scale : { 1.0f, 2.0f })
- {
- const auto file = folder.getChildFile (juce::String (p.file) + "-" + (before ? "before" : "after") + "-" + juce::String (juce::roundToInt (scale * 100)) + ".png");
- lynx::skin::resetTitleFit();
- savePng (editor->createComponentSnapshot (editor->getLocalBounds(), true, scale), file.getFullPathName());
- std::printf ("%s %dx%d\n", file.getFullPathName().toRawUTF8(), editor->getWidth(), editor->getHeight());
- if (scale == 1.0f) fit ("100");
- }
- // ... and at the smallest size its window allows (effect panels; the Pro editors scale as a whole)
- if (const auto smallest = lynx::nativeEditorMinimumSize (*editor); smallest.x > 0)
- {
- editor->setSize (smallest.x, smallest.y);
- const auto file = folder.getChildFile (juce::String (p.file) + "-" + (before ? "before" : "after") + "-min.png");
- lynx::skin::resetTitleFit();
- savePng (editor->createComponentSnapshot (editor->getLocalBounds(), true, 1.0f), file.getFullPathName());
- fit ("min");
- }
- }
- folder.getChildFile (juce::String ("titles-") + (before ? "before" : "after") + ".tsv").replaceWithText (titles);
- lynx::skin::setForcedStyle (-1);
- return ok;
- }
- struct ArtGuiRun final : juce::Timer
- {
- juce::File folder;
- juce::String mode, report;
- std::size_t at = 0;
- int phase = 0;
- double t0 = 0.0, c0 = 0.0;
- std::unique_ptr<lynx::AudioEngine> engine;
- std::unique_ptr<juce::DocumentWindow> window;
- std::function<void()> done;
- void start()
- {
- engine = std::make_unique<lynx::AudioEngine> (false);
- report << "editor\tmode\tcpu % of one core\tart layer animating\n";
- open();
- startTimer (100);
- }
- void open()
- {
- window.reset();
- const auto& pilots = artPilots();
- if (at >= pilots.size())
- {
- folder.getChildFile ("cpu-" + mode + ".txt").replaceWithText (report);
- stopTimer();
- lynx::skin::setForcedStyle (-1);
- lynx::skin::setArtMotion (true);
- if (done) done();
- return;
- }
- const auto& p = pilots[at];
- artPilotStyle (p, mode);
- auto editor = makeArtPilot (*engine, p);
- if (editor == nullptr) { ++at; open(); return; }
- window = std::make_unique<juce::DocumentWindow> (juce::String ("LYNX art - ") + juce::String (p.file), lynx::theme::colour::bg1, 0);
- window->setUsingNativeTitleBar (true);
- window->setContentOwned (editor.release(), true);
- const auto area = juce::Desktop::getInstance().getDisplays().getPrimaryDisplay()->userArea;
- window->setTopLeftPosition (area.getX() + 24, area.getY() + 24);
- window->setAlwaysOnTop (true);
- window->setVisible (true);
- phase = 0;
- t0 = juce::Time::getMillisecondCounterHiRes();
- }
- bool animating() const
- {
- if (window == nullptr || window->getContentComponent() == nullptr) return false;
- std::function<bool (juce::Component&)> find = [&] (juce::Component& c) {
- if (auto* l = dynamic_cast<lynx::skin::ArtLayer*> (&c); l != nullptr && l->animating()) return true;
- for (auto* child : c.getChildren())
- if (find (*child)) return true;
- return false;
- };
- return find (*window->getContentComponent());
- }
- void timerCallback() override
- {
- const auto now = juce::Time::getMillisecondCounterHiRes();
- const auto& p = artPilots()[at];
- const auto ready = folder.getChildFile (juce::String (p.file) + "-" + mode + ".ready");
- const auto shotDone = folder.getChildFile (juce::String (p.file) + "-" + mode + ".done");
- if (phase == 0 && now - t0 > 1500.0)
- {
- // the window's content on screen, in physical pixels, for the outside screenshot to crop
- auto* c = window->getContentComponent();
- const auto scale = juce::Desktop::getInstance().getDisplays().getPrimaryDisplay()->scale;
- const auto b = c->getScreenBounds();
- shotDone.deleteFile();
- ready.replaceWithText (juce::String (juce::roundToInt (b.getX() * scale)) + " " + juce::String (juce::roundToInt (b.getY() * scale)) + " "
- + juce::String (juce::roundToInt (b.getWidth() * scale)) + " " + juce::String (juce::roundToInt (b.getHeight() * scale)));
- phase = 1;
- t0 = now;
- return;
- }
- if (phase == 1 && (shotDone.existsAsFile() || now - t0 > 10000.0))
- {
- ready.deleteFile();
- shotDone.deleteFile();
- phase = 2;
- t0 = now;
- c0 = lynx::processCpuSeconds();
- return;
- }
- if (phase == 2 && now - t0 > 6000.0)
- {
- const auto cpu = (lynx::processCpuSeconds() - c0) / ((now - t0) * 0.001) * 100.0;
- report << juce::String (p.file) << "\t" << mode << "\t" << juce::String (cpu, 2) << "\t" << (animating() ? "yes" : "no") << "\n";
- ++at;
- open();
- }
- }
- };
- std::unique_ptr<ArtGuiRun> artGui;
- void runArtGui (const juce::File& folder, const juce::String& mode)
- {
- folder.createDirectory();
- artGui = std::make_unique<ArtGuiRun>();
- artGui->folder = folder;
- artGui->mode = mode;
- artGui->done = [this] { juce::MessageManager::callAsync ([this] { artGui.reset(); quit(); }); };
- artGui->start();
- }
- void runPluginEditorSnapshots (const juce::String& folder)
- {
- juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
- {
- const juce::File out (folder);
- out.createDirectory();
- lynx::AudioEngine offline (false);
- const auto roots = lynx::findFlStudioRoots();
- const auto presets = juce::File (juce::String::fromUTF8 (roots.data.c_str())).getChildFile ("Patches/Plugin presets/Effects");
- auto kinds = lynx::plugui::flLayoutKinds();
- kinds.push_back (lynx::EffectKind::maximus); // Soundgoodizer (below)
- for (const auto own : lynx::plugui::ownLayoutKinds()) // LYNX's own panels (mixing suite, round 96)
- kinds.push_back (own);
- kinds.push_back (lynx::EffectKind::apexLimiter); // round 114: display-first editor
- kinds.push_back (lynx::EffectKind::ridgeStrip); // round 145: the second pass shows the Vocal strip voicing
- kinds.push_back (lynx::EffectKind::ridgeStrip); // round 165: the third pass shows the E console voicing
- kinds.push_back (lynx::EffectKind::compressor); // round 152: the RComp role's panel (vintage voicing, RComp ranges)
- const auto database = juce::File (juce::String::fromUTF8 (roots.data.c_str())).getChildFile ("Patches/Plugin database/Effects");
- auto maximusPasses = 0; // Maximus has its own page (first pass); the second pass shows Soundgoodizer
- auto ridgePasses = 0;
- // round 173d3: the parity pictures of one editor — LYNX_PLUGUI_ONLY=<effect name>, LYNX_PLUGUI_PRESET=<.fst>,
- // LYNX_PLUGUI_PAGES=<page,page,…> (the page numbers as the editor encodes them)
- const auto only = juce::SystemStats::getEnvironmentVariable ("LYNX_PLUGUI_ONLY", {});
- const auto onlyPreset = juce::SystemStats::getEnvironmentVariable ("LYNX_PLUGUI_PRESET", {});
- const auto onlyPages = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_PLUGUI_PAGES", {}), ",", "");
- for (const auto kind : kinds)
- {
- if (only.isNotEmpty() && only != lynx::effectInfo (kind).name)
- continue;
- auto fx = lynx::makeEffectSlot (kind);
- juce::String name (lynx::effectInfo (kind).name);
- for (const auto& plugin : lynx::flPluginsForEffect (kind))
- {
- const auto dir = presets.getChildFile (juce::String::fromUTF8 (plugin.c_str()));
- auto file = dir.getChildFile ("Default.fst");
- if (! file.existsAsFile()) // plugins without presets: their entry of FL's plugin database
- for (const auto& f : database.findChildFiles (juce::File::findFiles, true, juce::String::fromUTF8 (plugin.c_str()) + ".fst"))
- file = f;
- if (only.isNotEmpty() && onlyPreset.isNotEmpty())
- file = juce::File (onlyPreset);
- if (! file.existsAsFile())
- {
- auto files = dir.findChildFiles (juce::File::findFiles, true, "*.fst");
- std::sort (files.begin(), files.end(), [] (const juce::File& a, const juce::File& b) { return a.getFullPathName().compareNatural (b.getFullPathName()) < 0; });
- file = files.isEmpty() ? juce::File() : files[0];
- }
- juce::MemoryBlock data;
- if (file.existsAsFile() && file.loadFileAsData (data))
- {
- const auto* bytes = static_cast<const std::uint8_t*> (data.getData());
- if (auto loaded = lynx::effectFromFlPreset (std::vector<std::uint8_t> (bytes, bytes + data.getSize()), 130.0, lynx::natives::flDataReader (lynx::flStudioAccess())); loaded && loaded->kind == kind)
- fx = *loaded;
- }
- name = juce::String::fromUTF8 (plugin.c_str());
- break;
- }
- if (kind == lynx::EffectKind::maximus && ++maximusPasses == 2) // Soundgoodizer: preset A of the installation, Amount 60 %
- {
- juce::MemoryBlock data;
- juce::File (juce::String::fromUTF8 (roots.factoryData.c_str())).getChildFile ("Plugins/Fruity/Effects/Soundgoodizer/Data/Presets/a.dat").loadFileAsData (data);
- lynx::maximusfx::Blob blob;
- blob.build = lynx::hlfx::MaximusBuild::soundgoodizer;
- blob.mix = 600;
- const auto* b = static_cast<const std::uint8_t*> (data.getData());
- blob.state.assign (b, b + data.getSize());
- fx = lynx::makeEffectSlot (kind);
- fx.state = lynx::maximusfx::pack (blob);
- name = "Soundgoodizer";
- }
- if (kind == lynx::EffectKind::ridgeStrip && ++ridgePasses == 2) // round 145: her Vocalstrip 2 setting
- {
- for (const auto& [param, value] : { std::pair<const char*, float> { "Vocal strip", 1.0f }, { "Compander", 1.0f },
- { "Compander threshold", 0.3083f }, { "Compander ratio", 0.6929f }, { "Compander attack", 0.2543f },
- { "Compander release", 0.5316f }, { "Make-up", 0.2917f }, { "Soft knee", 1.0f },
- { "Expander threshold", 0.2198f }, { "Vocal input", 0.6792f }, { "Vocal output", 0.3938f },
- { "Process order", 0.4783f }, { "De-esser", 1.0f } })
- fx.params[(std::size_t) lynx::plugui::paramIndex (kind, param)] = value;
- name = "Ridge Strip (Vocal strip)";
- }
- else if (kind == lynx::EffectKind::ridgeStrip && ridgePasses == 3) // round 165: the E console, EQ to the side chain
- {
- for (const auto& [param, value] : { std::pair<const char*, float> { "Voicing", 1.0f }, { "HPF", 0.3f }, { "HF gain", 0.8f },
- { "HF bell", 1.0f }, { "Ratio", 0.5f }, { "Comp. threshold", 0.4f }, { "EQ to SC", 1.0f },
- { "Filter split", 1.0f }, { "Expander", 1.0f } })
- fx.params[(std::size_t) lynx::plugui::paramIndex (kind, param)] = value;
- name = "Ridge Strip (E console)";
- }
- else if (kind == lynx::EffectKind::ridgeStrip) // a vocal setting, so the graphs show something
- for (const auto& [param, value] : { std::pair<const char*, float> { "HPF", 0.3f }, { "LMF gain", 0.35f }, { "HF gain", 0.7f },
- { "Ratio", 0.3f }, { "Comp. threshold", 0.55f } })
- fx.params[(std::size_t) lynx::plugui::paramIndex (kind, param)] = value;
- if (kind == lynx::EffectKind::compressor) // round 152: the vintage voicing with the reference's ranges and meter
- {
- for (const auto& [param, value] : { std::pair<const char*, float> { "Voicing", 1.0f }, { "Ranges", 1.0f }, { "Limiter", 1.0f },
- { "Threshold", 0.6f }, { "RC ratio", 0.4f } })
- fx.params[(std::size_t) lynx::plugui::paramIndex (kind, param)] = value;
- name = "Compressor (RComp role)";
- }
- if (kind == lynx::EffectKind::apexLimiter) // round 114: gain into the ceiling, so the display shows reduction
- fx.params[0] = 0.33f;
- if (kind == lynx::EffectKind::ember)
- {
- fx.params[(std::size_t) lynx::plugui::paramIndex (kind, "Drive")] = 0.5f;
- fx.params[(std::size_t) lynx::plugui::paramIndex (kind, "Bands")] = 1.0f; // round 108: the band rows
- fx.params[(std::size_t) lynx::plugui::paramIndex (kind, "B3 drive")] = 0.6f;
- }
- if (kind == lynx::EffectKind::crestCompressor) // round 108: a curve with a knee and a side-chain low cut
- for (const auto& [param, value] : { std::pair<const char*, float> { "Threshold", 0.55f }, { "Knee", 0.15f },
- { "SC1 shape", 0.5f }, { "SC1 freq.", 0.3f } })
- fx.params[(std::size_t) lynx::plugui::paramIndex (kind, param)] = value;
- lynx::Song song;
- song.mixer.resize (2);
- song.mixer[0].name = "Master";
- song.mixer[1].name = "Insert 1";
- song.mixer[1].effects.push_back (fx);
- offline.setSong (std::move (song));
- offline.dispatchPendingMessages();
- if (lynx::ProEditorWindows::handles (kind)) // round 114: the display-first editors, with a demo signal
- {
- auto editor = lynx::makeProEditor (offline, 1, 0, true);
- juce::Image image (juce::Image::ARGB, editor->getWidth(), editor->getHeight(), true);
- {
- juce::Graphics g (image);
- editor->paintEntireComponent (g, false);
- }
- const auto file = out.getChildFile (name + ".png");
- file.deleteFile();
- juce::PNGImageFormat png;
- if (auto stream = file.createOutputStream())
- png.writeImageToStream (image, *stream);
- continue;
- }
- const auto pages = name == "Soundgoodizer" ? 1 : juce::jmax (1, (int) lynx::plugui::layoutFor (kind).pages.size());
- std::vector<int> pageList;
- for (int page = 0; page < pages; ++page)
- pageList.push_back (page);
- if (only.isNotEmpty() && ! onlyPages.isEmpty())
- {
- pageList.clear();
- for (const auto& p : onlyPages)
- pageList.push_back (p.getIntValue());
- }
- for (const auto page : pageList)
- {
- auto editor = lynx::makeNativeEffectEditor (offline, 1, 0, 1.0f, page);
- juce::Image image (juce::Image::ARGB, editor->getWidth(), editor->getHeight(), true);
- {
- juce::Graphics g (image);
- g.fillAll (lynx::theme::panel);
- editor->paintEntireComponent (g, false);
- }
- const auto file = out.getChildFile (name + (page > 0 ? "-p" + juce::String (page + 1) : juce::String()) + ".png");
- file.deleteFile();
- juce::PNGImageFormat png;
- if (auto stream = file.createOutputStream())
- png.writeImageToStream (image, *stream);
- }
- }
- // round 137: Echoform in its Rhythm mode (EchoBoy's role) with the Present era
- {
- namespace ef = lynx::echosuite::echoform;
- auto fx = lynx::makeEffectSlot (lynx::EffectKind::echoform);
- fx.params[ef::rhythm] = 1.0f;
- fx.params[ef::rhythmRepeats] = 5.0f / 15.0f;
- fx.params[ef::rhythmDecay] = 0.25f;
- fx.params[ef::rhythmTap1 + 2] = 0.45f;
- fx.params[ef::feedback] = 0.25f;
- fx.params[ef::era] = 0.5f;
- for (const auto& [param, value] : ef::rhythmPresetEdits (0)) // round 144: a pattern in the rhythm editor (Grid)
- fx.params[(std::size_t) param] = value;
- fx.params[ef::rhythmShape] = 0.5f; // swell
- lynx::Song song;
- song.mixer.resize (2);
- song.mixer[0].name = "Master";
- song.mixer[1].name = "Insert 1";
- song.mixer[1].effects.push_back (fx);
- offline.setSong (std::move (song));
- offline.dispatchPendingMessages();
- auto editor = lynx::makeNativeEffectEditor (offline, 1, 0, 1.0f, 0);
- juce::Image image (juce::Image::ARGB, editor->getWidth(), editor->getHeight(), true);
- {
- juce::Graphics g (image);
- g.fillAll (lynx::theme::panel);
- editor->paintEntireComponent (g, false);
- }
- const auto file = out.getChildFile ("Echoform-rhythm.png");
- file.deleteFile();
- juce::PNGImageFormat png;
- if (auto stream = file.createOutputStream())
- png.writeImageToStream (image, *stream);
- }
- // round 150: Echoform with a voicing (the Stereo / L/R offset controls on the Rhythm row)
- {
- namespace ef = lynx::echosuite::echoform;
- auto fx = lynx::makeEffectSlot (lynx::EffectKind::echoform);
- fx.params[ef::voicing] = ef::voicingValue (ef::voicingForEchoBoyStyle (19));
- fx.params[ef::style] = ef::styleValue (ef::Style::dual);
- lynx::Song song;
- song.mixer.resize (2);
- song.mixer[0].name = "Master";
- song.mixer[1].name = "Insert 1";
- song.mixer[1].effects.push_back (fx);
- offline.setSong (std::move (song));
- offline.dispatchPendingMessages();
- auto editor = lynx::makeNativeEffectEditor (offline, 1, 0, 1.0f, 0);
- juce::Image image (juce::Image::ARGB, editor->getWidth(), editor->getHeight(), true);
- {
- juce::Graphics g (image);
- g.fillAll (lynx::theme::panel);
- editor->paintEntireComponent (g, false);
- }
- const auto file = out.getChildFile ("Echoform-voicing.png");
- file.deleteFile();
- juce::PNGImageFormat png;
- if (auto stream = file.createOutputStream())
- png.writeImageToStream (image, *stream);
- }
- // round 150: Auto-pan's Rhythm voicing with its Tweak row (PanMan's role)
- {
- auto fx = lynx::makeEffectSlot (lynx::EffectKind::autoPan);
- fx.params[lynx::autopan::count] = 1.0f; // the Rhythm voicing
- fx.params[lynx::autopan::count + 13] = 0.75f; // offset mod +90°
- lynx::Song song;
- song.mixer.resize (2);
- song.mixer[0].name = "Master";
- song.mixer[1].name = "Insert 1";
- song.mixer[1].effects.push_back (fx);
- offline.setSong (std::move (song));
- offline.dispatchPendingMessages();
- auto editor = lynx::makeNativeEffectEditor (offline, 1, 0, 1.0f, 0);
- juce::Image image (juce::Image::ARGB, editor->getWidth(), editor->getHeight(), true);
- {
- juce::Graphics g (image);
- g.fillAll (lynx::theme::panel);
- editor->paintEntireComponent (g, false);
- }
- const auto file = out.getChildFile ("Auto-pan-tweak.png");
- file.deleteFile();
- juce::PNGImageFormat png;
- if (auto stream = file.createOutputStream())
- png.writeImageToStream (image, *stream);
- }
- // round 165: Ember's Classic voicing (the Decapitator role) in its one-screen panel
- {
- namespace em = lynx::mixsuite::ember;
- auto fx = lynx::makeEffectSlot (lynx::EffectKind::ember);
- fx.params[em::voicing] = 1.0f;
- fx.params[em::classicDrive] = 0.35f;
- lynx::Song song;
- song.mixer.resize (2);
- song.mixer[0].name = "Master";
- song.mixer[1].name = "Insert 1";
- song.mixer[1].effects.push_back (fx);
- offline.setSong (std::move (song));
- offline.dispatchPendingMessages();
- auto editor = lynx::makeNativeEffectEditor (offline, 1, 0, 1.0f, 0);
- juce::Image image (juce::Image::ARGB, editor->getWidth(), editor->getHeight(), true);
- {
- juce::Graphics g (image);
- g.fillAll (lynx::theme::panel);
- editor->paintEntireComponent (g, false);
- }
- const auto file = out.getChildFile ("Ember Saturator-classic.png");
- file.deleteFile();
- juce::PNGImageFormat png;
- if (auto stream = file.createOutputStream())
- png.writeImageToStream (image, *stream);
- }
- // round 152: Foil Plate's one-knob Plate view (the Little Plate role)
- {
- auto fx = lynx::makeEffectSlot (lynx::EffectKind::foilPlate);
- fx.params[14] = 1.0f; // the measured plate voicing
- fx.params[15] = 1.0f; // View = Plate
- lynx::Song song;
- song.mixer.resize (2);
- song.mixer[0].name = "Master";
- song.mixer[1].name = "Insert 1";
- song.mixer[1].effects.push_back (fx);
- offline.setSong (std::move (song));
- offline.dispatchPendingMessages();
- auto editor = lynx::makeNativeEffectEditor (offline, 1, 0, 1.0f, 0);
- juce::Image image (juce::Image::ARGB, editor->getWidth(), editor->getHeight(), true);
- {
- juce::Graphics g (image);
- g.fillAll (lynx::theme::panel);
- editor->paintEntireComponent (g, false);
- }
- const auto file = out.getChildFile ("Foil Plate-plate.png");
- file.deleteFile();
- juce::PNGImageFormat png;
- if (auto stream = file.createOutputStream())
- png.writeImageToStream (image, *stream);
- }
- // LYNX's own editors with live displays (round 103): Facet EQ (a mixing curve, one dynamic band, demo analyser)
- // and LYNX Tune (demo pitch phrase)
- {
- lynx::setNativeEditorDemo (true);
- using namespace lynx::facet;
- auto eq = lynx::makeEffectSlot (lynx::EffectKind::facetEq);
- const struct { Shape s; double f, g, q; int slope; double range; } bandsDemo[] = {
- { Shape::lowCut, 32, 0, 1, 24, 0 }, { Shape::bell, 110, 3, 1.2, 12, 0 }, { Shape::bell, 380, -3.5, 1.6, 12, 0 },
- { Shape::bell, 3200, 0, 2.5, 12, -6 }, { Shape::highShelf, 9000, 2.5, 0.8, 12, 0 }
- };
- for (int b = 0; b < 5; ++b)
- {
- eq.params[(std::size_t) param (b, 0)] = shapeValue (bandsDemo[b].s);
- eq.params[(std::size_t) param (b, 1)] = hzValue (bandsDemo[b].f);
- eq.params[(std::size_t) param (b, 2)] = gainValue (bandsDemo[b].g);
- eq.params[(std::size_t) param (b, 3)] = qValue (bandsDemo[b].q);
- eq.params[(std::size_t) param (b, 4)] = slopeValue (bandsDemo[b].slope);
- eq.params[(std::size_t) (rangeParam0 + b)] = rangeValue (bandsDemo[b].range);
- }
- eq.params[(std::size_t) phaseParam] = phaseValue (Phase::natural);
- const auto own = [&] (const lynx::EffectSlot& fx, const juce::String& file, bool facetEditor, int page = 0) {
- lynx::Song song;
- song.mixer.resize (2);
- song.mixer[0].name = "Master";
- song.mixer[1].name = "Vocal";
- song.mixer[1].effects.push_back (fx);
- offline.setSong (std::move (song));
- offline.dispatchPendingMessages();
- auto editor = facetEditor ? lynx::makeFacetEqEditor (offline, 1, 0, true) : lynx::makeNativeEffectEditor (offline, 1, 0, 1.25f, page);
- juce::Image image (juce::Image::ARGB, editor->getWidth(), editor->getHeight(), true);
- {
- juce::Graphics g (image);
- g.fillAll (lynx::theme::panel);
- editor->paintEntireComponent (g, false);
- }
- const auto f = out.getChildFile (file);
- f.deleteFile();
- juce::PNGImageFormat png;
- if (auto stream = f.createOutputStream())
- png.writeImageToStream (image, *stream);
- };
- own (eq, "Facet EQ.png", true);
- own (lynx::makeEffectSlot (lynx::EffectKind::lynxTune), "LYNX Tune.png", false);
- {
- // round 128: the ADVANCED page, with E bypassed and A removed on the keyboard and a created vibrato
- auto tune = lynx::makeEffectSlot (lynx::EffectKind::lynxTune);
- tune.params[(std::size_t) (lynx::lynxtune::bypassC + 4)] = 1.0f;
- tune.params[(std::size_t) (lynx::lynxtune::noteC + 9)] = 0.0f;
- tune.params[lynx::lynxtune::vibratoShape] = 1.0f / 3.0f;
- // round 166c: the created vibrato's amplitude / formant / variation, a short throat, In scale +2
- tune.params[lynx::lynxtune::vibratoAmplitude] = 1.0f / 3.0f;
- tune.params[lynx::lynxtune::vibratoFormant] = 0.7f;
- tune.params[lynx::lynxtune::vibratoVariation] = 0.2f;
- tune.params[lynx::lynxtune::throatLength] = lynx::lynxtune::throatValue (80.0);
- tune.params[lynx::lynxtune::transposeInScale] = 1.0f;
- tune.params[lynx::lynxtune::scaleTranspose] = lynx::lynxtune::scaleTransposeValue (2);
- own (tune, "LYNX Tune-p2.png", false, 1);
- }
- own (lynx::makeEffectSlot (lynx::EffectKind::lynxTune), "LYNX Tune-p3.png", false, 2); // round 135w: Real-time
- lynx::setNativeEditorDemo (false);
- }
- // generators in FL's arrangement: the channel's plugin page with the FL preset's settings
- const auto generators = juce::File (juce::String::fromUTF8 (roots.data.c_str())).getChildFile ("Patches/Plugin presets/Generators");
- for (auto [folder, preset] : std::vector<std::pair<const char*, const char*>> { { "3x Osc", "Default.fst" }, { "FL Keys", "Grand Piano.fst" }, { "BooBass", "" }, { "Sytrus", "Default.fst" }, { "Harmor", "Default.fst" } })
- {
- juce::MemoryBlock data;
- if (juce::String (folder) == "Harmor") // the first preset whose state the engine reads
- {
- auto files = generators.getChildFile (folder).findChildFiles (juce::File::findFiles, true, "*.fst");
- files.sort();
- for (const auto& f : files)
- {
- juce::MemoryBlock block;
- if (! f.loadFileAsData (block))
- continue;
- const auto* b = static_cast<const std::uint8_t*> (block.getData());
- try
- {
- const auto p = flp::parseProject (std::vector<std::uint8_t> (b, b + block.getSize()), true);
- if (! p.channels.empty() && lynx::harmorStateUsable (p.channels.front().pluginState))
- {
- preset = nullptr;
- data = block;
- break;
- }
- }
- catch (const std::exception&)
- {
- }
- }
- }
- auto file = preset == nullptr ? juce::File() : juce::String (preset).isEmpty() ? database.getSiblingFile ("Generators").getChildFile ("Misc").getChildFile (juce::String (folder) + ".fst")
- : generators.getChildFile (folder).getChildFile (preset);
- if (! file.existsAsFile())
- {
- auto files = generators.getChildFile (folder).findChildFiles (juce::File::findFiles, true, "*.fst");
- files.sort();
- file = files.isEmpty() ? juce::File() : files[0];
- }
- if (data.isEmpty() && ! file.loadFileAsData (data))
- continue;
- try
- {
- const auto* bytes = static_cast<const std::uint8_t*> (data.getData());
- auto project = flp::parseProject (std::vector<std::uint8_t> (bytes, bytes + data.getSize()), true);
- if (project.channels.empty())
- continue;
- project.channels.front().type = flp::ChannelType::native;
- lynx::FlpImportOptions options;
- options.roots = roots;
- options.fileExists = [] (const std::string& path) { return lynx::platform::localFile (path).existsAsFile(); };
- options.readFile = [] (const std::string& path) {
- juce::MemoryBlock block;
- lynx::platform::localFile (path).loadFileAsData (block);
- const auto* b = static_cast<const std::uint8_t*> (block.getData());
- return std::vector<std::uint8_t> (b, b + block.getSize());
- };
- options.saveEmbedded = [out] (const std::vector<std::uint8_t>& wav, const std::string& name) {
- const auto f = out.getChildFile ("samples").getNonexistentChildFile (juce::String::fromUTF8 (name.c_str()), ".wav");
- f.getParentDirectory().createDirectory();
- f.replaceWithData (wav.data(), wav.size());
- return f.getFullPathName().toStdString();
- };
- auto song = lynx::importFlp (project, options);
- // the page only needs the plugin's saved state (FL Keys' sample zones need the installed wavetables)
- if (! song.channels.empty() && project.channels.front().pluginName == "BooBass" && song.channels.front().instrument != lynx::InstrumentKind::boobass)
- {
- song.channels.front().instrument = lynx::InstrumentKind::boobass; // (its sound needs the engine DLL; the page does not)
- song.channels.front().modelParams.assign (3, 32768.0f);
- }
- if (! song.channels.empty() && project.channels.front().pluginName == "FL Keys")
- {
- song.channels.front().instrument = lynx::InstrumentKind::flkeys;
- song.channels.front().pluginState = project.channels.front().pluginState;
- }
- offline.setSong (std::move (song));
- offline.dispatchPendingMessages();
- if (offline.getSong().channels.empty())
- continue;
- auto panel = lynx::makeChannelSettingsPanel (offline, 0);
- juce::Image image (juce::Image::ARGB, panel->getWidth(), panel->getHeight(), true);
- {
- juce::Graphics g (image);
- g.fillAll (lynx::theme::panel);
- panel->paintEntireComponent (g, false);
- }
- const auto out2 = out.getChildFile (juce::String (folder) + ".png");
- out2.deleteFile();
- juce::PNGImageFormat png;
- if (auto stream = out2.createOutputStream())
- png.writeImageToStream (image, *stream);
- }
- catch (const std::exception&)
- {
- }
- }
- }
- quit();
- }
- void runVideoShot (const juce::String& prefix, const juce::String& videoPath)
- {
- juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
- // the message loop runs while the frames decode (modal loops are off): a timer takes one snapshot per step
- struct VideoShot final : juce::Timer
- {
- lynx::AudioEngine offline { false };
- std::unique_ptr<juce::Component> editor;
- juce::String prefix, report;
- int step = 0;
- std::function<void()> done;
- void moveTo (double seconds)
- {
- offline.getTransport().positionTicks.store (seconds * offline.getSong().bpm / 60.0 * lynx::ppq);
- }
- void timerCallback() override
- {
- static constexpr double times[] = { 0.0, 1.5, 3.25 };
- constexpr int typeInStep = (int) std::size (times) + 1;
- if (step > 0 && step < typeInStep && editor != nullptr)
- savePng (editor->createComponentSnapshot (editor->getLocalBounds()), prefix + "-" + juce::String (step - 1) + ".png");
- if (editor != nullptr && step == (int) std::size (times))
- {
- // round 174d: FL's in-place type-in of the current time (a right click on it)
- lynx::videoview::openTypeIn (*editor, 2);
- ++step;
- return;
- }
- if (editor != nullptr && step == typeInStep)
- savePng (editor->createComponentSnapshot (editor->getLocalBounds()), prefix + "-typein.png");
- if (editor == nullptr || step >= typeInStep)
- {
- stopTimer();
- juce::File (prefix + "-report.txt").replaceWithText (report);
- if (done)
- done();
- return;
- }
- moveTo (times[step++]);
- }
- };
- static std::unique_ptr<VideoShot> shot;
- shot = std::make_unique<VideoShot>();
- shot->prefix = prefix;
- auto& offline = shot->offline;
- lynx::videoview::install (offline);
- lynx::Song song;
- song.mixer = lynx::Song::defaultMixer (2);
- lynx::ChannelDef c;
- c.name = "Fruity Video Player";
- c.instrument = lynx::InstrumentKind::videoplayer;
- lynx::video::Settings vs;
- vs.path = juce::File (videoPath).getFullPathName().toStdString();
- vs.delay = lynx::video::unitsPerSecond / 2; // the video starts at 0.5 s
- c.pluginState = lynx::video::write (vs);
- song.channels.push_back (c);
- song.patterns.emplace_back();
- {
- // round 174d (A3): the same Video Player in a song whose tempo drops from 120 to 60 BPM at bar 5, for FL
- // (LYNX.exe --export-flp <prefix>-tempo.lynx <prefix>-tempo.flp), to compare FL's video clock with LYNX's
- auto fl = song;
- fl.bpm = 120.0;
- fl.mode = lynx::PlayMode::song;
- auto settings = vs;
- settings.delay = 0;
- settings.timeDisplay = lynx::video::Settings {}.timeDisplay;
- fl.channels[0].pluginState = lynx::video::write (settings);
- fl.patterns[0].name = "Pattern 1";
- lynx::Automation tempo;
- tempo.name = "Tempo";
- tempo.target = { lynx::AutomationTargetKind::tempo, 0, 0, 0 };
- const auto bar = (std::int64_t) lynx::ppq * 4;
- tempo.points = { { 0, lynx::valueFromTempo (120.0), 0.0f }, { bar * 4 - 1, lynx::valueFromTempo (120.0), 0.0f },
- { bar * 4, lynx::valueFromTempo (60.0), 0.0f }, { bar * 8, lynx::valueFromTempo (60.0), 0.0f } };
- fl.automations.push_back (tempo);
- lynx::Clip at;
- at.kind = lynx::ClipKind::automation;
- at.automation = 0;
- at.track = 1;
- at.start = 0;
- at.length = bar * 8;
- fl.playlist.push_back (at);
- lynx::Clip pc;
- pc.pattern = 0;
- pc.track = 0;
- pc.start = 0;
- pc.length = bar * 8;
- fl.playlist.push_back (pc);
- juce::String error;
- lynx::ProjectFile::save (fl, juce::File (prefix + "-tempo.lynx"), error);
- }
- offline.setSong (std::move (song));
- offline.dispatchPendingMessages();
- auto& report = shot->report;
- report << "ffmpeg: " << lynx::findFfmpeg().getFullPathName() << "\n";
- report << lynx::videoview::report (vs.path).fromFirstOccurrenceOf ("Input #0", true, false).upToFirstOccurrenceOf ("At least", false, false) << "\n";
- shot->editor = lynx::makeChannelSettingsPanel (offline, 0);
- if (shot->editor != nullptr)
- shot->editor->setVisible (true);
- shot->done = [this] { juce::MessageManager::callAsync ([this] { shot.reset(); quit(); }); };
- shot->startTimer (1500);
- }
- void runVideoTrackShot (const juce::String& prefix, const juce::String& videoPath, const juce::String& secondPath)
- {
- juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
- struct TrackShot final : juce::Timer
- {
- lynx::AudioEngine offline { false };
- std::unique_ptr<lynx::PlaylistComponent> playlist;
- std::unique_ptr<lynx::media::FrameDecoder> decoder;
- juce::String prefix, report, path;
- double fps = 25.0;
- int step = 0, waits = 0, adrStep = 0;
- std::unique_ptr<juce::Component> adrPanel;
- std::function<void()> done;
- // song times (s): before, inside the first clip (on and between frame edges), across the second clip
- std::vector<double> times { 0.0, 1.0, 2.0 + 1.0 / 25.0, 2.5, 4.0, 7.3 };
- void timerCallback() override
- {
- if (step > 0 && adrStep == 0)
- {
- // the frame the decoder shows for the wanted file time (the clip starts at song 1.0 s, offset 0)
- const auto want = times[(std::size_t) step - 1] - 1.0;
- double ft = -1.0;
- const auto img = decoder->frame (ft);
- const auto expected = std::floor (want * fps + 1e-6) / fps;
- if (want >= 0.0 && ft < expected - 1e-3 && ++waits < 20)
- return; // (still decoding)
- waits = 0;
- report << "song " << juce::String (times[(std::size_t) step - 1], 3) << " s: wanted file time " << juce::String (want, 4)
- << ", frame shown at " << juce::String (ft, 4) << " (expected " << juce::String (expected, 4) << ")"
- << (want < 0.0 ? " [before the clip]" : std::abs (ft - expected) < 1e-3 ? " OK" : " MISMATCH") << "\n";
- savePng (playlist->createComponentSnapshot (playlist->getLocalBounds()), prefix + "-playlist-" + juce::String (step - 1) + ".png");
- if (img.isValid())
- savePng (img, prefix + "-frame-" + juce::String (step - 1) + ".png");
- for (int w = 0; w < juce::Desktop::getInstance().getNumComponents(); ++w)
- if (auto* c = juce::Desktop::getInstance().getComponent (w); c != nullptr && c->getName().startsWith ("Picture"))
- savePng (c->createComponentSnapshot (c->getLocalBounds()), prefix + "-window-" + juce::String (step - 1) + ".png");
- }
- if (step >= (int) times.size() && adrStep == 0)
- {
- // the ADR window: two cues, takes on the first; the play position inside the streamer before the in
- // point (4.0 s), so the video window shows the streamer and the line
- adrStep = 1;
- offline.editSong ([] (lynx::Song& s) {
- lynx::AdrCue a, b;
- a.id = "SC1-01";
- a.in = 4.0;
- a.out = 6.4;
- a.character = "Dr. Silva";
- a.line = "We have to leave before the storm reaches the coast.";
- a.notes = "softer, out of breath";
- a.status = lynx::AdrCue::Status::recorded;
- for (int n = 1; n <= 3; ++n)
- {
- lynx::AdrTake t;
- t.number = n;
- t.name = lynx::adr::takeName (a, n);
- t.rating = n == 2 ? 4 : n;
- t.circled = n == 2;
- a.takes.push_back (t);
- }
- a.selected = 2;
- lynx::adr::setCompRange (a, 4.0, 5.1, 2);
- lynx::adr::setCompRange (a, 5.1, 6.4, 3);
- b.id = "SC1-02";
- b.in = 8.0;
- b.out = 9.5;
- b.character = "Marta";
- b.line = "Then we go now.";
- s.adr.cues = { a, b };
- s.adr.current = 0;
- });
- adrPanel = lynx::adrwindow::makePanel (offline);
- adrPanel->setSize (1200, 640);
- adrPanel->setVisible (true);
- offline.getTransport().positionTicks.store (3.0 * offline.getSong().bpm / 60.0 * lynx::ppq);
- decoder->request (2.0, false);
- return;
- }
- if (adrStep == 1)
- {
- adrStep = 2;
- savePng (adrPanel->createComponentSnapshot (adrPanel->getLocalBounds()), prefix + "-adr.png");
- for (int w = 0; w < juce::Desktop::getInstance().getNumComponents(); ++w)
- if (auto* c = juce::Desktop::getInstance().getComponent (w); c != nullptr && c->getName().startsWith ("Picture"))
- savePng (c->createComponentSnapshot (c->getLocalBounds()), prefix + "-adr-window.png");
- offline.getTransport().positionTicks.store (4.5 * offline.getSong().bpm / 60.0 * lynx::ppq);
- decoder->request (3.5, false);
- return;
- }
- if (adrStep == 2)
- {
- for (int w = 0; w < juce::Desktop::getInstance().getNumComponents(); ++w)
- if (auto* c = juce::Desktop::getInstance().getComponent (w); c != nullptr && c->getName().startsWith ("Picture"))
- savePng (c->createComponentSnapshot (c->getLocalBounds()), prefix + "-adr-window-line.png");
- adrPanel.reset();
- // export with video: a 3 s mix under the picture, re-encoded (the clip starts at 1 s) and copied (from 1 s)
- {
- const juce::File wav (prefix + "-mix.wav");
- wav.deleteFile();
- juce::WavAudioFormat format;
- if (std::unique_ptr<juce::OutputStream> os (wav.createOutputStream().release()); os != nullptr)
- if (std::unique_ptr<juce::AudioFormatWriter> w (format.createWriterFor (os.get(), 48000.0, 2, 16, {}, 0)); w != nullptr)
- {
- os.release();
- juce::AudioBuffer<float> b (2, 48000 * 3);
- for (int k = 0; k < b.getNumSamples(); ++k)
- b.setSample (0, k, 0.25f * (float) std::sin (k * 2.0 * juce::MathConstants<double>::pi * 330.0 / 48000.0)), b.setSample (1, k, b.getSample (0, k));
- w->writeFromAudioSampleBuffer (b, 0, b.getNumSamples());
- }
- for (const auto origin : { 0.0, 1.0 })
- {
- const juce::File out (prefix + "-mux-" + juce::String ((int) origin) + ".mp4");
- const auto t0 = juce::Time::getMillisecondCounterHiRes();
- const auto error = lynx::videotracks::muxWithVideo (offline.getSong(), origin, wav, out);
- report << "export with video from " << origin << " s: " << (error.isEmpty() ? "OK " + juce::String (out.getSize()) + " bytes" : "FAILED " + error)
- << " (" << juce::String ((juce::Time::getMillisecondCounterHiRes() - t0) / 1000.0, 2) << " s)\n";
- }
- }
- stopTimer();
- report << "frames decoded " << decoder->frameCount() << ", dropped " << decoder->droppedCount() << "\n";
- juce::File (prefix + "-report.txt").replaceWithText (report);
- if (done)
- done();
- return;
- }
- const auto t = times[(std::size_t) step++];
- offline.getTransport().positionTicks.store (t * offline.getSong().bpm / 60.0 * lynx::ppq);
- decoder->request (std::max (0.0, t - 1.0), false);
- }
- };
- static std::unique_ptr<TrackShot> shot;
- shot = std::make_unique<TrackShot>();
- shot->prefix = prefix;
- auto& offline = shot->offline;
- lynx::Song song;
- song.mixer = lynx::Song::defaultMixer (2);
- song.patterns.emplace_back();
- song.mode = lynx::PlayMode::song;
- song.bpm = 120.0;
- offline.setSong (std::move (song));
- offline.dispatchPendingMessages();
- const juce::File video (videoPath);
- const auto pr = lynx::media::probe (video.getFullPathName());
- auto& report = shot->report;
- report << "decoder: " << (pr.backend.isEmpty() ? juce::String ("none") : pr.backend) << " (system: " << lynx::media::nativeBackendName()
- << ", ffmpeg: " << lynx::findFfmpeg().getFullPathName() << ")\n";
- report << "video: " << pr.info.width << "x" << pr.info.height << " " << juce::String (pr.info.fps, 3) << " fps " << juce::String (pr.info.duration, 3)
- << " s, sound " << (pr.info.hasAudio ? "yes" : "no") << "\n";
- shot->fps = pr.info.fps > 1.0 ? pr.info.fps : 25.0;
- shot->times[2] = 2.0 + 1.0 / shot->fps; // (exactly on a frame edge)
- lynx::videotracks::importVideo (offline, video, 1.0, -1);
- if (secondPath.isNotEmpty())
- lynx::videotracks::importVideo (offline, juce::File (secondPath), 3.0, 1);
- offline.editSong ([] (lynx::Song& s) {
- s.video.startTimecode = 3600.0;
- s.video.burnIn = true;
- if (s.videoTracks.size() < 2)
- s.videoTracks.push_back ({});
- s.videoTracks[0].name = "Picture";
- s.videoTracks[1].name = "Reference";
- });
- report << "project rate: " << lynx::vtime::rateName (offline.getSong().video.rate) << ", clip 1: "
- << juce::String (offline.getSong().videoTracks[0].clips.empty() ? -1.0 : offline.getSong().videoTracks[0].clips[0].length, 3) << " s\n";
- // the project round trip
- {
- const juce::File file (prefix + "-project.lynx");
- juce::String error;
- lynx::ProjectFile::save (offline.getSong(), file, error);
- const auto back = lynx::ProjectFile::load (file, error);
- report << "project file round trip: " << (back && back->videoTracks == offline.getSong().videoTracks && back->video == offline.getSong().video ? "OK" : "MISMATCH " + error) << "\n";
- }
- shot->playlist = std::make_unique<lynx::PlaylistComponent> (offline);
- shot->playlist->setSize (1400, 640);
- shot->playlist->setVisible (true);
- shot->decoder = std::make_unique<lynx::media::FrameDecoder>();
- shot->decoder->setSource (video.getFullPathName(), pr.info);
- shot->decoder->setSize (pr.info.width, pr.info.height);
- shot->decoder->startThread (juce::Thread::Priority::low);
- lynx::videotracks::showWindow (offline, 0);
- shot->done = [this] { juce::MessageManager::callAsync ([this] { shot.reset(); quit(); }); };
- shot->startTimer (700);
- }
- void runDanceShot (const juce::String& prefix)
- {
- juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
- // the moves: one row each, eight moments of a cycle (both facings for Spinning; Pose ends the sheet)
- {
- constexpr int cell = 120, cols = 8;
- juce::Image sheet (juce::Image::ARGB, 130 + cols * cell, lynx::dance::moveCount * cell + 10, true);
- juce::Graphics g (sheet);
- g.fillAll (lynx::theme::colour::bg0);
- for (int m = 0; m < lynx::dance::moveCount; ++m)
- {
- g.setColour (lynx::theme::colour::textSecondary);
- g.setFont (14.0f);
- g.drawText (lynx::dance::moveName (m), 8, m * cell + 5, 118, cell, juce::Justification::centredLeft);
- for (int k = 0; k < cols; ++k)
- {
- const auto pose = lynx::dance::pose (m, k / (double) cols + (m == lynx::dance::freestyle ? k * 2 : 0), 1);
- lynx::dancer::draw (g, { 130.0f + (k + 0.5f) * cell, (float) (m + 1) * cell - 6.0f }, 92.0f, pose, false, juce::Colour (0xffff3048));
- }
- }
- savePng (sheet, prefix + "-moves.png");
- }
- lynx::AudioEngine offline (false);
- lynx::Song song;
- song.mixer = lynx::Song::defaultMixer (2);
- for (int d = 0; d < 2; ++d)
- {
- lynx::ChannelDef c;
- c.name = d == 0 ? "Fruity Dance" : "Fruity Dance #2";
- c.instrument = lynx::InstrumentKind::fruitydance;
- lynx::dance::Settings s;
- s.move = d == 0 ? lynx::dance::stepping : lynx::dance::waving;
- s.x = d == 0 ? 520 : 760;
- s.y = 560;
- s.colour = d == 0 ? 0xffff3048 : 0xff30a8ff;
- s.mirrored = d == 1;
- c.pluginState = lynx::dance::toState (s);
- song.channels.push_back (c);
- }
- song.patterns.emplace_back();
- {
- const juce::File demo (prefix + "-demo.lynx");
- juce::String error;
- lynx::ProjectFile::save (song, demo, error);
- }
- offline.setSong (std::move (song));
- offline.dispatchPendingMessages();
- if (auto editor = lynx::makeChannelSettingsPanel (offline, 0))
- savePng (editor->createComponentSnapshot (editor->getLocalBounds()), prefix + "-editor.png");
- if (auto frame = lynx::makeChannelFrame (offline, 1, 0))
- savePng (frame->createComponentSnapshot (frame->getLocalBounds()), prefix + "-frame.png");
- }
- void runControllerShot (const juce::String& prefix)
- {
- juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
- lynx::AudioEngine offline (false);
- lynx::Song song;
- song.mixer = lynx::Song::defaultMixer (2);
- song.mixer[1].name = "Insert 1";
- auto fx = lynx::makeEffectSlot (lynx::EffectKind::formulaController);
- lynx::formula::State formula;
- formula.formula = "a*Sin(SongTime*Pi*b*4)+c";
- fx.state = lynx::formula::writeState (formula);
- fx.params[0] = 0.5f;
- fx.params[1] = 0.25f;
- fx.params[2] = 0.5f;
- song.mixer[1].effects.push_back (fx);
- // round 164: X-Y (slot 2), X-Y-Z (slot 3) and a Control Surface (slot 4)
- {
- auto xyFx = lynx::makeEffectSlot (lynx::EffectKind::xyController);
- xyFx.params[(std::size_t) lynx::xy::level (0)] = 0.3f;
- xyFx.params[(std::size_t) lynx::xy::level (1)] = 0.7f;
- xyFx.params[(std::size_t) lynx::xy::tension (0)] = 0.8f;
- song.mixer[1].effects.push_back (xyFx);
- auto xyzFx = lynx::makeEffectSlot (lynx::EffectKind::xyzController);
- xyzFx.params[(std::size_t) lynx::xy::level (2)] = 0.8f;
- song.mixer[1].effects.push_back (xyzFx);
- // round 165: an X-Y-Z whose X curve is FL's "Stairs" (tension +40 %) and Y a bent single curve
- xyzFx.params[(std::size_t) lynx::xy::curveMode (0)] = lynx::xy::curveModeValue (lynx::flcurve::stairs);
- xyzFx.params[(std::size_t) lynx::xy::tension (0)] = 0.7f;
- xyzFx.params[(std::size_t) lynx::xy::level (0)] = 0.62f;
- xyzFx.params[(std::size_t) lynx::xy::tension (1)] = 0.825f;
- song.mixer[1].effects.push_back (xyzFx);
- auto panel = lynx::makeEffectSlot (lynx::EffectKind::controlSurface);
- lynx::SurfaceControl c;
- for (const auto& [kind, name, v, x, y] : std::vector<std::tuple<lynx::SurfaceControl::Kind, const char*, float, float, float>> {
- { lynx::SurfaceControl::Kind::knob, "Cutoff", 0.65f, 20.0f, 20.0f },
- { lynx::SurfaceControl::Kind::knob, "Reso", 0.3f, 90.0f, 20.0f },
- { lynx::SurfaceControl::Kind::slider, "Mix", 0.8f, 170.0f, 20.0f },
- { lynx::SurfaceControl::Kind::xy, "Space", 0.4f, 230.0f, 20.0f },
- { lynx::SurfaceControl::Kind::button, "Drop", 0.0f, 20.0f, 110.0f },
- { lynx::SurfaceControl::Kind::checkBox, "Bypass", 1.0f, 20.0f, 160.0f } })
- {
- c.kind = kind;
- c.name = name;
- c.value = v;
- c.valueY = 0.6f;
- c.x = x;
- c.y = y;
- lynx::surface::add (panel, c);
- }
- song.mixer[1].effects.push_back (panel);
- }
- lynx::ChannelDef env;
- env.name = "Envelope Controller";
- env.instrument = lynx::InstrumentKind::controller;
- auto ecData = lynx::defaultEnvelopeController();
- ecData[0].lfoOn = true;
- ecData[0].lfoTempo = true;
- ecData[0].lfoSpeed = 40898;
- ecData[0].maps[lynx::mapKeyboard].count = 2;
- ecData[0].maps[lynx::mapKeyboard].time = { 0.2f, 0.8f };
- ecData[0].maps[lynx::mapKeyboard].level = { 0.0f, 1.0f };
- ecData[0].maps[lynx::mapModX] = ecData[0].maps[lynx::mapKeyboard];
- env.controllerState = lynx::writeEnvelopeController (ecData);
- song.channels.push_back (env);
- lynx::ChannelDef out;
- out.name = "MIDI Out";
- out.instrument = lynx::InstrumentKind::midiOut;
- lynx::midictl::MidiOutSettings settings;
- settings.port = 1;
- lynx::midictl::writeMidiOut (out.pluginState, settings);
- song.channels.push_back (out);
- // a Layer (round 164) over three synths split across the keyboard, crossfading
- for (const auto* name : { "Bass", "Pad", "Lead" })
- {
- lynx::ChannelDef c;
- c.name = name;
- c.instrument = lynx::InstrumentKind::synth;
- song.channels.push_back (c);
- }
- {
- lynx::ChannelDef layer;
- layer.name = "Layer";
- layer.instrument = lynx::InstrumentKind::layer;
- song.channels.push_back (layer);
- const auto self = (int) song.channels.size() - 1;
- lynx::layer::setChildren (song, self, { 2, 3, 4 });
- song.channels[2].keyLow = 0, song.channels[2].keyHigh = 47;
- song.channels[3].keyLow = 36, song.channels[3].keyHigh = 83;
- song.channels[4].keyLow = 72, song.channels[4].keyHigh = 127;
- song.channels[(std::size_t) self].layer.crossfade = true;
- song.channels[(std::size_t) self].layer.fade = 0.35f;
- }
- {
- lynx::ChannelDef dash; // channel 6
- dash.name = "Dashboard";
- dash.instrument = lynx::InstrumentKind::dashboard;
- dash.patcher.surface = lynx::surface::starterControls();
- song.channels.push_back (dash);
- }
- {
- lynx::ChannelDef volt; // channel 7: FL's render-test settings (main L pitch, R gate × 0.5) with Out 2 on insert 3
- volt.name = "Voltage Controller";
- volt.instrument = lynx::InstrumentKind::voltage;
- lynx::voltage::Settings v;
- v.enabled = true;
- v.params[9] = 49152;
- v.unipolar[2] = true;
- v.tracks = { 3, 0, 0 };
- v.source[6] = lynx::voltage::Source::clock;
- volt.pluginState = lynx::voltage::write (v);
- song.channels.push_back (volt);
- }
- song.patterns.emplace_back();
- offline.setSong (std::move (song));
- offline.dispatchPendingMessages();
- auto shoot = [&] (std::unique_ptr<juce::Component> c, const juce::String& name) {
- if (c == nullptr)
- return;
- savePng (c->createComponentSnapshot (c->getLocalBounds()), prefix + name);
- };
- shoot (lynx::makeChannelSettingsPanel (offline, 0), "-envelope-controller.png");
- shoot (lynx::makeChannelSettingsPanel (offline, 1), "-midi-out.png");
- shoot (lynx::makeChannelSettingsPanel (offline, 5), "-layer.png");
- shoot (lynx::makeChannelFrame (offline, 3, -1), "-layer-child-misc.png"); // (the key-region ruler over the root keyboard)
- {
- const auto slotOf = [] (int k) -> lynx::SlotLocator {
- return [k] (lynx::Song& s) { return &s.mixer[1].effects[(std::size_t) k]; };
- };
- const lynx::AutomationTarget target { lynx::AutomationTargetKind::effectParam, 1, 1, 0 };
- shoot (lynx::makeXyControllerEditor (offline, slotOf (1), nullptr, target), "-xy-controller.png");
- shoot (lynx::makeXyControllerEditor (offline, slotOf (2), nullptr, target), "-xyz-controller.png");
- shoot (lynx::makeXyControllerEditor (offline, slotOf (3), nullptr, target), "-xyz-controller-stairs.png");
- shoot (lynx::makeControlSurfaceEditor (offline, slotOf (4), target), "-control-surface.png");
- shoot (lynx::makeChannelSettingsPanel (offline, 6), "-dashboard.png");
- shoot (lynx::makeChannelSettingsPanel (offline, 7), "-voltage-controller.png");
- }
- // FL's Dashboard presets of this PC's FL Studio, imported (round 164f): one PNG each
- if (const auto fl = lynx::findFlStudio(); fl.installDir.isDirectory())
- for (const auto& file : fl.installDir.getChildFile ("Data/Patches/Plugin presets/Generators/Dashboard").findChildFiles (juce::File::findFiles, false, "*.fst"))
- {
- juce::MemoryBlock bytes;
- if (! file.loadFileAsData (bytes))
- continue;
- const auto preset = flp::parseProject ({ (const std::uint8_t*) bytes.getData(), bytes.getSize() }, true);
- const auto dash = preset.channels.empty() ? std::nullopt : lynx::surface::parseFlDashboard (preset.channels[0].pluginState);
- if (! dash || dash->controls.empty())
- continue;
- offline.editSong ([&] (lynx::Song& s) {
- s.channels[6].name = file.getFileNameWithoutExtension().toStdString();
- s.channels[6].patcher.surface = dash->controls;
- s.channels[6].pluginState = preset.channels[0].pluginState; // (its MIDI port, channel, program)
- });
- offline.dispatchPendingMessages();
- const auto name = file.getFileNameWithoutExtension().replaceCharacter (' ', '-');
- shoot (lynx::makeChannelSettingsPanel (offline, 6), "-dashboard-fl-" + name + ".png");
- // edit mode (round 165): each control's output number and the MIDI it sends ("1 CC74")
- if (auto panel = lynx::makeChannelSettingsPanel (offline, 6))
- {
- std::function<void (juce::Component&)> pressEdit = [&] (juce::Component& c) {
- for (auto* child : c.getChildren())
- {
- if (auto* b = dynamic_cast<juce::TextButton*> (child); b != nullptr && b->getButtonText() == lynx::tr ("Edit"))
- b->setToggleState (true, juce::sendNotificationSync);
- pressEdit (*child);
- }
- };
- pressEdit (*panel);
- shoot (std::move (panel), "-dashboard-fl-" + name + "-edit.png");
- }
- }
- // the Envelope Controller's pages (issue #7): one PNG per part of the dropdown
- if (auto ec = lynx::makeEnvelopeControllerEditor (offline, 0))
- for (int part = 0; part < 7; ++part)
- {
- for (auto* child : ec->getChildren())
- if (auto* box = dynamic_cast<juce::ComboBox*> (child))
- box->setSelectedItemIndex (part, juce::sendNotificationSync);
- savePng (ec->createComponentSnapshot (ec->getLocalBounds()), prefix + "-ec-part" + juce::String (part) + ".png");
- }
- lynx::FormulaControllerWindows::open (offline, 1, 0);
- for (int k = 0; k < juce::TopLevelWindow::getNumTopLevelWindows(); ++k)
- if (auto* w = dynamic_cast<juce::DocumentWindow*> (juce::TopLevelWindow::getTopLevelWindow (k)))
- if (w->getName().startsWith ("Formula") && w->getContentComponent() != nullptr)
- savePng (w->getContentComponent()->createComponentSnapshot (w->getContentComponent()->getLocalBounds()), prefix + "-formula-controller.png");
- lynx::FormulaControllerWindows::closeAll();
- }
- void runEdisonShot (const juce::String& prefix, const juce::String& file)
- {
- namespace ae = lynx::audioedit;
- juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
- lynx::AudioEngine offline (false);
- ae::Document d;
- if (file.isNotEmpty())
- {
- juce::MemoryBlock bytes;
- if (! juce::File (file).loadFileAsData (bytes) || ! ae::decodeWav (static_cast<const std::uint8_t*> (bytes.getData()), bytes.getSize(), d))
- {
- std::fprintf (stderr, "edisonshot: cannot read %s\n", file.toRawUTF8());
- return;
- }
- }
- else
- {
- // a drum loop with a hum and hiss under it (something for the denoiser and the EQ to show)
- d.title = "Drum loop";
- d.audio.sampleRate = 44100.0;
- const auto frames = (std::size_t) (44100 * 2);
- d.audio.channels.assign (2, std::vector<float> (frames, 0.0f));
- std::uint32_t seed = 7;
- for (std::size_t i = 0; i < frames; ++i)
- {
- seed = seed * 1664525u + 1013904223u;
- const auto hiss = ((float) (seed >> 8) / 16777216.0f - 0.5f) * 0.02f;
- const auto hum = 0.01f * (float) std::sin (2.0 * 3.141592653589793 * 50.0 * (double) i / 44100.0);
- d.audio.channels[0][i] = hiss + hum;
- d.audio.channels[1][i] = hiss * 0.9f + hum;
- }
- for (int hit = 0; hit < 8; ++hit)
- {
- const auto at = (std::size_t) hit * frames / 8;
- const auto kick = hit % 2 == 0;
- double phase = 0.0;
- for (std::size_t i = 0; i < 12000 && at + i < frames; ++i)
- {
- seed = seed * 1664525u + 1013904223u;
- const auto noise = (float) (seed >> 8) / 16777216.0f - 0.5f;
- const auto t = (double) i / 44100.0;
- phase += 2.0 * 3.141592653589793 * (kick ? 45.0 + 160.0 * std::exp (-t * 30.0) : 190.0) / 44100.0;
- const auto body = (float) std::sin (phase) * (float) std::exp (-t * (kick ? 9.0 : 22.0));
- const auto v = kick ? 0.85f * body : 0.35f * body + 0.6f * noise * (float) std::exp (-t * 18.0);
- d.audio.channels[0][at + i] += v;
- d.audio.channels[1][at + i] += kick ? v : v * 0.8f;
- }
- }
- for (int hit = 1; hit < 8; ++hit)
- ae::addMarker (d, (std::int64_t) (hit * frames / 8));
- ae::setLoop (d, { 0, (std::int64_t) frames });
- }
- // a volume envelope (a fade-in and a dip) to show the envelope mode and the envelope tools
- d.volumeEnvelope.points = { { 0.0, 0.0, 0.0f }, { 0.12, 0.5, 0.4f }, { 0.55, 0.5, 0.0f }, { 0.62, 0.25, 0.0f }, { 0.7, 0.5, 0.0f }, { 1.0, 0.5, 0.0f } };
- auto editor = lynx::makeAudioEditorForSnapshot (offline, d, false);
- auto shot = [&prefix] (juce::Component& c, const juce::String& name) {
- juce::Image image (juce::Image::ARGB, c.getWidth(), c.getHeight(), true);
- {
- juce::Graphics g (image);
- g.fillAll (lynx::theme::panel);
- c.paintEntireComponent (g, false);
- }
- savePng (image, prefix + name);
- };
- editor->setSize (1120, 600);
- lynx::setAudioEditorEnvelopeModeForSnapshot (*editor, 1);
- shot (*editor, "-editor-volume-envelope.png");
- lynx::setAudioEditorEnvelopeModeForSnapshot (*editor, 0);
- juce::File (prefix + "-menu.txt").replaceWithText (lynx::audioEditorMenuForSnapshot (*editor).joinIntoString ("\n") + "\n");
- for (int t = 0; lynx::audioToolNameForSnapshot (t) != nullptr; ++t)
- {
- const auto envelopeTool = t >= 10 && t <= 14; // Scale levels .. Create sequence work on the volume envelope
- if (auto panel = lynx::makeAudioToolPanelForSnapshot (*editor, t, envelopeTool ? 1 : 0))
- {
- offline.dispatchPendingMessages();
- const auto name = juce::String (lynx::audioToolNameForSnapshot (t)).toLowerCase().retainCharacters ("abcdefghijklmnopqrstuvwxyz ").trim().replaceCharacter (' ', '-');
- shot (*panel, "-tool-" + juce::String (t).paddedLeft ('0', 2) + "-" + name + ".png");
- if (envelopeTool)
- shot (*editor, "-tool-" + juce::String (t).paddedLeft ('0', 2) + "-" + name + "-editor.png");
- panel.reset(); // (puts the envelope back)
- }
- }
- }
- static juce::TextButton* findButton (juce::Component& root, const juce::String& text)
- {
- if (auto* b = dynamic_cast<juce::TextButton*> (&root); b != nullptr && b->getButtonText() == text)
- return b;
- for (auto* child : root.getChildren())
- if (auto* b = findButton (*child, text))
- return b;
- return nullptr;
- }
- // a VFX Script editor's Script / Log / API reference tabs, then the Script tab of a script with an error
- void shootScriptTabs (juce::Component& panel, lynx::AudioEngine& engine, int index, const juce::String& name)
- {
- const std::pair<const char*, const char*> tabs[] = { { "Script", "script" }, { "Log", "log" }, { "API reference", "api" } };
- for (const auto& [tab, file] : tabs)
- if (auto* b = findButton (panel, lynx::tr (tab)); b != nullptr && b->onClick)
- {
- b->onClick();
- savePng (panel.createComponentSnapshot (panel.getLocalBounds()), name + "-tab-" + file + ".png");
- }
- engine.editSong ([&] (lynx::Song& s) {
- auto st = *lynx::vfx::readState (s.channels[(std::size_t) index].pluginState);
- auto settings = lynx::vfx::parseScript (st.fl).value_or (lynx::vfx::defaultScript());
- settings.setSource ("import flvfx as vfx\n\ndef onTriggerVoice(incomingVoice):\n v = vfx.Voice(incomingVoice)\n"
- " v.note += 7\n v.trigger(\n\ndef onReleaseVoice(incomingVoice):\n pass\n");
- st.fl = lynx::vfx::writeScript (settings);
- s.channels[(std::size_t) index].pluginState = lynx::vfx::writeState (st);
- });
- engine.dispatchPendingMessages();
- if (auto broken = lynx::makeChannelSettingsPanel (engine, index))
- {
- engine.dispatchPendingMessages();
- if (auto* b = findButton (*broken, lynx::tr ("Script")); b != nullptr && b->onClick)
- b->onClick();
- savePng (broken->createComponentSnapshot (broken->getLocalBounds()), name + "-error.png");
- }
- }
- void runVfxShot (const juce::String& prefix)
- {
- juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
- lynx::AudioEngine offline (false);
- lynx::MainComponent ui (offline, false);
- ui.setSize (1280, 720);
- auto song = lynx::Song::makeDefault();
- song.channels.clear();
- for (const auto kind : lynx::vfx::allKinds)
- {
- lynx::ChannelDef c;
- lynx::vfx::makeChannel (c, kind);
- if (kind == lynx::vfx::Kind::keyMapper) // a chord on every key: something to see in the grid
- for (const auto& p : lynx::vfx::builtInPresets (kind))
- if (p.name == "Major triad")
- {
- auto st = *lynx::vfx::readState (c.pluginState);
- st.fl = p.fl;
- c.pluginState = lynx::vfx::writeState (st);
- }
- song.channels.push_back (c);
- }
- // a Patcher: its notes through a Color Mapper to three synths
- lynx::ChannelDef patcher;
- patcher.name = "Patcher";
- patcher.instrument = lynx::InstrumentKind::patcher;
- lynx::PatchNode mapper;
- mapper.generator = true;
- lynx::vfx::makeChannel (mapper.channel, lynx::vfx::Kind::colorMapper);
- mapper.x = 260.0f;
- patcher.patcher.nodes.push_back (mapper);
- lynx::PatchWire notes;
- notes.kind = lynx::PatchWire::Kind::midi, notes.to = 0;
- patcher.patcher.wires.push_back (notes);
- for (int k = 0; k < 3; ++k)
- {
- lynx::PatchNode synth;
- synth.generator = true;
- synth.channel.instrument = lynx::InstrumentKind::synth;
- synth.channel.name = "Synth " + std::to_string (k + 1);
- synth.x = 520.0f, synth.y = (float) k * 90.0f;
- patcher.patcher.nodes.push_back (synth);
- lynx::PatchWire in, out;
- in.kind = lynx::PatchWire::Kind::midi, in.from = 0, in.fromPort = k, in.to = 1 + k;
- out.from = 1 + k, out.to = lynx::patchToHost;
- patcher.patcher.wires.push_back (in);
- patcher.patcher.wires.push_back (out);
- }
- patcher.patcher.outputX = 760.0f;
- song.channels.push_back (patcher);
- offline.setSong (std::move (song));
- offline.dispatchPendingMessages();
- for (int c = 0; c < lynx::vfx::kindCount; ++c)
- if (auto panel = lynx::makeChannelSettingsPanel (offline, c))
- {
- offline.dispatchPendingMessages();
- savePng (panel->createComponentSnapshot (panel->getLocalBounds()),
- prefix + "-" + juce::String (lynx::vfx::flName (*lynx::vfx::kindOf (offline.getSong().channels[(std::size_t) c]))).replaceCharacter (' ', '-').toLowerCase() + ".png");
- }
- // with FL Studio installed: the Sequencer with FL's factory bank (to compare with FL's own editor) and
- // a Script with FL's "Snap To Scale"
- if (const auto roots = lynx::findFlStudioRoots(); ! roots.data.empty())
- {
- const auto data = juce::File (juce::String::fromUTF8 (roots.data.c_str()));
- const std::pair<lynx::vfx::Kind, juce::String> extra[] = {
- { lynx::vfx::Kind::sequencer, "Patches/Plugin database/Effects/Patcher/VFX Sequencer.fst" },
- { lynx::vfx::Kind::script, "Patches/Plugin presets/Effects/VFX Script/Snap To Scale.fst" },
- };
- for (const auto& [kind, path] : extra)
- {
- juce::MemoryBlock bytes;
- if (! data.getChildFile (path).loadFileAsData (bytes))
- continue;
- const auto* b = static_cast<const std::uint8_t*> (bytes.getData());
- const auto fl = lynx::vfx::stateFromFlPreset (std::vector<std::uint8_t> (b, b + bytes.getSize()), kind);
- int index = -1;
- for (int c = 0; c < lynx::vfx::kindCount; ++c)
- if (lynx::vfx::kindOf (offline.getSong().channels[(std::size_t) c]) == kind)
- index = c;
- if (! fl || index < 0)
- continue;
- offline.editSong ([&] (lynx::Song& s) {
- auto st = *lynx::vfx::readState (s.channels[(std::size_t) index].pluginState);
- st.fl = *fl;
- s.channels[(std::size_t) index].pluginState = lynx::vfx::writeState (st);
- });
- offline.dispatchPendingMessages();
- if (auto panel = lynx::makeChannelSettingsPanel (offline, index))
- {
- offline.dispatchPendingMessages();
- const auto name = prefix + "-" + juce::String (lynx::vfx::flName (kind)).replaceCharacter (' ', '-').toLowerCase();
- savePng (panel->createComponentSnapshot (panel->getLocalBounds()), name + "-fl.png");
- if (kind == lynx::vfx::Kind::script) // the editor's other tabs (round 165d)
- shootScriptTabs (*panel, offline, index, name);
- }
- }
- }
- lynx::PatcherWindows::openChannel (offline, lynx::vfx::kindCount);
- for (int k = 0; k < juce::TopLevelWindow::getNumTopLevelWindows(); ++k)
- if (auto* w = dynamic_cast<juce::DocumentWindow*> (juce::TopLevelWindow::getTopLevelWindow (k)))
- if (w->getName().startsWith (lynx::tr ("Patcher")) && w->getContentComponent() != nullptr)
- {
- auto* content = w->getContentComponent();
- savePng (content->createComponentSnapshot (content->getLocalBounds()), prefix + "-patcher.png");
- delete w;
- break;
- }
- lynx::PatcherWindows::shootMenus (offline, true, lynx::vfx::kindCount, 0, [&] (const juce::Image& image, const juce::String& name) {
- savePng (image, prefix + "-patcher-menu-" + name + ".png");
- });
- // a plugin renamed in the Plugin database ("1_EQ", FL): the Quick-add palette and the mixer slot show the new name
- if (juce::SystemStats::getEnvironmentVariable ("LYNX_TEST_MODE", {}).isNotEmpty())
- {
- const auto key = std::string ("lynx:fx:") + lynx::effectInfo (lynx::EffectKind::parametricEq).name;
- offline.getPluginHost().setPluginName (key, "1_EQ");
- offline.editSong ([] (lynx::Song& s) {
- if (s.mixer.size() > 1)
- {
- lynx::EffectSlot slot;
- slot.kind = lynx::EffectKind::parametricEq;
- s.mixer[1].effects.push_back (slot);
- }
- });
- offline.dispatchPendingMessages();
- {
- lynx::QuickAddTargets targets;
- targets.addInstrument = [] (lynx::ChannelDef) {};
- targets.addEffect = [] (lynx::EffectSlot) {};
- auto palette = lynx::makeQuickAddPalette (offline, std::move (targets));
- savePng (palette->createComponentSnapshot (palette->getLocalBounds()), prefix + "-quickadd-renamed.png");
- }
- ui.selectTabForSnapshot (3);
- ui.getMixerForSnapshot().selectTrack (1);
- offline.dispatchPendingMessages();
- savePng (ui.createComponentSnapshot (ui.getLocalBounds()), prefix + "-mixer-renamed.png");
- offline.getPluginHost().setPluginName (key, "");
- }
- }
- void runComp177Shot (const juce::String& prefix, const juce::String& projectPath)
- {
- juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
- lynx::AudioEngine offline (false);
- {
- lynx::MainComponent ui (offline, false);
- const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1600x900"), "x", "");
- ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
- ui.openFile (juce::File (projectPath));
- offline.dispatchPendingMessages();
- ui.selectTabForSnapshot (2);
- offline.dispatchPendingMessages();
- auto& playlist = ui.getPlaylistForSnapshot();
- std::int64_t last = 0;
- for (const auto& c : offline.getSong().playlist)
- last = std::max (last, c.end());
- const auto bars = juce::jmax (1, (int) (last / (4 * lynx::ppq)) + 1);
- playlist.setViewForSnapshot (juce::jmax (60.0, (ui.getWidth() - 300.0) / bars), 0, 0);
- // (the first paint asks for the clips' waveforms, a worker thread loads them)
- saveSnapshot (ui, prefix + "-opened.png");
- juce::Thread::sleep (3000);
- offline.dispatchPendingMessages();
- saveSnapshot (ui, prefix + "-opened.png");
- // a muted clip selected
- for (int c = 0; c < (int) offline.getSong().playlist.size(); ++c)
- if (offline.getSong().playlist[(std::size_t) c].muted)
- {
- playlist.selectClipsForSnapshot ({ c });
- offline.dispatchPendingMessages();
- saveSnapshot (ui, prefix + "-selected.png");
- playlist.selectClipsForSnapshot ({});
- break;
- }
- juce::String report;
- const auto listTracks = [&offline, &report] (const juce::String& title) {
- const auto& s = offline.getSong();
- report << title << "\n";
- for (int t = 0; t < (int) s.playlistTracks.size(); ++t)
- {
- int clips = 0, muted = 0;
- for (const auto& c : s.playlist)
- if (c.track == t)
- ++clips, muted += c.muted ? 1 : 0;
- const auto& pt = s.playlistTracks[(std::size_t) t];
- if (clips > 0 || pt.grouped || ! pt.name.empty())
- report << "track " << (t + 1) << " '" << juce::String::fromUTF8 (pt.name.c_str()) << "' grouped=" << (pt.grouped ? 1 : 0) << " collapsed=" << (pt.collapsed ? 1 : 0)
- << " comp=" << (pt.compTrack ? 1 : 0) << " clips=" << clips << " muted=" << muted << "\n";
- }
- };
- listTracks ("opened");
- // the first group's header (a member's menu holds "Comp these takes" too)
- int firstGroup = -1;
- for (int t = 0; t < (int) offline.getSong().playlistTracks.size() && firstGroup < 0; ++t)
- if (lynx::comp::canComp (offline.getSong(), t))
- firstGroup = t;
- report << "first group with takes: track " << (firstGroup + 1) << "\n";
- if (firstGroup >= 0)
- {
- saveMenus (juce::StringArray { "Playlist track" }, std::vector<juce::PopupMenu> { playlist.getTrackMenuForSnapshot (firstGroup) }, prefix + "-trackmenu.png");
- int comp = -1;
- offline.editSong ([firstGroup, &comp] (lynx::Song& s) { comp = lynx::comp::compTakes (s, firstGroup); });
- offline.dispatchPendingMessages();
- saveSnapshot (ui, prefix + "-comped.png");
- listTracks ("after Comp these takes");
- const auto g = lynx::comp::groupOf (offline.getSong(), comp);
- std::int64_t from = -1, to = 0;
- for (const auto& c : offline.getSong().playlist)
- if (c.track == g.first)
- from = from < 0 ? c.start : std::min (from, c.start), to = std::max (to, c.end());
- if (g.valid() && to > from)
- {
- offline.editSong ([&g, from, to] (lynx::Song& s) { lynx::comp::swipe (s, g.first, from + (to - from) / 4, from + (to - from) / 2); });
- offline.dispatchPendingMessages();
- saveSnapshot (ui, prefix + "-swiped.png");
- listTracks ("after a swipe of the middle of the first lane");
- // a lane auditioned; the crossfade close up; the comp flattened
- offline.editSong ([&g] (lynx::Song& s) { lynx::comp::setAudition (s, g.first); }, false);
- offline.dispatchPendingMessages();
- saveSnapshot (ui, prefix + "-audition.png");
- offline.editSong ([] (lynx::Song& s) { lynx::comp::setAudition (s, -1); }, false);
- const auto switchAt = from + (to - from) / 4;
- playlist.setViewForSnapshot (4.0 * 4.0 * lynx::ppq, 0, 0);
- playlist.setScrollTickForSnapshot ((double) (switchAt - 100));
- juce::Thread::sleep (1500);
- offline.dispatchPendingMessages();
- saveSnapshot (ui, prefix + "-crossfade.png");
- playlist.setViewForSnapshot (juce::jmax (60.0, (ui.getWidth() - 300.0) / bars), 0, 0);
- offline.editSong ([comp] (lynx::Song& s) { lynx::comp::flatten (s, comp); });
- offline.dispatchPendingMessages();
- saveSnapshot (ui, prefix + "-flattened.png");
- listTracks ("after Flatten comp");
- }
- }
- saveMenus (juce::StringArray { "Record" }, std::vector<juce::PopupMenu> { ui.getRecordMenuForSnapshot() }, prefix + "-recordmenu.png");
- juce::File (prefix + "-tracks.txt").replaceWithText (report);
- }
- }
- void runFeat166Shot (const juce::String& prefix, const juce::String& projectPath)
- {
- juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
- lynx::AudioEngine offline (false);
- {
- lynx::MainComponent ui (offline, false);
- const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1600x900"), "x", "");
- ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
- if (projectPath.isNotEmpty())
- ui.openFile (juce::File (projectPath));
- offline.dispatchPendingMessages();
- ui.selectTabForSnapshot (1); // the Piano Roll, on the channel with the most notes
- offline.dispatchPendingMessages();
- // the scale the pattern's notes fit best (major / minor, any root)
- const auto& song = offline.getSong();
- const auto& notes = song.patterns[(std::size_t) song.currentPattern].notes;
- int bestRoot = 0, bestScale = 1, bestHits = -1;
- for (int sc = 1; sc < (int) lynx::notetools::scales().size(); ++sc)
- {
- const juce::String name (lynx::notetools::scales()[(std::size_t) sc].name);
- if (name != "Major" && name != "Minor")
- continue;
- for (int root = 0; root < 12; ++root)
- {
- int hits = 0;
- for (const auto& n : notes)
- hits += lynx::notetools::inScale (n.key, root, sc) ? 1 : 0;
- if (hits > bestHits)
- bestHits = hits, bestRoot = root, bestScale = sc;
- }
- }
- auto& roll = ui.getPianoRollForSnapshot();
- roll.setScaleForSnapshot (bestRoot, bestScale);
- roll.scrollToNotes();
- offline.dispatchPendingMessages();
- saveSnapshot (ui, prefix + "-pr-scale.png");
- roll.setFoldToScale (true);
- offline.dispatchPendingMessages();
- saveSnapshot (ui, prefix + "-pr-folded.png");
- roll.setFoldToScale (false);
- // ghost channels: only the first other channel with notes stays a ghost
- const auto selected = offline.getSelectedChannel();
- int keep = -1;
- for (const auto& n : notes)
- if (n.channel != selected && keep < 0)
- keep = n.channel;
- offline.editSong ([keep] (lynx::Song& s) {
- for (int c = 0; c < (int) s.channels.size(); ++c)
- s.channels[(std::size_t) c].ghostHidden = c != keep;
- }, false);
- offline.dispatchPendingMessages();
- saveSnapshot (ui, prefix + "-pr-ghost-one.png");
- saveMenus (juce::StringArray { "Ghost channels" }, { roll.ghostChannelsMenu() }, prefix + "-ghostmenu.png");
- offline.editSong ([] (lynx::Song& s) {
- for (auto& c : s.channels)
- c.ghostHidden = false;
- }, false);
- // the Mixer at 500 inserts
- const auto t0 = juce::Time::getMillisecondCounterHiRes();
- offline.editSong ([] (lynx::Song& s) { lynx::mixerops::insertTracks (s, (int) s.mixer.size(), lynx::mixerops::roomForInserts (s)); }, false);
- const auto t1 = juce::Time::getMillisecondCounterHiRes();
- offline.dispatchPendingMessages();
- ui.selectTabForSnapshot (3);
- offline.dispatchPendingMessages();
- auto& mixer = ui.getMixerForSnapshot();
- const auto t2 = juce::Time::getMillisecondCounterHiRes();
- saveSnapshot (ui, prefix + "-mixer500-start.png");
- const auto t3 = juce::Time::getMillisecondCounterHiRes();
- mixer.selectTrack ((int) offline.getSong().mixer.size() - 1);
- offline.dispatchPendingMessages();
- saveSnapshot (ui, prefix + "-mixer500-end.png");
- juce::File (prefix + "-mixer500.txt")
- .replaceWithText ("inserts=" + juce::String ((int) offline.getSong().mixer.size() - 1) + "\nfill_ms=" + juce::String (t1 - t0, 2)
- + "\nsnapshot_ms=" + juce::String (t3 - t2, 2) + "\n");
- }
- }
- void runGridShot (const juce::String& prefix, const juce::String& projectPath = {})
- {
- juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
- lynx::AudioEngine offline (false);
- lynx::MainComponent ui (offline, false);
- const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1600x900"), "x", "");
- ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
- const auto write = [&prefix, &ui] (const char* name) {
- const auto file = juce::File (prefix + "-" + name + ".png");
- file.deleteFile();
- juce::FileOutputStream out (file);
- juce::PNGImageFormat().writeImageToStream (ui.createComponentSnapshot (ui.getLocalBounds(), true, 1.0f), out);
- };
- ui.selectTabForSnapshot (2); // the Playlist panel, maximized
- if (projectPath.isNotEmpty())
- {
- ui.openFile (juce::File (projectPath));
- offline.dispatchPendingMessages();
- ui.setClipLaunchWorkflow (true);
- offline.dispatchPendingMessages();
- write ("file-both");
- ui.setClipGridView (lynx::PlaylistArea::GridView::grid);
- write ("file-grid");
- const auto& song = offline.getSong();
- juce::String info;
- info << "grid " << (song.clipGrid ? "yes" : "no") << ", clips " << (song.clipGrid ? (int) song.clipGrid->clips.size() : 0)
- << ", scenes " << (song.clipGrid ? (int) song.clipGrid->scenes.size() : 0) << ", playlist clips " << (int) song.playlist.size() << "\n";
- juce::File (prefix + "-file.txt").replaceWithText (info);
- ui.setClipLaunchWorkflow (false);
- return;
- }
- write ("pattern"); // Pattern workflow: nothing of the grid exists yet
- const auto madeBefore = lynx::launcher::Runtime::instances.load();
- offline.editSong ([] (lynx::Song& s) {
- while (s.patterns.size() < 6)
- s.patterns.emplace_back();
- for (int p = 0; p < 6; ++p)
- {
- auto& pattern = s.patterns[(std::size_t) p];
- const char* names[] { "Drums A", "Drums B", "Bass", "Chords", "Lead", "Pad" };
- pattern.name = names[p];
- pattern.lengthTicks = 4 * lynx::ppq;
- }
- s.playlistTracks.resize (std::max<std::size_t> (s.playlistTracks.size(), 6));
- const char* tracks[] { "Drums", "Bass", "Chords", "Lead", "Vocals", "FX" };
- for (int t = 0; t < 6; ++t)
- s.playlistTracks[(std::size_t) t].name = tracks[t];
- const int placed[][3] { { 0, 0, 0 }, { 0, 1, 1 }, { 0, 2, 0 }, { 0, 3, 1 }, { 1, 0, 2 }, { 1, 2, 2 }, { 2, 1, 3 }, { 2, 2, 3 }, { 3, 2, 4 }, { 3, 3, 4 }, { 4, 3, 5 } };
- for (const auto& c : placed)
- {
- lynx::Clip clip;
- clip.pattern = c[2];
- clip.length = 4 * lynx::ppq;
- lynx::launcher::setClip (s, c[0], c[1], clip);
- }
- auto& grid = lynx::launcher::ensureGrid (s);
- const char* scenes[] { "Intro", "Verse", "Drop", "Break" };
- grid.scenes.resize (6);
- for (int r = 0; r < 4; ++r)
- grid.scenes[(std::size_t) r].name = scenes[r];
- }, false);
- offline.dispatchPendingMessages();
- write ("pattern-edited"); // the same song as -pattern-after: the workflow must leave no trace
- ui.setClipLaunchWorkflow (true);
- offline.dispatchPendingMessages();
- if (auto* runtime = offline.launcherStateForSnapshot())
- {
- runtime->tracks[0].playing.store (2);
- runtime->tracks[0].progress.store (0.4f);
- runtime->tracks[0].taken.store (true);
- runtime->tracks[1].playing.store (2);
- runtime->tracks[1].progress.store (0.4f);
- runtime->tracks[1].taken.store (true);
- runtime->tracks[2].pending.store (2);
- runtime->tracks[3].taken.store (true);
- }
- write ("both");
- ui.setClipGridView (lynx::PlaylistArea::GridView::grid);
- write ("grid");
- ui.setClipGridView (lynx::PlaylistArea::GridView::song);
- write ("song");
- ui.setClipLaunchWorkflow (false);
- write ("pattern-after");
- juce::File (prefix + "-counts.txt").replaceWithText ("runtimes before " + juce::String (madeBefore) + ", after " + juce::String (lynx::launcher::Runtime::instances.load()) + "\n");
- }
- void runSimpleShot (const juce::String& prefix)
- {
- juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
- lynx::AudioEngine offline (false);
- lynx::MainComponent ui (offline, false);
- const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1600x900"), "x", "");
- ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
- const auto writeImage = [&prefix] (const juce::Image& image, const char* name) {
- const auto file = juce::File (prefix + "-" + name + ".png");
- file.deleteFile();
- juce::FileOutputStream out (file);
- juce::PNGImageFormat().writeImageToStream (image, out);
- };
- const auto write = [&ui, &writeImage] (const char* name) { writeImage (ui.createComponentSnapshot (ui.getLocalBounds(), true, 1.0f), name); };
- // View › Layout style, with its submenu, as it is with `style` chosen
- const auto viewMenu = [&ui] {
- const auto names = ui.getMenuNamesForSnapshot();
- const auto view = names.indexOf (lynx::tr ("View"));
- return ui.getMenuForSnapshot (juce::jmax (0, view));
- };
- const auto saveStyleMenus = [&] (const juce::String& suffix) {
- const auto view = viewMenu();
- juce::StringArray names { lynx::tr ("View") };
- std::vector<juce::PopupMenu> menus { view };
- for (juce::PopupMenu::MenuItemIterator it (view); it.next();)
- if (it.getItem().subMenu != nullptr && it.getItem().text == lynx::tr ("Layout style"))
- {
- names.add (lynx::tr ("Layout style"));
- menus.push_back (*it.getItem().subMenu);
- }
- saveMenus (names, menus, prefix + "-menu-" + suffix + ".png");
- };
- // Settings › General with `style` selected, and its style list
- const auto saveSettings = [&] (lynx::layoutstyle::Style style, const char* name) {
- lynx::SettingsHooks hooks;
- hooks.getGeneral = [style] {
- lynx::GeneralOptions o;
- o.language = lynx::i18n::current();
- o.layoutStyle = (int) style;
- return o;
- };
- auto page = lynx::makeSettingsPanel (offline, lynx::SettingsPage::general, false, hooks);
- juce::Image image (juce::Image::ARGB, page->getWidth(), juce::jmin (page->getHeight(), 420), true);
- {
- juce::Graphics g (image);
- g.fillAll (lynx::theme::panel);
- page->paintEntireComponent (g, false);
- }
- writeImage (image, name);
- std::function<juce::ComboBox* (juce::Component&)> find = [&find] (juce::Component& c) -> juce::ComboBox* {
- if (c.getComponentID() == "layoutStyle")
- return dynamic_cast<juce::ComboBox*> (&c);
- for (auto* child : c.getChildren())
- if (auto* box = find (*child))
- return box;
- return nullptr;
- };
- if (auto* box = find (*page); box != nullptr && box->getRootMenu() != nullptr)
- saveMenus (juce::StringArray { lynx::tr ("Layout style") }, std::vector<juce::PopupMenu> { *box->getRootMenu() },
- prefix + "-" + name + "-list.png");
- };
- const auto madeBefore = lynx::SimpleWorkflow::instances.load();
- ui.selectTabForSnapshot (2); // the Playlist panel, maximized (as --gridshot)
- write ("pattern");
- saveStyleMenus ("pattern");
- saveSettings (lynx::layoutstyle::Style::pattern, "settings-pattern");
- const auto madePattern = lynx::SimpleWorkflow::instances.load();
- ui.setLayoutStyle (lynx::layoutstyle::Style::clipLaunch);
- saveStyleMenus ("cliplaunch");
- ui.setLayoutStyle (lynx::layoutstyle::Style::simple);
- offline.dispatchPendingMessages();
- if (auto* simple = ui.getSimpleWorkflowForSnapshot())
- simple->showChooser(); // (an empty project opens on it by itself; the offline project may hold the default song)
- write ("simple"); // the New track chooser (slice S3)
- if (auto* simple = ui.getSimpleWorkflowForSnapshot())
- {
- simple->showStarterPageForSnapshot();
- write ("simple-starter");
- simple->hideChooser();
- write ("simple-closed");
- }
- saveStyleMenus ("simple");
- saveSettings (lynx::layoutstyle::Style::simple, "settings-simple");
- ui.setLayoutStyle (lynx::layoutstyle::Style::pattern);
- offline.dispatchPendingMessages();
- write ("pattern-after");
- juce::File (prefix + "-counts.txt").replaceWithText ("simple workflows before " + juce::String (madeBefore) + ", in pattern workflow "
- + juce::String (madePattern) + ", after " + juce::String (lynx::SimpleWorkflow::instances.load())
- + "\nstyle after " + lynx::layoutstyle::id (ui.getLayoutStyle()) + "\n");
- }
- void runDetailShot (const juce::String& prefix)
- {
- juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
- lynx::AudioEngine offline (false);
- lynx::MainComponent ui (offline, false);
- const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1600x900"), "x", "");
- ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
- const auto write = [&prefix, &ui] (const char* name) {
- const auto file = juce::File (prefix + "-" + name + ".png");
- file.deleteFile();
- juce::FileOutputStream out (file);
- juce::PNGImageFormat().writeImageToStream (ui.createComponentSnapshot (ui.getLocalBounds(), true, 1.0f), out);
- };
- ui.setVisible (true); // (not on the desktop: only so the Clip page sees itself shown and docks the Piano roll)
- lynx::DetailView::shownSetting = lynx::DetailView::devicesPage = true;
- ui.selectTabForSnapshot (2); // the Playlist panel, maximized
- offline.editSong ([] (lynx::Song& s) {
- if (s.channels.size() < 2)
- s.channels.resize (2);
- s.channels[0].name = "Bass synth";
- s.channels[0].mixerTrack = 2;
- s.channels[1].mixerTrack = 3;
- if (s.mixer.size() < 4)
- s.mixer.resize (4);
- s.mixer[2].name = "Bass";
- s.mixer[2].effects.clear();
- for (auto kind : { lynx::EffectKind::eq, lynx::EffectKind::compressor, lynx::EffectKind::reverb, lynx::EffectKind::delay })
- {
- lynx::EffectSlot fx;
- fx.kind = kind;
- const auto& info = lynx::effectInfo (kind);
- for (std::size_t k = 0; k < info.params.size() && k < fx.params.size(); ++k)
- fx.params[k] = info.params[k].defaultValue;
- fx.enabled = kind != lynx::EffectKind::compressor; // one switched off
- s.mixer[2].effects.push_back (fx);
- }
- while (s.patterns.size() < 2)
- s.patterns.emplace_back();
- s.patterns[0].name = "Bass line";
- s.patterns[0].notes.clear();
- for (int n = 0; n < 4; ++n)
- {
- lynx::Note note;
- note.channel = 0;
- note.start = n * lynx::ppq;
- note.key = 36 + (n % 2) * 7;
- s.patterns[0].notes.push_back (note);
- }
- s.patterns[0].lengthTicks = 4 * lynx::ppq;
- lynx::PatternEvents lane; // a volume swell for the Envelopes tab (slice 3)
- lane.target = lynx::AutomationTarget { lynx::AutomationTargetKind::channelVolume, 0 };
- for (int e = 0; e < 16; ++e)
- lane.events.push_back ({ e * lynx::ppq / 4, 0.3f + 0.6f * (float) e / 15.0f });
- s.patterns[0].events = { lane };
- s.playlistTracks.resize (std::max<std::size_t> (s.playlistTracks.size(), 3));
- s.playlistTracks[1].name = "Bass";
- }, false);
- offline.dispatchPendingMessages();
- write ("pattern"); // Pattern workflow: no detail view exists
- ui.setClipLaunchWorkflow (true);
- offline.editSong ([] (lynx::Song& s) {
- lynx::Clip clip;
- clip.pattern = 0;
- clip.length = 4 * lynx::ppq;
- lynx::launcher::setClip (s, 1, 0, clip);
- }, false);
- offline.dispatchPendingMessages();
- juce::String counts;
- if (auto* detail = ui.getDetailViewForSnapshot())
- {
- detail->showSelection (1, 0);
- detail->setPage (lynx::DetailView::Page::devices);
- write ("devices");
- counts << "cards " << detail->cardCountForCheck() << ", insert " << detail->chainInsertForCheck() << ", channel " << detail->chainChannelForCheck() << "\n";
- detail->toggleFoldForCheck (3); // the reverb (card 0 is the instrument)
- write ("folded");
- counts << "folded card 3: " << (detail->isFoldedForCheck (3) ? 1 : 0) << "\n";
- detail->showSelection (2, 0); // an empty track
- write ("empty-track");
- detail->showSelection (1, 0);
- detail->setPage (lynx::DetailView::Page::clip);
- offline.dispatchPendingMessages();
- ui.getPianoRollForSnapshot().scrollToNotes(); // (the app does it on the message loop, which this shot doesn't run)
- write ("clip"); // slice 2: the Piano roll docked here
- {
- // round 190s: the Transform panel with each MIDI tool, then Arpeggiate applied (and undone again)
- auto& tools = detail->midiToolsForSnapshot();
- for (int t = 0; t < lynx::MidiToolsPanel::toolCount; ++t)
- {
- tools.setTool (t);
- write (("clip-mt-" + juce::String (lynx::MidiToolsPanel::toolName (t)).toLowerCase()).toRawUTF8());
- }
- // round 190aa: the pages again with the settings of the Live shots they are compared with
- tools.setAuto (false);
- tools.setLiveShotSettingsForSnapshot();
- for (int t : { (int) lynx::MidiToolsPanel::chop, (int) lynx::MidiToolsPanel::quantize, (int) lynx::MidiToolsPanel::timeWarp })
- {
- tools.setTool (t);
- write (("clip-mt-" + juce::String (lynx::MidiToolsPanel::toolName (t)).toLowerCase() + "-set").toRawUTF8());
- }
- tools.setAuto (true);
- tools.setTool (lynx::MidiToolsPanel::arpeggiate);
- tools.transformNow();
- offline.dispatchPendingMessages();
- write ("clip-mt-applied");
- counts << "midi tools: arpeggiate made " << (int) offline.getSong().patterns[0].notes.size() << " notes of 4\n";
- offline.undo();
- offline.dispatchPendingMessages();
- counts << "midi tools: undo gives " << (int) offline.getSong().patterns[0].notes.size() << " notes\n";
- }
- counts << "piano roll docked: " << (ui.getPianoRollForSnapshot().getParentComponent() != nullptr
- && ui.getPianoRollForSnapshot().getParentComponent()->getParentComponent() == detail ? 1 : 0) << "\n";
- detail->setClipTab (true); // slice 3: the pattern's events in the Envelopes tab
- offline.dispatchPendingMessages();
- write ("envelopes");
- detail->setClipTab (false);
- detail->setPage (lynx::DetailView::Page::devices);
- counts << "piano roll back in its panel: " << (ui.getPianoRollForSnapshot().getParentComponent() != nullptr
- && ui.getPianoRollForSnapshot().getParentComponent()->getParentComponent() != detail ? 1 : 0) << "\n";
- }
- else
- counts << "no detail view\n";
- ui.setClipLaunchWorkflow (false);
- offline.dispatchPendingMessages();
- write ("pattern-after");
- juce::File (prefix + "-counts.txt").replaceWithText (counts);
- }
- void runPerfShot (const juce::String& prefix, const juce::String& projectPath)
- {
- juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
- lynx::AudioEngine offline (false);
- {
- lynx::MainComponent ui (offline, false);
- const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1600x900"), "x", "");
- ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
- if (projectPath.isNotEmpty())
- ui.openFile (juce::File (projectPath));
- offline.dispatchPendingMessages();
- // LYNX_PERFSHOT_PREPARE=1: Tools › Macros › Prepare for performance mode first (16 one-bar columns)
- if (juce::SystemStats::getEnvironmentVariable ("LYNX_PERFSHOT_PREPARE", {}) == "1")
- offline.editSong ([] (lynx::Song& s) { lynx::perf::prepareForPerformance (s, 16, 4 * lynx::ppq); }, false);
- offline.editSong ([] (lynx::Song& s) { s.performanceMode = true; s.mode = lynx::PlayMode::song; }, false);
- offline.dispatchPendingMessages();
- // what the Player would publish: on each of the first tracks with zone clips, one clip playing (part way)
- // and on every other one the next clip waiting for its sync point
- const auto& song = offline.getSong();
- auto& live = offline.performanceStateForSnapshot();
- const auto zone = lynx::perf::zoneClips (song);
- int lastTrack = -1, launched = 0;
- for (const auto index : zone)
- {
- const auto& c = song.playlist[(std::size_t) index];
- if (c.track == lastTrack || c.track >= lynx::perf::maxTracks)
- continue;
- lastTrack = c.track;
- std::int64_t clips[64];
- const auto n = lynx::perf::trackZoneClips (song, zone, c.track, clips, 64);
- auto& view = live.tracks[(std::size_t) c.track];
- view.playing.store (clips[(std::size_t) ((launched % 3) % n)]);
- view.progress.store (0.2f + 0.15f * (float) (launched % 5));
- if (launched % 2 == 1 && n > 1)
- view.pending.store (clips[(std::size_t) ((launched % 3 + 1) % n)]);
- ++launched;
- }
- live.anyPlaying.store (launched > 0);
- ui.selectTabForSnapshot (2);
- offline.dispatchPendingMessages();
- auto& playlist = ui.getPlaylistForSnapshot();
- savePng (playlist.createComponentSnapshot (playlist.getLocalBounds()), prefix + "-playlist-song.png");
- playlist.runAction ("playlist.zoomPerformance"); // as FL opens these demos: the zone fills the view
- offline.dispatchPendingMessages();
- saveSnapshot (ui, prefix + "-playlist.png");
- savePng (playlist.createComponentSnapshot (playlist.getLocalBounds()), prefix + "-playlist-only.png");
- // patcherize: the first insert with effects (all of them) and the first channel that can be
- auto patched = offline.getSong();
- for (int t = 0; t < (int) patched.mixer.size(); ++t)
- if (lynx::patcherize::slotsForAll (patched, t).size() > 1)
- {
- lynx::patcherize::patcherizeSlots (patched, t, 0, true);
- break;
- }
- for (int c = 0; c < (int) patched.channels.size(); ++c)
- if (lynx::patcherize::patcherizeChannel (patched, c))
- break;
- juce::String error;
- lynx::ProjectFile::save (patched, juce::File (prefix + "-patcherized.lynx"), error);
- }
- }
- void runPatcherShot (const juce::String& prefix, const juce::String& projectPath)
- {
- juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
- lynx::AudioEngine offline (false);
- {
- lynx::MainComponent ui (offline, false);
- ui.setSize (1280, 720);
- if (projectPath.isNotEmpty())
- ui.openFile (juce::File (projectPath));
- else
- {
- auto song = lynx::Song::makeDefault();
- song.mixer.resize (4);
- auto slot = lynx::makeEffectSlot (lynx::EffectKind::patcher);
- slot.patcher.wires.clear();
- for (auto [kind, x, y] : { std::tuple { lynx::EffectKind::frequencySplitter, 200.0f, 60.0f }, { lynx::EffectKind::reverb, 420.0f, 0.0f },
- { lynx::EffectKind::fruityDelay3, 420.0f, 120.0f }, { lynx::EffectKind::peakController, 200.0f, 260.0f } })
- {
- lynx::PatchNode n;
- n.effect = lynx::makeEffectSlot (kind);
- n.x = x;
- n.y = y;
- slot.patcher.nodes.push_back (n);
- }
- { // round 165c: a Hardware Insert node (its editor opens from the node)
- lynx::PatchNode n;
- n.effect = lynx::makeEffectSlot (lynx::EffectKind::hardwareInsert);
- n.x = 420.0f, n.y = 260.0f;
- slot.patcher.nodes.push_back (n);
- }
- auto wire = [&] (int from, int fromPort, int to, int toPort, float gain = 1.0f, lynx::PatchWire::Kind kind = lynx::PatchWire::Kind::audio) {
- lynx::PatchWire w;
- w.kind = kind;
- w.from = from, w.fromPort = fromPort, w.to = to, w.toPort = toPort, w.gain = gain;
- slot.patcher.wires.push_back (w);
- };
- wire (lynx::patchFromHost, 0, 0, 0);
- wire (0, 1, 1, 0);
- wire (0, 3, 2, 0, 0.5f);
- wire (1, 0, lynx::patchToHost, 0);
- wire (2, 0, lynx::patchToHost, 0);
- wire (lynx::patchFromHost, 1, 3, 0);
- wire (3, 1, 2, 2, 1.0f, lynx::PatchWire::Kind::control);
- wire (0, 2, lynx::patchToHost, 1, 0.7f);
- // round 171b (issue #65): a Surface knob on the reverb's parameter input 1, the reverb's parameter 0 out to
- // the delay's parameter input 2 (FL's Inputs / Outputs › Parameters)
- {
- lynx::SurfaceControl knob;
- knob.name = "Knob 1";
- knob.value = 0.6f;
- slot.patcher.surface = { knob };
- slot.patcher.surfaceX = 200.0f, slot.patcher.surfaceY = 380.0f;
- lynx::patcher::setParamInput (slot.patcher, 1, 1, true, "Reverb - 2");
- lynx::patcher::setParamOutput (slot.patcher, 1, 0, true);
- lynx::patcher::setParamInput (slot.patcher, 2, 2, true, "Delay - 3");
- wire (lynx::patchSurface, 0, 1, 1, 1.0f, lynx::PatchWire::Kind::control);
- wire (1, lynx::patchParamOutput (0), 2, 2, 1.0f, lynx::PatchWire::Kind::control);
- }
- slot.patcher.outputTracks = { 3 };
- slot.patcher.inputX = -20.0f;
- slot.patcher.outputX = 660.0f;
- song.mixer[1].effects = { slot };
- lynx::ChannelDef ch;
- ch.name = "Patcher";
- ch.instrument = lynx::InstrumentKind::patcher;
- lynx::PatchNode synth, chorus;
- synth.generator = true;
- synth.channel.instrument = lynx::InstrumentKind::synth;
- synth.channel.name = "Synth";
- synth.x = 220.0f;
- chorus.effect = lynx::makeEffectSlot (lynx::EffectKind::chorus);
- chorus.x = 420.0f;
- // round 162: a MIDI Out node between the "MIDI port 5" pin and "To LYNX" MIDI port 3, an Envelope Controller
- // on the notes moving the chorus
- lynx::PatchNode midiOut, envelope;
- midiOut.generator = envelope.generator = true;
- midiOut.channel.instrument = lynx::InstrumentKind::midiOut;
- midiOut.channel.name = "MIDI Out";
- lynx::midictl::writeMidiOut (midiOut.channel.pluginState, { 3, 0, 0, -1, -1 });
- midiOut.x = 220.0f, midiOut.y = 160.0f;
- envelope.channel.instrument = lynx::InstrumentKind::controller;
- envelope.channel.name = "Envelope Controller";
- envelope.channel.controllerState = lynx::writeEnvelopeController (lynx::defaultEnvelopeController());
- envelope.x = 220.0f, envelope.y = 260.0f;
- lynx::PatchNode osc; // round 164f: an FL engine node (its editor opens from the node)
- osc.generator = true;
- osc.channel = lynx::natives::makeChannel (lynx::InstrumentKind::threeosc, lynx::flStudioAccess()).value_or (lynx::ChannelDef {});
- osc.channel.instrument = lynx::InstrumentKind::threeosc;
- osc.channel.name = "3x Osc";
- osc.x = 420.0f, osc.y = 260.0f;
- // round 165c: Keyboard Controller, SoundFont player, Granulizer and Dashboard nodes (their editors open from the node)
- lynx::PatchNode keys, soundfont, granulizer, dashboard;
- keys.generator = soundfont.generator = granulizer.generator = dashboard.generator = true;
- keys.channel.instrument = lynx::InstrumentKind::controller;
- keys.channel.name = "Keyboard Controller";
- {
- lynx::KeyboardControllerData ramp;
- for (std::size_t k = 0; k < ramp.keys.size(); ++k)
- ramp.keys[k] = (float) k / (float) (ramp.keys.size() - 1);
- lynx::writeKeyboardController (ramp, keys.channel.controllerState);
- }
- soundfont.channel = lynx::sf::makeChannel();
- granulizer.channel = lynx::natives::makeChannel (lynx::InstrumentKind::granulizer, lynx::flStudioAccess()).value_or (lynx::ChannelDef {});
- granulizer.channel.instrument = lynx::InstrumentKind::granulizer;
- granulizer.channel.name = "Fruity Granulizer";
- dashboard.channel.instrument = lynx::InstrumentKind::dashboard;
- dashboard.channel.name = "Dashboard";
- dashboard.channel.patcher.surface = lynx::surface::starterControls();
- keys.x = 20.0f, keys.y = 440.0f;
- soundfont.x = 220.0f, soundfont.y = 440.0f;
- granulizer.x = 420.0f, granulizer.y = 440.0f;
- dashboard.x = 20.0f, dashboard.y = 540.0f;
- // and a Layer node playing the SoundFont and Granulizer nodes on its Children pin (crossfaded)
- lynx::PatchNode layerNode;
- layerNode.generator = true;
- layerNode.channel.instrument = lynx::InstrumentKind::layer;
- layerNode.channel.name = "Layer";
- layerNode.channel.layer.crossfade = true;
- layerNode.channel.layer.fade = 0.35f;
- layerNode.x = 220.0f, layerNode.y = 540.0f;
- ch.patcher.nodes = { synth, chorus, midiOut, envelope, osc, keys, soundfont, granulizer, dashboard, layerNode };
- lynx::PatchWire notes, a, b, portIn, portOut, envNotes, envControl;
- notes.kind = lynx::PatchWire::Kind::midi, notes.to = 0;
- a.from = 0, a.to = 1;
- b.from = 1;
- portIn.kind = lynx::PatchWire::Kind::midi, portIn.fromPort = lynx::patchMidiPortPin (5), portIn.to = 2;
- portOut.kind = lynx::PatchWire::Kind::midi, portOut.from = 2, portOut.to = lynx::patchToHost, portOut.toPort = 3;
- envNotes.kind = lynx::PatchWire::Kind::midi, envNotes.to = 3;
- envControl.kind = lynx::PatchWire::Kind::control, envControl.from = 3, envControl.to = 1, envControl.toPort = 0;
- lynx::PatchWire oscNotes, oscOut;
- oscNotes.kind = lynx::PatchWire::Kind::midi, oscNotes.to = 4;
- oscOut.from = 4;
- lynx::PatchWire layerNotes, layerToFont, layerToGrains, fontOut, grainsOut;
- layerNotes.kind = layerToFont.kind = layerToGrains.kind = lynx::PatchWire::Kind::midi;
- layerNotes.to = 9;
- layerToFont.from = 9, layerToFont.to = 6;
- layerToGrains.from = 9, layerToGrains.to = 7;
- fontOut.from = 6;
- grainsOut.from = 7;
- ch.patcher.wires = { notes, a, b, portIn, portOut, envNotes, envControl, oscNotes, oscOut, layerNotes, layerToFont, layerToGrains, fontOut, grainsOut };
- ch.patcher.fromMidiPorts = { 1, 5 };
- ch.patcher.toMidiPorts = { 3 };
- ch.patcher.outputX = 640.0f;
- song.channels.push_back (ch);
- // LYNX_PATCHERSHOT_SAVE=file.lynx: the demo as a project (a GUI check of the same Patchers, round 164f)
- if (const auto save = juce::SystemStats::getEnvironmentVariable ("LYNX_PATCHERSHOT_SAVE", {}); save.isNotEmpty())
- {
- if (! song.patterns.empty())
- for (int k = 0; k < 4; ++k)
- song.patterns[0].notes.push_back ({ (std::int64_t) k * lynx::ppq, lynx::ppq / 2, (int) song.channels.size() - 1, 60 + 4 * k, 0.8f });
- juce::String error;
- lynx::ProjectFile::save (song, juce::File (save), error);
- // round 171b: the saved Patchers come back the same (parameter ports, event cables, published)
- juce::String report;
- if (const auto loaded = lynx::ProjectFile::load (juce::File (save), error))
- {
- const auto same = loaded->mixer.size() > 1 && ! loaded->mixer[1].effects.empty()
- && loaded->mixer[1].effects[0].patcher == song.mixer[1].effects[0].patcher;
- const auto& d = loaded->mixer.size() > 1 && ! loaded->mixer[1].effects.empty() ? loaded->mixer[1].effects[0].patcher : lynx::PatcherDoc {};
- report << "patcher round trip: " << (same ? "OK" : "DIFFERENT") << "\n";
- if (! same && loaded->mixer.size() > 1 && ! loaded->mixer[1].effects.empty())
- {
- const auto& a = song.mixer[1].effects[0].patcher;
- report << "wires " << (a.wires == d.wires ? "same" : "differ") << ", published " << (a.published == d.published ? "same" : "differ")
- << ", surface " << (a.surface == d.surface ? "same" : "differ") << "\n";
- for (std::size_t n = 0; n < std::min (a.nodes.size(), d.nodes.size()); ++n)
- if (! (a.nodes[n] == d.nodes[n]))
- report << "node " << (int) n << " differs: ports " << (a.nodes[n].paramIns == d.nodes[n].paramIns && a.nodes[n].paramOuts == d.nodes[n].paramOuts ? "same" : "differ")
- << ", effect " << (a.nodes[n].effect == d.nodes[n].effect ? "same" : "differ") << ", xy "
- << (a.nodes[n].x == d.nodes[n].x && a.nodes[n].y == d.nodes[n].y ? "same" : "differ") << "\n";
- }
- for (int n = 0; n < (int) d.nodes.size(); ++n)
- report << "node " << n << " paramIns " << (int) d.nodes[(std::size_t) n].paramIns.size() << " paramOuts "
- << (int) d.nodes[(std::size_t) n].paramOuts.size() << "\n";
- for (const auto& w : d.wires)
- if (w.kind == lynx::PatchWire::Kind::control)
- report << "control " << w.from << ":" << w.fromPort << " -> " << w.to << ":" << w.toPort << "\n";
- for (const auto& p : d.published)
- report << "published " << p.node << ":" << p.param << " " << juce::String::fromUTF8 (p.name.c_str()) << "\n";
- }
- else
- report << "patcher round trip: load failed: " << error << "\n";
- juce::File (prefix + "-roundtrip.txt").replaceWithText (report);
- }
- offline.setSong (std::move (song));
- }
- offline.dispatchPendingMessages();
- const auto& song = offline.getSong();
- auto shootOpen = [&] (const juce::String& name) {
- for (int k = 0; k < juce::TopLevelWindow::getNumTopLevelWindows(); ++k)
- if (auto* w = dynamic_cast<juce::DocumentWindow*> (juce::TopLevelWindow::getTopLevelWindow (k)))
- if (w->getName().startsWith (lynx::tr ("Patcher")) && w->getContentComponent() != nullptr)
- {
- auto* c = w->getContentComponent();
- savePng (c->createComponentSnapshot (c->getLocalBounds()), prefix + name);
- delete w;
- return;
- }
- };
- int shots = 0;
- for (int t = 0; t < (int) song.mixer.size() && shots < 12; ++t)
- for (int s = 0; s < (int) song.mixer[(std::size_t) t].effects.size(); ++s)
- if (song.mixer[(std::size_t) t].effects[(std::size_t) s].kind == lynx::EffectKind::patcher)
- {
- lynx::PatcherWindows::openSlot (offline, t, s);
- shootOpen ("-insert" + juce::String (t) + "-slot" + juce::String (s) + ".png");
- // each built-in node's editor, as a double-click opens it (round 165c)
- lynx::PatcherWindows::shootNodeEditors (offline, false, t, s, [&] (const juce::Image& image, int n) {
- savePng (image, prefix + "-insert" + juce::String (t) + "-slot" + juce::String (s) + "-node" + juce::String (n) + ".png");
- });
- ++shots;
- if (shots == 1) // its menus (round 162)
- lynx::PatcherWindows::shootMenus (offline, false, t, s, [&] (const juce::Image& image, const juce::String& name) {
- savePng (image, prefix + "-menu-" + name + ".png");
- });
- }
- for (int c = 0; c < (int) song.channels.size(); ++c)
- if (song.channels[(std::size_t) c].instrument == lynx::InstrumentKind::patcher)
- {
- lynx::PatcherWindows::openChannel (offline, c);
- shootOpen ("-channel" + juce::String (c) + ".png");
- // each node's editor, as a double-click opens it (round 164f; every built-in node since round 165c)
- lynx::PatcherWindows::shootNodeEditors (offline, true, c, 0, [&] (const juce::Image& image, int n) {
- savePng (image, prefix + "-channel" + juce::String (c) + "-node" + juce::String (n) + ".png");
- });
- lynx::PatcherWindows::shootMenus (offline, true, c, 0, [&] (const juce::Image& image, const juce::String& name) {
- savePng (image, prefix + "-channel" + juce::String (c) + "-menu-" + name + ".png");
- });
- }
- }
- }
- // Issue #64: FL's letter keys in a plugin menu (quickpick::showMenu), checked on the real menu windows
- struct TypeAheadTest final : private juce::Timer
- {
- juce::File out;
- juce::StringArray log;
- int step = 0, picked = 0;
- bool ok = true, menuShown = false;
- std::unique_ptr<juce::DocumentWindow> owner;
- juce::PopupMenu pending;
- static juce::String highlighted()
- {
- if (auto* window = juce::Component::getCurrentlyModalComponent())
- for (auto* child : window->getChildren())
- if (auto* h = child->getAccessibilityHandler(); h != nullptr && h->hasFocus (false))
- return h->getTitle();
- return "(none)";
- }
- static void press (const juce::KeyPress& key)
- {
- if (auto* window = juce::Component::getCurrentlyModalComponent())
- if (auto* peer = window->getPeer())
- peer->handleKeyPress (key);
- }
- void expect (const juce::String& what, const juce::String& got, const juce::String& wanted)
- {
- const auto good = got == wanted;
- ok = ok && good;
- log.add ((good ? "ok " : "FAIL ") + what + ": " + got + (good ? juce::String() : " (wanted " + wanted + ")"));
- }
- void start()
- {
- juce::PopupMenu menu, sub;
- auto item = [this] (juce::PopupMenu& m, int id, const char* text, bool enabled = true) {
- m.addItem (text, enabled, false, [this, id] { picked = id; });
- };
- menu.addSectionHeader ("LYNX SHARE");
- item (menu, 1, "Echoform");
- item (menu, 2, "EQ");
- item (menu, 3, "Halo");
- menu.addSectionHeader ("Misc");
- item (menu, 4, "Effector");
- item (menu, 5, "Exciter (unavailable)", false);
- item (sub, 10, "Delay");
- item (sub, 11, "Edison");
- item (sub, 12, "Eventide");
- menu.addSubMenu ("Tree", sub);
- // the menu belongs to a window in the foreground, as when the user right-clicks a mixer slot (JUCE closes a
- // menu of a background process at once)
- owner = std::make_unique<juce::DocumentWindow> ("LYNX type-ahead test", juce::Colours::black, 0);
- owner->setBounds (200, 200, 300, 200);
- owner->setVisible (true);
- lynx::forceForegroundForTest (*owner);
- pending = menu; // shown once the window is up and active (X11 maps and activates it asynchronously)
- startTimer (300);
- }
- void timerCallback() override
- {
- const auto e = juce::KeyPress ('e', {}, 'e');
- if (step == 0 && owner != nullptr && ! menuShown)
- {
- menuShown = true;
- lynx::forceForegroundForTest (*owner);
- lynx::quickpick::showMenu (pending, juce::PopupMenu::Options().withTargetComponent (owner.get()), {});
- return;
- }
- switch (step++)
- {
- case 0: expect ("menu open", juce::String ((int) (juce::Component::getCurrentlyModalComponent() != nullptr)), "1"); break;
- case 1: press (e); expect ("e", highlighted(), "Echoform"); break;
- case 2: press (e); expect ("e again", highlighted(), "EQ"); break;
- case 3: press (juce::KeyPress ('E', juce::ModifierKeys::shiftModifier, 'E')); expect ("E (shift)", highlighted(), "Effector"); break;
- case 4: press (e); expect ("e wraps (skips the disabled one)", highlighted(), "Echoform"); break;
- case 5: press (juce::KeyPress ('m', {}, 'm')); expect ("m (only a heading starts with it: no move)", highlighted(), "Echoform"); break;
- case 6: press (juce::KeyPress (juce::KeyPress::downKey)); expect ("down arrow", highlighted(), "EQ"); break;
- case 7: press (e); expect ("e after the arrow", highlighted(), "Effector"); break;
- case 8: press (juce::KeyPress ('t', {}, 't')); expect ("t", highlighted(), "Tree"); break;
- case 9: press (juce::KeyPress (juce::KeyPress::rightKey)); break; // opens the submenu (it takes the keys)
- case 10: press (e); expect ("e in the submenu", highlighted(), "Edison"); break;
- case 11: press (e); expect ("e again in the submenu", highlighted(), "Eventide"); break;
- case 12: expect ("nothing picked by the letters", juce::String (picked), "0"); press (juce::KeyPress (juce::KeyPress::returnKey)); break;
- case 13: break;
- default:
- expect ("Enter closed the menu", juce::String ((int) (juce::Component::getCurrentlyModalComponent() == nullptr)), "1");
- expect ("Enter picked", juce::String (picked), "12");
- stopTimer();
- owner.reset();
- log.add (ok ? "result=OK" : "result=FAIL");
- out.replaceWithText (log.joinIntoString ("\n") + "\n");
- juce::JUCEApplication::getInstance()->setApplicationReturnValue (ok ? 0 : 1);
- juce::JUCEApplication::quit();
- return;
- }
- }
- };
- std::unique_ptr<TypeAheadTest> typeAheadTest;
- struct ChooserTest final : private juce::Timer
- {
- juce::File out, file;
- juce::StringArray log;
- std::unique_ptr<juce::FileChooser> chooser;
- double started = 0;
- bool shot = false, done = false;
- void start()
- {
- log.add ("LYNX_FILE_DIALOG=" + juce::SystemStats::getEnvironmentVariable ("LYNX_FILE_DIALOG", {}));
- log.add ("native=" + juce::String ((int) lynx::ui::filechooser::nativeDialogs()));
- chooser = lynx::ui::makeFileChooser ("Open audio file", file.getParentDirectory(), "*.wav;*.flac");
- started = juce::Time::getMillisecondCounterHiRes();
- lynx::ui::launchChooser (chooser, juce::FileBrowserComponent::openMode | juce::FileBrowserComponent::canSelectFiles,
- [this] (const juce::FileChooser& fc) { finish (fc.getResult()); });
- startTimer (200);
- }
- static juce::FileChooserDialogBox* builtInDialog()
- {
- for (int i = 0; i < juce::Desktop::getInstance().getNumComponents(); ++i)
- if (auto* box = dynamic_cast<juce::FileChooserDialogBox*> (juce::Desktop::getInstance().getComponent (i)); box != nullptr && box->isShowing())
- return box;
- return nullptr;
- }
- static juce::FileBrowserComponent* findBrowser (juce::Component& c)
- {
- if (auto* b = dynamic_cast<juce::FileBrowserComponent*> (&c))
- return b;
- for (auto* child : c.getChildren())
- if (auto* b = findBrowser (*child))
- return b;
- return nullptr;
- }
- void timerCallback() override
- {
- if (done)
- return;
- if (auto* box = builtInDialog(); box != nullptr && ! shot)
- {
- shot = true;
- log.add ("built-in dialog shown after " + juce::String (juce::roundToInt (juce::Time::getMillisecondCounterHiRes() - started)) + " ms");
- const auto image = box->createComponentSnapshot (box->getLocalBounds());
- juce::FileOutputStream png (out.getSiblingFile (out.getFileName() + ".png"));
- if (png.openedOk())
- {
- png.setPosition (0), png.truncate();
- juce::PNGImageFormat().writeImageToStream (image, png);
- }
- if (auto* browser = findBrowser (*box))
- {
- browser->setRoot (file.getParentDirectory());
- browser->setFileName (file.getFileName());
- log.add ("typed " + file.getFileName());
- box->exitModalState (1);
- }
- else
- log.add ("no file browser in the dialog");
- }
- if (juce::Time::getMillisecondCounterHiRes() - started > 30000.0)
- finish ({}, "timeout");
- }
- void finish (const juce::File& result, const juce::String& why = {})
- {
- if (done)
- return;
- done = true;
- stopTimer();
- log.add ("callback after " + juce::String (juce::roundToInt (juce::Time::getMillisecondCounterHiRes() - started)) + " ms: "
- + (why.isNotEmpty() ? why : result.getFullPathName().isEmpty() ? juce::String ("(no file)") : result.getFullPathName()));
- log.add ("native now=" + juce::String ((int) lynx::ui::filechooser::nativeDialogs()));
- const auto ok = result == file && result.existsAsFile();
- log.add (ok ? "result=OK" : "result=FAIL");
- out.replaceWithText (log.joinIntoString ("\n") + "\n");
- juce::JUCEApplication::getInstance()->setApplicationReturnValue (ok ? 0 : 1);
- juce::MessageManager::callAsync ([] { juce::JUCEApplication::quit(); });
- }
- };
- std::unique_ptr<ChooserTest> chooserTest;
- void runChooserTest (const juce::File& out, const juce::File& file)
- {
- juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
- chooserTest = std::make_unique<ChooserTest>();
- chooserTest->out = out;
- chooserTest->file = file;
- chooserTest->start();
- }
- void runTypeAheadTest (const juce::File& out)
- {
- juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
- typeAheadTest = std::make_unique<TypeAheadTest>();
- typeAheadTest->out = out;
- typeAheadTest->start();
- }
- void runSnapshot (const juce::String& prefix, const juce::String& projectPath)
- {
- juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
- // LYNX_SNAPSHOT_THEME=file.lynxtheme: the pictures in that theme (round 162d)
- if (const auto themeFile = juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_THEME", {}); themeFile.isNotEmpty())
- if (const auto spec = lynx::themeui::loadFile (juce::File (themeFile)))
- lynx::themeui::apply (*spec, false);
- {
- lynx::AudioEngine offline (false);
- lynx::MainComponent ui (offline, false); // default layout and keys, nothing saved
- // LYNX_SNAPSHOT_SIZE=WxH (default 1280x720)
- const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1280x720"), "x", "");
- ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
- if (projectPath.isNotEmpty())
- ui.openFile (juce::File (projectPath));
- offline.dispatchPendingMessages(); // change notifications are asynchronous
- ui.waitForBrowserForSnapshot();
- // the workspace desktop: the default layout, then with the Piano Roll and Mixer floating too
- // (and a sample hint in the status strip, as when hovering a knob)
- ui.showDesktopForSnapshot (false);
- ui.setMetersForSnapshot (0.23, (std::int64_t) 412 << 20, 6);
- offline.dispatchPendingMessages();
- saveSnapshot (ui, prefix + "-desktop.png");
- // the first start: the setup wizard over the main window (round 140), also on a small screen (it scrolls)
- {
- const auto size = ui.getBounds();
- ui.showSetupWizard();
- offline.dispatchPendingMessages();
- saveSnapshot (ui, prefix + "-desktop-setup.png");
- ui.setSize (1024, 600);
- offline.dispatchPendingMessages();
- saveSnapshot (ui, prefix + "-desktop-setup-small.png");
- ui.closeSetupWizardForSnapshot();
- ui.setBounds (size);
- offline.dispatchPendingMessages();
- }
- // the start-up desktop and the toolbar at the usual window sizes: the untouched default layout
- // follows the window (default rects, not scaled ones); panels drop from the toolbar by priority
- {
- const auto size = ui.getBounds();
- for (const auto& [w, h] : std::vector<std::pair<int, int>> { { 1280, 720 }, { 1366, 768 }, { 1600, 900 }, { 1920, 1080 }, { 2560, 1440 }, { 3840, 2160 } })
- {
- ui.setSize (w, h);
- offline.dispatchPendingMessages();
- saveSnapshot (ui, prefix + "-desktop-" + juce::String (w) + ".png");
- saveArea (ui, ui.getToolbarBoundsForSnapshot(), prefix + "-toolbar-" + juce::String (w) + ".png");
- if (w == 1920) // the rack scrolled to its last steps: the controls column stays in view (round 90)
- {
- ui.scrollRackForSnapshot (100000);
- offline.dispatchPendingMessages();
- saveSnapshot (ui, prefix + "-desktop-rack-scrolled.png");
- ui.scrollRackForSnapshot (0);
- }
- }
- // the toolbar with small and large icons, and a customized one (groups hidden and reordered)
- ui.setSize (1600, 900);
- for (auto [iconSize, name] : { std::pair { lynx::toolbarlayout::IconSize::small, "small" }, { lynx::toolbarlayout::IconSize::large, "large" } })
- {
- auto layout = lynx::toolbarlayout::Layout::makeDefault();
- layout.iconSize = iconSize;
- ui.setToolbarLayoutForSnapshot (layout);
- saveArea (ui, ui.getToolbarBoundsForSnapshot(), prefix + "-toolbar-" + name + "-1600.png");
- }
- {
- auto layout = lynx::toolbarlayout::Layout::makeDefault();
- layout.move (lynx::toolbarlayout::Group::windows, -3);
- layout.setShown (lynx::toolbarlayout::Group::record, false);
- layout.setShown (lynx::toolbarlayout::Group::meters, false);
- ui.setToolbarLayoutForSnapshot (layout);
- saveArea (ui, ui.getToolbarBoundsForSnapshot(), prefix + "-toolbar-custom-1600.png");
- }
- {
- // round 170e: the toolbar after a knob was moved: the last tweaked read-out (its caption) and the snap magnet
- ui.setSize (1920, 1080); // the read-out needs room beside the hint bar
- ui.setToolbarLayoutForSnapshot (lynx::toolbarlayout::Layout::makeDefault());
- lynx::AutomationTarget t;
- t.kind = lynx::AutomationTargetKind::mixerVolume;
- t.index = 0;
- offline.noteTweaked (t);
- ui.refreshTweakReadoutForSnapshot();
- offline.dispatchPendingMessages();
- saveArea (ui, ui.getToolbarBoundsForSnapshot(), prefix + "-toolbar-tweak-1920.png");
- ui.setSize (1600, 900);
- }
- {
- // the toolbar's edit mode (round 115): outlined panels and the tray of panels under it
- ui.setToolbarLayoutForSnapshot (lynx::toolbarlayout::Layout::makeDefault());
- auto layout = lynx::toolbarlayout::Layout::makeDefault();
- layout.setShown (lynx::toolbarlayout::Group::meters, false);
- ui.setToolbarLayoutForSnapshot (layout);
- ui.setToolbarEditingForSnapshot (true);
- offline.dispatchPendingMessages();
- saveArea (ui, ui.getToolbarBoundsForSnapshot().withHeight (ui.getToolbarAndTrayHeightForSnapshot()), prefix + "-toolbar-edit-1600.png");
- ui.setToolbarEditingForSnapshot (false);
- // Ctrl+F11: only the menu and the hint bar
- layout = lynx::toolbarlayout::Layout::makeDefault();
- layout.visible = false;
- ui.setToolbarLayoutForSnapshot (layout);
- saveArea (ui, ui.getLocalBounds().withHeight (120), prefix + "-toolbar-hidden-1600.png");
- }
- ui.setToolbarLayoutForSnapshot (lynx::toolbarlayout::Layout::makeDefault());
- // quick tips: the toolbar and title bars with a few name bubbles, and every tip on one sheet
- offline.dispatchPendingMessages();
- saveQuickTips (ui, prefix);
- ui.setBounds (size);
- offline.dispatchPendingMessages();
- }
- // the hint bar: a value control while it is dragged (live value), a gesture line with mouse and key
- // glyphs, and a text too long for one line (two lines)
- {
- const auto toolbar = ui.getToolbarBoundsForSnapshot().withWidth (juce::jmin (ui.getWidth(), 900));
- const lynx::ui::Hint hints[] = {
- { lynx::tr ("Volume") + " - " + lynx::tr ("drag (Ctrl: fine), wheel, Alt+click resets"), "-3.2 dB", true, true },
- { lynx::tr ("Piano Roll: [LMB] add a note, drag to move [RMB] delete [Ctrl][LMB] drag to select [Ctrl][Wheel] zoom"), {}, false, false },
- { lynx::tr ("Global snap: the grid of the Piano Roll and Playlist (when they follow it) and the quantise of recorded notes "
- "[LMB] choose [Wheel] step [RMB] length of new notes [Backspace] snap on/off [Alt] while dragging: no snap"), {}, false, true },
- };
- for (int i = 0; i < 3; ++i)
- {
- ui.setHintForSnapshot (hints[i], i == 0);
- saveArea (ui, toolbar, prefix + "-hint-" + juce::String (i + 1) + ".png");
- }
- }
- ui.showDesktopForSnapshot (true);
- ui.setHintForSnapshot ({ lynx::tr ("Volume") + " - " + lynx::tr ("drag (Ctrl: fine), wheel, Alt+click resets"), "78%", true, true });
- saveSnapshot (ui, prefix + "-desktop-all.png");
- ui.selectTabForSnapshot (0);
- saveSnapshot (ui, prefix + "-rack.png");
- {
- // a pattern with piano-roll notes: those rows show a miniature instead of steps (round 90)
- int found = -1;
- const auto before = offline.getSong().currentPattern;
- {
- const auto& song = offline.getSong();
- for (int p = 0; p < (int) song.patterns.size() && found < 0; ++p)
- for (int c = 0; c < (int) song.channels.size() && found < 0; ++c)
- if (lynx::showsNotePreview (song.patterns[(std::size_t) p], c))
- found = p;
- }
- if (found >= 0)
- {
- offline.editSong ([found] (lynx::Song& s) { s.currentPattern = found; }, false);
- offline.dispatchPendingMessages();
- saveSnapshot (ui, prefix + "-rack-preview.png");
- offline.editSong ([before] (lynx::Song& s) { s.currentPattern = before; }, false);
- offline.dispatchPendingMessages();
- }
- }
- ui.selectTabForSnapshot (1);
- saveSnapshot (ui, prefix + "-pianoroll.png");
- if (const auto strip = ui.getToolStripAreaForSnapshot (false); ! strip.isEmpty())
- saveArea (ui, strip, prefix + "-pianoroll-tools.png");
- // the editors' mouse feel: the hovered note / clip edge (grip, outline) and its hint in the hint bar
- ui.setHintForSnapshot (ui.getPianoRollForSnapshot().hoverForSnapshot());
- saveSnapshot (ui, prefix + "-pianoroll-hover.png");
- {
- // a pattern with note Chance or a Velocity Range (round 187c): the Piano roll with those lanes
- const auto& song = offline.getSong();
- const auto& notes = song.patterns[(std::size_t) std::clamp (song.currentPattern, 0, (int) song.patterns.size() - 1)].notes;
- if (std::any_of (notes.begin(), notes.end(), [] (const lynx::Note& n) { return n.hasChance(); }))
- {
- auto& roll = ui.getPianoRollForSnapshot();
- ui.setHintForSnapshot ({});
- for (const auto& [lane, name] : { std::pair { lynx::PianoRollComponent::laneChance, "chance" },
- { lynx::PianoRollComponent::laneVelocityRange, "velrange" },
- { lynx::PianoRollComponent::laneVelocity, "velocity" } })
- {
- roll.setLaneForSnapshot (lane);
- offline.dispatchPendingMessages();
- saveSnapshot (ui, prefix + "-pianoroll-" + name + ".png");
- }
- }
- }
- ui.selectTabForSnapshot (2);
- saveSnapshot (ui, prefix + "-playlist.png");
- if (const auto strip = ui.getToolStripAreaForSnapshot (true); ! strip.isEmpty())
- saveArea (ui, strip, prefix + "-playlist-tools.png");
- ui.setHintForSnapshot (ui.getPlaylistForSnapshot().hoverForSnapshot());
- saveSnapshot (ui, prefix + "-playlist-hover.png");
- ui.setHintForSnapshot ({ lynx::tr ("Volume") + " - " + lynx::tr ("drag (Ctrl: fine), wheel, Alt+click resets"), "78%", true, true });
- // the Playlist with a time selection over bars 2-3 (it selects the clips it touches) and the Knife tool
- ui.getPlaylistForSnapshot().setTimeSelectionForSnapshot (1, 3);
- ui.getPlaylistForSnapshot().setToolForSnapshot (lynx::EditTool::knife);
- offline.dispatchPendingMessages();
- saveSnapshot (ui, prefix + "-playlist-timesel.png");
- ui.getPlaylistForSnapshot().setToolForSnapshot (lynx::EditTool::pencil);
- // round 177b: automation lanes on (two lanes under track 2: a volume ramp and a pan wobble)
- {
- const auto before = offline.getSong();
- offline.editSong ([] (lynx::Song& s) {
- s.loopStart = s.loopEnd = 0; // (no time selection in this one)
- const auto bar = (std::int64_t) lynx::ppq * s.beatsPerBar;
- const auto vol = lynx::autolanes::addLane (s, 1, { lynx::AutomationTargetKind::mixerVolume, 1, 0, 0 }, "Insert 1 - Volume", 0.3f);
- s.automations[(std::size_t) vol].points = { { 0, 0.3f, 0.0f }, { bar * 2, 0.8f, 0.4f }, { bar * 4, 0.6f, 0.0f } };
- const auto pan = lynx::autolanes::addLane (s, 1, { lynx::AutomationTargetKind::mixerPan, 1, 0, 0 }, "Insert 1 - Pan", 0.5f);
- s.automations[(std::size_t) pan].points = { { 0, 0.5f, 0.0f }, { bar, 0.2f, 0.0f }, { bar * 2, 0.8f, 0.0f }, { bar * 3, 0.5f, 0.0f } };
- }, false);
- lynx::autolanes::setShown (true);
- ui.getPlaylistForSnapshot().resized();
- offline.dispatchPendingMessages();
- saveSnapshot (ui, prefix + "-playlist-lanes.png");
- lynx::autolanes::setShown (false);
- offline.editSong ([before] (lynx::Song& s) { s = before; }, false);
- offline.dispatchPendingMessages();
- }
- // round 104: a folded track group (FL's thin member rows) and the Picker's audio tab
- {
- int header = -1;
- for (int t = 0; t < (int) offline.getSong().playlistTracks.size() && header < 0; ++t)
- if (lynx::noteedit::isGroupHeader (offline.getSong(), t))
- header = t;
- if (header >= 0)
- {
- offline.editSong ([header] (lynx::Song& s) { lynx::noteedit::setGroupCollapsed (s, header, true); }, false);
- offline.dispatchPendingMessages();
- saveSnapshot (ui, prefix + "-playlist-group-folded.png");
- offline.editSong ([header] (lynx::Song& s) { lynx::noteedit::setGroupCollapsed (s, header, false); }, false);
- }
- ui.getPickerForSnapshot().setView (1);
- offline.dispatchPendingMessages();
- saveSnapshot (ui, prefix + "-playlist-picker-audio.png");
- ui.getPickerForSnapshot().setView (0);
- }
- // round 104: the Channel Rack filtered to its first filter group
- if (! offline.getSong().channelGroups.empty())
- {
- ui.selectTabForSnapshot (0);
- ui.getRackForSnapshot().setFilterGroup (0);
- offline.dispatchPendingMessages();
- saveSnapshot (ui, prefix + "-rack-filter.png");
- ui.getRackForSnapshot().setFilterGroup (-1);
- }
- ui.selectTabForSnapshot (3);
- // LYNX_SNAPSHOT_ARRANGE=1 (round 186c): Mixer menu › "Arrange inserts like the Playlist" first
- if (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_ARRANGE", {}) == "1")
- {
- offline.editSong ([] (lynx::Song& s) { lynx::mixerops::arrangeLikePlaylist (s); });
- offline.dispatchPendingMessages();
- }
- // LYNX_SNAPSHOT_TRACK=n: shows the effects of that mixer track
- if (const auto track = juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_TRACK", {}); track.isNotEmpty())
- {
- ui.selectMixerTrackForSnapshot (track.getIntValue(),
- juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SLOT", "-1").getIntValue());
- offline.dispatchPendingMessages();
- }
- saveSnapshot (ui, prefix + "-mixer.png");
- // round 168h (issue #52): FL's 8 Mixer layouts
- {
- const auto before = lynx::MixerStrips::layout;
- for (int l = 0; l < lynx::mixerlayout::layoutCount; ++l)
- {
- ui.getMixerForSnapshot().getStripsForSnapshot().setLayout ((lynx::mixerlayout::Layout) l);
- offline.dispatchPendingMessages();
- saveSnapshot (ui, prefix + "-mixer168h-" + juce::String (l) + ".png");
- }
- ui.getMixerForSnapshot().getStripsForSnapshot().setLayout (before);
- offline.dispatchPendingMessages();
- }
- // round 163: the Mixer at short heights (UI zoom 150%+): the EQ folds, then the effects panel scrolls
- {
- const auto size = ui.getBounds();
- for (auto h : { 450, 560, 680, 820 })
- {
- ui.setSize (size.getWidth(), h);
- offline.dispatchPendingMessages();
- saveSnapshot (ui, prefix + "-mixer163-" + juce::String (h) + ".png");
- }
- ui.setBounds (size);
- offline.dispatchPendingMessages();
- }
- // round 170b (Busy Works Beats' review): inserts 1-3 selected and routed together to insert 4, a single effect
- // moved down into slot 2 (FL's slot places), and the plugin menus grouped by category, LYNX SHARE first
- {
- const auto before = offline.getSong();
- offline.editSong ([] (lynx::Song& s) {
- if (s.mixer.size() < 5)
- return;
- s.mixer[1].effects.clear();
- lynx::EffectSlot fx;
- fx.kind = lynx::EffectKind::compressor;
- s.mixer[1].effects.push_back (fx);
- lynx::mixerops::moveEffectBy (s, 1, 0, 1);
- lynx::mixerops::switchSelectedRoute (s, { 1, 2, 3 }, 4, true);
- });
- ui.selectMixerTrackForSnapshot (1);
- ui.getMixerForSnapshot().getStripsForSnapshot().setSelection ({ 1, 2, 3 }, 1);
- offline.dispatchPendingMessages();
- saveSnapshot (ui, prefix + "-mixer170b.png");
- juce::PopupMenu effects, generators;
- lynx::quickpick::addFolderGroups (effects, offline, std::function<void (lynx::EffectSlot)> ([] (lynx::EffectSlot) {}));
- lynx::quickpick::addFolderViewItems (effects, offline);
- lynx::quickpick::addGeneratorMenu (generators, offline, [] (lynx::ChannelDef) {}, {}, nullptr, nullptr);
- lynx::quickpick::addFolderViewItems (generators, offline);
- saveMenus (juce::StringArray { "Mixer slot: add an effect", "Channel Rack: add" }, { effects, generators }, prefix + "-menus170b.png");
- offline.setSong (before);
- offline.dispatchPendingMessages();
- }
- // standalone windows, with the theme background
- auto saveWindow = [&prefix] (std::unique_ptr<juce::Component> c, const juce::String& name) {
- juce::Component frame;
- frame.setSize (c->getWidth(), c->getHeight());
- frame.setOpaque (true);
- // an AlertWindow is built on the desktop: shown there first, it would take the foreground from whoever has it
- // (TopLevelWindow::visibilityChanged calls toFront (true)). Off the desktop, its control that showing it would
- // have focused (what grabKeyboardFocus picks) is marked, so the picture keeps that control's focus ring
- if (c->isOnDesktop())
- {
- c->removeFromDesktop();
- auto* focus = c.get();
- for (int depth = 0; focus != nullptr && depth < 32; ++depth)
- {
- if (focus->getWantsKeyboardFocus() && (focus->isEnabled() || focus == c.get()))
- {
- focus->getProperties().set ("lynxSnapshotFocus", true);
- break;
- }
- auto traverser = focus->createKeyboardFocusTraverser();
- focus = traverser != nullptr ? traverser->getDefaultComponent (focus) : nullptr;
- }
- }
- frame.addAndMakeVisible (*c);
- c->setTopLeftPosition (0, 0);
- checkTextFit (*c, name.fromFirstOccurrenceOf ("-", false, false).upToLastOccurrenceOf (".", false, false));
- juce::Image image (juce::Image::ARGB, frame.getWidth(), frame.getHeight(), true);
- {
- juce::Graphics g (image);
- g.fillAll (lynx::theme::panel);
- frame.paintEntireComponent (g, false);
- }
- const juce::File file (prefix + name);
- file.deleteFile();
- juce::PNGImageFormat png;
- if (auto out = file.createOutputStream())
- png.writeImageToStream (image, *out);
- };
- saveWindow (lynx::makeExportPanel (offline), "-export.png");
- saveWindow (lynx::makeExportPanel (offline, 1), "-export-mp3.png");
- saveWindow (lynx::makeExportPanel (offline, 3), "-export-flac-stems.png");
- {
- // REA round 165f-mixer: the mixer track's Track latency / routing submenus, Disk recording, PDC, and the
- // Export window for "Render selected tracks to wave file(s)"
- const auto before = offline.getSong();
- offline.editSong ([] (lynx::Song& s) {
- if (s.mixer.size() > 3)
- {
- s.mixer[1].latencyMs = 5.0f;
- s.mixer[1].latencyBypass = lynx::LatencyBypass::whenRecordingOrStopped;
- s.mixer[2].latencyMs = -1.5f;
- }
- });
- offline.dispatchPendingMessages();
- auto& strips = ui.getMixerForSnapshot().getStripsForSnapshot();
- strips.setSelection ({ 1, 2, 3 }, 1);
- const auto menu = strips.buildMenu (1);
- juce::StringArray names { "Mixer track" };
- std::vector<juce::PopupMenu> menus { menu };
- const auto latencyPrefix = lynx::tr ("Track latency: {0}", { juce::String() });
- const juce::String wanted[] = { lynx::tr ("Selected tracks ⇄ this track"), lynx::tr ("Disk recording"),
- lynx::tr ("Plugin delay compensation") };
- for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
- {
- const auto& item = it.getItem();
- if (item.subMenu != nullptr && (item.text.startsWith (latencyPrefix) || std::find (std::begin (wanted), std::end (wanted), item.text) != std::end (wanted)))
- {
- names.add (item.text.upToFirstOccurrenceOf (":", false, false));
- menus.push_back (*item.subMenu);
- }
- }
- saveMenus (names, menus, prefix + "-menus165-mixer.png");
- saveWindow (lynx::makeExportPanelForTracks (offline, { 1, 2, 3 }), "-export165-tracks.png");
- offline.setSong (before);
- offline.dispatchPendingMessages();
- }
- saveSplashFrames (prefix);
- saveIconSheet (prefix + "-icons.png", 1.0f);
- saveIconSheet (prefix + "-icons-150.png", 1.5f);
- saveWindow (lynx::MainComponent::makeHelpContent(), "-help.png");
- saveWindow (lynx::ui::makeTrackIconGrid (5, {}), "-trackicons168h.png"); // round 168h: the icon picker
- saveWindow (std::make_unique<lynx::toolbar::CustomizePanel> (lynx::toolbarlayout::Layout::makeDefault()), "-customize-toolbar.png");
- // two moved controls: Tools › Last tweaked and Add › Automation for last tweaked parameter show them (REA round 143)
- offline.noteTweaked ({ lynx::AutomationTargetKind::channelVolume, 0 });
- offline.noteTweaked ({ lynx::AutomationTargetKind::mixerVolume, 0 });
- saveMenus (ui, prefix + "-menus.png");
- {
- // the windows' own menus (title bars) and the toolbar's recording menu
- juce::StringArray names;
- std::vector<juce::PopupMenu> menus;
- for (auto [panel, name] : { std::pair { lynx::workspace::Panel::playlist, "Playlist" }, { lynx::workspace::Panel::channelRack, "Channel Rack" },
- { lynx::workspace::Panel::pianoRoll, "Piano Roll" }, { lynx::workspace::Panel::mixer, "Mixer" },
- { lynx::workspace::Panel::browser, "Browser" } })
- {
- names.add (name);
- menus.push_back (ui.getPanelMenuForSnapshot (panel));
- }
- names.add ("Recording");
- menus.push_back (ui.getRecordMenuForSnapshot());
- names.add ("Toolbar");
- menus.push_back (ui.getToolbarMenuForSnapshot());
- saveMenus (names, menus, prefix + "-panel-menus.png");
- }
- {
- // REA round 143: the piano roll Tools menu, a Playlist track menu and a mixer insert menu (FL's layouts)
- std::vector<juce::PopupMenu> menus { ui.getPianoRollForSnapshot().getToolsMenuForSnapshot(),
- ui.getPlaylistForSnapshot().getTrackMenuForSnapshot (0),
- ui.getMixerForSnapshot().getStripsForSnapshot().buildMenu (1) };
- saveMenus (juce::StringArray { "Piano roll tools", "Playlist track", "Mixer track" }, menus, prefix + "-menus143.png");
- // round 167l: the channel menu ("Lock active/mute state")
- if (! offline.getSong().channels.empty())
- saveMenus (juce::StringArray { "Channel" }, std::vector<juce::PopupMenu> { ui.getRackForSnapshot().getChannelMenuForSnapshot (0) }, prefix + "-channel-menu.png");
- // round 163: menu density, compact (default) and comfortable, on a Browser folder menu
- {
- juce::PopupMenu folder;
- folder.addSectionHeader ("Documents");
- folder.addItem (1, "Expand all");
- folder.addItem (2, "Collapse all");
- folder.addSeparator();
- folder.addItem (3, "Refresh");
- folder.addSectionHeader ("System");
- folder.addItem (4, "Open");
- folder.addItem (5, "Copy the file path");
- folder.addSectionHeader ("Tags");
- folder.addItem (6, "Starred", true, true);
- folder.addSeparator();
- folder.addItem (7, "Add folder...");
- const auto wasCompact = lynx::theme::menus::compact();
- lynx::theme::menus::setCompact (true);
- saveMenus (juce::StringArray { "Compact" }, { folder }, prefix + "-menu163-compact.png");
- lynx::theme::menus::setCompact (false);
- saveMenus (juce::StringArray { "Comfortable" }, { folder }, prefix + "-menu163-comfortable.png");
- lynx::theme::menus::setCompact (wasCompact);
- }
- // and the clip menus of the first pattern, audio and automation clips of the project
- juce::StringArray clipNames;
- std::vector<juce::PopupMenu> clipMenus;
- for (auto [kind, name] : { std::pair { lynx::ClipKind::pattern, "Pattern clip" }, { lynx::ClipKind::audio, "Audio clip" },
- { lynx::ClipKind::automation, "Automation clip" } })
- for (int c = 0; c < (int) offline.getSong().playlist.size(); ++c)
- if (offline.getSong().playlist[(std::size_t) c].kind == kind)
- {
- clipNames.add (name);
- clipMenus.push_back (ui.getPlaylistForSnapshot().getClipMenuForSnapshot (c));
- break;
- }
- if (! clipMenus.empty())
- saveMenus (clipNames, clipMenus, prefix + "-menus143-clips.png");
- }
- auto saveAlert = [&] (std::unique_ptr<juce::AlertWindow> alert, const juce::String& name) {
- alert->setOpaque (true);
- saveWindow (std::move (alert), name);
- };
- saveAlert (ui.makeConfirmDiscardWindow(), "-confirm.png");
- saveAlert (lynx::MainComponent::makeAboutWindow(), "-about.png");
- saveAlert (lynx::makeNameAndColourDialog (lynx::tr ("Rename pattern"), "Pattern 2", lynx::lynxPalette()[6]), "-rename.png");
- saveAlert (lynx::makeRecordChoiceDialog(), "-record-dialog.png");
- saveAlert (lynx::makeSamplePitchDialog (7.25f, true, true), "-sample-pitch.png"); // round 163c
- saveAlert (lynx::makeGradientColourDialog (juce::Colour (0xffe5383b), juce::Colour (0xff3a7bd5), 8), "-gradient.png"); // round 177a
- saveAlert (lynx::makeMidiImportDialog(), "-midi-import-dialog.png"); // File › Import › MIDI file (REA round 143)
- // round 186c: FL's mixer "Delete" questions and its Settings › General › Manage messages menu
- saveAlert (lynx::makeFlMessageDialog ({ lynx::tr ("Delete tracks"), lynx::tr ("This will |delete| {0} selected mixer track(s). Are you sure?", { "1" }),
- { lynx::tr ("Yes"), lynx::tr ("No") }, true }),
- "-delete-tracks.png");
- saveAlert (lynx::makeFlMessageDialog ({ lynx::tr ("Playlist tracks"),
- lynx::tr ("One or more mixer tracks that will be deleted are connected to instrument/audio tracks.") + "\n"
- + lynx::tr ("Do you want to unlink the tracks and channels or delete them?"),
- { lynx::tr ("Delete tracks and channels"), lynx::tr ("Unlink tracks and channels"), lynx::tr ("Cancel") }, false }),
- "-delete-tracks-linked.png");
- saveMenus (juce::StringArray { "Manage messages" }, std::vector<juce::PopupMenu> { lynx::messages::manageMenu() }, prefix + "-manage-messages.png");
- saveWindow (lynx::makeSetupWizardContent (offline, {}, {}), "-setup.png");
- saveWindow (lynx::crashreporter::makeDialogForSnapshot (false), "-crash-report.png"); // round 159
- saveWindow (lynx::crashreporter::makeDialogForSnapshot (true), "-report-problem.png");
- // round 166b: the update bar in its states (available, downloading, failed, ready) and the release notes window
- {
- struct Bars final : juce::Component
- {
- Bars()
- {
- constexpr int h = lynx::updater::UpdateBar::height;
- setSize (1100, 4 * (h + 6));
- for (int state = 0; state < 4; ++state)
- {
- bars[state].setBounds (0, state * (h + 6), getWidth(), h);
- bars[state].showForSnapshot (state);
- addAndMakeVisible (bars[state]);
- }
- }
- lynx::updater::UpdateBar bars[4];
- };
- saveWindow (std::make_unique<Bars>(), "-update-bar.png");
- saveWindow (lynx::updater::makeReleaseNotesForSnapshot(), "-update-notes.png");
- }
- saveWindow (lynx::makeMissingFilesPanel (lynx::missingFilesSnapshotInfo(), 0, 1), "-missing-files.png");
- saveWindow (lynx::makeMissingFilesPanel (lynx::missingFilesSnapshotInfo(), 1), "-missing-plugins.png");
- saveWindow (lynx::makeMissingFilesPanel (lynx::missingFilesSnapshotInfo(), 2), "-missing-found.png");
- {
- // the Settings pages, with credits like a project imported from FL would carry
- offline.editSong ([] (lynx::Song& s) {
- s.info = { "Night Drive", "LYNX SHARE demo", "Synthwave", "https://lynx-share.com",
- "Made with LYNX SHARE.\nDrums and bass from the Channel Rack, pads from the Browser.", false };
- }, false);
- saveWindow (lynx::makeSettingsPanel (offline, lynx::SettingsPage::project), "-settings-project.png");
- saveWindow (lynx::makeSettingsPanel (offline, lynx::SettingsPage::info), "-settings-info.png");
- saveWindow (lynx::makeSettingsPanel (offline, lynx::SettingsPage::files), "-settings-files.png");
- saveWindow (lynx::makeSettingsPanel (offline, lynx::SettingsPage::general), "-settings-general.png");
- {
- // the whole General page (round 186a: the Startup section is below the first screen)
- auto tall = lynx::makeSettingsPanel (offline, lynx::SettingsPage::general);
- tall->setSize (tall->getWidth(), 1500);
- saveWindow (std::move (tall), "-settings-general-tall.png");
- }
- saveWindow (lynx::makeSettingsPanel (offline, lynx::SettingsPage::theme), "-settings-theme.png");
- saveWindow (lynx::makeSettingsPanel (offline, lynx::SettingsPage::audio), "-settings-audio.png");
- saveWindow (lynx::makeSettingsPanel (offline, lynx::SettingsPage::midi), "-settings-midi.png");
- saveWindow (lynx::makePluginManagerPanel (offline, false), "-plugin-manager.png");
- saveWindow (lynx::makeShortcutManagerPanel (false), "-shortcuts.png");
- }
- {
- // round 84: New project, Clip properties, Arrangements, Plugin performance monitor, Touch keyboard
- saveWindow (lynx::makeNewProjectPanel(), "-new-project.png");
- const auto& clips = offline.getSong().playlist;
- for (int i = 0; i < (int) clips.size(); ++i)
- if (clips[(std::size_t) i].kind == lynx::ClipKind::pattern)
- {
- saveWindow (lynx::makeClipPropertiesPanel (offline, i, { i, (i + 1) % (int) clips.size() }), "-clip-properties.png");
- break;
- }
- for (int i = 0; i < (int) clips.size(); ++i)
- if (clips[(std::size_t) i].kind == lynx::ClipKind::audio)
- {
- saveWindow (lynx::makeClipPropertiesPanel (offline, i, { i }), "-clip-properties-audio.png");
- break;
- }
- if (offline.getSong().arrangements.size() < 2)
- offline.editSong ([] (lynx::Song& s) {
- const auto current = s.currentArrangement;
- s.addArrangement ("Radio edit", true);
- s.addArrangement ("Intro loop");
- s.selectArrangement (current);
- }, false);
- saveWindow (lynx::makeArrangementsPanel (offline), "-arrangements.png");
- saveWindow (lynx::makePluginMonitorPanel (offline), "-plugin-monitor.png");
- saveWindow (lynx::makeTouchKeyboardPanel (offline), "-touch-keyboard.png");
- }
- {
- // round 142: the Newtone / Newtime editors on a synthetic sung line (A3 B3 C4 · E4), one note moved
- const auto wav = juce::File::getSpecialLocation (juce::File::tempDirectory).getChildFile ("lynx-snapshot-newtone.wav");
- {
- juce::AudioBuffer<float> line (1, 44100 * 2);
- const double hz[] = { 220.0, 246.94, 261.63, 0.0, 329.63 };
- double ph = 0.0;
- for (int i = 0; i < line.getNumSamples(); ++i)
- {
- const auto f0 = hz[std::min (4, i / 17640)];
- ph += 2.0 * juce::MathConstants<double>::pi * f0 * (1.0 + 0.004 * std::sin (2.0 * juce::MathConstants<double>::pi * 5.5 * i / 44100.0)) / 44100.0;
- float v = 0.0f;
- for (int h = 1; f0 > 0.0 && h < 8; ++h)
- v += (float) (0.3 / h * std::sin (h * ph));
- line.setSample (0, i, v);
- }
- wav.deleteFile();
- juce::WavAudioFormat format;
- std::unique_ptr<juce::OutputStream> out (wav.createOutputStream().release());
- if (auto* w = out != nullptr ? format.createWriterFor (out.get(), 44100.0, 1, 16, {}, 0) : nullptr)
- {
- out.release();
- std::unique_ptr<juce::AudioFormatWriter> writer (w);
- writer->writeFromAudioSampleBuffer (line, 0, line.getNumSamples());
- }
- }
- if (const auto sample = offline.getSampleLibrary().load (wav.getFullPathName()))
- {
- auto notes = lynx::newtonefx::analyseNotes (*sample);
- if (notes.pitches.size() > 1)
- notes.pitches[1].shift = 2.0;
- lynx::newtonefx::WarpMap warp;
- warp.frames = (std::int64_t) sample->frames();
- warp.markers = { { 22050, 33075 } };
- int at = 0;
- offline.editSong ([&] (lynx::Song& song) {
- if (song.mixer.size() < 2)
- song.mixer.resize (2);
- auto& fx = song.mixer[1].effects;
- auto tone = lynx::makeEffectSlot (lynx::EffectKind::newtone);
- tone.samplePath = wav.getFullPathName().toStdString();
- tone.state = lynx::newtonefx::writeNative (notes);
- auto time = lynx::makeEffectSlot (lynx::EffectKind::newtime);
- time.samplePath = tone.samplePath;
- time.state = lynx::newtonefx::writeWarp (warp);
- at = (int) fx.size();
- fx.push_back (tone);
- fx.push_back (time);
- }, false);
- saveWindow (lynx::makeNewtoneEditor (offline, 1, at), "-newtone.png");
- saveWindow (lynx::makeNewtoneEditor (offline, 1, at + 1), "-newtime.png");
- offline.editSong ([at] (lynx::Song& song) {
- auto& fx = song.mixer[1].effects;
- fx.erase (fx.begin() + at, fx.begin() + at + 2);
- }, false);
- }
- }
- if (! offline.getSong().automations.empty())
- {
- auto editor = lynx::makeAutomationEditor (offline, 0);
- editor->setSize (760, 300);
- saveWindow (std::move (editor), "-automation.png");
- // round 177b: the same clip in FL's LFO mode: FL's defaults, then one shaped state (the UI gate pairs)
- const auto before = offline.getSong().automations[0].lfo;
- const auto lfoShot = [&offline, &saveWindow] (std::function<void (lynx::AutomationLfo&)> set, const char* suffix) {
- offline.editSong ([&set] (lynx::Song& song) {
- auto& lfo = song.automations[0].lfo;
- lfo = lynx::AutomationLfo {};
- lfo.on = true;
- set (lfo);
- }, false);
- auto lfoEditor = lynx::makeAutomationEditor (offline, 0);
- lfoEditor->setSize (760, 346);
- saveWindow (std::move (lfoEditor), suffix);
- };
- lfoShot ([] (lynx::AutomationLfo&) {}, "-automation-lfo.png");
- lfoShot ([] (lynx::AutomationLfo& lfo) {
- // the state set through FL's own UI for the UI gate (TNS 50 %, SKEW 25 %, PW 25 %, two points), as FL saved it
- lfo.tension = 64;
- lfo.skew = 32;
- lfo.pulseWidth = 28;
- lfo.amp = { { 0, 0.6716f, 0.0f }, { (std::int64_t) (lynx::ppq * 1.4128), 0.9204f, 0.0f } };
- }, "-automation-lfo-shape.png");
- offline.editSong ([before] (lynx::Song& song) { song.automations[0].lfo = before; }, false);
- }
- // round 177b: LYNX's modulators window, with one routed modulator
- {
- offline.editSong ([] (lynx::Song& song) {
- lynx::Modulator m;
- m.name = "LFO 1";
- m.shape = lynx::ModShape::triangle;
- m.routes = { { { lynx::AutomationTargetKind::mixerVolume, 1, 0, 0 }, 0.25f }, { { lynx::AutomationTargetKind::mixerPan, 1, 0, 0 }, -0.5f } };
- song.modulators.push_back (m);
- lynx::Modulator r;
- r.name = "LFO 2";
- r.shape = lynx::ModShape::smoothRandom;
- r.sync = false;
- r.hz = 0.5;
- song.modulators.push_back (r);
- }, false);
- auto mods = lynx::makeModulatorsPanel (offline);
- mods->setSize (720, 360);
- saveWindow (std::move (mods), "-modulators.png");
- offline.editSong ([] (lynx::Song& song) { song.modulators.clear(); }, false);
- }
- saveWindow (lynx::makeChannelSettingsPanel (offline, 0), "-sampler.png");
- // the channel window frame (REA round 143b): header strip + tabs; the Misc tab of the first channel and of a synth
- saveWindow (lynx::makeChannelFrame (offline, 0), "-channel-frame.png");
- saveWindow (lynx::makeChannelFrame (offline, 0, -1), "-channel-misc.png");
- for (int c = 0; c < (int) offline.getSong().channels.size(); ++c)
- if (offline.getSong().channels[(std::size_t) c].instrument == lynx::InstrumentKind::synth)
- {
- saveWindow (lynx::makeChannelSettingsPanel (offline, c), "-synth.png");
- saveWindow (lynx::makeChannelModulationPanel (offline, c), "-modulation.png");
- break;
- }
- for (int c = 0; c < (int) offline.getSong().channels.size(); ++c)
- if (offline.getSong().channels[(std::size_t) c].instrument == lynx::InstrumentKind::controller)
- {
- saveWindow (lynx::makeChannelSettingsPanel (offline, c), "-controller.png");
- break;
- }
- for (const auto kind : { lynx::InstrumentKind::sakura, lynx::InstrumentKind::drumpad })
- for (int c = 0; c < (int) offline.getSong().channels.size(); ++c)
- if (offline.getSong().channels[(std::size_t) c].instrument == kind)
- {
- saveWindow (lynx::makeChannelSettingsPanel (offline, c), kind == lynx::InstrumentKind::sakura ? "-sakura.png" : "-drumpad.png");
- break;
- }
- // round 180c: Fruity Slicer's editor
- for (int c = 0; c < (int) offline.getSong().channels.size(); ++c)
- if (offline.getSong().channels[(std::size_t) c].instrument == lynx::InstrumentKind::fruityslicer)
- {
- saveWindow (lynx::makeChannelSettingsPanel (offline, c), "-fruityslicer.png");
- break;
- }
- // parametric EQ: the one with the most pronounced curve (in an imported .flp, with FL's settings)
- {
- int bestTrack = -1, bestSlot = -1;
- double bestShape = -1.0;
- const auto& mixer = offline.getSong().mixer;
- for (int t = 0; t < (int) mixer.size(); ++t)
- for (int s = 0; s < (int) mixer[(std::size_t) t].effects.size(); ++s)
- if (const auto& fx = mixer[(std::size_t) t].effects[(std::size_t) s]; fx.kind == lynx::EffectKind::parametricEq)
- {
- double shape = 0.0;
- for (double hz = 30.0; hz < 18000.0; hz *= 1.5)
- shape += std::abs (lynx::peq::responseDb (fx.params, 48000.0, hz));
- if (shape > bestShape)
- {
- bestShape = shape;
- bestTrack = t;
- bestSlot = s;
- }
- }
- if (bestTrack >= 0)
- saveWindow (lynx::makeParametricEqEditor (offline, bestTrack, bestSlot), "-peq.png");
- }
- // Note inspector for the Piano Roll's notes (its selection, or all of the channel's notes)
- if (auto inspector = ui.getPianoRollForSnapshot().makeNoteInspectorForSnapshot())
- saveWindow (std::move (inspector), "-noteinspector.png");
- if (auto inspector = ui.getPianoRollForSnapshot().makeNoteInspectorForSnapshot (true))
- saveWindow (std::move (inspector), "-noteinspector-one.png");
- // workflow P2: note tool dialogs (they preview on the pattern; each one puts the notes back when destroyed)
- {
- auto& roll = ui.getPianoRollForSnapshot();
- const std::pair<lynx::NoteTool, const char*> tools[] = { { lynx::NoteTool::strum, "-tool-strum.png" },
- { lynx::NoteTool::arpeggiate, "-tool-arpeggiate.png" },
- { lynx::NoteTool::flip, "-tool-flip.png" },
- { lynx::NoteTool::randomise, "-tool-randomise.png" },
- { lynx::NoteTool::scaleLevels, "-tool-scalelevels.png" },
- { lynx::NoteTool::limit, "-tool-limit.png" },
- { lynx::NoteTool::quantize, "-tool-quantize.png" },
- { lynx::NoteTool::chop, "-tool-chop.png" },
- { lynx::NoteTool::flam, "-tool-flam.png" },
- { lynx::NoteTool::lfo, "-tool-lfo.png" },
- { lynx::NoteTool::claw, "-tool-claw.png" },
- { lynx::NoteTool::articulate, "-tool-articulate.png" },
- { lynx::NoteTool::riffMachine, "-tool-riff.png" },
- { lynx::NoteTool::chordProgression, "-tool-chords.png" } };
- for (const auto& [tool, name] : tools)
- saveWindow (lynx::makeNoteToolPanel (offline, tool, roll.noteIndicesForSnapshot(), roll.gridForSnapshot()), name);
- }
- // round 83: the event editor, with sample events on the selected channel's volume (removed afterwards)
- {
- const lynx::AutomationTarget volume { lynx::AutomationTargetKind::channelVolume, offline.getSelectedChannel() };
- const auto before = offline.getSong().patterns[(std::size_t) offline.getSong().currentPattern].events;
- offline.editSong ([&] (lynx::Song& s) {
- auto& lane = lynx::eventedit::laneFor (s.patterns[(std::size_t) s.currentPattern], volume);
- lynx::eventedit::line (lane, 0, lynx::ppq * 2, 0.2f, 0.9f, lynx::ticksPerStep);
- lynx::prtools::LfoOptions lfo;
- lfo.startSpeed = 7 * 4096; // one beat
- lynx::eventedit::applyLfo (lane, lynx::ppq * 2, lynx::ppq * 4, lfo, lynx::ticksPerStep);
- }, false);
- saveWindow (lynx::makeEventEditor (offline, volume), "-eventeditor.png");
- offline.editSong ([&] (lynx::Song& s) { s.patterns[(std::size_t) s.currentPattern].events = before; }, false);
- // issue #86: the same editor on the Tempo target, with the project's own Tempo events (a sample ramp if none)
- const lynx::AutomationTarget tempo { lynx::AutomationTargetKind::tempo, 0 };
- offline.editSong ([&] (lynx::Song& s) {
- auto& lane = lynx::eventedit::laneFor (s.patterns[(std::size_t) s.currentPattern], tempo);
- if (lane.events.empty())
- lynx::eventedit::line (lane, 0, lynx::ppq * 2, 0.05f, 0.11f, lynx::ticksPerStep);
- }, false);
- saveWindow (lynx::makeEventEditor (offline, tempo), "-eventeditor-tempo.png");
- {
- auto compact = lynx::makeEventEditor (offline, tempo); // the toolbar in a small window
- compact->setSize (640, 300);
- saveWindow (std::move (compact), "-eventeditor-tempo-small.png");
- auto narrowest = lynx::makeEventEditor (offline, tempo); // the tool window's lower limit
- narrowest->setSize (400, 300);
- saveWindow (std::move (narrowest), "-eventeditor-tempo-narrowest.png");
- }
- offline.editSong ([&] (lynx::Song& s) { s.patterns[(std::size_t) s.currentPattern].events = before; }, false);
- }
- // round 86: the audio editor with a synthetic drum loop (markers, a region, a loop), waveform and spectrogram,
- // and its menu items (-audioeditor-menu.txt)
- {
- namespace ae = lynx::audioedit;
- ae::Document d;
- d.title = "Drum loop";
- d.audio.sampleRate = 44100.0;
- const auto frames = (std::size_t) (44100 * 2);
- d.audio.channels.assign (2, std::vector<float> (frames, 0.0f));
- std::uint32_t seed = 7;
- for (int hit = 0; hit < 8; ++hit)
- {
- const auto at = (std::size_t) hit * frames / 8;
- const auto kick = hit % 2 == 0;
- double phase = 0.0;
- for (std::size_t i = 0; i < 12000 && at + i < frames; ++i)
- {
- seed = seed * 1664525u + 1013904223u;
- const auto noise = (float) (seed >> 8) / 16777216.0f - 0.5f;
- const auto t = (double) i / 44100.0;
- phase += 2.0 * 3.141592653589793 * (kick ? 45.0 + 160.0 * std::exp (-t * 30.0) : 190.0) / 44100.0;
- const auto body = (float) std::sin (phase) * (float) std::exp (-t * (kick ? 9.0 : 22.0));
- const auto v = kick ? 0.85f * body : 0.35f * body + 0.6f * noise * (float) std::exp (-t * 18.0);
- d.audio.channels[0][at + i] += v;
- d.audio.channels[1][at + i] += kick ? v : v * 0.8f + 0.1f * noise * (float) std::exp (-t * 30.0);
- }
- }
- ae::addMarker (d, (std::int64_t) frames / 8, "Snare");
- ae::addRegion (d, { (std::int64_t) frames / 2, (std::int64_t) frames * 3 / 4 }, "Fill");
- ae::setLoop (d, { 0, (std::int64_t) frames });
- auto wave = lynx::makeAudioEditorForSnapshot (offline, d, false);
- juce::File (prefix + "-audioeditor-menu.txt").replaceWithText (lynx::audioEditorMenuForSnapshot (*wave).joinIntoString ("\n") + "\n");
- saveWindow (std::move (wave), "-audioeditor.png");
- saveWindow (lynx::makeAudioEditorForSnapshot (offline, d, true), "-audioeditor-spectrum.png");
- }
- // warp markers (round 175a, M3): the audio editor of the first audio clip whose channel has warp markers,
- // opened as the Playlist opens it, with its warp lane
- {
- const auto& song = offline.getSong();
- for (int i = 0; i < (int) song.playlist.size(); ++i)
- {
- const auto& c = song.playlist[(std::size_t) i];
- if (c.kind == lynx::ClipKind::audio && juce::isPositiveAndBelow (c.channel, (int) song.channels.size())
- && song.channels[(std::size_t) c.channel].sampler.warp.size() >= 3)
- {
- if (auto panel = lynx::makeAudioEditorPanel (offline, c.channel, i, true))
- saveWindow (std::move (panel), "-audioeditor-warp.png");
- break;
- }
- }
- }
- // the tempo tapper after five steady taps (round 132)
- saveWindow (lynx::makeTempoTapperForSnapshot (offline, 5, 128.0), "-tempotapper.png");
- // the Channel Rack's piano-roll view (round 132)
- ui.selectTabForSnapshot (0);
- ui.getRackForSnapshot().setPianoRollView (true);
- offline.dispatchPendingMessages();
- saveSnapshot (ui, prefix + "-rack-pianoroll-view.png");
- ui.getRackForSnapshot().setPianoRollView (false);
- // the Channel Rack with the step graph lane (velocity), and the Euclidean fill window
- ui.selectTabForSnapshot (0);
- ui.getRackForSnapshot().setGraphLevelForSnapshot (0);
- offline.dispatchPendingMessages();
- saveSnapshot (ui, prefix + "-rack-graph.png");
- ui.getRackForSnapshot().setGraphLevelForSnapshot (1);
- saveSnapshot (ui, prefix + "-rack-graph-pan.png");
- ui.getRackForSnapshot().toggleGraphLanes();
- saveWindow (ui.getRackForSnapshot().makeEuclideanPanel (0), "-euclidean.png");
- // the Mixer with three inserts selected and one armed for recording
- ui.selectTabForSnapshot (3);
- if (offline.getSong().mixer.size() > 4)
- {
- ui.getMixerForSnapshot().getStripsForSnapshot().setSelection ({ 1, 2, 3 }, 2);
- offline.setInsertArmed (3, true);
- offline.dispatchPendingMessages();
- saveSnapshot (ui, prefix + "-mixer-multi.png");
- // the armed insert with an audio input (its input row in the side panel, the level bar on the strip)
- offline.editSong ([] (lynx::Song& s) { s.mixer[3].inputChannel = 0; });
- ui.getMixerForSnapshot().selectTrack (3);
- offline.dispatchPendingMessages();
- saveSnapshot (ui, prefix + "-mixer-input.png");
- offline.undo();
- offline.setInsertArmed (3, false);
- ui.getMixerForSnapshot().getStripsForSnapshot().setSelection ({}, 0);
- }
- // the Mixer's routing lane: an insert with sends selected (send knobs and wires)
- if (offline.getSong().mixer.size() > 6)
- {
- int source = -1;
- for (int t = 1; t < (int) offline.getSong().mixer.size() && source < 0; ++t)
- if (! offline.getSong().mixer[(std::size_t) t].sends.empty())
- source = t;
- const auto temporary = source < 0;
- if (temporary) // the demo has no sends: add two for the picture
- {
- source = 1;
- offline.editSong ([] (lynx::Song& s) { s.setRoute (1, 5, true, 0.6f); s.setRoute (1, 6, true, 0.3f); s.setRoute (4, 1, true, 0.8f); });
- }
- ui.getMixerForSnapshot().selectTrack (source);
- offline.dispatchPendingMessages();
- saveSnapshot (ui, prefix + "-mixer-sends.png");
- if (temporary)
- offline.editSong ([] (lynx::Song& s) { s.setRoute (1, 5, false); s.setRoute (1, 6, false); s.setRoute (4, 1, false); });
- ui.getMixerForSnapshot().selectTrack (0);
- }
- // the Playlist with ripple editing on
- ui.selectTabForSnapshot (2);
- ui.getPlaylistForSnapshot().setRipple (true);
- saveSnapshot (ui, prefix + "-playlist-ripple.png");
- ui.getPlaylistForSnapshot().setRipple (false);
- // FL's legacy Pattern Blocks (round 170f, issue #60): the section under the clip tracks, a row per pattern
- {
- const auto saved = offline.getSong();
- offline.editSong ([] (lynx::Song& s) {
- s.patternBlocksOn = true;
- while (s.patterns.size() < 5) // a few rows to show (Drums, Bass...: copies of the demo's pattern)
- lynx::clonePattern (s, (int) s.patterns.size() - 1);
- const auto rows = juce::jmin (6, (int) s.patterns.size());
- for (int r = 0; r < rows; ++r)
- lynx::patternblocks::paintRange (s, r, (std::int64_t) (r % 3) * 4 * lynx::ppq * 2,
- (std::int64_t) (8 + r * 2) * 4 * lynx::ppq);
- }, false);
- offline.dispatchPendingMessages();
- saveSnapshot (ui, prefix + "-playlist-blocks.png");
- offline.editSong ([saved] (lynx::Song& s) { s = saved; }, false);
- offline.dispatchPendingMessages();
- }
- // quick-add palette, and the Browser searching
- saveWindow (ui.makeQuickAddForSnapshot(), "-quickadd.png");
- ui.showDesktopForSnapshot (false);
- ui.getBrowserForSnapshot().setSearchForSnapshot ("kick");
- offline.dispatchPendingMessages();
- saveSnapshot (ui, prefix + "-browser-search.png");
- ui.getBrowserForSnapshot().setSearchForSnapshot ({});
- ui.getBrowserForSnapshot().selectFirstSampleForSnapshot(); // the tree with a sample selected and its waveform
- offline.dispatchPendingMessages();
- saveSnapshot (ui, prefix + "-browser-tree.png");
- // the Browser's PROJECT tab: the patterns, generators and audio files of the project in their colours
- ui.getBrowserForSnapshot().showProjectForSnapshot();
- offline.dispatchPendingMessages();
- saveSnapshot (ui, prefix + "-browser-project.png");
- ui.getBrowserForSnapshot().showPluginDatabaseForSnapshot(); // round 142: the Plugin database's FL engines
- offline.dispatchPendingMessages();
- saveSnapshot (ui, prefix + "-browser-plugins.png");
- ui.getBrowserForSnapshot().setTab (lynx::BrowserComponent::allTab);
- saveWindow (ui.getBrowserForSnapshot().makeFoldersPanelForSnapshot(), "-browser-folders.png"); // round 164
- {
- // round 164: the content filter leaves out the folders with nothing to list (a small library)
- const auto lib = juce::File::getSpecialLocation (juce::File::tempDirectory).getChildFile ("lynx-snapshot-library");
- lib.deleteRecursively();
- for (const auto* path : { "Drums/Kicks/kick 1.wav", "Drums/Kicks/kick 2.wav", "Drums/snare.wav", "Keys/pad.sf2", "Presets/Synth/lead.fst",
- "Projects/beat.flp", "Projects/MIDI/chords.mid", "Notes/readme.txt", "Empty/Nothing/.keep" })
- lib.getChildFile (path).create();
- ui.showDesktopForSnapshot (false);
- ui.getBrowserForSnapshot().showFilterForSnapshot (lib, lynx::browserview::ContentFilter::all);
- offline.dispatchPendingMessages();
- saveSnapshot (ui, prefix + "-browser164-all.png");
- ui.getBrowserForSnapshot().showFilterForSnapshot (lib, lynx::browserview::ContentFilter::samples);
- offline.dispatchPendingMessages();
- saveSnapshot (ui, prefix + "-browser164-samples.png");
- ui.getBrowserForSnapshot().showFilterForSnapshot (lib, lynx::browserview::ContentFilter::projects);
- offline.dispatchPendingMessages();
- saveSnapshot (ui, prefix + "-browser164-projects.png");
- lib.deleteRecursively();
- ui.getBrowserForSnapshot().resetViewForSnapshot();
- }
- // the undo history after a few edits
- offline.editSong ([] (lynx::Song& s) { s.bpm += 1.0; });
- offline.editSong ([] (lynx::Song& s) { if (! s.channels.empty()) s.channels[0].muted = ! s.channels[0].muted; });
- offline.editSong ([] (lynx::Song& s) { if (! s.patterns.empty()) s.patterns[(std::size_t) s.currentPattern].notes.push_back ({}); });
- offline.undo();
- saveWindow (lynx::makeHistoryPanel (offline), "-history.png");
- // spectral waveforms: a synthetic beat (kick, hats, a chord, a noise riser) as audio clips in spectral
- // colours, zoomed in, classic and stereo; the same file in the Sampler editor and the Browser preview
- {
- const juce::File wav (prefix + "-wavedemo.wav");
- writeWaveDemo (wav, offline.getSong().bpm);
- const auto path = wav.getFullPathName();
- const auto pathUtf8 = path.toStdString();
- int samplerChannel = -1, firstTrack = 0;
- offline.editSong ([&] (lynx::Song& s) {
- for (const auto& clip : s.playlist)
- firstTrack = std::max (firstTrack, clip.track + 1);
- lynx::ChannelDef audio;
- audio.name = "Beat (audio)";
- audio.instrument = lynx::InstrumentKind::audioClip;
- audio.samplePath = pathUtf8;
- s.channels.push_back (audio);
- const auto audioChannel = (int) s.channels.size() - 1;
- lynx::ChannelDef sampler = audio;
- sampler.name = "Beat (sampler)";
- sampler.instrument = lynx::InstrumentKind::sampler;
- sampler.sampler.regionStart = 0.06f;
- sampler.sampler.regionEnd = 0.94f;
- s.channels.push_back (sampler);
- samplerChannel = (int) s.channels.size() - 1;
- const auto bar = (std::int64_t) lynx::ppq * std::max (1, s.beatsPerBar);
- const auto whole = (std::int64_t) std::llround (8.0 * s.bpm / 60.0 * lynx::ppq);
- lynx::Clip clip;
- clip.kind = lynx::ClipKind::audio;
- clip.channel = audioChannel;
- clip.track = firstTrack;
- clip.length = whole;
- s.playlist.push_back (clip);
- clip.track = firstTrack + 1; // a slice of it, later in the song
- clip.start = bar;
- clip.offset = bar;
- clip.length = 2 * bar;
- s.playlist.push_back (clip);
- // taller rows for the audio (tracks can be resized: P18)
- if ((int) s.playlistTracks.size() < firstTrack + 2)
- s.playlistTracks.resize ((std::size_t) firstTrack + 2);
- s.playlistTracks[(std::size_t) firstTrack].height = 80;
- s.playlistTracks[(std::size_t) firstTrack + 1].height = 60;
- });
- offline.dispatchPendingMessages();
- auto& cache = *lynx::ui::WaveformCache::getInstance();
- cache.find (path, [&offline, path] { return offline.getSampleLibrary().load (path); });
- cache.waitUntilIdle (30000);
- ui.selectTabForSnapshot (2);
- auto& playlist = ui.getPlaylistForSnapshot();
- playlist.setTimeSelectionForSnapshot (0, 0);
- {
- // the Playlist alone (the floating Channel Rack would cover the clips)
- auto saveSnapshot = [&playlist] (juce::Component&, const juce::String& file) { saveArea (playlist, playlist.getLocalBounds(), file); };
- playlist.setViewForSnapshot (180.0, 0, std::max (0, firstTrack - 3));
- saveSnapshot (ui, prefix + "-playlist-audio.png");
- playlist.setViewForSnapshot (1400.0, 0, std::max (0, firstTrack - 3));
- saveSnapshot (ui, prefix + "-playlist-audio-zoom.png");
- lynx::ui::WaveformCache::stereo = true;
- saveSnapshot (ui, prefix + "-playlist-audio-stereo.png");
- lynx::ui::WaveformCache::stereo = false;
- lynx::ui::WaveformCache::spectral = true;
- playlist.setViewForSnapshot (180.0, 0, std::max (0, firstTrack - 3));
- saveSnapshot (ui, prefix + "-playlist-audio-spectral.png");
- lynx::ui::WaveformCache::spectral = false;
- playlist.setViewForSnapshot (40.0, 0, 0);
- saveSnapshot (ui, prefix + "-playlist-audio-far.png");
- // LYNX_SNAPSHOT_AUDIO=a.wav;b.wav...: real audio as clips (default-height tracks, one tall,
- // a fade, a reversed copy), at three zoom levels
- if (const auto files = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_AUDIO", {}), ";", "");
- ! files.isEmpty())
- {
- const auto realTrack = firstTrack + 2;
- std::vector<juce::String> paths;
- for (const auto& f : files)
- if (juce::File (f.trim()).existsAsFile())
- paths.push_back (f.trim());
- offline.editSong ([&] (lynx::Song& s) {
- const auto bar = (std::int64_t) lynx::ppq * std::max (1, s.beatsPerBar);
- const std::uint32_t colours[] = { 0, 0xffd9a441, 0xff6fb36a, 0xffb06fd0, 0xff5fb7c9, 0xffd06f6f };
- for (std::size_t i = 0; i < paths.size(); ++i)
- {
- lynx::ChannelDef audio;
- audio.name = juce::File (paths[i]).getFileNameWithoutExtension().toStdString();
- audio.instrument = lynx::InstrumentKind::audioClip;
- audio.samplePath = paths[i].toStdString();
- audio.colour = colours[i % 6];
- audio.sampler.stretchBeats = i % 2 == 0 ? 16.0f : 0.0f; // fitted to 4 bars, or as recorded
- audio.sampler.keepPitch = true;
- s.channels.push_back (audio);
- lynx::Clip clip;
- clip.kind = lynx::ClipKind::audio;
- clip.channel = (int) s.channels.size() - 1;
- clip.track = realTrack + (int) i;
- clip.length = 4 * bar;
- clip.fadeIn = i == 1 ? bar / 2 : 0;
- s.playlist.push_back (clip);
- clip.start = 4 * bar;
- clip.fadeIn = 0;
- clip.fadeOut = i == 0 ? bar : 0;
- s.playlist.push_back (clip);
- }
- if ((int) s.playlistTracks.size() < realTrack + (int) paths.size())
- s.playlistTracks.resize ((std::size_t) realTrack + paths.size());
- if (! paths.empty())
- s.playlistTracks[(std::size_t) realTrack].height = 90;
- });
- offline.dispatchPendingMessages();
- for (const auto& path2 : paths)
- cache.find (path2, [&offline, path2] { return offline.getSampleLibrary().load (path2); });
- cache.waitUntilIdle (60000);
- playlist.setViewForSnapshot (160.0, 0, std::max (0, realTrack - 4));
- saveSnapshot (ui, prefix + "-playlist-real.png");
- playlist.setViewForSnapshot (700.0, 0, std::max (0, realTrack - 1));
- saveSnapshot (ui, prefix + "-playlist-real-zoom.png");
- playlist.setViewForSnapshot (2400.0, 0, std::max (0, realTrack - 1));
- saveSnapshot (ui, prefix + "-playlist-real-close.png");
- playlist.setViewForSnapshot (50.0, 0, std::max (0, realTrack - 4));
- saveSnapshot (ui, prefix + "-playlist-real-far.png");
- // the clip menu of the first real clip
- if (const auto menu = playlist.getClipMenuForSnapshot ((int) offline.getSong().playlist.size() - (int) paths.size() * 2); menu.getNumItems() > 0)
- saveMenus (juce::StringArray { "Audio clip" }, std::vector<juce::PopupMenu> { menu }, prefix + "-clip-menu-audio.png");
- if (const auto menu = playlist.getClipMenuForSnapshot (0); menu.getNumItems() > 0)
- saveMenus (juce::StringArray { "Pattern clip" }, std::vector<juce::PopupMenu> { menu }, prefix + "-clip-menu-pattern.png");
- // the clip menu's actions, run through the menu itself; results in -clip-actions.txt
- {
- juce::StringArray log;
- auto clipOf = [&offline] (const std::string& channelName, int nth) {
- const auto& sg = offline.getSong();
- for (int i = 0; i < (int) sg.playlist.size(); ++i)
- {
- const auto& c = sg.playlist[(std::size_t) i];
- if (c.kind == lynx::ClipKind::audio && c.channel >= 0 && sg.channels[(std::size_t) c.channel].name == channelName && nth-- == 0)
- return i;
- }
- return -1;
- };
- std::function<bool (const juce::PopupMenu&, const juce::String&)> run = [&run] (const juce::PopupMenu& m, const juce::String& text) {
- for (juce::PopupMenu::MenuItemIterator it (m); it.next();)
- {
- auto& item = it.getItem();
- if (item.subMenu != nullptr && run (*item.subMenu, text))
- return true;
- if (item.text.startsWith (text) && item.isEnabled && item.action)
- {
- item.action();
- return true;
- }
- }
- return false;
- };
- auto act = [&] (const std::string& name, int nth, const juce::String& text) {
- const auto clip = clipOf (name, nth);
- const auto ok = clip >= 0 && run (playlist.getClipMenuForSnapshot (clip), text);
- offline.dispatchPendingMessages();
- return ok;
- };
- auto channelOf = [&] (const std::string& name) -> const lynx::ChannelDef* {
- for (const auto& c : offline.getSong().channels)
- if (c.name == name)
- return &c;
- return nullptr;
- };
- auto check = [&log] (const juce::String& what, bool ok) { log.add ((ok ? "OK " : "FAIL ") + what); };
- const auto names = [&] { std::vector<std::string> n; for (auto& p2 : paths) n.push_back (juce::File (p2).getFileNameWithoutExtension().toStdString()); return n; }();
- if (names.size() >= 4)
- {
- const auto channelsBefore = offline.getSong().channels.size();
- check ("Reverse", act (names[2], 0, lynx::tr ("Reverse")) && channelOf (names[2])->sampler.reverse);
- offline.undo();
- offline.dispatchPendingMessages();
- check ("Reverse undone", ! channelOf (names[2])->sampler.reverse);
- act (names[2], 0, lynx::tr ("Reverse"));
- check ("Make unique", act (names[3], 1, lynx::tr ("Make unique")) && offline.getSong().channels.size() == channelsBefore + 1
- && channelOf (names[3] + " #2") != nullptr);
- check ("Fit to tempo, resample", act (names[1], 0, lynx::tr ("Fit to tempo, resample ({0})", { juce::String() }).upToFirstOccurrenceOf ("(", false, false))
- && channelOf (names[1])->sampler.stretchBeats > 0.0f && ! channelOf (names[1])->sampler.keepPitch);
- const auto gainBefore = offline.getSong().playlist[(std::size_t) clipOf (names[0], 1)].gain;
- check ("Normalize", act (names[0], 1, lynx::tr ("Normalize"))
- && offline.getSong().playlist[(std::size_t) clipOf (names[0], 1)].gain != gainBefore);
- const auto clipsBefore = offline.getSong().playlist.size();
- check ("Split here", act (names[3], 0, lynx::tr ("Split here")) && offline.getSong().playlist.size() == clipsBefore + 1);
- check ("Mute", act (names[0], 0, lynx::tr ("Mute")) && offline.getSong().playlist[(std::size_t) clipOf (names[0], 0)].muted);
- check ("Copy + Paste here", act (names[0], 0, lynx::tr ("Copy")) && act (names[0], 1, lynx::tr ("Paste here"))
- && offline.getSong().playlist.size() == clipsBefore + 2);
- check ("Delete", act (names[0], 2, lynx::tr ("Delete")) && offline.getSong().playlist.size() == clipsBefore + 1);
- check ("Chop to grid", act (names[3], 0, lynx::tr ("Chop to grid")) && offline.getSong().playlist.size() > clipsBefore + 1);
- }
- playlist.setViewForSnapshot (160.0, 0, std::max (0, realTrack - 4));
- saveSnapshot (ui, prefix + "-playlist-real-actions.png");
- juce::File (prefix + "-clip-actions.txt").replaceWithText (log.joinIntoString ("\n") + "\n");
- }
- }
- }
- saveWindow (lynx::makeChannelSettingsPanel (offline, samplerChannel), "-sampler-wave.png");
- ui.showDesktopForSnapshot (false);
- ui.getBrowserForSnapshot().showPreviewForSnapshot (wav);
- saveSnapshot (ui, prefix + "-browser-preview.png");
- }
- }
- // round 165o: every Label / button / tick box whose text the drawing squeezes below its minimum scale or cuts
- // (an ellipsis), per language: `LYNX --lang de --snapshot shots/de` -> shots/de-textfit.txt
- juce::File (prefix + "-textfit.txt").replaceWithText (textFitLog().joinIntoString ("\n") + "\n");
- juce::LookAndFeel::setDefaultLookAndFeel (nullptr);
- quit();
- }
- // --snapshot: 8 s of a synthetic stereo beat whose parts sit in different bands (kick = low, chord = mid,
- // hats and the noise riser = high), to show the spectral waveform colours
- static void writeWaveDemo (const juce::File& file, double bpm)
- {
- constexpr double rate = 44100.0;
- const auto frames = (int) (8.0 * rate);
- juce::AudioBuffer<float> buffer (2, frames);
- buffer.clear();
- auto* l = buffer.getWritePointer (0);
- auto* r = buffer.getWritePointer (1);
- const auto beat = 60.0 / juce::jlimit (40.0, 300.0, bpm);
- std::uint32_t noise = 0x9e3779b9u;
- auto white = [&noise] {
- noise ^= noise << 13;
- noise ^= noise >> 17;
- noise ^= noise << 5;
- return (float) (noise & 0xffffff) / (float) 0x800000 - 1.0f;
- };
- float previous = 0.0f;
- for (int i = 0; i < frames; ++i)
- {
- const auto t = i / rate;
- const auto inBeat = std::fmod (t, beat);
- const auto bar = (int) (t / (beat * 4.0));
- float left = 0.0f, right = 0.0f;
- // kick on every beat: a falling sine
- {
- const auto phase = 2.0 * juce::MathConstants<double>::pi * (48.0 * inBeat + 4.0 * (1.0 - std::exp (-inBeat * 30.0)));
- const auto k = (float) (std::sin (phase) * std::exp (-inBeat * 7.0)) * 0.85f;
- left += k;
- right += k;
- }
- // hats on the off-beats: high-passed noise bursts, a little to the right
- {
- const auto h = std::fmod (t + beat * 0.5, beat);
- const auto n = white();
- const auto hp = (n - previous) * 0.5f;
- previous = n;
- const auto hat = hp * (float) std::exp (-h * 45.0) * 0.55f;
- left += hat * 0.6f;
- right += hat;
- }
- // a chord in the second and third bars (mid band)
- if (bar == 1 || bar == 2)
- {
- const auto env = (float) std::min (1.0, std::min (t - beat * 4.0, beat * 12.0 - t) * 8.0);
- float chord = 0.0f;
- for (const auto hz : { 523.25, 659.25, 783.99 })
- chord += (float) (std::sin (2.0 * juce::MathConstants<double>::pi * hz * t) + 0.3 * std::sin (4.0 * juce::MathConstants<double>::pi * hz * t));
- left += chord * 0.09f * std::max (0.0f, env);
- right += chord * 0.09f * std::max (0.0f, env);
- }
- // a white-noise riser over the last two seconds (high band)
- if (t > 6.0)
- {
- const auto rise = (float) ((t - 6.0) / 2.0);
- left += white() * 0.4f * rise * rise;
- right += white() * 0.4f * rise * rise;
- }
- l[i] = left;
- r[i] = right;
- }
- buffer.applyGain (0.9f / juce::jmax (1.0e-6f, buffer.getMagnitude (0, frames)));
- file.deleteFile();
- juce::WavAudioFormat wav;
- if (std::unique_ptr<juce::AudioFormatWriter> writer { wav.createWriterFor (file.createOutputStream().release(), rate, 2, 24, {}, 0) })
- writer->writeFromAudioSampleBuffer (buffer, 0, frames);
- }
- // the menu bar's menus side by side, drawn with the LookAndFeel as they appear when opened
- static void saveMenus (lynx::MainComponent& ui, const juce::String& path)
- {
- const auto names = ui.getMenuNamesForSnapshot();
- std::vector<juce::PopupMenu> source;
- for (int m = 0; m < names.size(); ++m)
- source.push_back (ui.getMenuForSnapshot (m));
- saveMenus (names, source, path);
- }
- // menus side by side, each under its name
- static void saveMenus (const juce::StringArray& names, const std::vector<juce::PopupMenu>& source, const juce::String& path)
- {
- auto& lf = juce::LookAndFeel::getDefaultLookAndFeel();
- struct Laid
- {
- juce::PopupMenu menu;
- int width = 0, height = 0;
- };
- std::vector<Laid> menus;
- const auto border = lf.getPopupMenuBorderSize();
- for (int m = 0; m < names.size(); ++m)
- {
- Laid laid { source[(std::size_t) m] };
- int width = 160, height = 2 * border;
- for (juce::PopupMenu::MenuItemIterator it (laid.menu); it.next();)
- {
- const auto& item = it.getItem();
- int w = 0, h = 0;
- lf.getIdealPopupMenuItemSize (item.text, item.isSeparator, item.isSectionHeader ? -1 : 0, w, h);
- if (item.isSectionHeader) h += h / 2; // as JUCE does
- if (item.shortcutKeyDescription.isNotEmpty() || item.text.containsChar ('\t'))
- w += 90;
- width = juce::jmax (width, w + 10);
- height += h;
- }
- laid.width = width;
- laid.height = height;
- menus.push_back (std::move (laid));
- }
- int totalWidth = 16, totalHeight = 0;
- for (const auto& l : menus)
- {
- totalWidth += l.width + 16;
- totalHeight = juce::jmax (totalHeight, l.height + 32);
- }
- juce::Image image (juce::Image::ARGB, totalWidth, totalHeight, true);
- {
- juce::Graphics g (image);
- g.fillAll (lynx::theme::colour::bg1);
- int x = 16;
- for (int m = 0; m < (int) menus.size(); ++m)
- {
- const auto& l = menus[(std::size_t) m];
- g.setColour (lynx::theme::colour::textSecondary);
- g.setFont (lynx::theme::font (lynx::theme::type::small, true));
- g.drawText (names[m], x, 0, l.width, 24, juce::Justification::centredLeft);
- {
- juce::Graphics::ScopedSaveState state (g);
- g.reduceClipRegion (x, 24, l.width, l.height);
- g.setOrigin (x, 24);
- lf.drawPopupMenuBackground (g, l.width, l.height);
- int y = border;
- bool first = true;
- for (juce::PopupMenu::MenuItemIterator it (l.menu); it.next();)
- {
- const auto& item = it.getItem();
- int w = 0, h = 0;
- lf.getIdealPopupMenuItemSize (item.text, item.isSeparator, item.isSectionHeader ? -1 : 0, w, h);
- if (item.isSectionHeader) h += h / 2; // as JUCE does
- const juce::Rectangle<int> r (0, y, l.width, h);
- auto text = item.text, shortcut = item.shortcutKeyDescription;
- if (text.containsChar ('\t'))
- {
- shortcut = text.fromFirstOccurrenceOf ("\t", false, false);
- text = text.upToFirstOccurrenceOf ("\t", false, false);
- }
- if (item.isSectionHeader)
- lf.drawPopupMenuSectionHeader (g, r, text);
- else
- lf.drawPopupMenuItem (g, r, item.isSeparator, item.isEnabled, first && ! item.isSeparator && m == 0, item.isTicked,
- item.subMenu != nullptr, text, shortcut, item.image.get(), nullptr);
- first = false;
- y += h;
- }
- }
- x += l.width + 16;
- }
- }
- const juce::File file (path);
- file.deleteFile();
- juce::PNGImageFormat png;
- if (auto out = file.createOutputStream())
- png.writeImageToStream (image, *out);
- }
- static void writePng (const juce::Image& image, const juce::String& path)
- {
- const juce::File file (path);
- file.deleteFile();
- juce::PNGImageFormat png;
- if (auto out = file.createOutputStream())
- png.writeImageToStream (image, *out);
- }
- // the splash screen: one settled frame, and a strip of frames through its animation
- static void saveSplashFrames (const juce::String& prefix)
- {
- lynx::SplashScreen splash;
- splash.setStatus (lynx::tr ("Loading the workspace..."));
- splash.setTimeForSnapshot (1.6);
- writePng (splash.createComponentSnapshot (splash.getLocalBounds()), prefix + "-splash.png");
- const double times[] = { 0.10, 0.22, 0.29, 0.40, 0.58, 0.75, 1.00, 1.30 };
- const auto w = lynx::SplashScreen::width / 2, h = lynx::SplashScreen::height / 2;
- juce::Image strip (juce::Image::ARGB, 4 * (w + 8) + 8, 2 * (h + 8) + 8, true);
- {
- juce::Graphics g (strip);
- g.fillAll (lynx::theme::colour::bg1);
- for (int i = 0; i < 8; ++i)
- {
- splash.setTimeForSnapshot (times[i]);
- const auto frame = splash.createComponentSnapshot (splash.getLocalBounds());
- g.drawImage (frame, 8 + (i % 4) * (w + 8), 8 + (i / 4) * (h + 8), w, h, 0, 0, frame.getWidth(), frame.getHeight());
- }
- }
- writePng (strip, prefix + "-splash-frames.png");
- }
- // every icon at 16, 20 and 24 px (at `scale`, e.g. 1.5 for a 150% display), in the toolbar's
- // colours: at rest, hovered and switched on
- static void saveIconSheet (const juce::String& path, float scale)
- {
- const int sizes[] = { 16, 20, 24 };
- const int cell = 34, columns = 3 * 3, labelWidth = 110;
- const auto w = labelWidth + columns * cell + 16, h = lynx::iconCount * cell + 16;
- juce::Image image (juce::Image::ARGB, juce::roundToInt ((float) w * scale), juce::roundToInt ((float) h * scale), true);
- {
- juce::Graphics g (image); // (drawing is flushed when it goes out of scope)
- g.addTransform (juce::AffineTransform::scale (scale));
- g.fillAll (lynx::theme::colour::bg3);
- g.setFont (lynx::theme::font (lynx::theme::type::small));
- for (int i = 1; i < lynx::iconCount; ++i)
- {
- const auto y = 8 + (i - 1) * cell;
- g.setColour (lynx::theme::colour::textDisabled);
- g.drawText (juce::String (i), 8, y, labelWidth - 8, cell, juce::Justification::centredLeft);
- for (int v = 0; v < 3; ++v)
- for (int s = 0; s < 3; ++s)
- {
- const juce::Rectangle<float> box ((float) (labelWidth + (v * 3 + s) * cell), (float) y, (float) cell, (float) cell);
- const auto bg = v == 2 ? lynx::theme::colour::accent : v == 1 ? lynx::theme::colour::bg5 : lynx::theme::colour::bg3;
- g.setColour (bg);
- g.fillRoundedRectangle (box.reduced (2.0f), 4.0f);
- const auto fg = v == 2 ? lynx::theme::colour::onAccent : v == 1 ? lynx::theme::colour::textPrimary
- : lynx::theme::colour::textSecondary.brighter (0.25f);
- lynx::icons::draw (g, (lynx::Icon) i, box.withSizeKeepingCentre ((float) sizes[s], (float) sizes[s]), fg);
- }
- }
- }
- writePng (image, path);
- }
- // a part of a component (e.g. the main toolbar)
- static void saveArea (juce::Component& c, juce::Rectangle<int> area, const juce::String& path)
- {
- const juce::File file (path);
- file.deleteFile();
- juce::PNGImageFormat png;
- if (auto out = file.createOutputStream())
- png.writeImageToStream (c.createComponentSnapshot (area), *out);
- }
- static void savePng (const juce::Image& image, const juce::String& path)
- {
- const juce::File file (path);
- file.deleteFile();
- juce::PNGImageFormat png;
- if (auto out = file.createOutputStream())
- png.writeImageToStream (image, *out);
- }
- // -toolbar-tips.png: the top of the window with the bubbles of a few controls as they appear under the
- // mouse; -tips-sheet.png: every quick tip of the window, to check names, shortcuts and translations
- static void saveQuickTips (lynx::MainComponent& ui, const juce::String& prefix)
- {
- const auto tips = ui.getQuickTipsForSnapshot();
- const auto top = juce::Rectangle<int> (0, 0, ui.getWidth(), juce::jmin (ui.getHeight(), ui.getToolbarBoundsForSnapshot().getHeight() + 72));
- auto image = ui.createComponentSnapshot (top);
- {
- juce::Graphics g (image);
- const juce::String shown[] = { lynx::tr ("Pattern mode"), lynx::tr ("Play"), lynx::tr ("Metronome"), lynx::tr ("Mixer"), lynx::tr ("Save project"),
- lynx::tr ("Window options"), lynx::tr ("Close") };
- std::vector<juce::Rectangle<int>> used;
- for (const auto& [area, tip] : tips)
- {
- const auto name = tip.upToFirstOccurrenceOf ("\t", false, false);
- if (std::find (std::begin (shown), std::end (shown), name) == std::end (shown))
- continue;
- const auto bubble = lynx::ui::quickTipBounds (tip, area, top);
- if (std::any_of (used.begin(), used.end(), [&] (const auto& r) { return r.intersects (bubble); }))
- continue;
- used.push_back (bubble);
- g.setColour (juce::Colours::white.withAlpha (0.075f)); // the hovered control
- g.fillRoundedRectangle (area.toFloat().reduced (0.5f), lynx::theme::radius::md);
- lynx::ui::paintQuickTip (g, bubble.toFloat(), tip);
- }
- }
- savePng (image, prefix + "-toolbar-tips.png");
- // the sheet: bubbles in rows
- const int width = 900;
- int x = 12, y = 12;
- std::vector<std::pair<juce::Rectangle<int>, juce::String>> placed;
- for (const auto& [area, tip] : tips)
- {
- auto r = lynx::ui::quickTipSize (tip);
- if (x + r.getWidth() > width - 12)
- {
- x = 12;
- y += r.getHeight() + 10;
- }
- placed.emplace_back (r.withPosition (x, y), tip);
- x += r.getWidth() + 10;
- }
- juce::Image sheet (juce::Image::ARGB, width, y + 20 + 12, true);
- {
- juce::Graphics g (sheet);
- g.fillAll (lynx::theme::colour::bg3);
- for (const auto& [r, tip] : placed)
- lynx::ui::paintQuickTip (g, r.toFloat(), tip);
- }
- savePng (sheet, prefix + "-tips-sheet.png");
- }
- static juce::StringArray& textFitLog()
- {
- static juce::StringArray log;
- return log;
- }
- // drawFittedText would shrink `text` below `minScale` or cut it: fewer visible glyphs than the text has
- static bool textIsCut (const juce::Font& font, const juce::String& text, juce::Rectangle<int> area, int maxLines, float minScale)
- {
- if (text.trim().isEmpty() || area.getWidth() <= 4 || area.getHeight() <= 4)
- return false;
- auto visible = [] (juce::GlyphArrangement& ga) {
- int n = 0;
- for (int i = 0; i < ga.getNumGlyphs(); ++i)
- n += ga.getGlyph (i).isWhitespace() ? 0 : 1;
- return n;
- };
- juce::GlyphArrangement fitted, full;
- fitted.addFittedText (font, text, 0.0f, 0.0f, (float) area.getWidth(), (float) area.getHeight(), juce::Justification::centredLeft,
- juce::jmax (1, maxLines), minScale);
- full.addLineOfText (font, text, 0.0f, 0.0f);
- return visible (fitted) < visible (full);
- }
- // walks the visible components under `root` and logs the texts that don't fit (labels, text buttons, tick boxes)
- static void checkTextFit (juce::Component& root, const juce::String& where)
- {
- std::function<void (juce::Component&)> visit = [&] (juce::Component& c) {
- if (! c.isVisible() || c.getWidth() <= 0 || c.getHeight() <= 0)
- return;
- juce::String text;
- bool cut = false;
- if (auto* label = dynamic_cast<juce::Label*> (&c); label != nullptr && ! label->isBeingEdited())
- {
- const auto font = label->getLookAndFeel().getLabelFont (*label);
- const auto area = label->getBorderSize().subtractedFrom (label->getLocalBounds());
- text = label->getText();
- cut = textIsCut (font, text, area, juce::jmax (1, (int) ((float) area.getHeight() / font.getHeight())),
- label->getMinimumHorizontalScale());
- }
- else if (auto* toggle = dynamic_cast<juce::ToggleButton*> (&c))
- {
- const auto tick = juce::jmin (16.0f, (float) c.getHeight() - 4.0f);
- text = toggle->getButtonText();
- cut = textIsCut (juce::Font (lynx::theme::font (juce::jmin ((float) lynx::theme::type::body, (float) c.getHeight() * 0.75f))), text,
- c.getLocalBounds().withTrimmedLeft (juce::roundToInt (tick) + 8).withTrimmedRight (2), 2, 0.85f);
- }
- else if (auto* button = dynamic_cast<juce::TextButton*> (&c);
- button != nullptr && (int) button->getProperties().getWithDefault (lynx::theme::LookAndFeel::iconProperty, 0) == 0)
- {
- text = button->getButtonText();
- cut = textIsCut (button->getLookAndFeel().getTextButtonFont (*button, button->getHeight()), text,
- button->getLocalBounds().reduced (juce::jmin (8, button->getWidth() / 6), 0), 2, 0.85f);
- }
- if (cut)
- {
- juce::String path;
- for (auto* p = &c; p != nullptr && p != &root; p = p->getParentComponent())
- if (p->getName().isNotEmpty())
- path = p->getName() + (path.isEmpty() ? "" : "/") + path;
- const auto line = where + " | " + juce::String (c.getWidth()) + "x" + juce::String (c.getHeight()) + " | " + text.replace ("\n", "\\n")
- + (path.isEmpty() ? juce::String() : " | " + path);
- textFitLog().addIfNotAlreadyThere (line);
- }
- for (auto* child : c.getChildren())
- visit (*child);
- };
- visit (root);
- }
- static void saveSnapshot (juce::Component& c, const juce::String& path)
- {
- checkTextFit (c, juce::File (path).getFileNameWithoutExtension());
- const juce::File file (path);
- file.deleteFile();
- juce::PNGImageFormat png;
- if (auto out = file.createOutputStream())
- png.writeImageToStream (c.createComponentSnapshot (c.getLocalBounds()), *out);
- }
- class MainWindow final : public juce::DocumentWindow
- {
- public:
- MainWindow (const juce::String& name, lynx::AudioEngine& engine)
- : DocumentWindow (name, lynx::theme::window, DocumentWindow::allButtons)
- {
- setUsingNativeTitleBar (true);
- setIcon (lynx::logoImage());
- content = new lynx::MainComponent (engine);
- setContentOwned (content, true);
- setResizable (true, true);
- setResizeLimits (800, 400, 10000, 10000);
- // ~88% of the main display's usable area (at least the UI's design size, but never larger than the
- // display: the AppImage catalog test runs on an 800x600 screen)
- if (const auto* display = juce::Desktop::getInstance().getDisplays().getPrimaryDisplay())
- {
- const auto area = display->userArea;
- const auto fit = [] (int design, int available) {
- return juce::jmin (available, juce::jmax (design, (int) (available * 0.88)));
- };
- setSize (fit (getWidth(), area.getWidth()), fit (getHeight(), area.getHeight()));
- }
- centreWithSize (getWidth(), getHeight());
- // where it was last time (round 167v); the first start opens maximized, the Playlist filling the screen
- // with the Browser at the left and the Channel Rack above it, like FL Studio's first start
- const auto saved = stateFile().loadFileAsString().trim();
- // (LYNX_TEST_MODE keeps the fixed-size window scripted checks expect, unless LYNX_TEST_MAXIMIZE=1)
- const auto firstStart = saved.isEmpty()
- && (! lynx::platform::testMode() || juce::SystemStats::getEnvironmentVariable ("LYNX_TEST_MAXIMIZE", {}) == "1");
- maximiseOnReveal = firstStart || saved.startsWithIgnoreCase ("fs");
- if (saved.isNotEmpty())
- restoreWindowStateFromString (saved.startsWithIgnoreCase ("fs") ? saved.substring (2).trim() : saved);
- }
- // Shows the window (built hidden while the splash screen is up).
- void reveal()
- {
- if (lynx::uitrace::enabled()) // LYNX_TRACE_UI: the frames per second and the longest gap in ui.log (round 173f)
- watchFrames ({});
- setVisible (true);
- lynx::applyWindowChrome (*this);
- lynx::fitWindowOnScreen (*this); // a size saved at another UI zoom still fits (round 163)
- if (maximiseOnReveal)
- setFullScreen (true); // (a title-bar window: maximized, the taskbar stays)
- toFront (true);
- content->grabKeyboardFocus();
- // issue #62: the detached panels restored with the layout (built before this window was shown): their saved
- // place and above it, once the window manager has placed this one
- juce::Timer::callAfterDelay (250, [safe = juce::Component::SafePointer<MainWindow> (this)] {
- if (safe != nullptr)
- safe->content->restoreDetachedWindows();
- });
- }
- // The window's place and maximized state for the next start (main-window.txt in the settings folder).
- void saveState() { stateFile().replaceWithText (getWindowStateAsString()); }
- static juce::File stateFile() { return lynx::PluginHost::settingsFolder().getChildFile ("main-window.txt"); }
- void openFile (const juce::File& file) { content->openFile (file); }
- lynx::MainComponent& getContent() { return *content; }
- void showSetupWizard() { content->showSetupWizard(); }
- void confirmDiscard (std::function<void()> then) { content->confirmDiscard (std::move (then)); }
- void closeButtonPressed() override { JUCEApplication::getInstance()->systemRequestedQuit(); }
- // Every frame the window paints, with its dirty area (ui/FrameProbe.h; --uiperf, LYNX_TRACE_UI). The trace keeps
- // counting when --uiperf watches too.
- void watchFrames (std::function<void (double, juce::Rectangle<int>)> callback)
- {
- if (probe == nullptr)
- {
- probe = std::make_unique<lynx::ui::FrameProbe>();
- Component::addAndMakeVisible (*probe); // (ResizableWindow hides the plain overload)
- probe->setBounds (getLocalBounds());
- }
- probe->onFrame = [callback = std::move (callback)] (double now, juce::Rectangle<int> area) {
- if (lynx::uitrace::enabled())
- lynx::uitrace::frame (now);
- if (callback)
- callback (now, area);
- };
- }
- void resized() override
- {
- DocumentWindow::resized();
- if (probe != nullptr)
- probe->setBounds (getLocalBounds());
- }
- // --uiperf: the time of each frame the window paints (its own paint, then every child's, up to the last)
- std::function<void (double)> onFrame;
- void paint (juce::Graphics& g) override
- {
- if (onFrame)
- frameStart = juce::Time::getMillisecondCounterHiRes();
- DocumentWindow::paint (g);
- }
- void paintOverChildren (juce::Graphics& g) override
- {
- DocumentWindow::paintOverChildren (g);
- if (onFrame && frameStart > 0.0)
- onFrame (juce::Time::getMillisecondCounterHiRes() - frameStart);
- frameStart = 0.0;
- }
- private:
- lynx::MainComponent* content = nullptr; // owned by the window
- std::unique_ptr<lynx::ui::FrameProbe> probe; // (on top of the content; see watchFrames)
- double frameStart = 0.0;
- bool maximiseOnReveal = false;
- JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MainWindow)
- };
- lynx::theme::LookAndFeel lookAndFeel;
- std::unique_ptr<lynx::AudioEngine> engine;
- std::unique_ptr<juce::XmlElement> savedDeviceState; // --rtstress: the user's device before this run's --type/--buffer
- // Hidden test mode --asiodll "<driver.dll>[|{CLSID}]" (REA round 97): an ASIO driver loaded straight from its file,
- // without registering it, listed as the driver type "ASIO driver file". True when one was added.
- bool addDriverFileDeviceType()
- {
- const auto args = juce::JUCEApplication::getCommandLineParameterArray();
- const auto i = args.indexOf ("--asiodll");
- if (i < 0 || i + 1 >= args.size() || engine == nullptr)
- return false;
- auto& devices = engine->getDeviceManager();
- devices.getAvailableDeviceTypes(); // creates the standard types first
- for (auto* t : devices.getAvailableDeviceTypes())
- if (t->getTypeName() == lynx::dllAsioTypeName)
- return true;
- auto type = lynx::makeDllAsioDeviceType (args[i + 1].unquoted());
- if (type == nullptr)
- return false;
- devices.addAudioDeviceType (std::move (type));
- return true;
- }
- void restoreSavedDeviceState()
- {
- if (engine != nullptr)
- engine->restoreAudioDeviceState (savedDeviceState.get());
- }
- std::unique_ptr<MainWindow> mainWindow;
- std::unique_ptr<juce::Timer> perf; // --uiperf
- std::unique_ptr<lynx::SplashScreen> splash;
- double splashDuration = lynx::SplashScreen::minimumDuration; // seconds of its clock (round 121: from the process start)
- lynx::StartupOptions startupOptions;
- juce::File fileToOpen;
- bool startupFileHandled = false;
- juce::File openTimeReport; // --opentime
- int openTimeIdleSeconds = 10;
- };
- START_JUCE_APPLICATION (LynxApplication)
|