Main.cpp 702 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527
  1. #include <juce_gui_basics/juce_gui_basics.h>
  2. #include "engine/FileSort.h"
  3. #include "platform/Paths.h"
  4. #include "core/PlaylistOps.h"
  5. #include "core/Comping.h"
  6. #include "core/Drumaxx.h"
  7. #include "core/PatternBlocks.h"
  8. #include "core/LoadTrace.h"
  9. #include "core/ProjectSafety.h"
  10. #include "core/Patcher.h"
  11. #include "core/Patcherize.h"
  12. #include "core/Performance.h"
  13. #include "core/VideoPlayer.h"
  14. #include "core/Effects.h"
  15. #include "core/MixSuite.h"
  16. #include "core/HardwareInsert.h"
  17. #include "core/EchoSuite.h"
  18. #include "core/LynxTune.h"
  19. #include "core/FlEffects.h"
  20. #include "core/FlpImport.h"
  21. #include "core/NoteEdit.h"
  22. #include "core/MaximusFx.h"
  23. #include "core/Harmor.h"
  24. #include "flp/Flp.h"
  25. #include "core/SynthPresets.h"
  26. #include "core/FlWrapper.h"
  27. #include "engine/AudioEngine.h"
  28. #include "engine/Metronome.h"
  29. #include "engine/AudioLogger.h"
  30. #include "engine/DllAsioDevice.h"
  31. #include "engine/PipeWireDevice.h"
  32. #include "platform/LinuxRealtime.h"
  33. #include "engine/Exporter.h"
  34. #include "engine/FlStudioExport.h"
  35. #include "engine/MidiFileIo.h"
  36. #include "engine/PluginHost.h"
  37. #include "engine/PluginSandbox.h"
  38. #include "engine/Bridge32Test.h"
  39. #include "engine/ProjectFile.h"
  40. #include "core/Sha256.h"
  41. #include "engine/SessionPack.h"
  42. #include "engine/LiveTest.h"
  43. #include "core/SessionIds.h"
  44. #include "core/SessionParts.h"
  45. #include "engine/SampleLibrary.h"
  46. #include "engine/Text.h"
  47. #include "platform/FileTypes.h"
  48. #include "platform/Package.h"
  49. #include "core/AlsImport.h"
  50. #include "ui/AlsExportDialog.h"
  51. #include "ui/GamepadInput.h"
  52. #include "ui/SettingsPages.h"
  53. #include "ui/OtherAppsExport.h"
  54. #include "ui/TimerWhileShowing.h"
  55. #include "ui/MixerBasicsCheck.h"
  56. #include "ui/VideoPlayerView.h"
  57. #include "ui/VideoMedia.h"
  58. #include "ui/VideoTracks.h"
  59. #include "ui/AdrWindow.h"
  60. #include "ui/PlaylistComponent.h"
  61. #include "ui/PatcherEditor.h"
  62. #include "ui/VisualEditors.h"
  63. #include "ui/FlExtraEditors.h"
  64. #include "ui/VisualGl.h"
  65. #include "ui/DanceView.h"
  66. #include "ui/PluginPresetMenu.h"
  67. #include "ui/PluginWindow.h"
  68. #include "ui/NativeChild.h"
  69. #include "ui/Workspace.h"
  70. #include "ui/PluginThumbs.h"
  71. #include "ui/ClipProperties.h"
  72. #include "ui/NewProjectDialog.h"
  73. #include "ui/PluginMonitorWindow.h"
  74. #include "ui/TouchKeyboard.h"
  75. #include "ui/AutomationUi.h"
  76. #include "ui/PluginSkin.h"
  77. #include "ui/ChannelSettings.h"
  78. #include "core/LynxBanks.h"
  79. #include "core/NativeEngines.h"
  80. #include "ui/ControllerEditors.h"
  81. #include "ui/NewtoneEditor.h"
  82. #include "core/NewtoneFx.h"
  83. #include "core/FormulaController.h"
  84. #include "core/MidiControls.h"
  85. #include "core/FlSynths.h"
  86. #include "core/SoundFont.h"
  87. #include "core/Sfz.h"
  88. #include "ui/Dialogs.h"
  89. #include "ui/FileChoosers.h"
  90. #include "ui/TrackIcons.h"
  91. #include "core/RackOps.h"
  92. #include "core/Layer.h"
  93. #include "core/XyController.h"
  94. #include "core/FlCurve.h"
  95. #include "core/ControlSurface.h"
  96. #include "core/VoltageController.h"
  97. #include "ui/Controllers164.h"
  98. #include "ui/ExportDialog.h"
  99. #include "ui/QuickAddPalette.h"
  100. #include "ui/I18n.h"
  101. #include "ui/MainComponent.h"
  102. #include "ui/MidiToolsPanel.h"
  103. #include "ui/FrameProbe.h"
  104. #include "ui/UiTrace.h"
  105. #include "core/MixerOps.h"
  106. #include "ui/QuickPick.h"
  107. #include "core/NoteTools.h"
  108. #include "engine/ProjectPackage.h"
  109. #include "ui/SetupWizard.h"
  110. #include "engine/FlStudio.h"
  111. #include "ui/HistoryPanel.h"
  112. #include "ui/MissingFilesDialog.h"
  113. #include "ui/SettingsDialog.h"
  114. #include "ui/PluginManager.h"
  115. #include "ui/ShortcutManager.h"
  116. #include "ui/NoteToolDialogs.h"
  117. #include "ui/EventEditor.h"
  118. #include "ui/AudioEditor.h"
  119. #include "ui/TempoTapper.h"
  120. #include "core/EventEdit.h"
  121. #include "core/FacetEq.h"
  122. #include "ui/FacetEqEditor.h"
  123. #include "core/RackRenderer.h"
  124. #include "ui/ProEditors.h"
  125. #include "ui/ParametricEqEditor.h"
  126. #include "ui/PluginEditors.h"
  127. #include "core/PluginLayout.h"
  128. #include "core/EffectPresets.h"
  129. #include "core/Vfx.h"
  130. #include "ui/Splash.h"
  131. #include "ui/Theme.h"
  132. #include "ui/ThemeSettings.h"
  133. #include "ui/WaveformView.h"
  134. #include "ui/WindowOwner.h"
  135. #include "ui/PluginKeysTest.h"
  136. #include "ui/Toolbar.h"
  137. #include "ui/ToolWindow.h"
  138. #include "platform/CrashGuard.h"
  139. #include "ui/CrashReporter.h"
  140. #include "ui/Updater.h"
  141. #include "ui/StemExtract.h"
  142. #include "ui/AudioToMidi.h"
  143. #include <atomic>
  144. #include <chrono>
  145. #include <cstdio>
  146. #include <cstdlib>
  147. #include <mutex>
  148. #include <thread>
  149. namespace
  150. {
  151. lynx::AudioEngine* crashEngine = nullptr;
  152. // Startup trace (REA round 116): with LYNX_TRACE_STARTUP set, the time of each startup step since the C++ runtime
  153. // started is written to %APPDATA%\LYNX\startup.log (the loader's own time before that is not included).
  154. struct StartupTrace
  155. {
  156. using clock = std::chrono::steady_clock;
  157. const clock::time_point t0 = clock::now(); // static initialisation: no JUCE yet, standard library only
  158. const bool on = std::getenv ("LYNX_TRACE_STARTUP") != nullptr;
  159. juce::String text;
  160. clock::time_point last = t0;
  161. double seconds() const { return std::chrono::duration<double> (clock::now() - t0).count(); } // since the process started
  162. void mark (const char* step)
  163. {
  164. if (! on)
  165. return;
  166. const auto now = clock::now();
  167. const auto ms = [] (clock::duration d) { return std::chrono::duration<double, std::milli> (d).count(); };
  168. text << juce::String (ms (now - t0), 1).paddedLeft (' ', 8) << " ms +" << juce::String (ms (now - last), 1).paddedLeft (' ', 7) << " " << step << "\n";
  169. last = now;
  170. lynx::platform::settingsFile ("startup.log").replaceWithText (text);
  171. }
  172. };
  173. StartupTrace startupTrace;
  174. void startupMarkHook (const char* step) { startupTrace.mark (step); }
  175. // Crashed: try to save the project and write the backtrace (like FL's "emergency save").
  176. void onCrash (void* exceptionPointers)
  177. {
  178. const auto folder = lynx::platform::settingsFile ("autosave");
  179. folder.createDirectory();
  180. const auto stamp = juce::Time::getCurrentTime().formatted ("%Y-%m-%d %H-%M-%S");
  181. // JUCE's backtrace (named frames only), then every frame of the faulting thread as module+offset (round 157a: a
  182. // release LYNX.exe has no symbols, so its own frames were missing from the file)
  183. folder.getChildFile ("crash " + stamp + ".txt").replaceWithText (juce::SystemStats::getStackBacktrace() + "\n--- frames (module+offset)\n"
  184. + juce::String::fromUTF8 (lynx::crashguard::exceptionBacktrace (exceptionPointers).c_str()));
  185. lynx::crashguard::note (("crashed: backtrace in autosave\\crash " + stamp + ".txt").toStdString());
  186. if (crashEngine != nullptr)
  187. {
  188. juce::String error;
  189. lynx::ProjectFile::save (crashEngine->getSong(), folder.getChildFile ("recovered " + stamp + lynx::ProjectFile::extension), error);
  190. }
  191. }
  192. juce::File sessionsFolder()
  193. {
  194. return lynx::PluginHost::settingsFolder().getChildFile ("sessions");
  195. }
  196. // Sessions of earlier runs whose process is gone without closing (a fail-fast, a crash, a forced end): each is appended
  197. // to %APPDATA%\LYNX\crash-history.log and its file removed. Returns the last step of the newest one ("" when none).
  198. juce::StringArray uncleanSteps; // the newest unclean session's steps (without their times)
  199. juce::String uncleanSessionText; // the newest unclean session's whole file (round 159: the crash report reads it)
  200. // What the newest unclean session tells (round 157a): the plugin whose editor was opening / shown when it ended, and
  201. // whether its crash file blames a graphics driver
  202. struct UncleanCause
  203. {
  204. juce::String editorPlugin; // the last steps were that plugin's editor
  205. bool gpuDriver = false; // the crash file's top frames are in a GPU driver / Direct3D / Direct2D module
  206. juce::String driverModule;
  207. };
  208. UncleanCause uncleanCause()
  209. {
  210. UncleanCause cause;
  211. juce::File crashFile;
  212. for (int i = uncleanSteps.size(); --i >= 0 && i >= uncleanSteps.size() - 4;)
  213. {
  214. const auto& step = uncleanSteps[i];
  215. if (step.startsWith ("crashed: backtrace in "))
  216. crashFile = lynx::platform::settingsFolder().getChildFile (step.fromFirstOccurrenceOf ("backtrace in ", false, false).replaceCharacter ('\\', '/'));
  217. for (const auto* prefix : { "opening the editor of ", "editor open: ", "editor shown: " })
  218. if (cause.editorPlugin.isEmpty() && step.startsWith (prefix))
  219. cause.editorPlugin = step.fromFirstOccurrenceOf (prefix, false, false).trim();
  220. if (step.startsWith ("closing the editor of ") || step.startsWith ("loaded plugin") || step.startsWith ("opening project"))
  221. break; // older steps than these did not end the session
  222. }
  223. // issue #32 (round 174a): a plugin whose editor already faulted in this session (caught, LYNX went on) is the
  224. // likely cause when the session then ended without a word: offer it a separate process too
  225. for (int i = uncleanSteps.size(); --i >= 0 && cause.editorPlugin.isEmpty();)
  226. if (const auto editor = lynx::crashreport::parseEditorCrashStep (uncleanSteps[i].toStdString()); ! editor.plugin.empty())
  227. cause.editorPlugin = juce::String::fromUTF8 (editor.plugin.c_str());
  228. if (crashFile.existsAsFile())
  229. {
  230. // the first frames after the crash handler's own (the "--- frames" part lists the faulting thread)
  231. auto text = crashFile.loadFileAsString();
  232. if (text.contains ("--- frames"))
  233. text = text.fromFirstOccurrenceOf ("--- frames", false, false);
  234. auto lines = juce::StringArray::fromLines (text);
  235. int looked = 0;
  236. for (const auto& line : lines)
  237. {
  238. const auto module = line.fromFirstOccurrenceOf (": ", false, false).upToFirstOccurrenceOf ("+", false, false).trim().toLowerCase();
  239. if (module.isEmpty() || ! module.endsWith (".dll"))
  240. continue;
  241. if (++looked > 12)
  242. break;
  243. for (const auto* driver : { "igd", "ig9icd", "ig7icd", "igxelp", "nvwgf2um", "nvoglv", "nvd3dum", "atidxx", "atio6axx", "amdxx", "aticfx",
  244. "d3d11.dll", "d3d10warp", "dxgi.dll", "d2d1.dll", "opengl32.dll", "dcomp.dll" })
  245. if (module.startsWith (driver))
  246. {
  247. cause.gpuDriver = true;
  248. cause.driverModule = module;
  249. break;
  250. }
  251. if (cause.gpuDriver)
  252. break;
  253. }
  254. }
  255. return cause;
  256. }
  257. juce::String collectUncleanSessions()
  258. {
  259. juce::String lastStep;
  260. juce::Time newest;
  261. for (const auto& file : sessionsFolder().findChildFiles (juce::File::findFiles, false, "session-*.txt"))
  262. {
  263. const auto text = file.loadFileAsString();
  264. juce::StringPairArray values;
  265. juce::StringArray steps;
  266. for (const auto& line : juce::StringArray::fromLines (text))
  267. {
  268. if (line.startsWith ("step="))
  269. steps.add (line.fromFirstOccurrenceOf ("=", false, false));
  270. else if (line.contains ("="))
  271. values.set (line.upToFirstOccurrenceOf ("=", false, false), line.fromFirstOccurrenceOf ("=", false, false));
  272. }
  273. const auto pid = (std::uint32_t) values["pid"].getLargeIntValue();
  274. const auto start = (std::uint64_t) values["start"].getLargeIntValue();
  275. if (pid == lynx::crashguard::processId() || lynx::crashguard::processRunning (pid, start))
  276. continue; // this run, or another LYNX window still open
  277. lynx::PluginHost::settingsFolder().getChildFile ("crash-history.log")
  278. .appendText (juce::Time::getCurrentTime().toISO8601 (true) + " previous session ended without closing\n" + text + "\n");
  279. file.deleteFile();
  280. if (const auto modified = file.getLastModificationTime(); lastStep.isEmpty() || modified > newest)
  281. {
  282. newest = modified;
  283. lastStep = steps.isEmpty() ? juce::String ("start-up") : steps[steps.size() - 1].fromFirstOccurrenceOf (" ", false, false);
  284. uncleanSessionText = text;
  285. uncleanSteps.clear();
  286. for (const auto& step : steps)
  287. uncleanSteps.add (step.fromFirstOccurrenceOf (" ", false, false));
  288. }
  289. }
  290. return lastStep;
  291. }
  292. } // namespace
  293. // --uiperf (round 173f, discussion #10): a mixer fader dragged up and down with the mouse while the pattern plays. A
  294. // high-resolution timer delivers 125 moves a second to the message thread through the window's own mouse path
  295. // (ComponentPeer::handleMouseEvent), at most one waiting at a time as Windows does with WM_MOUSEMOVE; every frame the
  296. // window paints tells whether it covered the fader. Measured: how long a move waited for the message thread, the time
  297. // from a move to the first frame that shows the fader after it (input → paint), and whether the value stays put when
  298. // the mouse is released.
  299. struct UiPerfDrag final : public std::enable_shared_from_this<UiPerfDrag>,
  300. private juce::HighResolutionTimer
  301. {
  302. ~UiPerfDrag() override { stopTimer(); }
  303. void start (juce::Component& windowIn, juce::Component& strips, juce::Rectangle<int> rail, lynx::AudioEngine* engineIn, int trackIn)
  304. {
  305. window = &windowIn;
  306. engine = engineIn;
  307. track = trackIn;
  308. railInWindow = window->getLocalArea (&strips, rail);
  309. watch = railInWindow.expanded (6, 40); // the cap, its tip above and the dB read-out below
  310. visible = strips.isShowing() && window->getLocalArea (&strips, strips.getLocalBounds()).contains (railInWindow.getCentre());
  311. const auto volume = engine->getSong().mixer[(std::size_t) track].volume;
  312. x = (float) railInWindow.getCentreX();
  313. startY = (float) railInWindow.getBottom() - volume * (float) railInWindow.getHeight(); // on the cap: no jump
  314. amplitude = 0.4f * (float) railInWindow.getHeight();
  315. centreY = juce::jlimit ((float) railInWindow.getY() + amplitude, (float) railInWindow.getBottom() - amplitude, startY);
  316. t0 = juce::Time::getMillisecondCounterHiRes();
  317. inject (x, startY, false);
  318. juce::ModifierKeys::currentModifiers = juce::ModifierKeys (juce::ModifierKeys::leftButtonModifier);
  319. inject (x, startY, true);
  320. active = true;
  321. startTimer (8);
  322. }
  323. // message thread
  324. void framePainted (double now, juce::Rectangle<int> area)
  325. {
  326. if (pending.empty() || ! area.intersects (watch))
  327. return;
  328. for (const auto t : pending)
  329. latencies.push_back (now - t);
  330. pending.clear();
  331. ++framesOverFader;
  332. }
  333. // the moves end; as in the reporter's clip, the song is stopped while the button is still down
  334. juce::String stop()
  335. {
  336. stopTimer();
  337. active = false;
  338. valueAtRelease = engine->getSong().mixer[(std::size_t) track].volume;
  339. engine->stop();
  340. juce::String text;
  341. text << " drag of insert " << track << "'s fader" << (visible ? "" : " (NOT VISIBLE)") << ": " << moves << " moves handled, " << dropped
  342. << " folded into the next (the message thread still busy with the previous one)\n"
  343. << " move waited for the message thread: " << describe (queueDelays) << "\n"
  344. << " input -> paint (move to the first frame over the fader): " << describe (latencies) << ", " << framesOverFader
  345. << " frames over the fader\n";
  346. return text;
  347. }
  348. juce::String release()
  349. {
  350. const auto now = engine->getSong().mixer[(std::size_t) track].volume;
  351. juce::ModifierKeys::currentModifiers = {};
  352. inject (x, lastY, false);
  353. return " song stopped, button still down: fader " + juce::String (now, 4) + " (" + juce::String (valueAtRelease, 4) + " at the last move) "
  354. + (std::abs (now - valueAtRelease) < 1.0e-4f ? "kept" : "CHANGED") + "\n";
  355. }
  356. juce::String released() const
  357. {
  358. const auto now = engine->getSong().mixer[(std::size_t) track].volume;
  359. return " after the release: fader " + juce::String (now, 4) + " (" + juce::String (valueAtRelease, 4) + " when released) "
  360. + (std::abs (now - valueAtRelease) < 1.0e-4f ? "kept" : "CHANGED") + "\n";
  361. }
  362. private:
  363. juce::Component* window = nullptr;
  364. lynx::AudioEngine* engine = nullptr;
  365. int track = 1;
  366. juce::Rectangle<int> railInWindow, watch;
  367. bool visible = false;
  368. float x = 0.0f, startY = 0.0f, centreY = 0.0f, amplitude = 0.0f, lastY = 0.0f;
  369. double t0 = 0.0;
  370. std::atomic<bool> active { false }, posted { false };
  371. std::atomic<int> dropped { 0 };
  372. int moves = 0, framesOverFader = 0;
  373. float valueAtRelease = 0.0f;
  374. std::vector<double> pending, latencies, queueDelays;
  375. static juce::String describe (std::vector<double> v)
  376. {
  377. if (v.empty())
  378. return "none";
  379. std::sort (v.begin(), v.end());
  380. const auto at = [&v] (double q) { return v[std::min (v.size() - 1, (std::size_t) (q * (double) v.size()))]; };
  381. return "p50 " + juce::String (at (0.5), 1) + " / p95 " + juce::String (at (0.95), 1) + " / p99 " + juce::String (at (0.99), 1) + " / max "
  382. + juce::String (v.back(), 1) + " ms";
  383. }
  384. void inject (float px, float py, bool down)
  385. {
  386. lastY = py;
  387. if (auto* peer = window != nullptr ? window->getPeer() : nullptr)
  388. {
  389. const auto local = peer->globalToLocal (window->localPointToGlobal (juce::Point<float> (px, py)));
  390. peer->handleMouseEvent (juce::MouseInputSource::InputSourceType::mouse, local,
  391. down ? juce::ModifierKeys (juce::ModifierKeys::leftButtonModifier) : juce::ModifierKeys(),
  392. juce::MouseInputSource::defaultPressure, juce::MouseInputSource::defaultOrientation,
  393. juce::Time::currentTimeMillis());
  394. }
  395. }
  396. void hiResTimerCallback() override
  397. {
  398. if (! active.load())
  399. return;
  400. if (posted.exchange (true))
  401. {
  402. ++dropped;
  403. return;
  404. }
  405. const auto postedAt = juce::Time::getMillisecondCounterHiRes();
  406. juce::MessageManager::callAsync ([self = shared_from_this(), postedAt] {
  407. self->posted = false;
  408. if (! self->active.load())
  409. return;
  410. const auto now = juce::Time::getMillisecondCounterHiRes();
  411. self->queueDelays.push_back (now - postedAt);
  412. // up and down ~1.3 times a second, like the reporter's hand
  413. const auto y = self->centreY + self->amplitude * (float) std::sin (2.0 * juce::MathConstants<double>::pi * 1.3 * (now - self->t0) / 1000.0);
  414. self->inject (self->x, y, true);
  415. self->pending.push_back (postedAt);
  416. ++self->moves;
  417. });
  418. }
  419. };
  420. class LynxApplication final : public juce::JUCEApplication
  421. {
  422. public:
  423. const juce::String getApplicationName() override { return JUCE_APPLICATION_NAME_STRING; }
  424. const juce::String getApplicationVersion() override { return JUCE_APPLICATION_VERSION_STRING; }
  425. // the plugin scan runs copies of LYNX as child processes
  426. bool moreThanOneInstanceAllowed() override { return true; }
  427. // A file handed to the running application. macOS does this for every Finder double-click, "Open With" and Dock drop,
  428. // also the one that starts LYNX (its argv has no file). On Windows and Linux a second start is a second process
  429. // (moreThanOneInstanceAllowed) with the file as an argument, so this is not called there. Only the first file of a
  430. // multiple selection opens: a project replaces the one before it. (D#92, round 180a)
  431. void anotherInstanceStarted (const juce::String& commandLine) override
  432. {
  433. const auto files = lynx::safety::filesInCommandLine (commandLine.toStdString());
  434. if (files.empty())
  435. return;
  436. const auto file = juce::File::getCurrentWorkingDirectory().getChildFile (juce::String::fromUTF8 (files.front().c_str()));
  437. if (! startupFileHandled) // still starting: openStartupFile takes it, nothing to ask about yet
  438. {
  439. fileToOpen = file;
  440. return;
  441. }
  442. if (mainWindow != nullptr)
  443. {
  444. mainWindow->toFront (true);
  445. mainWindow->getContent().openFileRequest (file);
  446. }
  447. }
  448. void initialise (const juce::String& commandLine) override
  449. {
  450. // round 166b: the copy of LYNX.exe that installs an update (ui/Updater.h) waits, installs, starts LYNX again
  451. if (commandLine.contains ("--apply-update") && lynx::updater::runApplyHelper (juce::StringArray::fromTokens (commandLine, true)))
  452. {
  453. updateHelper = true;
  454. quit();
  455. return;
  456. }
  457. // Windows, LYNX.exe in a folder with accents: run again from its ASCII short path (Waves editors crash otherwise)
  458. if (int code = 0; lynx::platform::relaunchFromAsciiPath (code))
  459. {
  460. relaunched = true;
  461. setApplicationReturnValue (code);
  462. quit();
  463. return;
  464. }
  465. // a crash in any mode (UI, command line) writes its backtrace to %APPDATA%\LYNX\autosave
  466. juce::SystemStats::setApplicationCrashHandler (onCrash);
  467. lynx::crashguard::hardenSignals(); // issue #115: stack overflows and SIGTERM / SIGHUP leave a trace (Linux / macOS)
  468. // SFZ instruments (round 167o): their FLAC / OGG / AIFF / MP3 samples through JUCE's readers
  469. lynx::sfz::setDecoder ([] (const std::string& path, lynx::sfz::Audio& out) {
  470. juce::AudioFormatManager formats;
  471. formats.registerBasicFormats();
  472. std::unique_ptr<juce::AudioFormatReader> reader (formats.createReaderFor (juce::File (juce::String::fromUTF8 (path.c_str()))));
  473. if (reader == nullptr || reader->lengthInSamples <= 0 || reader->lengthInSamples > (1 << 28) || reader->numChannels == 0)
  474. return false;
  475. const auto frames = (int) reader->lengthInSamples;
  476. juce::AudioBuffer<float> buffer ((int) std::min (2u, reader->numChannels), frames);
  477. if (! reader->read (&buffer, 0, frames, 0, true, buffer.getNumChannels() > 1))
  478. return false;
  479. out.channels.clear();
  480. for (int ch = 0; ch < buffer.getNumChannels(); ++ch)
  481. out.channels.emplace_back (buffer.getReadPointer (ch), buffer.getReadPointer (ch) + frames);
  482. out.sampleRate = reader->sampleRate;
  483. out.loopStart = out.loopEnd = -1;
  484. return true;
  485. });
  486. // child process of a sandboxed plugin: no window or audio of its own
  487. if (lynx::runPluginSandboxWorker (commandLine))
  488. {
  489. lynx::crashguard::quietCrashReports();
  490. sandboxChild = true;
  491. return;
  492. }
  493. const auto args = juce::StringArray::fromTokens (commandLine, true);
  494. // interface language: saved in %APPDATA%\LYNX\language.txt; --lang pt-BR overrides it for this run
  495. lynx::i18n::initialise (args);
  496. // interface font: saved in Settings › General; --uifont "Name" overrides it for this run
  497. const auto uiFontArg = args.indexOf ("--uifont");
  498. lookAndFeel.applyInterfaceFont (lynx::i18n::current(), uiFontArg >= 0 ? args[uiFontArg + 1].unquoted() : juce::String());
  499. if (args.contains ("--showcase"))
  500. {
  501. // LYNX's own demo project (README screenshots): --showcase output.lynx [pattern]
  502. const auto i = args.indexOf ("--showcase");
  503. runShowcase (args[i + 1].unquoted(), args[i + 2].getIntValue());
  504. return;
  505. }
  506. if (args.contains ("--sandboxtest"))
  507. {
  508. const auto i = args.indexOf ("--sandboxtest");
  509. runSandboxTest (args[i + 1].unquoted(), args[i + 2].unquoted());
  510. return;
  511. }
  512. if (args.contains ("--bridge32test"))
  513. {
  514. // LYNX.exe --bridge32test "LYNX Test Synth 32.dll" report.txt [--compare "LYNX Test Synth.dll"] (round 176a):
  515. // the 32-bit plugin bridge (engine/Bridge32Test.cpp)
  516. const auto i = args.indexOf ("--bridge32test");
  517. const auto compare = args.contains ("--compare") ? args[args.indexOf ("--compare") + 1].unquoted() : juce::String();
  518. setApplicationReturnValue (lynx::runBridge32Test (args[i + 1].unquoted(), args[i + 2].unquoted(), compare));
  519. quit();
  520. return;
  521. }
  522. if (args.contains ("--rtstress"))
  523. {
  524. // LYNX.exe --rtstress project.(flp|lynx) report.txt [seconds] [--buffer N] [--type "driver type"] [--device "output"]
  525. // [--no-window] [--record take.wav]: the real app (window, audio device) plays the project and reports the callbacks
  526. // that missed their deadline (REA round 87); --type/--device pick another driver for this run only (round 97);
  527. // --record also records the input during the run, like Rec + Play, and moves the take to take.wav (round 106)
  528. const auto i = args.indexOf ("--rtstress");
  529. const auto seconds = args[i + 3].getDoubleValue();
  530. const auto buffer = args.contains ("--buffer") ? args[args.indexOf ("--buffer") + 1].getIntValue() : 0;
  531. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  532. const auto option = [&args] (const char* name) { return args.contains (name) ? args[args.indexOf (name) + 1].unquoted() : juce::String(); };
  533. runRealtimeStress (juce::File (args[i + 1].unquoted()), juce::File (args[i + 2].unquoted()), seconds > 0.0 ? seconds : 30.0, buffer,
  534. option ("--type"), option ("--device"), option ("--record"));
  535. return;
  536. }
  537. if (args.contains ("--cliplooptest"))
  538. {
  539. // LYNX --cliplooptest report.txt [export.wav] (round 167q, issue #25: 0.1.21 drew the repeats of a stretched
  540. // pattern clip but played the pattern once). The real engine's device callback (a stand-in device, driven
  541. // block by block) plays a synth's 1-bar pattern in a 4-bar clip: every repeat must sound as bar 1, also
  542. // starting inside a repeat, after a jump mid-clip and in a loop region; the WAV export (written to
  543. // export.wav and read back) the same. With the LYNX extra off, bars 2-4 must be silent (FL's behaviour).
  544. const auto i = args.indexOf ("--cliplooptest");
  545. runClipLoopTest (juce::File (args[i + 1].unquoted()), args.size() > i + 2 && ! args[i + 2].startsWith ("--") ? juce::File (args[i + 2].unquoted()) : juce::File());
  546. return;
  547. }
  548. if (args.contains ("--countinrectest"))
  549. {
  550. // LYNX --countinrectest report.txt (round 170d, the Busy Works video: the chord on the downbeat after the
  551. // pre-count was lost). The real engine's device callback (a stand-in device: 48 kHz, blocks of 512, 256
  552. // samples of output latency) records a Song-mode take from bar 3 with a 1-bar count-in. Pass 1 finds where
  553. // the metronome's bar-3 click is heard; pass 2 plays MIDI notes stamped at the times they are heard around
  554. // 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
  555. // LYNX's MIDI input. Every note must land on the tick it was heard at (the chord on bar 3).
  556. const auto i = args.indexOf ("--countinrectest");
  557. runCountInRecordTest (juce::File (args[i + 1].unquoted()));
  558. return;
  559. }
  560. if (args.contains ("--bendrectest"))
  561. {
  562. // LYNX --bendrectest report.txt [song|pattern] (round 167a, issue #12): pitch bend recording end to end. A
  563. // controller's pitch wheel is injected into LYNX's MIDI input (as a device would send it) while recording
  564. // plays: a held note and a wheel sweep 0 → full up → full down → centre. The recorded lane (pattern mode) or
  565. // automation clip (song mode) of the channel's pitch bend must follow the sweep.
  566. const auto i = args.indexOf ("--bendrectest");
  567. const auto songMode = args.size() > i + 2 && args[i + 2] == "song";
  568. runBendRecordTest (juce::File (args[i + 1].unquoted()), songMode);
  569. return;
  570. }
  571. if (args.contains ("--rectest"))
  572. {
  573. // LYNX --rectest report.txt [seconds] [--type T] [--device D] [--input I] [--loop] [--buffer N]
  574. // (round 163): records a click track through a loopback (cable, interface loopback or PipeWire's
  575. // pw-loopback): pings the round trip, plays a click on every beat from an audio clip, records it on Insert 1,
  576. // stops, and checks every recorded click's song position on the Playlist against its beat (samples).
  577. // --loop: loop recording over bars 2-4 (take lanes). --punch: punch in/out on bars 3-4 with 1 bar of pre-roll
  578. // and 1 of post-roll (playback stops by itself after the post-roll).
  579. const auto i = args.indexOf ("--rectest");
  580. const auto option = [&args] (const char* name) { return args.contains (name) ? args[args.indexOf (name) + 1].unquoted() : juce::String(); };
  581. const auto seconds = args.size() > i + 2 && ! args[i + 2].startsWith ("--") ? args[i + 2].getDoubleValue() : 20.0;
  582. runRecordTest (juce::File (args[i + 1].unquoted()), seconds > 0.0 ? seconds : 20.0, option ("--type"), option ("--device"), option ("--input"),
  583. args.contains ("--loop") ? 1 : args.contains ("--punch") ? 2 : 0, option ("--pdc").getIntValue(), option ("--buffer").getIntValue());
  584. return;
  585. }
  586. if (args.contains ("--hwinserttest"))
  587. {
  588. // LYNX --hwinserttest report.txt [seconds] [--type T] [--device D] [--input I] [--buffer N] (round 164d): a
  589. // hardware insert through a loopback cable (output pair 1-2 -> input pair 1-2; the Master plays nowhere, so
  590. // the cable carries the send only). The same click track plays on two inserts: Insert 1 through the
  591. // hardware insert (panned left), Insert 2 dry (panned right). The insert's own ping measures the round
  592. // trip, PDC delays the dry path by it, and every click of the Master's left side must sit on the same
  593. // sample as the right side's.
  594. const auto i = args.indexOf ("--hwinserttest");
  595. const auto option = [&args] (const char* name) { return args.contains (name) ? args[args.indexOf (name) + 1].unquoted() : juce::String(); };
  596. const auto seconds = args.size() > i + 2 && ! args[i + 2].startsWith ("--") ? args[i + 2].getDoubleValue() : 10.0;
  597. // round 165c: --patcher puts the insert inside a Patcher on Insert 1; --bounce file.wav then exports the song in real
  598. // time through the device (Export › "Render through the hardware in real time") and offline, and compares them
  599. runHwInsertTest (juce::File (args[i + 1].unquoted()), seconds > 0.0 ? seconds : 10.0, option ("--type"), option ("--device"), option ("--input"),
  600. option ("--buffer").getIntValue(), args.contains ("--patcher"),
  601. args.contains ("--bounce") ? juce::File (option ("--bounce")) : juce::File());
  602. return;
  603. }
  604. if (args.contains ("--uiperf"))
  605. {
  606. // LYNX --uiperf project.(flp|lynx) report.txt: the heavy UI cases in the real window, every frame timed (round 161)
  607. const auto i = args.indexOf ("--uiperf");
  608. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  609. runUiPerf (juce::File (args[i + 1].unquoted()), juce::File (args[i + 2].unquoted()));
  610. return;
  611. }
  612. if (args.contains ("--cachetest"))
  613. {
  614. // LYNX --cachetest project.(flp|lynx) report.txt (round 174f): the Playlist's cached picture against exact
  615. // paints after zooms, scrolls and repaints, off screen (no window)
  616. const auto i = args.indexOf ("--cachetest");
  617. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  618. runCacheTest (juce::File (args[i + 1].unquoted()), juce::File (args[i + 2].unquoted()));
  619. return;
  620. }
  621. if (args.contains ("--timertest"))
  622. {
  623. // LYNX --timertest report.txt (round 174f): ui::TimerWhileShowing through hide / show / minimise (opens a small window)
  624. runTimerTest (juce::File (args[args.indexOf ("--timertest") + 1].unquoted()));
  625. return;
  626. }
  627. if (args.contains ("--livetest"))
  628. {
  629. // LYNX --livetest report.txt [--relay URL]: a live session of four peers over the relay (round 169b)
  630. setApplicationReturnValue (lynx::livetest::run (args));
  631. quit();
  632. return;
  633. }
  634. if (args.contains ("--selftest"))
  635. {
  636. const auto i = args.indexOf ("--selftest");
  637. runSelfTest (args[i + 1].unquoted(), args[i + 2].unquoted());
  638. return;
  639. }
  640. if (args.contains ("--scan-one"))
  641. {
  642. // child process of the plugin scan (see PluginHost::scan)
  643. const auto i = args.indexOf ("--scan-one");
  644. // no crash dialogs from the plugin being examined; and once the result is written, the process ends without
  645. // unloading it: a Waves shell crashed in its own teardown at exit (Intel GPU driver fail-fast, 0xC0000409),
  646. // which showed Windows' crash dialog and made the scan reject the whole shell (round 111)
  647. lynx::crashguard::quietCrashReports();
  648. lynx::PluginHost::scanOneFile (args[i + 1].unquoted(), args[i + 2].unquoted(), juce::File (args[i + 3].unquoted()));
  649. lynx::crashguard::exitNow (0);
  650. }
  651. if (args.contains ("--packageinfo"))
  652. {
  653. // round 165n: the Microsoft Store (MSIX) build's identity and folders (platform/Package.h); the release
  654. // workflow runs it inside the installed test package
  655. juce::File (args[args.indexOf ("--packageinfo") + 1].unquoted()).replaceWithText (lynx::platform::packageReport());
  656. quit();
  657. return;
  658. }
  659. if (args.contains ("--paths"))
  660. {
  661. // diagnostics: folders LYNX searches
  662. const auto programs = juce::File::getSpecialLocation (juce::File::globalApplicationsDirectory);
  663. juce::String report;
  664. report << "programs=" << programs.getFullPathName() << "\n";
  665. for (const auto& dir : programs.getChildFile ("Image-Line").findChildFiles (juce::File::findDirectories, false, "FL Studio*"))
  666. report << "fl=" << dir.getFullPathName() << " packs=" << (int) dir.getChildFile ("Data").getChildFile ("Patches").getChildFile ("Packs").isDirectory() << "\n";
  667. juce::File (args[args.indexOf ("--paths") + 1].unquoted()).replaceWithText (report);
  668. quit();
  669. return;
  670. }
  671. if (args.contains ("--fldb"))
  672. {
  673. // diagnostics: LYNX.exe --fldb report.txt [project.flp]: the FL Studio installation, its plugin database,
  674. // the suggested plugin folders and, for a project, how each of its plugins resolves (read-only)
  675. const auto i = args.indexOf ("--fldb");
  676. const auto fl = lynx::findFlStudio();
  677. lynx::PluginHost host (false);
  678. juce::String report;
  679. report << "install=" << fl.installDir.getFullPathName() << "\nuserdata=" << fl.userData.getFullPathName() << "\n";
  680. for (const auto& f : fl.vstFolders)
  681. report << "flvstfolder=" << f << "\n";
  682. report << "dbfiles=" << host.flPluginDatabaseFiles() << " entries=" << (int) host.flPluginDatabase().entries().size() << "\n";
  683. for (const auto& e : host.flPluginDatabase().entries())
  684. report << " entry: " << juce::String::fromUTF8 (e.name.c_str()) << " | " << juce::String::fromUTF8 (e.path.c_str()) << " | role=" << e.role << "\n";
  685. const auto suggested = host.suggestedFolders();
  686. for (int k = 0; k < suggested.getNumPaths(); ++k)
  687. report << "folder=" << suggested[k].getFullPathName() << "\n";
  688. if (const juce::File project (args[i + 2].unquoted()); project.existsAsFile())
  689. {
  690. juce::MemoryBlock data;
  691. project.loadFileAsData (data);
  692. try
  693. {
  694. for (const auto& use : lynx::flpForeignPlugins (flp::parseProject ({ static_cast<const std::uint8_t*> (data.getData()), data.getSize() })))
  695. {
  696. juce::String how;
  697. const auto d = host.findForeign (use.plugin, use.instrument, &how);
  698. const auto* entry = host.flPluginDatabase().match (use.plugin, use.instrument);
  699. report << "plugin: " << juce::String::fromUTF8 (use.plugin.name.c_str()) << " -> "
  700. << (d ? d->fileOrIdentifier + " (" + how + ")" : juce::String ("not known"))
  701. << (entry != nullptr ? " | fl db: " + juce::String::fromUTF8 (entry->path.c_str()) : juce::String()) << "\n";
  702. }
  703. const auto uses = lynx::flpForeignPlugins (flp::parseProject ({ static_cast<const std::uint8_t*> (data.getData()), data.getSize() }));
  704. const auto candidates = host.filesToScanFor (uses);
  705. report << "scan_candidates=" << candidates.joinIntoString (";") << "\n";
  706. if (args.contains ("--scan"))
  707. {
  708. // the targeted scan an open would run (child processes; the user's plugin list is not touched)
  709. report << "scanned_new=" << host.scanFiles (candidates, {}) << "\n";
  710. for (const auto& use : uses)
  711. {
  712. juce::String how;
  713. const auto d = host.findForeign (use.plugin, use.instrument, &how);
  714. report << "after_scan: " << juce::String::fromUTF8 (use.plugin.name.c_str()) << " -> "
  715. << (d ? d->fileOrIdentifier + " (" + how + ")" : juce::String ("not known")) << "\n";
  716. }
  717. }
  718. }
  719. catch (const flp::Error& e)
  720. {
  721. report << "error=" << e.what() << "\n";
  722. }
  723. }
  724. juce::File (args[i + 1].unquoted()).replaceWithText (report);
  725. quit();
  726. return;
  727. }
  728. if (args.contains ("--midisync-test"))
  729. {
  730. // LYNX --midisync-test report.txt ["output device"] ["input device"] (round 165f): MIDI clock timing
  731. const auto i = args.indexOf ("--midisync-test");
  732. const auto out = args.size() > i + 2 && ! args[i + 2].startsWith ("--") ? args[i + 2].unquoted() : juce::String();
  733. const auto in = args.size() > i + 3 && ! args[i + 3].startsWith ("--") ? args[i + 3].unquoted() : juce::String();
  734. juce::File (args[i + 1].unquoted()).replaceWithText (lynx::MidiSyncIo::selfTest (out, in));
  735. quit();
  736. return;
  737. }
  738. if (args.contains ("--devices") || args.contains ("--dispositivos")) // --dispositivos: legacy alias
  739. {
  740. // diagnostics: driver types and output devices JUCE offers (without opening any)
  741. juce::AudioDeviceManager manager;
  742. juce::String report;
  743. manager.getAvailableDeviceTypes();
  744. if (auto pipeWire = lynx::makePipeWireDeviceType()) // Linux: LYNX's own PipeWire client (round 161)
  745. manager.addAudioDeviceType (std::move (pipeWire));
  746. #if JUCE_LINUX
  747. report << lynx::describePipeWire() << "\n";
  748. #endif
  749. for (auto* type : manager.getAvailableDeviceTypes())
  750. {
  751. type->scanForDevices();
  752. report << "type=" << type->getTypeName() << "\n";
  753. for (const auto& name : type->getDeviceNames (false))
  754. report << " output=" << name << "\n";
  755. for (const auto& name : type->getDeviceNames (true))
  756. report << " input=" << name << "\n";
  757. }
  758. for (const auto& d : juce::MidiInput::getAvailableDevices())
  759. report << "midi-in=" << d.name << "\n";
  760. for (const auto& d : juce::MidiOutput::getAvailableDevices())
  761. report << "midi-out=" << d.name << "\n";
  762. const auto flag = args.contains ("--devices") ? args.indexOf ("--devices") : args.indexOf ("--dispositivos");
  763. juce::File (args[flag + 1].unquoted()).replaceWithText (report);
  764. quit();
  765. return;
  766. }
  767. if (args.contains ("--devicetest"))
  768. {
  769. // LYNX.exe --devicetest "type" "device" report.txt ["input device"] [--buffer N] [--roundtrip]: opens that output device (and, with the
  770. // 4th argument, an input: "*" = the same device / the driver's default input), receives 1 s of callbacks
  771. // writing silence, closes it and reports rate, block size, latency, callbacks and the input channels with
  772. // their peak level (driver check, no sound). --roundtrip: clicks out, found again on input 1 through a loopback
  773. // cable / PipeWire link: the round-trip latency (3 s)
  774. const auto i = args.indexOf ("--devicetest");
  775. const auto typeName = args[i + 1].unquoted(), deviceName = args[i + 2].unquoted();
  776. auto inputName = args.size() > i + 4 && ! args[i + 4].startsWith ("--") ? args[i + 4].unquoted() : juce::String();
  777. const auto wantInput = inputName.isNotEmpty();
  778. juce::String report;
  779. const juce::File reportFile (args[i + 3].unquoted());
  780. auto step = [&] (const juce::String& line) { report << line << "\n"; reportFile.replaceWithText (report); }; // progress survives a driver that ends the process
  781. step ("step=start");
  782. juce::AudioDeviceManager manager;
  783. manager.getAvailableDeviceTypes();
  784. if (auto pipeWire = lynx::makePipeWireDeviceType())
  785. manager.addAudioDeviceType (std::move (pipeWire));
  786. std::unique_ptr<juce::AudioIODevice> device;
  787. for (auto* type : manager.getAvailableDeviceTypes())
  788. if (type->getTypeName() == typeName)
  789. {
  790. type->scanForDevices();
  791. if (wantInput && type->hasSeparateInputsAndOutputs())
  792. {
  793. const auto inputs = type->getDeviceNames (true);
  794. if (inputName == "*" || ! inputs.contains (inputName))
  795. {
  796. const auto index = type->getDefaultDeviceIndex (true);
  797. inputName = juce::isPositiveAndBelow (index, inputs.size()) ? inputs[index] : juce::String();
  798. }
  799. for (const auto& n : inputs)
  800. step ("input_device=" + n);
  801. step ("input_chosen=" + inputName);
  802. }
  803. else if (wantInput)
  804. inputName = deviceName;
  805. step ("step=create");
  806. device.reset (type->createDevice (deviceName, type->hasSeparateInputsAndOutputs() ? inputName : juce::String()));
  807. step ("step=created");
  808. }
  809. struct Silence final : juce::AudioIODeviceCallback
  810. {
  811. std::atomic<int> calls { 0 }, inputs { 0 };
  812. std::array<std::atomic<float>, 64> peaks {};
  813. // --roundtrip (round 161): a click every quarter second on the outputs, found again on input 1 through a
  814. // loopback; the delays in samples
  815. bool roundtrip = false;
  816. int period = 12000;
  817. std::int64_t position = 0, lastClick = -1;
  818. std::vector<int> delays;
  819. void audioDeviceIOCallbackWithContext (const float* const* in, int numIn, float* const* out, int channels, int n,
  820. const juce::AudioIODeviceCallbackContext&) override
  821. {
  822. for (int c = 0; c < channels; ++c)
  823. if (out[c] != nullptr)
  824. juce::FloatVectorOperations::clear (out[c], n);
  825. if (roundtrip)
  826. {
  827. for (int i = 0; i < n; ++i)
  828. {
  829. if (numIn > 0 && in[0] != nullptr && lastClick >= 0 && std::abs (in[0][i]) > 0.5f)
  830. {
  831. if (delays.size() < delays.capacity())
  832. delays.push_back ((int) (position + i - lastClick));
  833. lastClick = -1;
  834. }
  835. if ((position + i) % period == 0 && position + i > 0)
  836. {
  837. for (int c = 0; c < channels; ++c)
  838. if (out[c] != nullptr)
  839. out[c][i] = 0.9f;
  840. lastClick = position + i;
  841. }
  842. }
  843. position += n;
  844. }
  845. inputs.store (numIn);
  846. for (int c = 0; c < juce::jmin (numIn, 64); ++c)
  847. if (in[c] != nullptr)
  848. {
  849. const auto range = juce::FloatVectorOperations::findMinAndMax (in[c], n);
  850. const auto peak = juce::jmax (std::abs (range.getStart()), std::abs (range.getEnd()));
  851. if (peak > peaks[(std::size_t) c].load())
  852. peaks[(std::size_t) c].store (peak);
  853. }
  854. ++calls;
  855. }
  856. void audioDeviceAboutToStart (juce::AudioIODevice*) override {}
  857. void audioDeviceStopped() override {}
  858. } silence;
  859. bool ok = false;
  860. if (device == nullptr)
  861. step ("error=device not found");
  862. else
  863. {
  864. step ("step=open");
  865. juce::BigInteger outputs;
  866. outputs.setRange (0, 2, true);
  867. const auto rates = device->getAvailableSampleRates();
  868. const auto rate = device->getCurrentSampleRate() > 0 ? device->getCurrentSampleRate()
  869. : rates.contains (48000.0) ? 48000.0 : rates.isEmpty() ? 44100.0 : rates[0];
  870. step ("rates=" + juce::String (rates.size()) + " chosen=" + juce::String (rate) + " default_block=" + juce::String (device->getDefaultBufferSize()));
  871. juce::BigInteger inputs;
  872. if (wantInput)
  873. {
  874. const auto names = device->getInputChannelNames();
  875. step ("input_channels=" + juce::String (names.size()));
  876. for (int c = 0; c < names.size(); ++c)
  877. step (" in" + juce::String (c + 1) + "=" + names[c]);
  878. inputs.setRange (0, juce::jmin (64, names.size()), true);
  879. }
  880. // --buffer N: ask for that block size (REA round 97 latency survey); default: the driver's default
  881. const auto wantedBlock = args.contains ("--buffer") ? args[args.indexOf ("--buffer") + 1].getIntValue() : 0;
  882. const auto error = device->open (inputs, outputs, rate, wantedBlock > 0 ? wantedBlock : device->getDefaultBufferSize());
  883. if (error.isNotEmpty())
  884. step ("error=" + error);
  885. else
  886. {
  887. step ("step=start_callbacks");
  888. silence.roundtrip = args.contains ("--roundtrip");
  889. silence.period = juce::jmax (1, (int) (rate / 4));
  890. silence.delays.reserve (64);
  891. device->start (&silence);
  892. juce::Thread::sleep (silence.roundtrip ? 3000 : 1000);
  893. device->stop();
  894. if (silence.roundtrip)
  895. {
  896. auto d = silence.delays;
  897. std::sort (d.begin(), d.end());
  898. report << "roundtrip_clicks=" << (int) d.size() << "\n";
  899. if (! d.empty())
  900. report << "roundtrip_samples=min " << d.front() << " median " << d[d.size() / 2] << " max " << d.back() << "\n"
  901. << "roundtrip_ms=" << juce::String (1000.0 * d[d.size() / 2] / device->getCurrentSampleRate(), 2) << "\n";
  902. }
  903. report << "rate=" << device->getCurrentSampleRate() << "\n"
  904. << "block=" << device->getCurrentBufferSizeSamples() << "\n"
  905. << "output_latency=" << device->getOutputLatencyInSamples() << "\n"
  906. << "callbacks=" << silence.calls.load() << "\n";
  907. if (wantInput)
  908. {
  909. report << "input_latency=" << device->getInputLatencyInSamples() << "\n"
  910. << "active_inputs=" << device->getActiveInputChannels().countNumberOfSetBits() << "\n"
  911. << "callback_inputs=" << silence.inputs.load() << "\n";
  912. for (int c = 0; c < juce::jmin (64, silence.inputs.load()); ++c)
  913. report << " peak_in" << (c + 1) << "=" << juce::Decibels::gainToDecibels (silence.peaks[(std::size_t) c].load(), -150.0f) << " dB\n";
  914. }
  915. ok = silence.calls.load() > 0 && (! wantInput || silence.inputs.load() > 0);
  916. device->close();
  917. }
  918. }
  919. step (juce::String ("result=") + (ok ? "OK" : "FAILED"));
  920. setApplicationReturnValue (ok ? 0 : 1);
  921. quit();
  922. return;
  923. }
  924. if (args.contains ("--scantest"))
  925. {
  926. // LYNX.exe --scantest folder report.txt: scan (in child processes) without touching the user's list
  927. const auto i = args.indexOf ("--scantest");
  928. lynx::PluginHost host (false);
  929. const auto found = host.scan (juce::FileSearchPath (args[i + 1].unquoted()), {});
  930. juce::String report;
  931. report << "found=" << found << "\n";
  932. for (const auto& t : host.getKnownPlugins().getTypes())
  933. report << " " << (t.isInstrument ? "instrument: " : "effect: ") << t.name << "\n";
  934. for (const auto& f : host.getKnownPlugins().getBlacklistedFiles())
  935. report << " blacklisted: " << f << "\n";
  936. juce::File (args[i + 2].unquoted()).replaceWithText (report);
  937. setApplicationReturnValue (found > 0 ? 0 : 1);
  938. quit();
  939. return;
  940. }
  941. if (args.contains ("--wrappermiditest"))
  942. {
  943. // LYNX.exe --wrappermiditest plugin.dll report.txt (round 181c), with LYNX_TEST_VST2_MIDILOG set: what a
  944. // hosted plugin receives after a wrapper MIDI option changes while it runs
  945. const auto i = args.indexOf ("--wrappermiditest");
  946. runWrapperMidiTest (args[i + 1].unquoted(), args[i + 2].unquoted());
  947. return;
  948. }
  949. if (args.contains ("--vst2test"))
  950. {
  951. const auto i = args.indexOf ("--vst2test");
  952. runVst2Test (args[i + 1].unquoted(), args[i + 2].unquoted());
  953. return;
  954. }
  955. if (args.contains ("--lv2scantest"))
  956. {
  957. runLv2ScanTest (args[args.indexOf ("--lv2scantest") + 1].unquoted());
  958. return;
  959. }
  960. if (args.contains ("--wrappertest"))
  961. {
  962. const auto i = args.indexOf ("--wrappertest");
  963. runWrapperTest (args[i + 1].unquoted(), args[i + 2].unquoted());
  964. return;
  965. }
  966. if (args.contains ("--plugintest"))
  967. {
  968. const auto i = args.indexOf ("--plugintest");
  969. // optional 3rd argument: the plugin's name inside a shell (e.g. "CLA-2A Stereo" in a WaveShell)
  970. const auto only = i + 3 < args.size() && ! args[i + 3].startsWith ("--") ? args[i + 3].unquoted() : juce::String();
  971. runPluginTest (args[i + 1].unquoted(), args[i + 2].unquoted(), only);
  972. return;
  973. }
  974. if (args.contains ("--claprestarttest"))
  975. {
  976. // LYNX.exe --claprestarttest "LYNX Test Restart.clap" report.txt (tools/testplugin/lynx_test_restart.c)
  977. const auto i = args.indexOf ("--claprestarttest");
  978. runClapRestartTest (args[i + 1].unquoted(), args[i + 2].unquoted());
  979. return;
  980. }
  981. if (args.contains ("--editortest"))
  982. {
  983. // LYNX.exe --editortest plugin.vst3 report.txt ["name"]: opens the plugin's own editor in a window for a few
  984. // seconds, then closes it (a plugin whose UI crashes the host ends the process before the report says OK)
  985. const auto i = args.indexOf ("--editortest");
  986. const auto only = i + 3 < args.size() && ! args[i + 3].startsWith ("--") ? args[i + 3].unquoted() : juce::String();
  987. runEditorTest (args[i + 1].unquoted(), args[i + 2].unquoted(), only);
  988. return;
  989. }
  990. if (args.contains ("--editorcrashtest"))
  991. {
  992. // LYNX.exe --editorcrashtest "LYNX Test Crash.clap" report.txt (issue #32, round 174a; Windows): the test
  993. // plugin's editor faults in its own window procedure (LYNX_TEST_CRASH=editor). LYNX must catch it, close
  994. // that editor, record the trace and keep running its message loop.
  995. const auto i = args.indexOf ("--editorcrashtest");
  996. runEditorCrashTest (args[i + 1].unquoted(), args[i + 2].unquoted());
  997. return;
  998. }
  999. if (args.contains ("--plugwintest"))
  1000. {
  1001. // LYNX --plugwintest plugin report.txt ["name"] [seconds]: round 162d. Puts the plugin in a channel (an
  1002. // instrument) or on insert 1 (an effect) of an offline engine, opens its plugin window (wrapper header,
  1003. // presets), checks a preset round trip, keeps the window `seconds` on screen (default 15: time for xdotool /
  1004. // screenshots), then removes the plugin from the song and reports whether its window closed by itself.
  1005. const auto i = args.indexOf ("--plugwintest");
  1006. const auto only = i + 3 < args.size() && ! args[i + 3].startsWith ("--") && ! args[i + 3].containsOnly ("0123456789") ? args[i + 3].unquoted() : juce::String();
  1007. auto seconds = 15;
  1008. for (int k = i + 3; k < juce::jmin (args.size(), i + 5); ++k)
  1009. if (args[k].containsOnly ("0123456789"))
  1010. seconds = args[k].getIntValue();
  1011. runPlugWinTest (args[i + 1].unquoted(), args[i + 2].unquoted(), only, seconds);
  1012. return;
  1013. }
  1014. if (args.contains ("--fittest"))
  1015. {
  1016. // LYNX.exe --fittest report.txt [percent]: round 163 — at that UI zoom (default 150) a window taller than
  1017. // the screen and a big resizable window that grows with a zoom change keep their title bar and close
  1018. // button on the screen. The windows show for about two seconds.
  1019. const auto i = args.indexOf ("--fittest");
  1020. runFitTest (args[i + 1].unquoted(), i + 2 < args.size() ? args[i + 2].getIntValue() : 150);
  1021. return;
  1022. }
  1023. if (args.contains ("--windowtest"))
  1024. {
  1025. // LYNX.exe --windowtest report.txt: opens the Quick-add palette, the Audio editor, a plugin-like window and a name dialog
  1026. // over the main window and checks that each one stays in front, owned by the main window, with the
  1027. // keyboard focus (issue #4). The windows appear on screen for a few seconds.
  1028. runWindowTest (args[args.indexOf ("--windowtest") + 1].unquoted());
  1029. return;
  1030. }
  1031. if (args.contains ("--pluginstyle")) // round 126: force one style for this run (glow, neon, hardware, vivid; auto = per plugin)
  1032. {
  1033. const auto i = args.indexOf ("--pluginstyle");
  1034. if (i + 1 < args.size())
  1035. {
  1036. const auto name = args[i + 1].unquoted();
  1037. lynx::skin::setForcedStyle (name.equalsIgnoreCase ("auto") ? -1 : (int) lynx::skin::styleFromName (name));
  1038. }
  1039. }
  1040. if (args.contains ("--gfxprobe"))
  1041. {
  1042. // LYNX.exe --gfxprobe report.txt (round 170c, issue #11): renderer checks on this platform's native images —
  1043. // text drawn with a gradient fill (a word with a space in it) and an empty path filled with a gradient must
  1044. // stay inside their shapes. JUCE 8.0.4's CoreGraphics renderer (macOS) clipped to an empty glyph or path as
  1045. // "no clip" and flooded the whole component (Facet EQ's blank pink window).
  1046. const auto i = args.indexOf ("--gfxprobe");
  1047. juce::File (args[i + 1].unquoted()).replaceWithText (lynx::skin::rendererProbeReport());
  1048. quit();
  1049. return;
  1050. }
  1051. if (args.contains ("--steppertest"))
  1052. {
  1053. // LYNX.exe --steppertest <report.txt>: round 170c (#14) — every value stepper of every generated effect editor
  1054. // driven by synthetic input (arrows, click on the value, drag, wheel, trackpad); ends with result=OK / FAIL
  1055. const auto i = args.indexOf ("--steppertest");
  1056. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  1057. juce::String report;
  1058. int fails = 0, count = 0, skips = 0;
  1059. {
  1060. lynx::AudioEngine offline (false);
  1061. auto kinds = lynx::plugui::flLayoutKinds();
  1062. for (const auto own : lynx::plugui::ownLayoutKinds())
  1063. kinds.push_back (own);
  1064. // FL's Default preset when the installation has one (the state-backed controls need FL's state)
  1065. const auto roots = lynx::findFlStudioRoots();
  1066. const auto presets = juce::File (juce::String::fromUTF8 (roots.data.c_str())).getChildFile ("Patches/Plugin presets/Effects");
  1067. for (const auto kind : kinds)
  1068. {
  1069. auto fx = lynx::makeEffectSlot (kind);
  1070. for (const auto& plugin : lynx::flPluginsForEffect (kind))
  1071. {
  1072. juce::MemoryBlock data;
  1073. const auto file = presets.getChildFile (juce::String::fromUTF8 (plugin.c_str())).getChildFile ("Default.fst");
  1074. if (file.existsAsFile() && file.loadFileAsData (data))
  1075. {
  1076. const auto* bytes = static_cast<const std::uint8_t*> (data.getData());
  1077. 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)
  1078. fx = *loaded;
  1079. }
  1080. break;
  1081. }
  1082. lynx::Song song;
  1083. song.mixer.resize (2);
  1084. song.mixer[0].name = "Master";
  1085. song.mixer[1].name = "Insert 1";
  1086. song.mixer[1].effects.push_back (fx);
  1087. offline.setSong (std::move (song));
  1088. offline.dispatchPendingMessages();
  1089. const auto lines = lynx::stepperSelfTest (offline, 1, 0, (int) lynx::plugui::layoutFor (kind).pages.size());
  1090. for (const auto& line : juce::StringArray::fromLines (lines))
  1091. if (line.isNotEmpty())
  1092. {
  1093. ++count;
  1094. fails += line.contains (": FAIL") ? 1 : 0;
  1095. skips += line.contains (": SKIP") ? 1 : 0;
  1096. }
  1097. report << lines;
  1098. juce::PopupMenu::dismissAllActiveMenus();
  1099. offline.dispatchPendingMessages();
  1100. }
  1101. }
  1102. report << "steppers=" << count << " failures=" << fails << " skipped=" << skips << "\nresult=" << (fails == 0 && count > 0 ? "OK" : "FAIL") << "\n";
  1103. juce::File (args[i + 1].unquoted()).replaceWithText (report);
  1104. quit();
  1105. return;
  1106. }
  1107. if (args.contains ("--plugui"))
  1108. {
  1109. // LYNX.exe --plugui <folder>: the native effect editors at FL's size (one PNG per editor and page), each
  1110. // loaded with the FL plugin's Default preset when the FL installation has one
  1111. const auto i = args.indexOf ("--plugui");
  1112. runPluginEditorSnapshots (args[i + 1].unquoted());
  1113. return;
  1114. }
  1115. if (args.contains ("--parityshot"))
  1116. {
  1117. // LYNX.exe --parityshot <out.png> <effect name> [<params file>]: one built-in effect's editor with the given
  1118. // parameters ("index value" lines, tools/fxrender --dump), its displays fed by the demo song — the LYNX side
  1119. // of the third-party parity pictures (round tp172b)
  1120. const auto i = args.indexOf ("--parityshot");
  1121. runParityShot (args[i + 1].unquoted(), args[i + 2].unquoted(), i + 3 < args.size() ? args[i + 3].unquoted() : juce::String());
  1122. if (parityShotFailed)
  1123. setApplicationReturnValue (2);
  1124. if (parityShow == nullptr)
  1125. quit();
  1126. return;
  1127. }
  1128. if (args.contains ("--design168rshot"))
  1129. {
  1130. // LYNX.exe --design168rshot <folder>: round 168r's editors (FL effects that had a generated page and LYNX's own
  1131. // simple built-ins) at 100 % and 200 %, with their default settings and, when they have one, the first
  1132. // preset of LYNX's own bank. "--design168rshot <folder> generated": the generated pages they had before
  1133. const auto i = args.indexOf ("--design168rshot");
  1134. if (i + 2 < args.size() && args[i + 2] == "generated")
  1135. lynx::plugui::showGeneratedLayoutsOnly (true);
  1136. runDesign168rShots (args[i + 1].unquoted());
  1137. quit();
  1138. return;
  1139. }
  1140. if (args.contains ("--eq166fshot"))
  1141. {
  1142. // LYNX.exe --eq166fshot <folder>: round 166f's pictures (issue #16) — Parametric EQ 2's spectrum and heatmap
  1143. // (flat, a +12 dB band, a -12 dB band, Top position) and Facet EQ's comparative EQ (listening to the target,
  1144. // its spectrum over the source's), each fed by the demo song rendered offline
  1145. const auto i = args.indexOf ("--eq166fshot");
  1146. runEq166fShots (args[i + 1].unquoted());
  1147. quit();
  1148. return;
  1149. }
  1150. if (args.contains ("--editorcpu"))
  1151. {
  1152. // LYNX.exe --editorcpu report.txt: opens built-in plugin editors one at a time in a small window (no audio
  1153. // device: a silent, idle editor) and writes the process CPU each costs while idle and while its display
  1154. // animates (demo signal) — round 122's check that an idle editor burns no CPU
  1155. const auto i = args.indexOf ("--editorcpu");
  1156. runEditorCpu (args[i + 1].unquoted());
  1157. return;
  1158. }
  1159. if (args.contains ("--precomputeshot"))
  1160. {
  1161. // LYNX.exe --precomputeshot project.(flp|lynx) <prefix>: round 167h — <prefix>-precompute.png (channel 1's
  1162. // Precomputed effects panel) and <prefix>-project.png (Options › Project with "Fast declick for cut groups")
  1163. const auto i = args.indexOf ("--precomputeshot");
  1164. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  1165. lynx::AudioEngine shotEngine (false);
  1166. const juce::File input (args[i + 1].unquoted());
  1167. const auto prefix = args[i + 2].unquoted();
  1168. juce::String error;
  1169. bool ok = false;
  1170. if (input.hasFileExtension ("flp"))
  1171. ok = shotEngine.importFlpFile (input, error);
  1172. else if (auto song = lynx::ProjectFile::load (input, error))
  1173. shotEngine.setSong (std::move (*song)), ok = true;
  1174. shotEngine.dispatchPendingMessages();
  1175. auto shoot = [&] (std::unique_ptr<juce::Component> c, const juce::String& name) {
  1176. if (c == nullptr)
  1177. return false;
  1178. if (c->getWidth() <= 0)
  1179. c->setSize (520, 600);
  1180. savePng (c->createComponentSnapshot (c->getLocalBounds()), prefix + name);
  1181. return true;
  1182. };
  1183. ok = ok && shoot (lynx::makeChannelPrecomputePanel (shotEngine, 0), "-precompute.png");
  1184. ok = ok && shoot (lynx::makeSettingsPanel (shotEngine, lynx::SettingsPage::project), "-project.png");
  1185. setApplicationReturnValue (ok ? 0 : 1);
  1186. quit();
  1187. return;
  1188. }
  1189. if (args.contains ("--pluginthumbs"))
  1190. {
  1191. // LYNX.exe --pluginthumbs <folder> [key,key...]: the Plugin picker's pictures of LYNX's own plugins (round 171c,
  1192. // ui/PluginThumbs.h), each editor drawn off-screen and kept as <folder>/<name>.png; the picker starts this in
  1193. // the background when pictures are missing. One line per plugin on stdout.
  1194. const auto i = args.indexOf ("--pluginthumbs");
  1195. lynx::crashguard::quietCrashReports();
  1196. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  1197. juce::StringArray only;
  1198. if (i + 2 < args.size() && ! args[i + 2].startsWith ("--"))
  1199. only.addTokens (args[i + 2].unquoted(), ",", "");
  1200. const auto t0 = juce::Time::getMillisecondCounterHiRes();
  1201. const auto drawn = lynx::pluginthumbs::renderNative (juce::File (args[i + 1].unquoted()), only, [] (const juce::String& line) {
  1202. std::printf ("%s\n", line.toRawUTF8());
  1203. std::fflush (stdout);
  1204. });
  1205. std::printf ("drawn %d in %.0f ms\n", drawn, juce::Time::getMillisecondCounterHiRes() - t0);
  1206. setApplicationReturnValue (0);
  1207. quit();
  1208. return;
  1209. }
  1210. if (args.contains ("--artshot"))
  1211. {
  1212. // LYNX.exe --artshot <folder> [before|after] [name,name...]: every editor with art of its own (round 170j/170k: the
  1213. // Themed style; or only the named ones, e.g. "sakura,facet-eq") drawn off-screen at 100 % and 200 % as
  1214. // <folder>/<plugin>-<before|after>-<scale>.png. "before" draws each in the style it had before the Themed style
  1215. const auto i = args.indexOf ("--artshot");
  1216. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  1217. const auto mode = i + 2 < args.size() && ! args[i + 2].startsWith ("--") ? args[i + 2].unquoted() : juce::String ("after");
  1218. if (i + 3 < args.size() && ! args[i + 3].startsWith ("--")) // [name,name...]: only these arts
  1219. artOnly().addTokens (args[i + 3].unquoted(), ",", "");
  1220. setApplicationReturnValue (runArtShots (juce::File (args[i + 1].unquoted()), mode == "before") ? 0 : 1);
  1221. quit();
  1222. return;
  1223. }
  1224. if (args.contains ("--artgui"))
  1225. {
  1226. // LYNX.exe --artgui <folder> [before|after|still] [name,name...]: the same editors in REAL windows on the desktop, one at a
  1227. // time (always on top, no focus taken), each held while an outside script screenshots it (it writes
  1228. // <folder>/<plugin>.ready with the window's bounds and waits up to 10 s for <folder>/<plugin>.done), then the
  1229. // process CPU it costs over 6 s is written to <folder>/cpu-<mode>.txt. "still": Themed with the motion off
  1230. const auto i = args.indexOf ("--artgui");
  1231. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  1232. const auto mode = i + 2 < args.size() && ! args[i + 2].startsWith ("--") ? args[i + 2].unquoted() : juce::String ("after");
  1233. if (i + 3 < args.size() && ! args[i + 3].startsWith ("--")) // [name,name...]: only these arts
  1234. artOnly().addTokens (args[i + 3].unquoted(), ",", "");
  1235. runArtGui (juce::File (args[i + 1].unquoted()), mode);
  1236. return;
  1237. }
  1238. if (args.contains ("--instrumentshot"))
  1239. {
  1240. // LYNX.exe --instrumentshot <folder> <engine,engine...|banks> [lynx|fl]: round 168n — the channel window of
  1241. // each engine (its Plugin tab) at 100 %, 150 % and 200 %, as <folder>/<engine>-<source>-<scale>.png. Source
  1242. // "lynx" starts from the engine's LYNX bank (what a PC without FL gets), "fl" from FL's Default preset.
  1243. const auto i = args.indexOf ("--instrumentshot");
  1244. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  1245. const auto source = i + 3 < args.size() && ! args[i + 3].startsWith ("--") ? args[i + 3].unquoted() : juce::String ("lynx");
  1246. setApplicationReturnValue (runInstrumentShots (juce::File (args[i + 1].unquoted()), args[i + 2].unquoted(), source) ? 0 : 1);
  1247. quit();
  1248. return;
  1249. }
  1250. if (args.contains ("--flextrashot"))
  1251. {
  1252. // LYNX.exe --flextrashot <folder>: pictures of the editors of round 165g (Big Clock, Tuner, HTML NoteBook, Mute 2, Scratcher, Transmitter) + round 167n Transporter
  1253. const auto i = args.indexOf ("--flextrashot");
  1254. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  1255. lynx::AudioEngine shotEngine (false);
  1256. const auto ok = lynx::runFlExtraShots (shotEngine, juce::File (args[i + 1].unquoted()));
  1257. setApplicationReturnValue (ok ? 0 : 1);
  1258. quit();
  1259. return;
  1260. }
  1261. if (args.contains ("--visualtest"))
  1262. {
  1263. // LYNX.exe --visualtest <folder> [project.flp]: the visual plugins (round 164c) — the audio path's CPU, every
  1264. // Wave Candy mode and Visualizer scene drawn from a test signal (PNG + the editor's CPU each), and the video
  1265. // export of a project (default: FL's first ZGameEditor demo) with ffmpeg and as images. Writes report.txt.
  1266. const auto i = args.indexOf ("--visualtest");
  1267. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  1268. const auto project = i + 2 < args.size() && ! args[i + 2].startsWith ("--") ? juce::File (args[i + 2].unquoted()) : juce::File();
  1269. lynx::runVisualTest (juce::File (args[i + 1].unquoted()), project, [this] (bool ok) {
  1270. setApplicationReturnValue (ok ? 0 : 1);
  1271. quit();
  1272. });
  1273. return;
  1274. }
  1275. if (args.contains ("--menu-entry"))
  1276. {
  1277. // LYNX.AppImage --menu-entry on|off: puts the AppImage in the applications menu (and .lynx files on it) or
  1278. // takes it out again, without opening a window; the same as the switch in Options › General (round 161)
  1279. const auto i = args.indexOf ("--menu-entry");
  1280. const auto on = args[i + 1].unquoted() != "off";
  1281. const auto ok = lynx::runningAsAppImage() && lynx::setAppImageMenuEntry (on);
  1282. std::fprintf (ok ? stdout : stderr, "%s\n", ok ? (on ? "LYNX SHARE added to the applications menu" : "LYNX SHARE removed from the applications menu")
  1283. : "only the LYNX SHARE AppImage on Linux can do this");
  1284. setApplicationReturnValue (ok ? 0 : 1);
  1285. quit();
  1286. return;
  1287. }
  1288. if (args.contains ("--send-test-report"))
  1289. {
  1290. // LYNX.exe --send-test-report out.txt [--dry]: builds a crash report marked "test" from the newest crash /
  1291. // hang file and this computer's facts, writes its JSON to out.txt.json and (without --dry) sends it to
  1292. // lynx-share.com (LYNX_CRASH_ENDPOINT overrides); out.txt gets "id=…" and "result=OK" or the error (round 159)
  1293. const auto i = args.indexOf ("--send-test-report");
  1294. const juce::File out (args[i + 1].unquoted());
  1295. lynx::crashreporter::Session session;
  1296. session.version = getApplicationVersion();
  1297. for (const auto* pattern : { "crash *.txt", "hang *.txt" })
  1298. {
  1299. auto files = lynx::platform::settingsFile ("autosave").findChildFiles (juce::File::findFiles, false, pattern);
  1300. lynx::filesort::byTime (files, lynx::filesort::By::modificationTime, true);
  1301. if (! files.isEmpty())
  1302. (juce::String (pattern).startsWith ("crash") ? session.crashFile : session.hangFile) = files[0];
  1303. }
  1304. session.steps = { "00:00:01 test report (LYNX.exe --send-test-report)", "00:00:02 opening project " + out.getFileName() };
  1305. auto input = lynx::crashreporter::makeInput (session, session.crashFile.existsAsFile() ? "crash" : "manual", nullptr);
  1306. input.test = true;
  1307. const auto json = lynx::crashreporter::buildJson (input, false);
  1308. out.withFileExtension (out.getFileExtension() + ".json").replaceWithText (json);
  1309. const auto error = args.contains ("--dry") ? juce::String() : lynx::crashreporter::sendNow (json);
  1310. out.replaceWithText ("id=" + juce::String::fromUTF8 (input.id.c_str()) + "\nendpoint=" + lynx::crashreporter::endpoint() + "\nbytes="
  1311. + juce::String (json.getNumBytesAsUTF8()) + "\nresult=" + (error.isEmpty() ? juce::String ("OK") : error) + "\n");
  1312. setApplicationReturnValue (error.isEmpty() ? 0 : 1);
  1313. quit();
  1314. return;
  1315. }
  1316. if (args.contains ("--symbolize"))
  1317. {
  1318. // LYNX.exe --symbolize "crash … .txt" out.txt: names the LYNX.exe+offset frames of a user's crash / hang file
  1319. // (needs this build's LYNX.pdb next to LYNX.exe — the release's "LYNX-symbols" CI artifact; round 157a)
  1320. const auto i = args.indexOf ("--symbolize");
  1321. const auto text = juce::File (args[i + 1].unquoted()).loadFileAsString();
  1322. juce::File (args[i + 2].unquoted()).replaceWithText (juce::String::fromUTF8 (lynx::crashguard::symbolizeOwnFrames (text.toStdString()).c_str()));
  1323. quit();
  1324. return;
  1325. }
  1326. if (args.contains ("--opentest"))
  1327. {
  1328. // LYNX.exe --opentest report.txt [--visible]: every built-in effect and instrument window opened as the mixer /
  1329. // Channel rack open them, with default, extreme, random and old-project states; a watchdog fails the test on
  1330. // a hang (round 157a: opening the Parametric EQ froze LYNX). Windows stay off-screen without --visible.
  1331. const auto i = args.indexOf ("--opentest");
  1332. runOpenTest (args[i + 1].unquoted(), args.contains ("--visible"), [this] (bool ok) {
  1333. setApplicationReturnValue (ok ? 0 : 1);
  1334. quit();
  1335. });
  1336. return;
  1337. }
  1338. if (args.contains ("--fxfuzz"))
  1339. {
  1340. // LYNX.exe --fxfuzz report.txt [rounds] [--drags]: every built-in effect in its editor, parameters swept (and
  1341. // dragged with the mouse), audio rendered at several rates; a crash ends the process (round 111)
  1342. const auto i = args.indexOf ("--fxfuzz");
  1343. const auto rounds = args.size() > i + 2 ? juce::jmax (1, args[i + 2].getIntValue()) : 6;
  1344. // --drags: also mouse drags over the editors (their menus may flash on screen: not for the selftest)
  1345. const auto ok = runEffectFuzz (rounds, args[i + 1].unquoted(), args.contains ("--drags"));
  1346. setApplicationReturnValue (ok ? 0 : 1);
  1347. quit();
  1348. return;
  1349. }
  1350. if (args.contains ("--controllershot"))
  1351. {
  1352. // LYNX.exe --controllershot prefix: the built-in controllers' editors (round 133) as PNGs
  1353. const auto i = args.indexOf ("--controllershot");
  1354. runControllerShot (args[i + 1].unquoted());
  1355. quit();
  1356. return;
  1357. }
  1358. if (args.contains ("--edisonshot"))
  1359. {
  1360. // LYNX.exe --edisonshot prefix [audio.wav]: the audio editor's Edison tool windows (round 165l) and the
  1361. // editor before / after some of them, as PNGs (a synthetic drum loop without a file)
  1362. const auto i = args.indexOf ("--edisonshot");
  1363. runEdisonShot (args[i + 1].unquoted(), i + 2 < args.size() ? args[i + 2].unquoted() : juce::String());
  1364. quit();
  1365. return;
  1366. }
  1367. if (args.contains ("--danceshot"))
  1368. {
  1369. // LYNX.exe --danceshot prefix: LYNX Dance (round 165e) — every move as a contact sheet, the channel's editor,
  1370. // and a demo project with two dance channels (for --snapshot)
  1371. const auto i = args.indexOf ("--danceshot");
  1372. runDanceShot (args[i + 1].unquoted());
  1373. quit();
  1374. return;
  1375. }
  1376. if (args.contains ("--videoshot") && args.indexOf ("--videoshot") + 2 < args.size())
  1377. {
  1378. // LYNX.exe --videoshot prefix video: the Video Player's editor (round 165g) at a few song positions, with
  1379. // the user's ffmpeg, as PNGs + report.txt (frames decoded, the sound track)
  1380. const auto i = args.indexOf ("--videoshot");
  1381. runVideoShot (args[i + 1].unquoted(), args[i + 2].unquoted());
  1382. return;
  1383. }
  1384. if (args.contains ("--videotrackshot") && args.indexOf ("--videotrackshot") + 2 < args.size())
  1385. {
  1386. // LYNX.exe --videotrackshot prefix video [video2]: round 174d — the Playlist with video tracks (filmstrips,
  1387. // timecode row) and the video window at a few song positions, as PNGs + report.txt (the decoder, the
  1388. // frame shown for each wanted time: frame accuracy, frames dropped)
  1389. const auto i = args.indexOf ("--videotrackshot");
  1390. runVideoTrackShot (args[i + 1].unquoted(), args[i + 2].unquoted(), i + 3 < args.size() ? args[i + 3].unquoted() : juce::String());
  1391. return;
  1392. }
  1393. if (args.contains ("--vfxshot"))
  1394. {
  1395. // LYNX.exe --vfxshot prefix: the VFX note effects' editors (round 164b), on channels and in a Patcher, as PNGs
  1396. const auto i = args.indexOf ("--vfxshot");
  1397. runVfxShot (args[i + 1].unquoted());
  1398. quit();
  1399. return;
  1400. }
  1401. if (args.contains ("--patchershot"))
  1402. {
  1403. // LYNX.exe --patchershot prefix [project]: every Patcher's editor (round 141) as PNGs (a demo one without a project)
  1404. const auto i = args.indexOf ("--patchershot");
  1405. runPatcherShot (args[i + 1].unquoted(), i + 2 < args.size() ? args[i + 2].unquoted() : juce::String());
  1406. quit();
  1407. return;
  1408. }
  1409. if (args.contains ("--comp177shot"))
  1410. {
  1411. // LYNX.exe --comp177shot prefix project (round 177c): a project of loop takes in the maximised
  1412. // Playlist as it opened; every group after "Comp these takes", with a swipe on the first; the track and record menus
  1413. const auto i = args.indexOf ("--comp177shot");
  1414. runComp177Shot (args[i + 1].unquoted(), args[i + 2].unquoted());
  1415. quit();
  1416. return;
  1417. }
  1418. if (args.contains ("--feat166shot"))
  1419. {
  1420. // LYNX.exe --feat166shot prefix [project]: round 166d (issue #14) — the Piano Roll with a scale, folded to
  1421. // it, with one ghost channel, the ghost channels menu, and the Mixer filled to 500 inserts (its start and
  1422. // its end, and the time a full repaint takes)
  1423. const auto i = args.indexOf ("--feat166shot");
  1424. runFeat166Shot (args[i + 1].unquoted(), i + 2 < args.size() ? args[i + 2].unquoted() : juce::String());
  1425. quit();
  1426. return;
  1427. }
  1428. if (args.contains ("--perfshot"))
  1429. {
  1430. // LYNX.exe --perfshot prefix project: the Playlist in Performance mode with a few clips launched and waiting,
  1431. // then the project patcherized (every insert's effects, the first channels) saved as prefix-patcherized.lynx
  1432. // for --patchershot (round 165m)
  1433. const auto i = args.indexOf ("--perfshot");
  1434. runPerfShot (args[i + 1].unquoted(), i + 2 < args.size() ? args[i + 2].unquoted() : juce::String());
  1435. quit();
  1436. return;
  1437. }
  1438. if (args.contains ("--gridshot"))
  1439. {
  1440. // LYNX.exe --gridshot prefix [project]: the Clip-launch workflow's layout off-screen, with a grid of sample
  1441. // clips, some playing and waiting, at the size of LYNX_SNAPSHOT_SIZE (round 181a); with a project (.lynx,
  1442. // .flp, .als), that project's grid instead (round 181c: a Live set's Session view as LYNX imports it)
  1443. const auto i = args.indexOf ("--gridshot");
  1444. const auto project = i + 2 < args.size() && ! args[i + 2].startsWith ("--") ? args[i + 2].unquoted() : juce::String();
  1445. runGridShot (args[i + 1].unquoted(), project);
  1446. quit();
  1447. return;
  1448. }
  1449. if (args.contains ("--simpleshot"))
  1450. {
  1451. // LYNX.exe --simpleshot prefix: round 184a's Simple workflow off-screen — View › Layout style with each style
  1452. // chosen, Settings › General (Pattern, then Simple selected) with its style list, the window in Pattern, then
  1453. // Simple, then Pattern again, and how many Simple workflow objects existed before and after (0 before)
  1454. const auto i = args.indexOf ("--simpleshot");
  1455. runSimpleShot (args[i + 1].unquoted());
  1456. quit();
  1457. return;
  1458. }
  1459. if (args.contains ("--detailshot"))
  1460. {
  1461. // LYNX.exe --detailshot prefix: the Clip-launch workflow's detail view off-screen (round 183a): a track's chain
  1462. // (instrument, effects, one off, one folded), its clip page, and Pattern workflow before / after, at
  1463. // LYNX_SNAPSHOT_SIZE. Writes prefix-counts.txt with what the chain shows.
  1464. const auto i = args.indexOf ("--detailshot");
  1465. runDetailShot (args[i + 1].unquoted());
  1466. quit();
  1467. return;
  1468. }
  1469. if (args.contains ("--typeaheadtest"))
  1470. {
  1471. // LYNX.exe --typeaheadtest out.txt: issue #64 — a real popup menu (headings, a submenu) driven by key presses
  1472. // through its window's peer, as the OS delivers them; writes what got the highlight and what was picked
  1473. const auto i = args.indexOf ("--typeaheadtest");
  1474. runTypeAheadTest (juce::File (args[i + 1].unquoted()));
  1475. return;
  1476. }
  1477. if (args.contains ("--choosertest"))
  1478. {
  1479. // LYNX --choosertest out.txt file: issue #72 — opens LYNX's file chooser as the UI does (makeFileChooser +
  1480. // launchChooser) and reports which dialog came up and what reached the callback. A built-in dialog is shot
  1481. // (out.txt.png), `file` typed into it and confirmed; a native one (zenity / kdialog) is left to answer.
  1482. const auto i = args.indexOf ("--choosertest");
  1483. runChooserTest (juce::File (args[i + 1].unquoted()), juce::File (args[i + 2].unquoted()));
  1484. return;
  1485. }
  1486. if (args.contains ("--snapshot"))
  1487. {
  1488. const auto i = args.indexOf ("--snapshot");
  1489. runSnapshot (args[i + 1].unquoted(), args[i + 2].unquoted());
  1490. return;
  1491. }
  1492. if (args.contains ("--stemsplit"))
  1493. {
  1494. // LYNX.exe --stemsplit input.wav folder: the stem separation of the clip menu, without the window
  1495. const auto i = args.indexOf ("--stemsplit");
  1496. lynx::AudioEngine loader (false);
  1497. const auto error = lynx::extractStemsToFolder (loader, juce::File (args[i + 1].unquoted()), juce::File (args[i + 2].unquoted()));
  1498. juce::File (args[i + 2].unquoted()).getSiblingFile ("stemsplit.txt").replaceWithText (error.isEmpty() ? "result=OK\n" : "result=FAIL " + error + "\n");
  1499. setApplicationReturnValue (error.isEmpty() ? 0 : 1);
  1500. quit();
  1501. return;
  1502. }
  1503. if (args.contains ("--audio2midi"))
  1504. {
  1505. // LYNX.exe --audio2midi input.wav melody|harmony|drums notes.csv: the clip menu's Convert to MIDI, without the
  1506. // window (round a2m189b's measurements)
  1507. const auto i = args.indexOf ("--audio2midi");
  1508. const auto mode = args[i + 2] == "drums" ? lynx::a2m::Mode::drums : args[i + 2] == "harmony" ? lynx::a2m::Mode::harmony : lynx::a2m::Mode::melody;
  1509. lynx::AudioEngine loader (false);
  1510. const juce::File csv (args[i + 3].unquoted());
  1511. const auto error = lynx::convertFileToMidiCsv (loader, juce::File (args[i + 1].unquoted()), mode, csv);
  1512. csv.getSiblingFile ("audio2midi.txt").replaceWithText (error.isEmpty() ? "result=OK\n" : "result=FAIL " + error + "\n");
  1513. setApplicationReturnValue (error.isEmpty() ? 0 : 1);
  1514. quit();
  1515. return;
  1516. }
  1517. if (args.contains ("--stems"))
  1518. {
  1519. // LYNX.exe --stems project.(flp|als|lynx) base.wav: one WAV per insert that has sound (like "Export stems")
  1520. const auto i = args.indexOf ("--stems");
  1521. juce::String error, report;
  1522. int written = 0;
  1523. {
  1524. lynx::AudioEngine loader (false);
  1525. const juce::File input (args[i + 1].unquoted()), base (args[i + 2].unquoted());
  1526. // an .flp or a Live set (.als) opens through the import, as File › Open does (round 182b)
  1527. auto ok = input.hasFileExtension ("flp;als") ? loader.importFlpFile (input, error) : false;
  1528. if (! input.hasFileExtension ("flp;als"))
  1529. if (auto song = lynx::ProjectFile::load (input, error))
  1530. {
  1531. loader.setSong (std::move (*song));
  1532. ok = true;
  1533. }
  1534. const auto& song = loader.getSong();
  1535. for (int t = 1; ok && t < (int) song.mixer.size(); ++t)
  1536. {
  1537. if (std::none_of (song.channels.begin(), song.channels.end(), [t] (const lynx::ChannelDef& c) { return c.mixerTrack == t; }))
  1538. continue;
  1539. const auto file = base.getSiblingFile (base.getFileNameWithoutExtension() + " - " + juce::String (t) + ".wav");
  1540. lynx::ExportSettings settings;
  1541. lynx::ExportJob job (lynx::makeBounceSong (song, t), settings, file);
  1542. if (job.run ({}, error))
  1543. {
  1544. ++written;
  1545. report << file.getFileName() << " peak=" << job.getPeak() << "\n";
  1546. }
  1547. }
  1548. }
  1549. report << "stems=" << written << "\n";
  1550. juce::File (args[i + 2].unquoted() + ".txt").replaceWithText (report);
  1551. setApplicationReturnValue (written > 0 ? 0 : 1);
  1552. quit();
  1553. return;
  1554. }
  1555. // --export-als <in.lynx|.flp|.als> <folder> [--live11] [--reference] [--scan]: "<folder>/<name> Project/<name>.als" (round 175a)
  1556. if (args.contains ("--export-als"))
  1557. {
  1558. const auto i = args.indexOf ("--export-als");
  1559. runAlsExport (args[i + 1].unquoted(), args[i + 2].unquoted(), args.contains ("--live11"), args.contains ("--reference"));
  1560. return;
  1561. }
  1562. // --gamepadshot <prefix> (round 184a, S16): the game controller's hints overlay and the MIDI settings page with
  1563. // the option on, offscreen, plus the poller fed fake pad states ("<prefix>-gamepad.txt")
  1564. if (args.contains ("--gamepadshot"))
  1565. {
  1566. runGamepadShot (args[args.indexOf ("--gamepadshot") + 1].unquoted());
  1567. return;
  1568. }
  1569. // --export-bundle <in.lynx|.flp|.als> <folder> [--zip] [--no-mixdown] [--shot <prefix>] (round 184a, S9): File ›
  1570. // Export › "For other apps..." without the window; the report goes to "<folder>/export-bundle.txt"
  1571. if (args.contains ("--export-bundle"))
  1572. {
  1573. const auto i = args.indexOf ("--export-bundle");
  1574. runBundleExport (args[i + 1].unquoted(), args[i + 2].unquoted(), args.contains ("--zip"), ! args.contains ("--no-mixdown"),
  1575. args.contains ("--shot") ? args[args.indexOf ("--shot") + 1].unquoted() : juce::String());
  1576. return;
  1577. }
  1578. if (args.contains ("--export-flp"))
  1579. {
  1580. const auto i = args.indexOf ("--export-flp");
  1581. runFlExport (args[i + 1].unquoted(), args[i + 2].unquoted(), args.contains ("--substitute"));
  1582. return;
  1583. }
  1584. if (args.contains ("--export"))
  1585. {
  1586. const auto i = args.indexOf ("--export");
  1587. const auto insert = args.contains ("--insert") ? args[args.indexOf ("--insert") + 1].getIntValue() : 0;
  1588. runExport (args[i + 1].unquoted(), args[i + 2].unquoted(), args.contains ("--pattern"), insert);
  1589. return;
  1590. }
  1591. if (args.contains ("--render"))
  1592. {
  1593. const auto i = args.indexOf ("--render");
  1594. runRender (args[i + 1].unquoted(), args[i + 2].unquoted(), args[i + 3].getDoubleValue());
  1595. return;
  1596. }
  1597. // session breadcrumb: a fail-fast (no crash handler runs) still leaves the last steps behind (round 111)
  1598. uncleanLastStep = collectUncleanSessions();
  1599. sessionsFolder().createDirectory();
  1600. lynx::crashguard::beginSession (
  1601. sessionsFolder().getChildFile ("session-" + juce::String (lynx::crashguard::processId()) + ".txt").getFullPathName().toStdString(),
  1602. ("LYNX session\nversion=" + getApplicationVersion() + "\npid=" + juce::String (lynx::crashguard::processId())
  1603. + "\nstart=" + juce::String ((juce::int64) lynx::crashguard::processStartTime())
  1604. + "\nstarted=" + juce::Time::getCurrentTime().toISO8601 (true) + "\n").toStdString());
  1605. startHangWatch();
  1606. // LYNX_PROFILE_MAIN=<file> (round 174f): the message thread sampled every millisecond, 5-second windows
  1607. if (const auto profile = juce::SystemStats::getEnvironmentVariable ("LYNX_PROFILE_MAIN", {}); profile.isNotEmpty())
  1608. lynx::crashguard::startMainProfiler (profile.toStdString());
  1609. startupTrace.mark ("initialise (normal start)");
  1610. if (startupTrace.on)
  1611. lynx::startupMark = startupMarkHook;
  1612. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  1613. lynx::themeui::loadSaved(); // the user's theme (Options › Theme, round 162d)
  1614. startupOptions = lynx::StartupOptions::load();
  1615. lynx::registerFileTypes();
  1616. startupTrace.mark ("options + file types");
  1617. // Double-clicking a .lynx/.flp opens LYNX with the file as an argument; a path typed in a terminal may be relative
  1618. // (D#92, round 180a: it was ignored, leaving the blank project with no message). A missing file gets "Could not open".
  1619. if (args.size() > 0 && lynx::safety::isFileArgument (args[0].unquoted().toStdString()))
  1620. fileToOpen = juce::File::getCurrentWorkingDirectory().getChildFile (args[0].unquoted());
  1621. // LYNX_TEST_MODE=1 LYNX --open-event-test <ms> <file>: the file arrives the way macOS's Finder delivers it (a Linux
  1622. // or Windows run can exercise that path): 0 ms = at once, before the window exists
  1623. if (lynx::platform::testMode() && args[0] == "--open-event-test" && args.size() > 2)
  1624. {
  1625. const auto file = args[2].unquoted().quoted();
  1626. if (args[1].getIntValue() == 0)
  1627. anotherInstanceStarted (file);
  1628. else
  1629. juce::Timer::callAfterDelay (args[1].getIntValue(), [this, file] { anotherInstanceStarted (file); });
  1630. }
  1631. // LYNX --opentime project.(flp|lynx)|- report.txt [idle seconds] (round 165i): the normal start-up (splash, audio
  1632. // device, window) opens the project, waits until it is loaded and LYNX has gone quiet, measures the idle CPU and
  1633. // memory, writes the times and quits normally (a benchmark that killed LYNX left "closed unexpectedly" behind)
  1634. if (args.contains ("--opentime"))
  1635. {
  1636. const auto i = args.indexOf ("--opentime");
  1637. const auto project = args[i + 1].unquoted();
  1638. fileToOpen = project != "-" && juce::File::isAbsolutePath (project) ? juce::File (project) : juce::File();
  1639. openTimeReport = juce::File (args[i + 2].unquoted());
  1640. if (args.size() > i + 3 && ! args[i + 3].startsWith ("--"))
  1641. openTimeIdleSeconds = juce::jlimit (1, 120, args[i + 3].getIntValue());
  1642. }
  1643. if (! startupOptions.splash)
  1644. {
  1645. startEngine();
  1646. createMainWindow();
  1647. mainWindow->reveal();
  1648. showUncleanNotice();
  1649. startupTrace.mark ("window revealed");
  1650. openStartupFile();
  1651. startupTrace.mark ("startup file opened");
  1652. startOpenTimeProbe();
  1653. startUpdateCheck();
  1654. juce::MessageManager::callAsync ([] { startupTrace.mark ("first message loop turn"); });
  1655. return;
  1656. }
  1657. // the splash first, so it is on screen while the audio device opens; the main window is built
  1658. // once the pepper has landed (the scene is still for a moment then) and shown when the splash ends
  1659. splash = std::make_unique<lynx::SplashScreen>();
  1660. startupTrace.mark ("splash made");
  1661. splash->showOnDesktop();
  1662. startupTrace.mark ("splash on the desktop");
  1663. juce::Timer::callAfterDelay (40, [this] {
  1664. startEngine();
  1665. if (splash == nullptr) // quit meanwhile
  1666. return;
  1667. splash->setStatus (lynx::tr ("Loading the workspace..."));
  1668. splash->startClock();
  1669. // the minimum counts from the process start (the audio device took part of it already)
  1670. splashDuration = lynx::SplashScreen::remainingDuration (startupTrace.seconds());
  1671. splash->setBarDuration (splashDuration);
  1672. juce::Timer::callAfterDelay (1050, [this] {
  1673. if (splash == nullptr || engine == nullptr)
  1674. return;
  1675. createMainWindow();
  1676. const auto wait = juce::jmax (0.0, splashDuration - splash->getElapsed());
  1677. juce::Timer::callAfterDelay ((int) (wait * 1000.0), [this] {
  1678. if (splash == nullptr || mainWindow == nullptr)
  1679. return;
  1680. mainWindow->reveal();
  1681. startupTrace.mark ("window revealed (after the splash)");
  1682. splash->toFront (false);
  1683. splash->finish ([this] { splash = nullptr; });
  1684. showUncleanNotice();
  1685. openStartupFile();
  1686. startupTrace.mark ("startup file opened");
  1687. startOpenTimeProbe();
  1688. startUpdateCheck();
  1689. juce::MessageManager::callAsync ([] { startupTrace.mark ("first message loop turn"); });
  1690. // first run: language, audio, plugin folders (FL Studio's included) and a background scan
  1691. if (! lynx::setupWizardDone() && lynx::platform::testMode())
  1692. lynx::platform::testModeLog ("setup wizard");
  1693. else if (! lynx::setupWizardDone())
  1694. mainWindow->showSetupWizard();
  1695. });
  1696. });
  1697. });
  1698. }
  1699. void startEngine()
  1700. {
  1701. startupTrace.mark ("before the audio engine");
  1702. engine = std::make_unique<lynx::AudioEngine>();
  1703. lynx::videoview::install (*engine); // (Fruity Video Player channels: their sound tracks)
  1704. startupTrace.mark ("audio engine + device");
  1705. crashEngine = engine.get();
  1706. lynx::crashreporter::watchAudioDevice (engine->getDeviceManager()); // (the session file names the device: crash reports)
  1707. addDriverFileDeviceType();
  1708. if (startupOptions.sound)
  1709. {
  1710. // Options › Theme › Startup sound (issue #12): the user's file, else (or when it can't be read) LYNX's own
  1711. std::shared_ptr<const lynx::SampleData> sound;
  1712. if (const auto& own = lynx::themeui::current().startupSound; ! own.empty() && juce::File (juce::String::fromUTF8 (own.c_str())).existsAsFile())
  1713. sound = engine->getSampleLibrary().load (juce::String::fromUTF8 (own.c_str()));
  1714. engine->previewSample (sound != nullptr ? sound : lynx::makeStartupSample());
  1715. }
  1716. startupTrace.mark ("startup sound");
  1717. // a project given on the command line: its slow plugin modules (a Waves shell) start now, on their own
  1718. // thread, while the splash and the main window come up (round 121)
  1719. if (fileToOpen.hasFileExtension ("flp"))
  1720. if (juce::MemoryBlock data; fileToOpen.loadFileAsData (data))
  1721. try
  1722. {
  1723. engine->getPluginHost().startModulesFor (lynx::flpForeignPlugins (flp::parseProject ({ static_cast<const std::uint8_t*> (data.getData()), data.getSize() })));
  1724. startupTrace.mark ("plugin modules started ahead");
  1725. }
  1726. catch (const flp::Error&)
  1727. {
  1728. }
  1729. }
  1730. void createMainWindow()
  1731. {
  1732. mainWindow = std::make_unique<MainWindow> ("LYNX SHARE", *engine); // the brand; getApplicationName() stays "LYNX" (an id: instance lock, X11 WM_CLASS, ALSA client)
  1733. lynx::setMainWindowForOwnership (mainWindow.get());
  1734. lynx::applyRenderingChoice (*mainWindow); // (GPU rendering off: GDI; round 157a)
  1735. lynx::startRenderingWatch();
  1736. startupTrace.mark ("main window built");
  1737. }
  1738. // the previous run ended without closing (see collectUncleanSessions): say so once, with its last step — and, as
  1739. // Settings › General › "Crash reports" says (round 159), ask whether to send a report, send it unasked, or not
  1740. void showUncleanNotice()
  1741. {
  1742. if (lynx::platform::testMode()) // LYNX_TEST_MODE: no prompt, no report sent (written to test-mode.log)
  1743. {
  1744. if (uncleanLastStep.isNotEmpty())
  1745. lynx::platform::testModeLog ("\"closed unexpectedly\" notice (last step: " + uncleanLastStep + ")");
  1746. return;
  1747. }
  1748. if (uncleanLastStep.isEmpty())
  1749. {
  1750. lynx::crashreporter::retryPending(); // (reports an earlier run could not send: once more)
  1751. return;
  1752. }
  1753. auto message = lynx::tr ("The last session ended without closing normally. Last step: {0}. Backup copies of your project are in "
  1754. "LYNX SHARE's autosave folder; details in crash-history.log.",
  1755. { uncleanLastStep });
  1756. uncleanLastStep.clear();
  1757. const auto cause = uncleanCause();
  1758. // round 157a: a plugin's editor was opening — it crashed (often in the graphics driver, inside the plugin's own
  1759. // OpenGL window): offer to keep that plugin in its own process, where a crash takes only the plugin down
  1760. juce::String separatePlugin;
  1761. if (cause.editorPlugin.isNotEmpty() && ! lynx::pluginSandboxEnabled() && ! lynx::pluginAlwaysSeparate (cause.editorPlugin))
  1762. separatePlugin = cause.editorPlugin;
  1763. // LYNX's own drawing crashed in the graphics driver (Direct2D / Direct3D): draw with the CPU from now on
  1764. else if (cause.gpuDriver && lynx::gpuRenderingEnabled())
  1765. {
  1766. lynx::setGpuRenderingEnabled (false);
  1767. message << "\n\n"
  1768. << lynx::tr ("The crash was in the graphics driver ({0}). LYNX SHARE now draws its windows without the GPU; you can turn GPU "
  1769. "rendering back on in Options > General settings (after a driver update, for example).",
  1770. { cause.driverModule });
  1771. }
  1772. // round 165e: the Visualizer's GPU view was drawing when the session ended (a driver crash, a hang, the machine
  1773. // going down): the Visualizer draws with the 2D renderer from now on (its GPU button turns it back on)
  1774. for (int i = uncleanSteps.size(); --i >= 0;)
  1775. {
  1776. if (uncleanSteps[i].contains (lynx::visualgl::stopNote))
  1777. break;
  1778. if (uncleanSteps[i].contains (lynx::visualgl::startNote))
  1779. {
  1780. if (lynx::visualgl::enabled())
  1781. {
  1782. lynx::visualgl::setEnabled (false);
  1783. message << "\n\n"
  1784. << lynx::tr ("The Visualizer was drawing with the GPU (OpenGL) when it happened. It now draws without the GPU; its GPU "
  1785. "button turns it back on.");
  1786. }
  1787. break;
  1788. }
  1789. }
  1790. const auto session = lynx::crashreporter::parseSession (uncleanSessionText);
  1791. auto* devices = engine != nullptr ? &engine->getDeviceManager() : nullptr;
  1792. const auto action = lynx::crashreport::actionFor (lynx::crashreporter::consent());
  1793. lynx::crashreporter::retryPending();
  1794. if (action == lynx::crashreport::Action::askUser)
  1795. {
  1796. if (separatePlugin.isNotEmpty())
  1797. message << "\n\n"
  1798. << lynx::tr ("It happened while the window of {0} was opening{1}.",
  1799. { separatePlugin, cause.gpuDriver ? lynx::tr (" (in the graphics driver, {0})", { cause.driverModule }) : juce::String() });
  1800. lynx::crashreporter::showStartupDialog (session, message, separatePlugin, [separatePlugin] { lynx::setPluginAlwaysSeparate (separatePlugin, true); },
  1801. devices);
  1802. return;
  1803. }
  1804. if (action == lynx::crashreport::Action::sendSilently)
  1805. {
  1806. const auto input = lynx::crashreporter::makeInput (session, session.kind(), devices);
  1807. lynx::crashreporter::send (lynx::crashreporter::buildJson (input, false), juce::String::fromUTF8 (input.id.c_str()));
  1808. message << "\n\n" << lynx::tr ("A crash report is being sent to help fix it (Options > General settings > Crash reports).");
  1809. }
  1810. if (separatePlugin.isNotEmpty())
  1811. {
  1812. juce::AlertWindow::showOkCancelBox (
  1813. juce::MessageBoxIconType::WarningIcon, lynx::tr ("LYNX SHARE closed unexpectedly"),
  1814. message + "\n\n"
  1815. + lynx::tr ("It happened while the window of {0} was opening{1}. Run {0} in a separate process from now on? If it "
  1816. "crashes again, only the plugin stops and LYNX SHARE keeps running (Plugin wrapper menu: \"Always run in a "
  1817. "separate process\").",
  1818. { separatePlugin, cause.gpuDriver ? lynx::tr (" (in the graphics driver, {0})", { cause.driverModule }) : juce::String() }),
  1819. lynx::tr ("Run separately"), lynx::tr ("No"), nullptr,
  1820. juce::ModalCallbackFunction::create ([separatePlugin] (int result) {
  1821. if (result != 0)
  1822. lynx::setPluginAlwaysSeparate (separatePlugin, true);
  1823. }));
  1824. return;
  1825. }
  1826. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::WarningIcon, lynx::tr ("LYNX SHARE closed unexpectedly"), message);
  1827. }
  1828. // --opentime: after the start-up file was handed to the window
  1829. void startOpenTimeProbe()
  1830. {
  1831. if (openTimeReport == juce::File())
  1832. return;
  1833. struct Probe final : juce::Timer
  1834. {
  1835. LynxApplication& app;
  1836. juce::File report, project;
  1837. int idleSeconds;
  1838. int phase = 0; // 0 loading, 1 settling, 2 idle measurement
  1839. double revealedS = 0.0, loadedS = -1.0, settledS = -1.0, cpuAtLoaded = 0.0;
  1840. double lastCpu = 0.0, lastT = 0.0, quietSince = -1.0, idleCpu0 = 0.0, idleT0 = 0.0;
  1841. Probe (LynxApplication& a, juce::File r, juce::File p, int idle)
  1842. : app (a), report (std::move (r)), project (std::move (p)), idleSeconds (idle)
  1843. {
  1844. revealedS = startupTrace.seconds();
  1845. startTimer (250);
  1846. }
  1847. bool loaded() const
  1848. {
  1849. if (project == juce::File())
  1850. return true;
  1851. return app.mainWindow != nullptr
  1852. && app.mainWindow->getName().containsIgnoreCase (project.getFileNameWithoutExtension());
  1853. }
  1854. void finish (const juce::String& result)
  1855. {
  1856. stopTimer();
  1857. const auto now = startupTrace.seconds();
  1858. const auto cpu = lynx::processCpuSeconds();
  1859. juce::String text;
  1860. text << "project=" << (project == juce::File() ? juce::String ("-") : project.getFullPathName()) << "\n"
  1861. << "window_s=" << juce::String (revealedS, 3) << "\n"
  1862. << "loaded_s=" << juce::String (loadedS, 3) << "\n"
  1863. << "settled_s=" << juce::String (settledS, 3) << "\n"
  1864. << "cpu_at_loaded_s=" << juce::String (cpuAtLoaded, 3) << "\n"
  1865. << "idle_s=" << juce::String (now - idleT0, 2) << "\n"
  1866. << "idle_cpu_pct=" << juce::String (phase == 2 && now > idleT0 ? 100.0 * (cpu - idleCpu0) / (now - idleT0) : -1.0, 1) << "\n"
  1867. << "working_set_mb=" << juce::String ((double) lynx::toolbar::PerformanceMeter::processMemoryBytes() / 1048576.0, 0) << "\n"
  1868. << "cpu_total_s=" << juce::String (cpu, 3) << "\n"
  1869. << "result=" << result << "\n";
  1870. report.replaceWithText (text);
  1871. app.setApplicationReturnValue (result == "OK" ? 0 : 1);
  1872. app.quit();
  1873. }
  1874. void timerCallback() override
  1875. {
  1876. const auto now = startupTrace.seconds();
  1877. const auto cpu = lynx::processCpuSeconds();
  1878. if (phase == 0)
  1879. {
  1880. if (loaded())
  1881. {
  1882. loadedS = now;
  1883. cpuAtLoaded = cpu;
  1884. phase = 1;
  1885. lastCpu = cpu;
  1886. lastT = now;
  1887. }
  1888. else if (now - revealedS > 240.0)
  1889. finish ("TIMEOUT loading");
  1890. return;
  1891. }
  1892. if (phase == 1)
  1893. {
  1894. // quiet = under 10 % of one core for 1.5 s (the harness's rule), at most 30 s after loading
  1895. const auto use = now > lastT ? 100.0 * (cpu - lastCpu) / (now - lastT) : 0.0;
  1896. lastCpu = cpu;
  1897. lastT = now;
  1898. if (use < 10.0)
  1899. {
  1900. if (quietSince < 0.0)
  1901. quietSince = now - 0.25;
  1902. if (now - quietSince >= 1.5)
  1903. settledS = quietSince;
  1904. }
  1905. else
  1906. quietSince = -1.0;
  1907. if (settledS >= 0.0 || now - loadedS > 30.0)
  1908. {
  1909. phase = 2;
  1910. idleCpu0 = cpu;
  1911. idleT0 = now;
  1912. }
  1913. return;
  1914. }
  1915. if (now - idleT0 >= (double) idleSeconds)
  1916. finish ("OK");
  1917. }
  1918. };
  1919. perf = std::make_unique<Probe> (*this, openTimeReport, fileToOpen, openTimeIdleSeconds);
  1920. }
  1921. // round 166b: the update check of a normal start (never in --opentime and the other command-line modes), a few
  1922. // seconds after the window is up so it never competes with the start-up; and the result of an update just installed
  1923. void startUpdateCheck()
  1924. {
  1925. if (openTimeReport != juce::File())
  1926. return;
  1927. lynx::updater::afterStart();
  1928. juce::Timer::callAfterDelay (3000, [] { lynx::updater::startAutomaticCheck(); });
  1929. }
  1930. void openStartupFile()
  1931. {
  1932. startupFileHandled = true;
  1933. if (fileToOpen != juce::File() && mainWindow != nullptr)
  1934. mainWindow->openFile (fileToOpen);
  1935. else if (mainWindow != nullptr && openTimeReport == juce::File())
  1936. mainWindow->getContent().openStartupProject(); // issue #123 (FL's Startup project)
  1937. }
  1938. void shutdown() override
  1939. {
  1940. parityShow.reset(); // (LYNX_PARITYSHOT_SHOW's window, before the engine it shows)
  1941. if (relaunched || updateHelper)
  1942. return; // the copy that ran owns the session (its crash notes stay for the next start)
  1943. lynx::crashguard::note ("closing");
  1944. lynx::shutdownPluginSandboxWorker();
  1945. splash = nullptr;
  1946. lynx::shutdownStemExtraction(); // (a separation in flight stops before its window and the engine go)
  1947. lynx::shutdownAudioToMidi(); // (the same for a conversion to MIDI)
  1948. if (mainWindow != nullptr && mainWindow->isVisible())
  1949. mainWindow->saveState();
  1950. mainWindow = nullptr; // the UI goes before the engine
  1951. lynx::updater::shutdown(); // (a check or download in flight stops)
  1952. crashEngine = nullptr;
  1953. engine = nullptr;
  1954. juce::LookAndFeel::setDefaultLookAndFeel (nullptr);
  1955. heartbeat.stopTimer();
  1956. lynx::crashreporter::shutdown(); // (an upload in flight gets a moment, never long)
  1957. lynx::crashguard::stopHangWatch();
  1958. lynx::crashguard::stopMainProfiler();
  1959. lynx::crashguard::endSession(); // a clean exit: no breadcrumb left behind
  1960. // everything is saved and closed: a process that loaded third-party plugins ends here, before the DLLs' own
  1961. // teardown runs (some crash in it at exit, round 111)
  1962. if (sandboxChild || lynx::PluginHost::pluginsWereLoaded())
  1963. lynx::crashguard::exitNow (getApplicationReturnValue());
  1964. }
  1965. void systemRequestedQuit() override
  1966. {
  1967. if (mainWindow != nullptr)
  1968. mainWindow->confirmDiscard ([] { juce::JUCEApplication::quit(); });
  1969. else
  1970. quit();
  1971. }
  1972. private:
  1973. // round 157a: a frozen UI (Windows' "not responding") writes the message thread's stack to autosave\hang <time>.txt
  1974. // and a session step, so a freeze can be told apart from a crash and located. The timer is the heartbeat.
  1975. struct Heartbeat final : juce::Timer
  1976. {
  1977. void timerCallback() override { lynx::crashguard::heartbeat(); }
  1978. } heartbeat;
  1979. void startHangWatch()
  1980. {
  1981. const auto folder = lynx::platform::settingsFile ("autosave");
  1982. folder.createDirectory();
  1983. // keep the newest hang files only
  1984. auto old = folder.findChildFiles (juce::File::findFiles, false, "hang *.txt");
  1985. lynx::filesort::byTime (old, lynx::filesort::By::modificationTime, true);
  1986. for (int i = 20; i < old.size(); ++i)
  1987. old.getReference (i).deleteFile();
  1988. lynx::crashguard::startHangWatch (folder.getFullPathName().replaceCharacter ('\\', '/').toStdString());
  1989. heartbeat.startTimerHz (5);
  1990. }
  1991. bool sandboxChild = false;
  1992. bool relaunched = false; // relaunchFromAsciiPath ran LYNX from its short path: this process only waited
  1993. bool updateHelper = false; // --apply-update (round 166b)
  1994. juce::String uncleanLastStep; // last step of a previous run that ended without closing
  1995. // LYNX_PROFILE_DIR=<folder> LYNX --lv2scantest report.txt (Linux, issue #85): the LV2 scan's promise, with real child
  1996. // processes. A new PluginHost per step, as every start of LYNX has. The LV2 folders of the machine are read too.
  1997. void runLv2ScanTest (const juce::String& reportPath)
  1998. {
  1999. juce::String report;
  2000. auto ok = lynx::platform::profileOverride() != juce::File();
  2001. #if JUCE_LINUX
  2002. const auto folder = lynx::platform::profileOverride().getChildFile ("lv2-test");
  2003. const juce::FileSearchPath paths (folder.getFullPathName());
  2004. const auto check = [&] (const juce::String& name, bool passed) {
  2005. report << name << "=" << (passed ? "ok" : "FAILED") << "\n";
  2006. ok = ok && passed;
  2007. };
  2008. const auto install = [&] (const juce::String& name) {
  2009. const auto bundle = folder.getChildFile (name + ".lv2");
  2010. bundle.createDirectory();
  2011. bundle.getChildFile ("manifest.ttl").replaceWithText ("@prefix lv2: <http://lv2plug.in/ns/lv2core#> .\n@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .\n"
  2012. "<urn:lynx-test:" + name + "> a lv2:Plugin ; lv2:binary <" + name + ".so> ; rdfs:seeAlso <plugin.ttl> .\n");
  2013. bundle.getChildFile ("plugin.ttl").replaceWithText ("@prefix doap: <http://usefulinc.com/ns/doap#> .\n<urn:lynx-test:" + name + "> doap:name \"" + name + "\" .\n");
  2014. };
  2015. auto date = juce::Time::getCurrentTime();
  2016. const auto touch = [&] { // the next date, whatever the file system's date resolution
  2017. date += juce::RelativeTime::seconds (2.0);
  2018. folder.getChildFile ("a.lv2/plugin.ttl").setLastModificationTime (date);
  2019. };
  2020. const auto listed = [] (lynx::PluginHost& host, const juce::String& name) {
  2021. for (const auto& d : host.getKnownPlugins().getTypes())
  2022. if (d.fileOrIdentifier == "urn:lynx-test:" + name)
  2023. return true;
  2024. return false;
  2025. };
  2026. const auto step = [&] (const juce::String& name, int children, const std::function<void (lynx::PluginHost&)>& prepare = {}) {
  2027. lynx::PluginHost host (true);
  2028. if (prepare)
  2029. prepare (host);
  2030. host.scan (paths, {});
  2031. check (name, host.scanChildrenStarted() == children && listed (host, "a"));
  2032. };
  2033. install ("a");
  2034. step ("first_scan_one_child", 1);
  2035. step ("nothing_changed_no_child", 0);
  2036. touch();
  2037. step ("ttl_updated", 1);
  2038. install ("b");
  2039. step ("bundle_installed", 1);
  2040. step ("forget_file", 1, [] (lynx::PluginHost& host) { host.forgetFile ("urn:lynx-test:a"); });
  2041. step ("forget_all", 1, [] (lynx::PluginHost& host) { host.forgetAll(); });
  2042. lynx::platform::settingsFile ("plugins.xml").deleteFile();
  2043. step ("list_lost", 1);
  2044. step ("nothing_changed_again", 0);
  2045. // cancelled while the child works: stopped at once, and nothing is taken for done
  2046. touch();
  2047. setenv ("LYNX_TEST_CRASH", "lv2-batch-hang", 1);
  2048. {
  2049. lynx::PluginHost host (true);
  2050. const auto started = juce::Time::getMillisecondCounter();
  2051. host.scan (paths, [] (float, const juce::String&) { return false; });
  2052. check ("cancel_stops_the_child", host.scanChildrenStarted() == 1 && juce::Time::getMillisecondCounter() - started < 20000);
  2053. }
  2054. unsetenv ("LYNX_TEST_CRASH");
  2055. step ("described_after_cancel", 1);
  2056. // the child dies: plugin by plugin takes over (stopped after two of them: a machine may have hundreds)
  2057. touch();
  2058. setenv ("LYNX_TEST_CRASH", "lv2-batch", 1);
  2059. {
  2060. lynx::PluginHost host (true);
  2061. host.scan (paths, [&host] (float, const juce::String&) { return host.scanChildrenStarted() < 3; });
  2062. check ("crash_falls_back_plugin_by_plugin", host.scanChildrenStarted() == 3);
  2063. auto blamed = false;
  2064. for (const auto& file : host.getKnownPlugins().getBlacklistedFiles())
  2065. blamed = blamed || file.startsWith ("lv2-folders:");
  2066. check ("crash_blacklists_nothing", ! blamed);
  2067. }
  2068. unsetenv ("LYNX_TEST_CRASH");
  2069. step ("described_after_crash", 1);
  2070. #endif
  2071. juce::File (reportPath).replaceWithText (report + "result=" + (ok ? "OK" : "FAILED") + "\n");
  2072. setApplicationReturnValue (ok ? 0 : 1);
  2073. quit();
  2074. }
  2075. // LYNX.exe --selftest report.txt: renders 2 s without a sound card and writes the result.
  2076. // Exit code 0 = audio came out, 1 = silence.
  2077. void runSelfTest (const juce::String& reportPath, const juce::String& demoProjectPath)
  2078. {
  2079. lynx::AudioEngine offline (false);
  2080. const auto peak = offline.renderOffline (2.0, 48000.0);
  2081. const auto audioOk = peak > 0.01f && peak < 10.0f;
  2082. // project format round trip, with accents in the name
  2083. auto original = lynx::Song::makeDefault();
  2084. original.channels[0].name = "Bumbo ação";
  2085. original.playlist.push_back ({ 0, 2, 3840, 1920, 960 });
  2086. original.mode = lynx::PlayMode::song;
  2087. original.mixer[3].effects.push_back (lynx::makeEffectSlot (lynx::EffectKind::delay));
  2088. original.mixer[3].effects[0].params[1] = 0.25f;
  2089. lynx::Automation automation;
  2090. automation.name = "Pan";
  2091. automation.target = { lynx::AutomationTargetKind::effectParam, 3, 0, 1 };
  2092. automation.points = { { 0, 0.25f, 0.5f }, { 3840, 1.0f, 0.0f } };
  2093. original.automations.push_back (automation);
  2094. lynx::Clip automationClip;
  2095. automationClip.kind = lynx::ClipKind::automation;
  2096. automationClip.automation = 0;
  2097. automationClip.track = 4;
  2098. automationClip.length = 3840;
  2099. original.playlist.push_back (automationClip);
  2100. original.loopStart = 960;
  2101. original.loopEnd = 7680;
  2102. original.playlistTracks.resize (3);
  2103. original.playlistTracks[2].colour = 0xFF2A6FDB; // a track colour (round 90)
  2104. { // the clip grid (round 181a)
  2105. lynx::launcher::setClip (original, 1, 2, { 0, 0, 0, 1920, 0 });
  2106. auto& slot = *lynx::launcher::settingsAt (*original.clipGrid, 1, 2);
  2107. slot.name = "Clip ação";
  2108. slot.mode = lynx::LaunchMode::toggle;
  2109. slot.quant = lynx::LaunchQuant::eighthTriplet;
  2110. slot.legato = true;
  2111. slot.loop = false;
  2112. original.clipGrid->scenes[0].name = "Intro";
  2113. original.clipGrid->globalQuant = lynx::LaunchQuant::bars2;
  2114. }
  2115. original.playlistTracks[2].grouped = true; // track groups and rack filter groups (round 104)
  2116. original.playlistTracks[1].collapsed = true;
  2117. original.channelGroups = { "Drums", "Keys" };
  2118. original.channels[1].group = 1;
  2119. juce::String error;
  2120. if (demoProjectPath.isNotEmpty()) // sample project for checking the UI with --snapshot
  2121. lynx::ProjectFile::save (original, juce::File (demoProjectPath), error);
  2122. const auto reloaded = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (original), error);
  2123. const auto projectOk = reloaded && reloaded->channels.size() == original.channels.size()
  2124. && reloaded->channels[0].name == original.channels[0].name
  2125. && reloaded->patterns[0].notes.size() == original.patterns[0].notes.size()
  2126. && reloaded->patterns[0].notes[3].start == original.patterns[0].notes[3].start
  2127. && reloaded->mode == lynx::PlayMode::song && reloaded->playlist.size() == 2
  2128. && reloaded->clipGrid.has_value() && reloaded->clipGrid->globalQuant == lynx::LaunchQuant::bars2
  2129. && reloaded->clipGrid->scenes.size() == 3 && reloaded->clipGrid->scenes[0].name == "Intro"
  2130. && lynx::launcher::clipAt (*reloaded->clipGrid, 1, 2) != nullptr
  2131. && [&reloaded] {
  2132. auto grid = *reloaded->clipGrid;
  2133. const auto* slot = lynx::launcher::settingsAt (grid, 1, 2);
  2134. return slot != nullptr && slot->name == "Clip ação" && slot->mode == lynx::LaunchMode::toggle
  2135. && slot->quant == lynx::LaunchQuant::eighthTriplet && slot->legato && ! slot->loop;
  2136. }()
  2137. && reloaded->playlist[1].kind == lynx::ClipKind::automation && reloaded->playlist[1].automation == 0
  2138. && reloaded->automations.size() == 1 && reloaded->automations[0].target == automation.target
  2139. && reloaded->automations[0].points.size() == 2 && reloaded->automations[0].points[0].tension == 0.5f
  2140. && reloaded->automations[0].points[1].tick == 3840
  2141. && reloaded->loopStart == 960 && reloaded->loopEnd == 7680
  2142. && reloaded->playlistTracks.size() == 3 && reloaded->playlistTracks[2].colour == 0xFF2A6FDB
  2143. && reloaded->playlistTracks[1].colour == 0
  2144. && reloaded->playlistTracks[2].grouped && reloaded->playlistTracks[1].collapsed && ! reloaded->playlistTracks[1].grouped
  2145. && reloaded->channelGroups == original.channelGroups && reloaded->channels[1].group == 1 && reloaded->channels[0].group == -1
  2146. && reloaded->playlist[0].offset == 960 && reloaded->playlist[0].track == 2
  2147. && reloaded->mixer[3].effects.size() == 1
  2148. && reloaded->mixer[3].effects[0].kind == lynx::EffectKind::delay
  2149. && reloaded->mixer[3].effects[0].params[1] == 0.25f;
  2150. // round trip of the newer features: synth/sampler with modulation, EQs, utility, markers
  2151. auto rich = lynx::Song::makeDefault();
  2152. auto& synth = rich.channels[4].synth;
  2153. synth.osc[1] = { lynx::Waveform::square, -1, 7.0f, 0.4f, 5, -0.25f };
  2154. synth.filterType = 2;
  2155. synth.mono = true;
  2156. synth.portaBeats = 0.125f;
  2157. synth.am = true;
  2158. synth.filterEnv = { 3.0f, 0.01f, 0.02f, 0.3f, 0.25f, 0.4f };
  2159. synth.lfo[lynx::lfoPitch] = { 0.5f, 0.25f, true, 1, 0.1f, 0.2f };
  2160. auto& sampler = rich.channels[0].sampler;
  2161. sampler.cutoff = 1200.0f;
  2162. sampler.resonance = 0.3f;
  2163. sampler.filterType = 1;
  2164. sampler.pitchEnv = { -12.0f, 0.0f, 0.0f, 0.05f, 0.0f, 0.1f };
  2165. sampler.lfo[lynx::lfoVolume] = { 0.5f, 0.5f, false, 2, 0.0f, 0.0f };
  2166. rich.mixer[2].eq.gainDb = { 3.0f, -2.5f, 1.0f };
  2167. rich.mixer[2].eq.hz[1] = 2200.0f;
  2168. auto peqSlot = lynx::makeEffectSlot (lynx::EffectKind::parametricEq);
  2169. peqSlot.params[(std::size_t) lynx::peq::param (2, 2)] = lynx::peq::gainValue (6.0);
  2170. peqSlot.params[(std::size_t) (lynx::peq::slopeParam + 0)] = lynx::peq::slopeValue (3);
  2171. rich.mixer[2].effects.push_back (peqSlot);
  2172. auto utilitySlot = lynx::makeEffectSlot (lynx::EffectKind::utility);
  2173. utilitySlot.params[1] = 0.2f;
  2174. rich.mixer[2].effects.push_back (utilitySlot);
  2175. auto vocodexSlot = lynx::makeEffectSlot (lynx::EffectKind::vocodex); // FL's raw state travels as base64
  2176. for (int i = 0; i < 300; ++i)
  2177. vocodexSlot.state.push_back ((std::uint8_t) (i * 37));
  2178. vocodexSlot.sidechain = 1;
  2179. vocodexSlot.sidechain2 = 2;
  2180. rich.mixer[3].effects.push_back (vocodexSlot);
  2181. rich.addMarker ({ 3840, "Refrão", 0, 4 });
  2182. rich.addMarker ({ 7680, {}, 7, 8 });
  2183. const auto richBack = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (rich), error);
  2184. auto paramsClose = [] (const lynx::EffectParams& a, const lynx::EffectParams& b) {
  2185. for (std::size_t i = 0; i < a.size(); ++i)
  2186. if (std::abs (a[i] - b[i]) > 1.0e-3f)
  2187. return false;
  2188. return true;
  2189. };
  2190. const auto richOk = richBack && richBack->channels[4].synth == synth && richBack->channels[0].sampler == sampler
  2191. && richBack->mixer[2].eq == rich.mixer[2].eq && richBack->mixer[2].effects.size() == 2
  2192. && richBack->mixer[2].effects[0].kind == lynx::EffectKind::parametricEq
  2193. && paramsClose (richBack->mixer[2].effects[0].params, peqSlot.params)
  2194. && richBack->mixer[2].effects[1].kind == lynx::EffectKind::utility
  2195. && paramsClose (richBack->mixer[2].effects[1].params, utilitySlot.params)
  2196. && richBack->mixer[3].effects.size() == 1 && richBack->mixer[3].effects[0].kind == lynx::EffectKind::vocodex
  2197. && richBack->mixer[3].effects[0].state == vocodexSlot.state && richBack->mixer[3].effects[0].sidechain2 == 2
  2198. && richBack->markers() == rich.markers();
  2199. // issue #96's per-plugin option: saved only when on; old projects (no field) read as off
  2200. bool hostKeysOk = false;
  2201. {
  2202. auto song = lynx::Song::makeDefault();
  2203. lynx::ChannelDef plugin;
  2204. plugin.instrument = lynx::InstrumentKind::plugin;
  2205. plugin.plugin.id = "x";
  2206. song.channels.push_back (plugin);
  2207. const auto channel = song.channels.size() - 1;
  2208. const auto off = lynx::ProjectFile::toJson (song);
  2209. song.channels[channel].plugin.allowHostKeys = true;
  2210. song.channels[channel].plugin.hostKeysFirst = true;
  2211. const auto on = lynx::ProjectFile::toJson (song);
  2212. const auto offBack = lynx::ProjectFile::fromJson (off, error);
  2213. const auto onBack = lynx::ProjectFile::fromJson (on, error);
  2214. hostKeysOk = ! off.contains ("allowHostKeys") && on.contains ("allowHostKeys") && offBack && onBack
  2215. && ! offBack->channels[channel].plugin.allowHostKeys && onBack->channels[channel].plugin.allowHostKeys
  2216. && ! off.contains ("hostKeysFirst") && ! offBack->channels[channel].plugin.hostKeysFirst && onBack->channels[channel].plugin.hostKeysFirst;
  2217. }
  2218. // hardware output targets (REA round 156): saved only when set; old projects (no field) keep the defaults
  2219. bool hwOutOk = false;
  2220. {
  2221. auto song = lynx::Song::makeDefault();
  2222. const auto plain = lynx::ProjectFile::toJson (song);
  2223. song.mixer[0].outputChannel = lynx::outputNone;
  2224. song.mixer[1].outputChannel = 2;
  2225. song.mixer[1].outputMode = lynx::OutputMode::monoRight;
  2226. song.mixer[2].outputChannel = 6;
  2227. song.mixer[3].outputChannel = 4;
  2228. song.mixer[3].outputMode = lynx::OutputMode::monoSum;
  2229. const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), error);
  2230. const auto plainBack = lynx::ProjectFile::fromJson (plain, error);
  2231. hwOutOk = back && back->mixer[0].outputChannel == lynx::outputNone && back->mixer[1].outputChannel == 2
  2232. && back->mixer[1].outputMode == lynx::OutputMode::monoRight && back->mixer[2].outputChannel == 6
  2233. && back->mixer[2].outputMode == lynx::OutputMode::stereo && back->mixer[3].outputMode == lynx::OutputMode::monoSum
  2234. && back->mixer[4].outputChannel == lynx::outputDefault && ! plain.contains ("\"output\"") && plainBack
  2235. && plainBack->mixer[0].outputChannel == lynx::outputDefault && plainBack->mixer[1].outputChannel == lynx::outputDefault;
  2236. }
  2237. // round 168j: FL's icons (channel / mixer track / playlist track), PDC Automatic / Compensate automations, Time
  2238. // settings, scale highlighting and data folder — saved only when set, old projects load with FL's defaults
  2239. bool flp168jOk = false;
  2240. {
  2241. auto song = lynx::Song::makeDefault();
  2242. const auto plain = lynx::ProjectFile::toJson (song);
  2243. song.channels[0].icon = 75;
  2244. song.mixer[2].icon = 71;
  2245. song.playlistTracks.resize (3);
  2246. song.playlistTracks[2].icon = 30;
  2247. song.autoPdc = false;
  2248. song.compensateAutomations = false;
  2249. song.timeSignatureMode = true;
  2250. song.scaleHighlight = { 10, 5 };
  2251. song.dataFolder = "D:\\Projects\\data";
  2252. const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), error);
  2253. const auto plainBack = lynx::ProjectFile::fromJson (plain, error);
  2254. flp168jOk = back && back->channels[0].icon == 75 && back->mixer[2].icon == 71 && back->playlistTracks.size() >= 3
  2255. && back->playlistTracks[2].icon == 30 && ! back->autoPdc && ! back->compensateAutomations && back->timeSignatureMode
  2256. && back->scaleHighlight == song.scaleHighlight && back->dataFolder == song.dataFolder && plainBack && plainBack->autoPdc
  2257. && plainBack->compensateAutomations && ! plainBack->timeSignatureMode && plainBack->scaleHighlight == lynx::Song::ScaleHighlight {}
  2258. && plainBack->dataFolder.empty() && plainBack->channels[0].icon == 0 && ! plain.contains ("\"icon\"")
  2259. && ! plain.contains ("autoPdc") && ! plain.contains ("scaleHighlight");
  2260. }
  2261. // round 180d: clip fades take FL's S curve; a project saved before that keeps its straight fades, also after another
  2262. // save, and a clip made in it takes the S curve. FL's fade tensions and stretch mode and PITCH survive a save.
  2263. // issue #122: playlist tracks linked to inserts (audio) and channels (instrument) survive save, load and save
  2264. // again byte for byte (they were read before the mixer and fell back to Unassigned)
  2265. bool trackModes122Ok = false;
  2266. {
  2267. auto song = lynx::Song::makeDefault();
  2268. song.playlistTracks.resize (6);
  2269. song.playlistTracks[1].mode = lynx::PlaylistTrackMode::audio;
  2270. song.playlistTracks[1].mixerTrack = 3;
  2271. song.playlistTracks[4].mode = lynx::PlaylistTrackMode::audio;
  2272. song.playlistTracks[4].mixerTrack = (int) song.mixer.size() - 1;
  2273. song.playlistTracks[5].mode = lynx::PlaylistTrackMode::instrument;
  2274. song.playlistTracks[5].channel = 1;
  2275. song.playlistTracks[5].mixerTrack = 2;
  2276. const auto json = lynx::ProjectFile::toJson (song, false);
  2277. const auto loaded = lynx::ProjectFile::fromJson (json, error);
  2278. const auto again = loaded ? lynx::ProjectFile::toJson (*loaded, false) : juce::String();
  2279. trackModes122Ok = loaded && json.contains ("playlistTrackModes") && again == json && loaded->playlistTracks.size() >= 6
  2280. && loaded->playlistTracks[1].mode == lynx::PlaylistTrackMode::audio && loaded->playlistTracks[1].mixerTrack == 3
  2281. && loaded->playlistTracks[4].mode == lynx::PlaylistTrackMode::audio
  2282. && loaded->playlistTracks[4].mixerTrack == (int) song.mixer.size() - 1
  2283. && loaded->playlistTracks[5].mode == lynx::PlaylistTrackMode::instrument && loaded->playlistTracks[5].channel == 1;
  2284. }
  2285. bool clipFades180dOk = false;
  2286. {
  2287. auto song = lynx::Song::makeDefault();
  2288. lynx::Clip faded;
  2289. faded.kind = lynx::ClipKind::audio;
  2290. faded.channel = 0;
  2291. faded.length = lynx::ppq * 8;
  2292. faded.fadeIn = lynx::ppq;
  2293. faded.fadeOutTension = -812.933f;
  2294. faded.fadeOut = lynx::ppq * 2;
  2295. lynx::Clip plainClip = faded;
  2296. plainClip.fadeIn = plainClip.fadeOut = 0;
  2297. plainClip.fadeOutTension = 0.0f;
  2298. plainClip.start = lynx::ppq * 16;
  2299. song.playlist = { faded, plainClip };
  2300. song.channels[0].sampler.flStretchMode = 5;
  2301. song.channels[0].sampler.flStretchPitch = 247;
  2302. const auto json = lynx::ProjectFile::toJson (song);
  2303. const auto current = lynx::ProjectFile::fromJson (json, error);
  2304. const auto oldJson = json.replace ("\"clipFadesPerClip\"", "\"clipFadesOther\"");
  2305. auto old = lynx::ProjectFile::fromJson (oldJson, error);
  2306. auto resaved = old;
  2307. if (resaved)
  2308. {
  2309. auto added = faded;
  2310. added.start = lynx::ppq * 32;
  2311. added.linearFades = 0;
  2312. resaved->playlist.push_back (added);
  2313. resaved = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (*resaved), error);
  2314. }
  2315. clipFades180dOk = current && old && resaved && json.contains ("clipFadesPerClip") && ! oldJson.contains ("clipFadesPerClip")
  2316. && current->playlist.size() == 2 && ! current->playlist[0].linearFades
  2317. && current->playlist[0].fadeOutTension == -812.933f && ! current->playlist[1].linearFades
  2318. && current->channels[0].sampler.flStretchMode == 5 && current->channels[0].sampler.flStretchPitch == 247
  2319. && old->playlist.size() == 2 && old->playlist[0].linearFades && ! old->playlist[1].linearFades
  2320. && resaved->playlist.size() == 3 && resaved->playlist[0].linearFades && ! resaved->playlist[1].linearFades
  2321. && ! resaved->playlist[2].linearFades && resaved->playlist[0].fadeOutTension == -812.933f;
  2322. }
  2323. // FL's legacy Pattern Blocks (round 170f): the option and every arrangement's blocks are saved; a project without
  2324. // them has neither in its file and loads with the option off
  2325. bool blocksOk = false;
  2326. {
  2327. auto song = lynx::Song::makeDefault();
  2328. const auto plain = lynx::ProjectFile::toJson (song);
  2329. song.patternBlocksOn = true;
  2330. lynx::patternblocks::place (song, 0, 0);
  2331. lynx::patternblocks::place (song, 0, 4 * 4 * lynx::ppq);
  2332. song.addArrangement ("Second");
  2333. lynx::patternblocks::place (song, 0, 2 * 4 * lynx::ppq);
  2334. song.selectArrangement (0);
  2335. const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), error);
  2336. const auto plainBack = lynx::ProjectFile::fromJson (plain, error);
  2337. blocksOk = back && back->patternBlocksOn && back->blocks == song.blocks && song.blocks.size() == 2
  2338. && back->arrangements.size() == 2 && back->arrangements[1].blocks == song.arrangements[1].blocks
  2339. && song.arrangements[1].blocks.size() == 1 && back->songLength() == song.songLength() && plainBack
  2340. && ! plainBack->patternBlocksOn && plainBack->blocks.empty() && ! plain.contains ("blocks")
  2341. && ! plain.contains ("patternBlocks");
  2342. }
  2343. // comping (round 177c): a comp's equal-power crossfades (Clip::fadeCurve) and the crossfade length are saved; a
  2344. // project without them has neither in its file
  2345. bool compOk = false;
  2346. {
  2347. auto song = lynx::Song::makeDefault();
  2348. const auto plain = lynx::ProjectFile::toJson (song);
  2349. lynx::ChannelDef take;
  2350. take.instrument = lynx::InstrumentKind::audioClip;
  2351. take.samplePath = "take.wav";
  2352. song.channels.push_back (take);
  2353. lynx::Clip a;
  2354. a.kind = lynx::ClipKind::audio;
  2355. a.channel = (int) song.channels.size() - 1;
  2356. a.length = lynx::ppq;
  2357. a.fadeOut = 20;
  2358. a.fadeCurve = 2;
  2359. auto b = a;
  2360. b.start = lynx::ppq - 20;
  2361. b.fadeOut = 0;
  2362. b.fadeIn = 20;
  2363. b.fadeCurve = 1;
  2364. // round 180d's FL fade fields (indices 17..20) and the comp curve (index 21) on one clip, all kept
  2365. auto c = a;
  2366. c.start = 4 * lynx::ppq;
  2367. c.fadeIn = 30;
  2368. c.fadeInTension = -0.75f;
  2369. c.fadeOutTension = 0.5f;
  2370. c.linearFades = 2;
  2371. c.flFadeFlags = 0x1234u;
  2372. c.fadeCurve = 3;
  2373. song.playlist = { a, b, c };
  2374. song.compCrossfadeMs = 12.5f;
  2375. song.playlistTracks.resize (2);
  2376. song.playlistTracks[0].compTrack = true;
  2377. song.playlistTracks[1].grouped = true;
  2378. const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), error);
  2379. const auto plainBack = lynx::ProjectFile::fromJson (plain, error);
  2380. const auto* both = back && back->playlist.size() == 3 ? &back->playlist[2] : nullptr;
  2381. compOk = back && back->playlist.size() == 3 && back->playlist[0].fadeCurve == 2 && back->playlist[1].fadeCurve == 1
  2382. && both != nullptr && both->fadeCurve == 3 && both->fadeInTension == -0.75f && both->fadeOutTension == 0.5f
  2383. && both->linearFades == 2 && both->flFadeFlags == 0x1234u && both->fadeIn == 30
  2384. && back->playlist[1].fadeIn == 20 && back->compCrossfadeMs == 12.5f && back->playlistTracks[0].compTrack && ! back->playlistTracks[1].compTrack && plainBack
  2385. && plainBack->compCrossfadeMs == lynx::Song::defaultCompCrossfadeMs && ! plain.contains ("compCrossfadeMs") && ! plain.contains ("playlistCompTracks");
  2386. }
  2387. // Misc › Mono / Porta / Slide on every generator (round 168l): kept in the file; a project saved before (an
  2388. // imported engine's flags in its synth settings) gets them back, a Max polyphony of 1 is not Mono
  2389. bool polyOk = false;
  2390. {
  2391. auto song = lynx::Song::makeDefault();
  2392. lynx::ChannelDef osc;
  2393. osc.instrument = lynx::InstrumentKind::threeosc;
  2394. osc.misc.mono = osc.misc.porta = true;
  2395. osc.misc.portaBeats = 0.25f;
  2396. song.channels.push_back (osc);
  2397. auto old = osc;
  2398. old.misc = {};
  2399. old.synth.mono = old.synth.porta = true;
  2400. old.synth.portaBeats = 0.5f;
  2401. song.channels.push_back (old);
  2402. old.maxPolyphony = 1;
  2403. song.channels.push_back (old);
  2404. const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), error);
  2405. const auto n = song.channels.size();
  2406. polyOk = back && back->channels.size() == n && back->channels[n - 3].misc.mono && back->channels[n - 3].misc.porta
  2407. && std::abs (back->channels[n - 3].misc.portaBeats - 0.25f) < 1e-6f && back->channels[n - 2].misc.mono
  2408. && back->channels[n - 2].misc.porta && std::abs (back->channels[n - 2].misc.portaBeats - 0.5f) < 1e-6f
  2409. && ! back->channels[n - 1].misc.mono && back->channels[n - 1].maxPolyphony == 1
  2410. && ! back->channels[4].misc.mono; // (the LYNX Synth keeps its own flags)
  2411. }
  2412. // FL's track latency (REA round 165f-mixer): manual ms, bypass mode and master compensation saved only when set
  2413. bool latencyOk = false;
  2414. {
  2415. auto song = lynx::Song::makeDefault();
  2416. const auto plain = lynx::ProjectFile::toJson (song);
  2417. song.mixer[1].latencyMs = -20.0f;
  2418. song.mixer[2].latencyMs = 12.5f;
  2419. song.mixer[2].latencyBypass = lynx::LatencyBypass::always;
  2420. song.mixer[3].latencyBypass = lynx::LatencyBypass::whenRecordingOrStopped;
  2421. song.mixer[3].compensateMasterLatency = false;
  2422. const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), error);
  2423. latencyOk = back && back->mixer[1].latencyMs == -20.0f && back->mixer[2].latencyMs == 12.5f
  2424. && back->mixer[2].latencyBypass == lynx::LatencyBypass::always
  2425. && back->mixer[3].latencyBypass == lynx::LatencyBypass::whenRecordingOrStopped && ! back->mixer[3].compensateMasterLatency
  2426. && back->mixer[4].latencyMs == 0.0f && back->mixer[4].compensateMasterLatency
  2427. && ! plain.contains ("latencyMs") && ! plain.contains ("latencyBypass") && ! plain.contains ("compensateMaster");
  2428. }
  2429. // LYNX substitutes (round 98): a missing plugin's slot plays a built-in equivalent and the project keeps the
  2430. // original reference byte for byte (.flp record and LYNX plugin state)
  2431. bool substituteOk = false;
  2432. {
  2433. auto song = lynx::Song::makeDefault();
  2434. lynx::ForeignPlugin vv; // an .flp VST3 record (ValhallaVintageVerb's class ID), opaque state
  2435. vv.format = lynx::ForeignPlugin::Format::vst3;
  2436. const std::uint8_t cid[] = { 0x76, 0x54, 0x53, 0x56, 0x65, 0x65, 0x76, 0x33, 0x61, 0x6c, 0x68, 0x61, 0x6c, 0x6c, 0x61, 0x76 };
  2437. std::copy (std::begin (cid), std::end (cid), vv.classId.begin());
  2438. vv.hasClassId = true;
  2439. vv.name = "ValhallaVintageVerb";
  2440. vv.path = "C:\\x\\ValhallaVintageVerb.vst3";
  2441. for (int i = 0; i < 777; ++i)
  2442. vv.state.push_back ((std::uint8_t) (i * 13 + 1));
  2443. lynx::EffectSlot fromFlp;
  2444. fromFlp.kind = lynx::EffectKind::plugin;
  2445. fromFlp.plugin.foreign = vv;
  2446. lynx::EffectSlot fromLynx; // a LYNX reference whose plugin isn't installed here
  2447. fromLynx.kind = lynx::EffectKind::plugin;
  2448. fromLynx.plugin.id = "VST3-FabFilter Pro-Q 3-1a2b3c4d-5e6f7a8b";
  2449. fromLynx.plugin.name = "FabFilter Pro-Q 3";
  2450. fromLynx.plugin.state = "AAECAwQFBgcICQ==";
  2451. const auto flpRef = fromFlp.plugin, lynxRef = fromLynx.plugin;
  2452. song.mixer[1].effects = { fromFlp, fromLynx };
  2453. const auto substitutesOn = lynx::pluginSubstitutesEnabled();
  2454. const auto changed = offline.getPluginHost().applySubstitutes (song);
  2455. auto& fx = song.mixer[1].effects;
  2456. // only the LYNX reference is substituted here (an .flp record is the import's job); do the .flp one directly
  2457. const auto flpSubstituted = lynx::substituteEffectSlot (fx[0], lynx::pluginIdentity (vv));
  2458. const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), error);
  2459. substituteOk = flpSubstituted && fx[0].kind == lynx::EffectKind::epochVerb
  2460. && (! substitutesOn || (changed == 1 && fx[1].kind == lynx::EffectKind::facetEq && fx[1].substituteFor == lynxRef))
  2461. && back && back->mixer[1].effects.size() == 2 && back->mixer[1].effects[0].kind == lynx::EffectKind::epochVerb
  2462. && back->mixer[1].effects[0].substituteFor == flpRef && back->mixer[1].effects[0].substituteFor.foreign.state == vv.state
  2463. && back->mixer[1].effects[1].kind == fx[1].kind && back->mixer[1].effects[1].substituteFor == fx[1].substituteFor;
  2464. }
  2465. // undo/redo
  2466. offline.editSong ([] (lynx::Song& s) { s.bpm = 99.0; });
  2467. offline.editSong ([] (lynx::Song& s) { s.bpm = 101.0; });
  2468. offline.undo();
  2469. const auto afterUndo = offline.getSong().bpm;
  2470. offline.redo();
  2471. const auto undoOk = afterUndo == 99.0 && offline.getSong().bpm == 101.0 && offline.canUndo() && ! offline.canRedo()
  2472. && offline.isModified();
  2473. // recording from the PC keyboard: a one-beat note lands in the pattern, in a single undo step
  2474. // (Blend on: this checks that the take joins the pattern's notes; a new install starts with Blend off)
  2475. const auto notesBefore = offline.getSong().patterns[0].notes.size();
  2476. {
  2477. auto o = offline.getRecordOptions();
  2478. o.mode = lynx::RecordMode::overdub;
  2479. offline.setRecordOptions (o);
  2480. }
  2481. offline.setRecording (true);
  2482. offline.play();
  2483. offline.getTransport().positionTicks.store (960.0);
  2484. offline.sendLiveNote (2, 72, 0.9f, true, true);
  2485. offline.getTransport().positionTicks.store (1920.0);
  2486. offline.sendLiveNote (2, 72, 0.0f, false, true);
  2487. offline.setRecording (false);
  2488. offline.stop();
  2489. const auto& recorded = offline.getSong().patterns[0].notes;
  2490. const auto recordOk = recorded.size() == notesBefore + 1
  2491. && std::any_of (recorded.begin(), recorded.end(), [] (const lynx::Note& n) {
  2492. return n.key == 72 && n.channel == 2 && n.length == 960 && n.start >= 960 && n.start < 3840;
  2493. });
  2494. offline.undo();
  2495. const auto recordUndoOk = offline.getSong().patterns[0].notes.size() == notesBefore;
  2496. // FL's Tools › Cancel recording (round 187a): the pass's notes go, an edit made before it stays, recording turns
  2497. // off and playback goes on; nothing to redo
  2498. bool cancelRecordOk = false;
  2499. {
  2500. offline.editSong ([] (lynx::Song& s) { s.bpm = 123.0; });
  2501. const auto notesThen = offline.getSong().patterns[0].notes.size();
  2502. offline.setRecording (true);
  2503. offline.play();
  2504. offline.getTransport().positionTicks.store (960.0);
  2505. offline.sendLiveNote (2, 74, 0.9f, true, true);
  2506. offline.getTransport().positionTicks.store (1920.0);
  2507. offline.sendLiveNote (2, 74, 0.0f, false, true);
  2508. offline.sendLiveNote (2, 76, 0.9f, true, true); // (still held when the pass is cancelled)
  2509. const auto cancelled = offline.cancelRecording();
  2510. cancelRecordOk = cancelled && ! offline.isRecording() && offline.getTransport().playing.load()
  2511. && offline.getSong().patterns[0].notes.size() == notesThen && offline.getSong().bpm == 123.0 && ! offline.canRedo()
  2512. && ! offline.cancelRecording(); // (not recording: nothing to cancel)
  2513. offline.sendLiveNote (2, 76, 0.0f, false, false);
  2514. offline.stop();
  2515. }
  2516. // MIDI: exporting the pattern and importing it back gives the same notes
  2517. bool midiOk = false;
  2518. {
  2519. auto source = lynx::Song::makeDefault();
  2520. source.patterns[0].notes.push_back ({ 1000, 480, 4, 67, 0.5f });
  2521. source.patterns[0].sortNotes();
  2522. const auto midiFile = juce::File::getSpecialLocation (juce::File::tempDirectory).getChildFile ("lynx-selftest.mid");
  2523. juce::String midiError;
  2524. const auto saved = lynx::MidiFileIo::savePattern (source, 0, midiFile, midiError);
  2525. const auto song = saved ? lynx::MidiFileIo::loadSong (midiFile, midiError) : std::nullopt;
  2526. midiFile.deleteFile();
  2527. if (song && song->patterns.size() == 1 && song->patterns[0].notes.size() == source.patterns[0].notes.size()
  2528. && std::abs (song->bpm - source.bpm) < 0.01)
  2529. {
  2530. midiOk = true;
  2531. const auto& a = source.patterns[0].notes;
  2532. const auto& b = song->patterns[0].notes;
  2533. for (std::size_t i = 0; i < a.size(); ++i)
  2534. midiOk = midiOk && a[i].start == b[i].start && a[i].key == b[i].key && a[i].length == b[i].length;
  2535. }
  2536. }
  2537. // project package (REA round 118): a project with a sample exported as .zip, extracted and opened again,
  2538. // finds its sample inside the extracted folder
  2539. bool packageOk = false;
  2540. {
  2541. const auto dir = juce::File::getSpecialLocation (juce::File::tempDirectory).getChildFile ("lynx-selftest-package");
  2542. dir.deleteRecursively();
  2543. dir.getChildFile ("src").createDirectory();
  2544. const auto wav = dir.getChildFile ("src/hit.wav");
  2545. {
  2546. juce::WavAudioFormat format;
  2547. juce::AudioBuffer<float> hit (1, 480);
  2548. for (int i = 0; i < 480; ++i)
  2549. hit.setSample (0, i, 0.5f * std::sin (0.1f * (float) i));
  2550. std::unique_ptr<juce::OutputStream> out (wav.createOutputStream().release());
  2551. if (auto* w = format.createWriterFor (out.get(), 48000.0, 1, 16, {}, 0))
  2552. {
  2553. out.release();
  2554. std::unique_ptr<juce::AudioFormatWriter> writer (w);
  2555. writer->writeFromAudioSampleBuffer (hit, 0, 480);
  2556. }
  2557. }
  2558. auto source = lynx::Song::makeDefault();
  2559. lynx::ChannelDef c;
  2560. c.name = "Hit";
  2561. c.instrument = lynx::InstrumentKind::sampler;
  2562. c.samplePath = wav.getFullPathName().toStdString();
  2563. source.channels.push_back (c);
  2564. lynx::ProjectPackage::Result packed;
  2565. juce::String packageError;
  2566. const auto zip = dir.getChildFile ("Beat.zip");
  2567. if (wav.existsAsFile() && lynx::ProjectPackage::exportZip (source, "Beat", zip, packed, packageError) && packed.files == 1)
  2568. {
  2569. const auto project = lynx::ProjectPackage::extractZip (zip, dir.getChildFile ("out"), packageError);
  2570. const auto song = project.existsAsFile() ? lynx::ProjectFile::load (project, packageError) : std::nullopt;
  2571. if (song && ! song->channels.empty())
  2572. {
  2573. const juce::File back (juce::String::fromUTF8 (song->channels.back().samplePath.c_str()));
  2574. packageOk = back.existsAsFile() && back.isAChildOf (project.getParentDirectory()) && back.getSize() == wav.getSize();
  2575. }
  2576. }
  2577. dir.deleteRecursively();
  2578. }
  2579. // D#92, round 180a: a non-ASCII folder and a dotted name save and load back; an unwritable place says so, and a
  2580. // relative path resolves as the start-up argument does
  2581. bool projectSaveOk = false;
  2582. {
  2583. const auto dir = juce::File::getSpecialLocation (juce::File::tempDirectory).getChildFile ("lynx-selftest-save180a");
  2584. dir.deleteRecursively();
  2585. const auto folder = dir.getChildFile (juce::String::fromUTF8 ("M\xc3\xbasica nova"));
  2586. folder.createDirectory();
  2587. const auto named = lynx::ProjectFile::withProjectExtension (folder.getChildFile (juce::String::fromUTF8 ("Can\xc3\xa7\xc3\xa3o.v2")));
  2588. auto song = lynx::Song::makeDefault();
  2589. lynx::Note note;
  2590. note.length = 240;
  2591. note.key = 64;
  2592. song.patterns[0].notes.push_back (note);
  2593. juce::String error, blockedError;
  2594. const auto again = lynx::ProjectFile::save (song, named, error) ? lynx::ProjectFile::load (named, error) : std::nullopt;
  2595. const auto blocker = dir.getChildFile ("a file");
  2596. blocker.replaceWithText ("x");
  2597. const auto cwd = juce::File::getCurrentWorkingDirectory();
  2598. folder.setAsCurrentWorkingDirectory();
  2599. const auto relative = juce::File::getCurrentWorkingDirectory().getChildFile (named.getFileName());
  2600. cwd.setAsCurrentWorkingDirectory();
  2601. projectSaveOk = named.getFileName().endsWith (".v2.lynx") && again && again->patterns[0].notes.size() == song.patterns[0].notes.size()
  2602. && relative == named && ! lynx::ProjectFile::save (song, blocker.getChildFile ("x.lynx"), blockedError)
  2603. && blockedError.isNotEmpty() && lynx::ProjectFile::withProjectExtension (named) == named;
  2604. dir.deleteRecursively();
  2605. }
  2606. // Online Sessions (round 168a): a project sent as a .lynxpack (one sample used twice is stored once, the uids
  2607. // survive), a stand-in rendered through an ExportJob, the guest's part sent back and merged by the host
  2608. juce::String sessionResult = "ERROR";
  2609. {
  2610. const auto dir = juce::File::getSpecialLocation (juce::File::tempDirectory).getChildFile ("lynx-selftest-session");
  2611. dir.deleteRecursively();
  2612. dir.getChildFile ("src").createDirectory();
  2613. const auto wav = dir.getChildFile ("src/hit.wav");
  2614. {
  2615. juce::WavAudioFormat format;
  2616. juce::AudioBuffer<float> hit (1, 4800);
  2617. for (int i = 0; i < 4800; ++i)
  2618. hit.setSample (0, i, 0.5f * std::sin (0.05f * (float) i) * (1.0f - (float) i / 4800.0f));
  2619. std::unique_ptr<juce::OutputStream> out (wav.createOutputStream().release());
  2620. if (auto* w = format.createWriterFor (out.get(), 48000.0, 1, 16, {}, 0))
  2621. {
  2622. out.release();
  2623. std::unique_ptr<juce::AudioFormatWriter> writer (w);
  2624. writer->writeFromAudioSampleBuffer (hit, 0, 4800);
  2625. }
  2626. }
  2627. auto host = lynx::Song::makeDefault();
  2628. host.mode = lynx::PlayMode::song;
  2629. const auto copyOfWav = dir.getChildFile ("src/hit copy.wav"); // the same bytes under another name: stored once
  2630. wav.copyFileTo (copyOfWav);
  2631. for (const auto& [name, file] : { std::pair<const char*, juce::File> { "Hit", wav }, { "Hit 2", copyOfWav } })
  2632. {
  2633. lynx::ChannelDef c;
  2634. c.name = name;
  2635. c.instrument = lynx::InstrumentKind::sampler;
  2636. c.samplePath = file.getFullPathName().toStdString();
  2637. host.channels.push_back (c);
  2638. }
  2639. const auto hitChannel = (int) host.channels.size() - 2;
  2640. lynx::Note hitNote;
  2641. hitNote.channel = hitChannel;
  2642. hitNote.length = 480;
  2643. host.patterns[0].notes.push_back (hitNote);
  2644. host.playlist.push_back ({ 0, 0, 0, host.patterns[0].effectiveLength (host.beatsPerBar), 0 });
  2645. lynx::uids::normalize (host);
  2646. const auto* guest = lynx::parts::invite (host, "Host", "Ana", 0xFF3D9BE9, false);
  2647. juce::String e;
  2648. std::vector<lynx::sessionpack::Rendered> rendered;
  2649. // (a sampler stands in for a plugin channel here: render() renders whatever it is given)
  2650. const std::vector<lynx::sessionpack::RenderItem> items { { false, hitChannel, false, "Hit", "Test" } };
  2651. const auto renderedOk = guest != nullptr && lynx::sessionpack::render (host, items, 44100.0, dir.getChildFile ("stems"), "Host", rendered, {}, e)
  2652. && rendered.size() == 1 && rendered[0].standIns.size() == 2
  2653. && juce::File (juce::String::fromUTF8 (rendered[0].standIns[0].path.c_str())).getSize() > 1000;
  2654. if (renderedOk)
  2655. lynx::sessionpack::apply (host, rendered);
  2656. lynx::sessionpack::Manifest m;
  2657. m.projectName = "Selftest";
  2658. m.from = *host.session.find (lynx::session::hostTag);
  2659. m.to = *host.session.find (2);
  2660. lynx::sessionpack::WriteResult written;
  2661. const auto pack = dir.getChildFile (juce::String ("Selftest") + lynx::sessionpack::extension);
  2662. const auto packOk = renderedOk && lynx::sessionpack::write (lynx::parts::guestCopy (host, 2), m, offline.getPluginHost(), pack, written, e)
  2663. && written.media == 3 && written.duplicates == 1; // the sample once (used twice), the stand-in pair
  2664. auto opened = packOk ? lynx::sessionpack::open (pack, dir.getChildFile ("received"), e) : std::nullopt;
  2665. bool openOk = false, mergeOk = false;
  2666. if (opened && opened->corrupt.isEmpty())
  2667. {
  2668. const auto& g = opened->song;
  2669. const juce::File sample (juce::String::fromUTF8 (g.channels[(std::size_t) hitChannel].samplePath.c_str()));
  2670. openOk = g.session.me == 2 && g.projectId == host.projectId && g.channels[(std::size_t) hitChannel].uid == host.channels[(std::size_t) hitChannel].uid
  2671. && sample.existsAsFile() && sample.isAChildOf (opened->folder) && g.channels[(std::size_t) hitChannel].standIns.size() == 2
  2672. && juce::File (juce::String::fromUTF8 (g.channels[(std::size_t) hitChannel].standIns[1].path.c_str())).existsAsFile();
  2673. // the guest adds a channel and a pattern of his own, sends his part back
  2674. auto copy = g;
  2675. lynx::ChannelDef mine;
  2676. mine.name = "Ana's hit";
  2677. mine.instrument = lynx::InstrumentKind::sampler;
  2678. mine.samplePath = sample.getFullPathName().toStdString();
  2679. copy.channels.push_back (mine);
  2680. lynx::Pattern p;
  2681. p.name = "Ana";
  2682. lynx::Note note;
  2683. note.channel = (int) copy.channels.size() - 1;
  2684. note.length = 240;
  2685. note.key = 64;
  2686. p.notes.push_back (note);
  2687. copy.patterns.push_back (p);
  2688. lynx::uids::normalize (copy);
  2689. // its uids survive a save and a load
  2690. const auto saved = dir.getChildFile ("guest.lynx");
  2691. auto reloaded = lynx::ProjectFile::save (copy, saved, e) ? lynx::ProjectFile::load (saved, e) : std::nullopt;
  2692. lynx::sessionpack::Manifest back;
  2693. back.part = true;
  2694. back.from = *copy.session.self();
  2695. const auto partFile = dir.getChildFile (juce::String ("Ana part") + lynx::sessionpack::extension);
  2696. lynx::sessionpack::WriteResult partWritten;
  2697. auto part = reloaded && reloaded->channels.back().uid == copy.channels.back().uid && lynx::uids::tagOf (reloaded->channels.back().uid) == 2
  2698. ? lynx::sessionpack::write (lynx::parts::extract (*reloaded, 2), back, offline.getPluginHost(), partFile, partWritten, e)
  2699. : false;
  2700. auto partOpened = part ? lynx::sessionpack::open (partFile, dir.getChildFile ("parts"), e) : std::nullopt;
  2701. if (partOpened && partOpened->manifest.part && lynx::sessionpack::adoptMedia (partOpened->song, dir.getChildFile ("Session media/Ana"), e))
  2702. {
  2703. const auto report = lynx::parts::merge (host, partOpened->song, 2);
  2704. const auto& added = host.channels.back();
  2705. mergeOk = report.ok && report.channels >= 1 && added.name == "Ana's hit" && lynx::uids::tagOf (added.uid) == 2
  2706. && juce::File (juce::String::fromUTF8 (added.samplePath.c_str())).isAChildOf (dir.getChildFile ("Session media/Ana"))
  2707. && host.channels[(std::size_t) hitChannel].name == "Hit";
  2708. }
  2709. }
  2710. // a crafted package whose project points at a file elsewhere on this computer: opening it must not
  2711. // reach that file, or merging would copy it into the project and the next package would send it on
  2712. if (mergeOk)
  2713. {
  2714. const auto secret = dir.getChildFile ("secret.wav");
  2715. wav.copyFileTo (secret);
  2716. auto evil = lynx::Song::makeDefault();
  2717. lynx::ChannelDef c;
  2718. c.instrument = lynx::InstrumentKind::sampler;
  2719. c.samplePath = secret.getFullPathName().toStdString();
  2720. evil.channels.push_back (c);
  2721. lynx::ChannelDef keys; // (FL Keys' zones are read by the engine but are not in the media list)
  2722. keys.instrument = lynx::InstrumentKind::flkeys;
  2723. keys.zones.push_back ({});
  2724. keys.zones.back().path = c.samplePath;
  2725. evil.channels.push_back (keys);
  2726. lynx::ChannelDef patch; // (a Patcher's nodes are not in the media list either)
  2727. patch.instrument = lynx::InstrumentKind::patcher;
  2728. patch.patcher.nodes.resize (2);
  2729. patch.patcher.nodes[0].generator = true;
  2730. patch.patcher.nodes[0].channel = c;
  2731. patch.patcher.nodes[1].effect.samplePath = c.samplePath;
  2732. evil.channels.push_back (patch);
  2733. evil.mixer[1].recordTo = dir.getChildFile ("overwritten.wav").getFullPathName().toStdString();
  2734. const auto evilProject = dir.getChildFile ("evil.lynx");
  2735. lynx::sessionpack::Manifest em;
  2736. em.part = true;
  2737. juce::ZipFile::Builder b;
  2738. const auto json = lynx::sessionpack::manifestToJson (em);
  2739. b.addEntry (new juce::MemoryInputStream (json.toRawUTF8(), json.getNumBytesAsUTF8(), true), 0, "manifest.json", {});
  2740. const auto evilPack = dir.getChildFile (juce::String ("Evil") + lynx::sessionpack::extension);
  2741. bool zipped = false;
  2742. if (lynx::ProjectFile::save (evil, evilProject, e))
  2743. {
  2744. b.addFile (evilProject, 0, "project.lynx");
  2745. juce::FileOutputStream out (evilPack);
  2746. zipped = out.openedOk() && b.writeToStream (out, nullptr);
  2747. }
  2748. auto evilOpened = zipped ? lynx::sessionpack::open (evilPack, dir.getChildFile ("evil"), e) : std::nullopt;
  2749. const auto media = dir.getChildFile ("Session media/Evil");
  2750. mergeOk = evilOpened && lynx::sessionpack::adoptMedia (evilOpened->song, media, e)
  2751. && std::none_of (evilOpened->song.channels.begin(), evilOpened->song.channels.end(), [&] (const lynx::ChannelDef& ch) {
  2752. return juce::File (juce::String::fromUTF8 (ch.samplePath.c_str())) == secret
  2753. || std::any_of (ch.zones.begin(), ch.zones.end(), [&] (const lynx::SampleZone& z) { return juce::File (juce::String::fromUTF8 (z.path.c_str())) == secret; });
  2754. })
  2755. && evilOpened->song.channels.back().patcher.nodes.size() == 2
  2756. && juce::File (juce::String::fromUTF8 (evilOpened->song.channels.back().patcher.nodes[0].channel.samplePath.c_str())) != secret
  2757. && juce::File (juce::String::fromUTF8 (evilOpened->song.channels.back().patcher.nodes[1].effect.samplePath.c_str())) != secret
  2758. && evilOpened->song.mixer[1].recordTo.empty()
  2759. && media.findChildFiles (juce::File::findFiles, true).isEmpty();
  2760. if (! mergeOk && e.isEmpty())
  2761. e = "a received package reached a file outside it";
  2762. }
  2763. // ... nor through its own folder: "..", Windows' dotted names (". ." climbs like ".." there), and a manifest
  2764. // media entry outside the package (it must not even be read: "/dev/zero" would never end)
  2765. if (mergeOk)
  2766. {
  2767. const auto secret = dir.getChildFile ("secret.wav");
  2768. const auto folder = dir.getChildFile ("evil2").getChildFile ("Evil2"); // (where open() will unpack it)
  2769. const auto climb = folder.getFullPathName() + "/media/../../../secret.wav";
  2770. const auto dotted = folder.getFullPathName() + "/. ./.. ./secret.wav";
  2771. auto evil = lynx::Song::makeDefault();
  2772. for (const auto& path : { climb, dotted })
  2773. {
  2774. lynx::ChannelDef c;
  2775. c.instrument = lynx::InstrumentKind::sampler;
  2776. c.samplePath = path.toStdString();
  2777. evil.channels.push_back (c);
  2778. }
  2779. juce::MemoryBlock secretBytes;
  2780. secret.loadFileAsData (secretBytes);
  2781. lynx::sessionpack::Manifest em;
  2782. em.part = true;
  2783. em.media.push_back ({ "sha256-" + juce::String (lynx::sha256Hex ((const std::uint8_t*) secretBytes.getData(), secretBytes.getSize())),
  2784. "secret.wav", (juce::int64) secretBytes.getSize(), "../../secret.wav" });
  2785. const auto evilProject = dir.getChildFile ("evil2.lynx");
  2786. juce::ZipFile::Builder b;
  2787. const auto json = lynx::sessionpack::manifestToJson (em);
  2788. b.addEntry (new juce::MemoryInputStream (json.toRawUTF8(), json.getNumBytesAsUTF8(), true), 0, "manifest.json", {});
  2789. const auto evilPack = dir.getChildFile (juce::String ("Evil2") + lynx::sessionpack::extension);
  2790. bool zipped = false;
  2791. if (lynx::ProjectFile::save (evil, evilProject, e))
  2792. {
  2793. b.addFile (evilProject, 0, "project.lynx");
  2794. juce::FileOutputStream out (evilPack);
  2795. zipped = out.openedOk() && b.writeToStream (out, nullptr);
  2796. }
  2797. auto evilOpened = zipped ? lynx::sessionpack::open (evilPack, dir.getChildFile ("evil2"), e) : std::nullopt;
  2798. const auto media = dir.getChildFile ("Session media/Evil2");
  2799. mergeOk = evilOpened && evilOpened->folder == folder && evilOpened->corrupt.contains ("secret.wav")
  2800. && lynx::sessionpack::adoptMedia (evilOpened->song, media, e) && evilOpened->song.channels.size() >= 2
  2801. && std::none_of (evilOpened->song.channels.begin(), evilOpened->song.channels.end(), [&] (const lynx::ChannelDef& ch) {
  2802. const auto p = juce::String::fromUTF8 (ch.samplePath.c_str());
  2803. return p == climb || p == dotted || (juce::File::isAbsolutePath (p) && juce::File (p) == secret);
  2804. })
  2805. && media.findChildFiles (juce::File::findFiles, true).isEmpty();
  2806. if (! mergeOk && e.isEmpty())
  2807. e = "a received package climbed out of its folder";
  2808. }
  2809. if (! packOk && e.isEmpty())
  2810. e = "media " + juce::String (written.media) + ", duplicates " + juce::String (written.duplicates) + ", missing "
  2811. + written.missing.joinIntoString (";");
  2812. sessionResult = mergeOk ? juce::String ("OK")
  2813. : "ERROR (" + juce::String (renderedOk ? packOk ? openOk ? "merge" : "open" : "pack" : "render") + (e.isEmpty() ? "" : ": " + e) + ")";
  2814. dir.deleteRecursively();
  2815. }
  2816. // WavPack: a .wv from the FL packs (if installed) opens through the sample loader
  2817. juce::String wavpack = "NO_FL";
  2818. {
  2819. const auto roots = lynx::findFlStudioRoots();
  2820. const auto packs = juce::File (juce::String::fromUTF8 (roots.data.c_str())).getChildFile ("Patches/Packs");
  2821. const auto found = packs.isDirectory() ? packs.findChildFiles (juce::File::findFiles, true, "*.wv") : juce::Array<juce::File> {};
  2822. if (! found.isEmpty())
  2823. {
  2824. lynx::SampleLibrary library;
  2825. const auto sample = library.load (found.getFirst().getFullPathName());
  2826. float peakWv = 0.0f;
  2827. if (sample != nullptr)
  2828. for (std::size_t i = 0; i < sample->frames(); ++i)
  2829. peakWv = std::max (peakWv, std::abs (sample->leftData()[i]));
  2830. wavpack = sample != nullptr && sample->frames() > 0 && peakWv > 1e-4f ? "OK" : "ERROR";
  2831. }
  2832. }
  2833. // every built-in effect's editor and engine with extreme settings (round 111): a crash or NaN output fails here
  2834. const auto effectsOk = runEffectFuzz (4, {}); // (no mouse drags: nothing may open on screen)
  2835. // FL's Patcher (round 141): a mixer slot and a generator channel with their graphs survive save / load, and the
  2836. // generator one plays through the rack
  2837. bool patcherOk = false;
  2838. {
  2839. auto song = lynx::Song::makeDefault();
  2840. song.mixer.resize (4);
  2841. auto slot = lynx::makeEffectSlot (lynx::EffectKind::patcher);
  2842. lynx::PatchNode reverb, gain;
  2843. reverb.effect = lynx::makeEffectSlot (lynx::EffectKind::utility); // (exact defaults: params are saved to 4 decimals)
  2844. reverb.label = "Room";
  2845. reverb.x = 120.5f;
  2846. reverb.y = 40.0f;
  2847. gain.effect = lynx::makeEffectSlot (lynx::EffectKind::utility);
  2848. gain.effect.enabled = false;
  2849. slot.patcher.nodes = { reverb, gain };
  2850. lynx::PatchWire a, b, c, control;
  2851. a.to = 0;
  2852. b.from = 0, b.to = 1, b.gain = 0.5f;
  2853. c.from = 1;
  2854. control.kind = lynx::PatchWire::Kind::control, control.from = 0, control.to = 1, control.toPort = 0, control.curve = { 0.0f, 0.25f, 1.0f };
  2855. slot.patcher.wires = { a, b, c, control };
  2856. slot.patcher.outputTracks = { 3 };
  2857. song.mixer[1].effects = { slot };
  2858. lynx::ChannelDef ch;
  2859. ch.name = "Patched";
  2860. ch.instrument = lynx::InstrumentKind::patcher;
  2861. lynx::PatchNode synth;
  2862. synth.generator = true;
  2863. synth.channel.instrument = lynx::InstrumentKind::synth;
  2864. synth.channel.name = "Synth";
  2865. ch.patcher.nodes = { synth };
  2866. lynx::PatchWire notes, out;
  2867. notes.kind = lynx::PatchWire::Kind::midi, notes.to = 0;
  2868. out.from = 0;
  2869. ch.patcher.wires = { notes, out };
  2870. // round 162: the I/O nodes' MIDI pins and a MIDI Out node between them
  2871. lynx::PatchNode midiOutNode;
  2872. midiOutNode.generator = true;
  2873. midiOutNode.channel.instrument = lynx::InstrumentKind::midiOut;
  2874. lynx::midictl::writeMidiOut (midiOutNode.channel.pluginState, { 4, 0, 0, -1, -1 });
  2875. ch.patcher.nodes.push_back (midiOutNode);
  2876. lynx::PatchWire portIn, portOut;
  2877. portIn.kind = portOut.kind = lynx::PatchWire::Kind::midi;
  2878. portIn.fromPort = lynx::patchMidiPortPin (7), portIn.to = 1;
  2879. portOut.from = 1, portOut.to = lynx::patchToHost, portOut.toPort = 9;
  2880. ch.patcher.wires.push_back (portIn);
  2881. ch.patcher.wires.push_back (portOut);
  2882. ch.patcher.fromMidiPorts = { 2, 7 };
  2883. ch.patcher.toMidiPorts = { 9, 11 };
  2884. ch.patcher.fromNotesHidden = true;
  2885. song.channels.push_back (ch);
  2886. const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), error);
  2887. patcherOk = back && back->mixer.size() >= 2 && back->mixer[1].effects.size() == 1
  2888. && back->mixer[1].effects[0].kind == lynx::EffectKind::patcher && back->mixer[1].effects[0].patcher == slot.patcher
  2889. && back->channels.back().instrument == lynx::InstrumentKind::patcher && back->channels.back().patcher.nodes.size() == 2
  2890. && back->channels.back().patcher.fromMidiPorts == ch.patcher.fromMidiPorts
  2891. && back->channels.back().patcher.toMidiPorts == ch.patcher.toMidiPorts && back->channels.back().patcher.fromNotesHidden
  2892. && back->channels.back().patcher.nodes[1].channel.pluginState == midiOutNode.channel.pluginState
  2893. && back->channels.back().patcher.nodes[0].generator
  2894. && back->channels.back().patcher.nodes[0].channel.instrument == lynx::InstrumentKind::synth
  2895. && back->channels.back().patcher.wires == ch.patcher.wires;
  2896. }
  2897. // FL engines in a native project (round 142, issue #5): every engine this PC can make survives save / load and
  2898. // the instruments play through the rack
  2899. juce::String nativesResult = "OK";
  2900. int nativesMade = 0, nativesSilent = 0;
  2901. {
  2902. auto song = lynx::Song::makeDefault();
  2903. song.channels.clear();
  2904. song.patterns[0].notes.clear();
  2905. song.mixer.resize (3);
  2906. const auto& fl = lynx::flStudioAccess();
  2907. for (const auto& e : lynx::natives::instrumentEngines())
  2908. if (lynx::natives::available (e, fl))
  2909. if (auto c = lynx::natives::makeChannel (e.kind, fl))
  2910. {
  2911. c->mixerTrack = 1;
  2912. song.channels.push_back (*c);
  2913. }
  2914. for (const auto& e : lynx::natives::effectEngines())
  2915. if (auto fx = lynx::natives::makeSlot (e.kind, fl))
  2916. song.mixer[2].effects.push_back (*fx);
  2917. nativesMade = (int) (song.channels.size() + song.mixer[2].effects.size());
  2918. const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), error);
  2919. auto same = back && back->channels.size() == song.channels.size() && back->mixer.size() >= 3
  2920. && back->mixer[2].effects.size() == song.mixer[2].effects.size();
  2921. for (std::size_t i = 0; same && i < song.channels.size(); ++i)
  2922. {
  2923. const auto& a = song.channels[i];
  2924. const auto& b = back->channels[i];
  2925. same = a.instrument == b.instrument && a.pluginState == b.pluginState && a.samplePath == b.samplePath && a.zones.size() == b.zones.size()
  2926. && a.modelParams.size() == b.modelParams.size();
  2927. if (! same)
  2928. nativesResult = "ERROR channel " + juce::String::fromUTF8 (a.name.c_str());
  2929. }
  2930. for (std::size_t i = 0; same && i < song.mixer[2].effects.size(); ++i)
  2931. {
  2932. const auto& a = song.mixer[2].effects[i];
  2933. const auto& b = back->mixer[2].effects[i];
  2934. same = a.kind == b.kind && a.state == b.state;
  2935. for (std::size_t p = 0; same && p < a.params.size(); ++p)
  2936. same = std::abs (a.params[p] - b.params[p]) < 1.0e-3f;
  2937. if (! same)
  2938. nativesResult = juce::String ("ERROR effect ") + lynx::effectInfo (a.kind).name;
  2939. }
  2940. if (! back)
  2941. nativesResult = "ERROR " + error;
  2942. // each instrument plays a note alone. The Granulizer and Wave Traveller play the channel's sample, and a new
  2943. // one has none (a PC without FL Studio, macOS / Linux: FL's presets are not there either), so they get a
  2944. // generated one: a second of a 220 Hz tone (round 167m, PR #19: Wave Traveller was "SILENT 1" on macOS)
  2945. const auto toneWav = juce::File::getSpecialLocation (juce::File::tempDirectory).getChildFile ("lynx-selftest-natives.wav");
  2946. {
  2947. juce::WavAudioFormat format;
  2948. juce::AudioBuffer<float> tone (1, 48000);
  2949. for (int i = 0; i < 48000; ++i)
  2950. tone.setSample (0, i, 0.5f * std::sin (juce::MathConstants<float>::twoPi * 220.0f * (float) i / 48000.0f));
  2951. toneWav.deleteFile();
  2952. std::unique_ptr<juce::OutputStream> out (toneWav.createOutputStream().release());
  2953. if (auto* w = format.createWriterFor (out.get(), 48000.0, 1, 16, {}, 0))
  2954. {
  2955. out.release();
  2956. std::unique_ptr<juce::AudioFormatWriter> writer (w);
  2957. writer->writeFromAudioSampleBuffer (tone, 0, 48000);
  2958. }
  2959. }
  2960. juce::StringArray silentNames;
  2961. for (std::size_t i = 0; same && i < song.channels.size(); ++i)
  2962. {
  2963. auto one = song;
  2964. one.channels = { song.channels[i] };
  2965. one.channels[0].mixerTrack = 1;
  2966. const auto kind = song.channels[i].instrument;
  2967. // A new Fruity Slicer has no sample and no slices, and FL's is silent then too (round 180c), so it is
  2968. // not one of the engines that must sound here (Linux / macOS CI: "SILENT 1 [Fruity Slicer]", 0.1.25)
  2969. if (kind == lynx::InstrumentKind::fruityslicer && one.channels[0].samplePath.empty())
  2970. continue;
  2971. if ((kind == lynx::InstrumentKind::granulizer || kind == lynx::InstrumentKind::wavetraveller) && one.channels[0].samplePath.empty())
  2972. one.channels[0].samplePath = toneWav.getFullPathName().toStdString();
  2973. one.mixer[2].effects.clear();
  2974. // Drumaxx plays pad 1's key: FL's default kit has a pad at 48, LYNX's own bank kits (a PC without FL,
  2975. // macOS / Linux; round 168p) start at 36 (round 169d: "SILENT 1 [Drumaxx]" on the Linux / macOS CI)
  2976. auto key = 60;
  2977. if (kind == lynx::InstrumentKind::drumaxx)
  2978. {
  2979. const auto padKey = lynx::drumaxxParam (one.channels[0].pluginState, 4);
  2980. key = std::isfinite (padKey) && padKey >= 0.0f && padKey <= 127.0f ? (int) padKey : 48;
  2981. }
  2982. one.patterns[0].notes = { { 0, 1920, 0, key, 0.8f } };
  2983. lynx::AudioEngine player (false);
  2984. player.setSong (std::move (one));
  2985. player.dispatchPendingMessages();
  2986. if (! (player.renderOffline (1.0, 48000.0) > 1.0e-4f))
  2987. {
  2988. ++nativesSilent;
  2989. silentNames.add (juce::String::fromUTF8 (song.channels[i].name.c_str()));
  2990. }
  2991. }
  2992. toneWav.deleteFile();
  2993. if (nativesSilent > 0 && nativesResult == "OK")
  2994. nativesResult = "SILENT " + juce::String (nativesSilent) + " [" + silentNames.joinIntoString (", ") + "]";
  2995. }
  2996. const auto nativesOk = nativesResult == "OK";
  2997. // The metronome as FL 2026 plays it (round 165z-a2): FL's five sounds from its install, the downbeat at
  2998. // 0.9404 × the Tick two semitones up, into the Master ("---") by default; insert 2 as its track plays it through
  2999. // insert 2 (muted: silent); never in an export
  3000. juce::String metronomeResult = "OK";
  3001. int metronomeFlSounds = 0;
  3002. float metronomeMaster = 0.0f;
  3003. {
  3004. const auto& flData = lynx::flStudioAccess().roots.data;
  3005. const auto sounds = lynx::Metronome::loadSounds (flData.empty() ? juce::File() : lynx::platform::localFile (flData));
  3006. for (const auto& s : sounds)
  3007. metronomeFlSounds += s.fromFl ? 1 : 0;
  3008. auto renderClick = [] (int track, bool muteInsert, bool include) {
  3009. auto song = lynx::Song::makeDefault();
  3010. song.channels.clear();
  3011. song.playlist.clear();
  3012. for (auto& p : song.patterns)
  3013. p.notes.clear();
  3014. song.mixer[0].effects.clear(); // (the default Master limiter)
  3015. song.mixer[2].muted = muteInsert;
  3016. lynx::AudioEngine player (false);
  3017. player.setSong (std::move (song));
  3018. player.dispatchPendingMessages();
  3019. auto& t = player.getTransport();
  3020. t.metronome = true;
  3021. t.metronomeSound = 1; // Tick
  3022. t.metronomeTrack = track;
  3023. lynx::AudioEngine::RenderOptions o;
  3024. o.seconds = 0.25;
  3025. o.sampleRate = 44100.0;
  3026. o.pluginWarmUp = false;
  3027. o.includeMetronome = include;
  3028. return player.renderOffline (o);
  3029. };
  3030. metronomeMaster = renderClick (0, false, true);
  3031. const auto insert = renderClick (2, false, true);
  3032. const auto muted = renderClick (2, true, true);
  3033. const auto exported = renderClick (0, false, false);
  3034. // FL's Tick peaks at 1.0: its downbeat at most 0.9404 (the interpolation may land between peaks)
  3035. const auto expectHigh = metronomeFlSounds == lynx::metronome::soundCount ? lynx::metronome::downbeatGain + 1.0e-3f : 1.0f;
  3036. if (! (metronomeMaster > 0.5f && metronomeMaster < expectHigh))
  3037. metronomeResult = "ERROR master " + juce::String (metronomeMaster, 4);
  3038. else if (std::abs (insert - metronomeMaster) > 2.0e-3f)
  3039. metronomeResult = "ERROR insert " + juce::String (insert, 4);
  3040. else if (muted > 1.0e-4f)
  3041. metronomeResult = "ERROR muted insert " + juce::String (muted, 4);
  3042. else if (exported > 1.0e-4f)
  3043. metronomeResult = "ERROR in export " + juce::String (exported, 4);
  3044. }
  3045. const auto metronomeOk = metronomeResult == "OK";
  3046. // Settings › Audio "Driver settings…" with a fake driver panel (issue #13's crash, the panel's buffer kept)
  3047. const auto driverPanel = lynx::AudioEngine::driverPanelSelfTest();
  3048. // Online Sessions P2 (round 169b): live sessions without a network (the JSON round trip of every entity, replicas
  3049. // through it, the invite code's keys)
  3050. const auto liveResult = lynx::livetest::selfTest (&rich);
  3051. // issue #67: every built-in effect's parameters, named and hidden (the Parametric EQ's FL law, processing, band
  3052. // mask...), at odd values, through a project save and reload: the same floats back
  3053. juce::String effectParamsResult = "OK";
  3054. {
  3055. auto song = lynx::Song::makeDefault();
  3056. song.mixer.resize (1);
  3057. for (int k = 0; k <= (int) lynx::lastEffectKind; ++k)
  3058. {
  3059. const auto kind = (lynx::EffectKind) k;
  3060. if (kind == lynx::EffectKind::plugin || kind == lynx::EffectKind::parallel)
  3061. continue;
  3062. auto fx = lynx::makeEffectSlot (kind);
  3063. for (std::size_t i = 0; i < fx.params.size(); ++i)
  3064. {
  3065. auto v = (float) ((double) ((i * 7919 + (std::size_t) k * 104729) % 65521) / 65521.0);
  3066. fx.params[i] = v == fx.params[i] ? 1.0f - v : v;
  3067. }
  3068. if (kind == lynx::EffectKind::fruitySend) // ("Send to" is written over the insert span)
  3069. fx.params[3] = 0.0f;
  3070. song.mixer.emplace_back();
  3071. song.mixer.back().name = "Insert " + std::to_string (song.mixer.size() - 1);
  3072. song.mixer.back().effects.push_back (fx);
  3073. }
  3074. // round 171b's Patcher round trip (coordinator): the Frequency Splitter, Fruity Delay 3 and Peak Controller
  3075. // nodes came back different (their FL defaults, e.g. the LFO speed 32750 / 65336, lost to 4 decimals)
  3076. {
  3077. auto patch = lynx::makeEffectSlot (lynx::EffectKind::patcher);
  3078. for (const auto kind : { lynx::EffectKind::frequencySplitter, lynx::EffectKind::fruityDelay3, lynx::EffectKind::peakController,
  3079. lynx::EffectKind::reverb, lynx::EffectKind::hardwareInsert })
  3080. {
  3081. lynx::PatchNode node;
  3082. node.effect = lynx::natives::newEffect (kind, lynx::flStudioAccess()).value_or (lynx::makeEffectSlot (kind));
  3083. if (kind == lynx::EffectKind::peakController)
  3084. node.effect.params[7] = 32750.0f / 65336.0f;
  3085. node.x = 200.0f, node.y = 60.0f * (float) patch.patcher.nodes.size();
  3086. patch.patcher.nodes.push_back (node);
  3087. }
  3088. song.mixer.emplace_back();
  3089. song.mixer.back().name = "Patcher";
  3090. song.mixer.back().effects.push_back (patch);
  3091. }
  3092. juce::String why;
  3093. const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), why);
  3094. if (back && back->mixer.size() == song.mixer.size())
  3095. {
  3096. const auto& a = song.mixer.back().effects[0].patcher.nodes;
  3097. const auto& b = back->mixer.back().effects[0].patcher.nodes;
  3098. for (std::size_t n = 0; n < a.size(); ++n)
  3099. if (n >= b.size() || ! (a[n].effect == b[n].effect))
  3100. effectParamsResult = juce::String ("ERROR Patcher node ") + lynx::effectInfo (a[n].effect.kind).name;
  3101. }
  3102. if (! back || back->mixer.size() != song.mixer.size())
  3103. effectParamsResult = "ERROR load " + why;
  3104. else
  3105. for (std::size_t t = 1; t + 1 < song.mixer.size() && effectParamsResult == "OK"; ++t)
  3106. if (back->mixer[t].effects.size() != 1 || back->mixer[t].effects[0].params != song.mixer[t].effects[0].params)
  3107. {
  3108. effectParamsResult = juce::String ("ERROR ") + lynx::effectInfo (song.mixer[t].effects[0].kind).name;
  3109. break;
  3110. }
  3111. }
  3112. // round 170j: the Themed plugin style (its resolution with and without art; every art draws)
  3113. const auto artResult = lynx::skin::artSelfTest();
  3114. // round 177b: a plugin's sidechain bus gets the slot's sidechain (one-click sidechain)
  3115. const auto sidechainResult = lynx::pluginSidechainSelfTest();
  3116. // round 177b: automation lanes come back from a project (track, automation, height, folded)
  3117. juce::String lanesResult = "OK";
  3118. {
  3119. auto song = lynx::Song::makeDefault();
  3120. const auto lane = lynx::autolanes::addLane (song, 3, { lynx::AutomationTargetKind::mixerVolume, 1, 0, 0 }, "Vol", 0.4f);
  3121. song.playlistTracks[3].lanes[0].height = 72;
  3122. song.playlistTracks[3].lanesFolded = true;
  3123. // (the same round's clip LFO and modulators ride along)
  3124. auto& lfo = song.automations[(std::size_t) lane].lfo;
  3125. lfo.on = true;
  3126. lfo.level = -40;
  3127. lfo.speed = 30000;
  3128. lfo.flags = 1 | 4;
  3129. lfo.phase = 123456789u;
  3130. lfo.amp = { { 0, 0.5f, 0.0f }, { 960, 1.0f, 0.0f } };
  3131. lynx::Modulator mod;
  3132. mod.name = "LFO 1";
  3133. mod.shape = lynx::ModShape::square;
  3134. mod.sync = false;
  3135. mod.hz = 2.5;
  3136. mod.routes = { { { lynx::AutomationTargetKind::mixerPan, 1, 0, 0 }, -0.5f } };
  3137. song.modulators.push_back (mod);
  3138. juce::String why;
  3139. const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), why);
  3140. if (! back || back->playlistTracks.size() < 4 || ! (back->playlistTracks[3].lanes == song.playlistTracks[3].lanes)
  3141. || ! back->playlistTracks[3].lanesFolded || back->automations.size() != song.automations.size()
  3142. || ! (back->automations[(std::size_t) lane].points == song.automations[(std::size_t) lane].points)
  3143. || ! (back->automations[(std::size_t) lane].lfo == lfo) || ! (back->modulators == song.modulators))
  3144. lanesResult = "ERROR " + why;
  3145. }
  3146. const auto mixerBasics = lynx::mixerbasics::run();
  3147. 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
  3148. && sessionResult == "OK" && liveResult.startsWith ("OK")
  3149. && wavpack != "ERROR" && effectsOk && driverPanel == "OK" && metronomeOk && artResult == "OK" && effectParamsResult == "OK"
  3150. && sidechainResult == "OK" && lanesResult == "OK";
  3151. juce::String report;
  3152. report << "connections=" << offline.getNumGraphConnections() << "\n"
  3153. << "peak=" << peak << "\n"
  3154. << "project=" << (projectOk ? "OK" : "ERROR " + error) << "\n"
  3155. << "playlist_track_modes_roundtrip=" << (trackModes122Ok ? "OK" : "ERROR") << "\n"
  3156. << "project_features=" << (richOk ? "OK" : "ERROR") << "\n"
  3157. << "hardware_outputs=" << (hwOutOk ? "OK" : "ERROR") << "\n"
  3158. << "plugin_host_keys_option=" << (hostKeysOk ? "OK" : "ERROR") << "\n"
  3159. << "flp168j_fields=" << (flp168jOk ? "OK" : "ERROR") << "\n"
  3160. << "clip_fades_180d=" << (clipFades180dOk ? "OK" : "ERROR") << "\n"
  3161. << "pattern_blocks=" << (blocksOk ? "OK" : "ERROR") << "\n"
  3162. << "comp_crossfades=" << (compOk ? "OK" : "ERROR") << "\n"
  3163. << "channel_polyphony=" << (polyOk ? "OK" : "ERROR") << "\n"
  3164. << "track_latency=" << (latencyOk ? "OK" : "ERROR") << "\n"
  3165. << "plugin_substitutes=" << (substituteOk ? "OK" : "ERROR") << "\n"
  3166. << "patcher=" << (patcherOk ? "OK" : "ERROR") << "\n"
  3167. << "native_engines=" << nativesResult << " (" << nativesMade << " made)\n"
  3168. << "undo=" << (undoOk ? "OK" : "ERROR") << "\n"
  3169. << "mixer_basics=" << mixerBasics << "\n"
  3170. << "recording=" << (recordOk && recordUndoOk ? "OK" : "ERROR") << "\n"
  3171. << "cancel_recording=" << (cancelRecordOk ? "OK" : "ERROR") << "\n"
  3172. << "midi=" << (midiOk ? "OK" : "ERROR") << "\n"
  3173. << "package=" << (packageOk ? "OK" : "ERROR") << "\n"
  3174. << "projectSave=" << (projectSaveOk ? "OK" : "ERROR") << "\n"
  3175. << "online_session=" << sessionResult << "\n"
  3176. << "live_session=" << liveResult << "\n"
  3177. << "wavpack=" << wavpack << "\n"
  3178. << "effects=" << (effectsOk ? "OK" : "NONFINITE") << "\n"
  3179. << "effect_params_saved=" << effectParamsResult << "\n"
  3180. << "driver_panel=" << driverPanel << "\n"
  3181. << "plugin_art=" << artResult << "\n"
  3182. << "plugin_sidechain=" << sidechainResult << "\n"
  3183. << "lanes_saved=" << lanesResult << "\n"
  3184. << "metronome=" << metronomeResult << " (FL sounds " << metronomeFlSounds << "/" << lynx::metronome::soundCount
  3185. << ", downbeat peak " << juce::String (metronomeMaster, 4) << ")\n"
  3186. << "result=" << (ok ? "OK" : "FAILED") << "\n";
  3187. if (reportPath.isNotEmpty())
  3188. juce::File (reportPath).replaceWithText (report);
  3189. setApplicationReturnValue (ok ? 0 : 1);
  3190. quit();
  3191. }
  3192. // Every built-in effect in its native editor: random / extreme parameters, mouse drags over the editor, the editor
  3193. // painted, audio rendered at 44.1 / 48 / 96 kHz. Returns false when an effect output NaN / inf (muted by the
  3194. // renderer's guard). The report lists each effect. Used by --fxfuzz and (a short run) by --selftest.
  3195. bool runEffectFuzz (int rounds, const juce::String& reportPath, bool drags = false)
  3196. {
  3197. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  3198. lynx::setNativeEditorDemo (true);
  3199. juce::String report;
  3200. auto allFinite = true;
  3201. {
  3202. lynx::AudioEngine offline (false);
  3203. juce::Random random (111);
  3204. const auto value = [&] { const auto r = random.nextInt (6); return r == 0 ? 0.0f : r == 1 ? 1.0f : random.nextFloat(); };
  3205. for (int k = 0; k <= (int) lynx::lastEffectKind; ++k)
  3206. {
  3207. const auto kind = (lynx::EffectKind) k;
  3208. if (! lynx::NativeEffectWindows::canOpen (kind) || kind == lynx::EffectKind::patcher) // (the Patcher's editor is a graph window)
  3209. continue;
  3210. const auto before = lynx::RackRenderer::nonFiniteEffectBlocks();
  3211. const auto& info = lynx::effectInfo (kind);
  3212. // (FL engines: a fresh instance as the menus make it, from the user's FL installation; round 142)
  3213. auto fx = lynx::natives::newEffect (kind, lynx::flStudioAccess()).value_or (lynx::makeEffectSlot (kind));
  3214. int dragged = 0; // parameter changes made by the mouse drags
  3215. for (int round = 0; round < rounds; ++round)
  3216. {
  3217. if (round > 0)
  3218. for (std::size_t p = 0; p < info.params.size(); ++p)
  3219. fx.params[p] = round == 1 ? 0.0f : round == 2 ? 1.0f : value();
  3220. auto song = lynx::Song::makeDefault(); // its demo beat feeds the effect
  3221. song.mixer.resize (2);
  3222. song.mixer[0].name = "Master";
  3223. song.mixer[1].name = "Insert 1";
  3224. song.mixer[1].effects.assign (1, fx);
  3225. for (auto& channel : song.channels)
  3226. channel.mixerTrack = 1;
  3227. offline.setSong (std::move (song));
  3228. offline.dispatchPendingMessages();
  3229. const auto pages = juce::jmax (1, (int) lynx::plugui::layoutFor (kind).pages.size());
  3230. for (int page = 0; page < pages; ++page)
  3231. {
  3232. auto editor = kind == lynx::EffectKind::facetEq ? lynx::makeFacetEqEditor (offline, 1, 0, false)
  3233. : lynx::makeNativeEffectEditor (offline, 1, 0, 1.0f, page);
  3234. if (editor == nullptr || editor->getWidth() <= 0 || editor->getHeight() <= 0)
  3235. continue;
  3236. juce::Image image (juce::Image::ARGB, editor->getWidth(), editor->getHeight(), true);
  3237. const auto paint = [&] {
  3238. juce::Graphics g (image);
  3239. editor->paintEntireComponent (g, false);
  3240. };
  3241. paint();
  3242. // drags from a grid of points, as a user moving every control (plain left button)
  3243. if (round >= 3 && drags)
  3244. {
  3245. const auto source = juce::Desktop::getInstance().getMainMouseSource();
  3246. const auto step = juce::jmax (12, juce::jmin (editor->getWidth(), editor->getHeight()) / 8);
  3247. for (int y = step / 2; y < editor->getHeight(); y += step)
  3248. for (int x = step / 2; x < editor->getWidth(); x += step)
  3249. {
  3250. auto* target = editor->getComponentAt (x, y);
  3251. if (target == nullptr)
  3252. continue;
  3253. const auto at = target->getLocalPoint (editor.get(), juce::Point<float> ((float) x, (float) y));
  3254. const auto now = juce::Time::getCurrentTime();
  3255. const auto event = [&] (juce::Point<float> p, juce::ModifierKeys mods) {
  3256. return juce::MouseEvent (source, p, mods, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, target, target, now, at, now, 1, false);
  3257. };
  3258. const auto down = juce::ModifierKeys (juce::ModifierKeys::leftButtonModifier);
  3259. const juce::Component::SafePointer<juce::Component> alive (target);
  3260. target->mouseDown (event (at, down));
  3261. const auto dy = (float) (random.nextBool() ? 400 : -400), dx = (float) (random.nextInt (401) - 200);
  3262. if (alive != nullptr)
  3263. target->mouseDrag (event (at + juce::Point<float> (dx * 0.5f, dy * 0.5f), down));
  3264. if (alive != nullptr)
  3265. target->mouseDrag (event (at + juce::Point<float> (dx, dy), down));
  3266. if (alive != nullptr)
  3267. target->mouseUp (event (at + juce::Point<float> (dx, dy), juce::ModifierKeys()));
  3268. juce::PopupMenu::dismissAllActiveMenus();
  3269. offline.dispatchPendingMessages();
  3270. }
  3271. paint();
  3272. }
  3273. }
  3274. for (const auto rate : { 44100.0, 48000.0, 96000.0 })
  3275. offline.renderOffline (0.05, rate);
  3276. if (round == 0 || round >= 3) // keep what the drags set for the next round
  3277. if (offline.getSong().mixer.size() > 1 && ! offline.getSong().mixer[1].effects.empty())
  3278. {
  3279. const auto& now = offline.getSong().mixer[1].effects[0];
  3280. for (std::size_t p = 0; p < fx.params.size(); ++p)
  3281. dragged += now.params[p] != fx.params[p] ? 1 : 0;
  3282. dragged += now.state != fx.state ? 1 : 0;
  3283. fx = now;
  3284. }
  3285. }
  3286. const auto broken = lynx::RackRenderer::nonFiniteEffectBlocks() - before;
  3287. allFinite = allFinite && broken == 0;
  3288. report << info.name << ": " << (broken == 0 ? juce::String ("OK") : "non-finite output in " + juce::String ((juce::int64) broken) + " blocks")
  3289. << " (" << dragged << " changes by mouse)\n";
  3290. if (reportPath.isNotEmpty())
  3291. juce::File (reportPath).replaceWithText (report + "(running)\n"); // what was reached, if it crashes
  3292. }
  3293. }
  3294. lynx::setNativeEditorDemo (false);
  3295. juce::LookAndFeel::setDefaultLookAndFeel (nullptr);
  3296. report << "result=" << (allFinite ? "OK" : "NONFINITE") << "\n";
  3297. if (reportPath.isNotEmpty())
  3298. juce::File (reportPath).replaceWithText (report);
  3299. return allFinite;
  3300. }
  3301. // --opentest (round 157a): see the command line. Runs on the message loop (the editors' timers, animations and
  3302. // native windows are real); one step per timer tick.
  3303. void runOpenTest (const juce::String& reportPath, bool visible, std::function<void (bool)> done)
  3304. {
  3305. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  3306. struct OpenTest final : juce::Timer
  3307. {
  3308. juce::String reportPath, report;
  3309. bool visible = false, ok = true;
  3310. std::function<void (bool)> done;
  3311. std::unique_ptr<lynx::AudioEngine> engine;
  3312. std::vector<std::pair<juce::String, std::function<void()>>> steps;
  3313. std::size_t next = 0;
  3314. std::atomic<std::int64_t> lastStep { 0 };
  3315. std::atomic<bool> finished { false };
  3316. std::thread watchdog;
  3317. juce::String current;
  3318. std::mutex currentLock;
  3319. int opened = 0, painted = 0;
  3320. // LYNX_OPENTEST_TIMEOUT (seconds): longer for sanitizer builds
  3321. const std::int64_t timeoutMs = 1000 * juce::jmax (5, juce::SystemStats::getEnvironmentVariable ("LYNX_OPENTEST_TIMEOUT", "20").getIntValue());
  3322. static std::int64_t now() { return (std::int64_t) juce::Time::getMillisecondCounter(); }
  3323. void write (const juce::String& tail = {}) { juce::File (reportPath).replaceWithText (report + tail); }
  3324. ~OpenTest() override
  3325. {
  3326. finished = true;
  3327. if (watchdog.joinable())
  3328. watchdog.join();
  3329. }
  3330. void start()
  3331. {
  3332. lastStep = now();
  3333. // the UI hang watch runs during the whole test (5 s): a slow step leaves its stack next to the report
  3334. const auto folder = juce::File (reportPath).getParentDirectory().getChildFile ("opentest-hang");
  3335. folder.deleteRecursively();
  3336. folder.createDirectory();
  3337. lynx::crashguard::startHangWatch (folder.getFullPathName().replaceCharacter ('\\', '/').toStdString(), 5000);
  3338. watchdog = std::thread ([this] {
  3339. while (! finished)
  3340. {
  3341. std::this_thread::sleep_for (std::chrono::milliseconds (200));
  3342. if (now() - lastStep.load() > timeoutMs)
  3343. {
  3344. juce::String at;
  3345. {
  3346. const std::lock_guard<std::mutex> l (currentLock);
  3347. at = current;
  3348. }
  3349. juce::File (reportPath).replaceWithText (report + "HANG at " + at + " (no progress for " + juce::String (timeoutMs / 1000) + " s; stack in opentest-hang)\nresult=HANG\n");
  3350. lynx::crashguard::exitNow (3);
  3351. }
  3352. }
  3353. });
  3354. startTimer (30);
  3355. }
  3356. // every LYNX window but none of the main one (there is none here): moved off-screen, painted once into an image
  3357. void touchWindows (bool resize, bool large)
  3358. {
  3359. auto& desktop = juce::Desktop::getInstance();
  3360. for (int i = desktop.getNumComponents(); --i >= 0;)
  3361. if (auto* c = desktop.getComponent (i); c != nullptr && c->isVisible())
  3362. {
  3363. if (! visible && c->getScreenX() > -3000)
  3364. c->setTopLeftPosition (-6000, -6000);
  3365. if (resize)
  3366. if (auto* w = dynamic_cast<juce::ResizableWindow*> (c))
  3367. {
  3368. const auto b = w->getBounds();
  3369. w->setSize (large ? b.getWidth() * 2 : juce::jmax (40, b.getWidth() / 3), large ? b.getHeight() * 2 : juce::jmax (40, b.getHeight() / 3));
  3370. }
  3371. if (c->getWidth() > 0 && c->getHeight() > 0 && c->getWidth() < 8000 && c->getHeight() < 8000)
  3372. {
  3373. juce::Image image (juce::Image::ARGB, c->getWidth(), c->getHeight(), true);
  3374. juce::Graphics g (image);
  3375. c->paintEntireComponent (g, false);
  3376. ++painted;
  3377. // LYNX_OPENTEST_SHOTS=folder: each window as first painted (before the resizes), for a look
  3378. if (const auto shots = juce::SystemStats::getEnvironmentVariable ("LYNX_OPENTEST_SHOTS", {}); shots.isNotEmpty() && ! resize)
  3379. {
  3380. juce::FileOutputStream out (juce::File (shots).getChildFile (juce::String (painted).paddedLeft ('0', 4) + ".png"));
  3381. if (out.openedOk())
  3382. {
  3383. out.setPosition (0), out.truncate();
  3384. juce::PNGImageFormat().writeImageToStream (c->createComponentSnapshot (c->getLocalBounds()), out);
  3385. }
  3386. }
  3387. }
  3388. }
  3389. }
  3390. void timerCallback() override
  3391. {
  3392. if (next >= steps.size())
  3393. {
  3394. stopTimer();
  3395. lynx::NativeEffectWindows::closeAll();
  3396. lynx::closeChannelSettings();
  3397. // the UI hang watch itself: the message thread spins past the stall time; the watcher must write the stack
  3398. {
  3399. const auto before = lynx::crashguard::lastHangFile();
  3400. for (const auto until = now() + 7000; now() < until;)
  3401. lastStep = now(); // (busy: no heartbeat; the test's own watchdog stays quiet)
  3402. for (const auto until = now() + 1500; now() < until && lynx::crashguard::lastHangFile() == before;)
  3403. std::this_thread::sleep_for (std::chrono::milliseconds (20));
  3404. lynx::crashguard::stopHangWatch();
  3405. const juce::File hang (juce::String::fromUTF8 (lynx::crashguard::lastHangFile().c_str()));
  3406. const auto text = hang.loadFileAsString();
  3407. const auto frames = juce::StringArray::fromLines (text).size() - 2;
  3408. #if JUCE_WINDOWS
  3409. const auto hangOk = lynx::crashguard::lastHangFile() != before && hang.existsAsFile() && text.contains ("LYNX.exe+0x") && frames >= 3;
  3410. #else
  3411. const auto hangOk = lynx::crashguard::lastHangFile() != before && hang.existsAsFile() && frames >= 3;
  3412. #endif
  3413. report << "hang watch: " << (hangOk ? "OK" : "FAIL") << " (" << hang.getFileName() << ", " << frames << " lines"
  3414. << (before.empty() ? juce::String() : "; a step stalled > 5 s earlier: " + juce::String::fromUTF8 (before.c_str())) << ")\n";
  3415. ok = ok && hangOk;
  3416. }
  3417. report << "windows opened: " << opened << ", paints: " << painted << "\nresult=" << (ok ? "OK" : "FAIL") << "\n";
  3418. write();
  3419. finished = true;
  3420. if (done)
  3421. done (ok);
  3422. return;
  3423. }
  3424. auto& [label, fn] = steps[next++];
  3425. {
  3426. const std::lock_guard<std::mutex> l (currentLock);
  3427. current = label;
  3428. }
  3429. fn();
  3430. lastStep = now();
  3431. lynx::crashguard::heartbeat();
  3432. }
  3433. };
  3434. auto* test = new OpenTest();
  3435. test->reportPath = reportPath;
  3436. test->visible = visible;
  3437. test->engine = std::make_unique<lynx::AudioEngine> (false);
  3438. test->done = [test, done] (bool ok) {
  3439. juce::MessageManager::callAsync ([test, done, ok] {
  3440. delete test;
  3441. juce::LookAndFeel::setDefaultLookAndFeel (nullptr);
  3442. done (ok);
  3443. });
  3444. };
  3445. auto& engine = *test->engine;
  3446. lynx::setNativeEditorDemo (true); // live displays animate without an audio device
  3447. const auto songWith = [] (const lynx::EffectSlot& fx) {
  3448. auto song = lynx::Song::makeDefault();
  3449. song.mixer.resize (2);
  3450. song.mixer[0].name = "Master";
  3451. song.mixer[1].name = "Insert 1";
  3452. song.mixer[1].effects.assign (1, fx);
  3453. for (auto& channel : song.channels)
  3454. channel.mixerTrack = 1;
  3455. return song;
  3456. };
  3457. // an older project's slot: its parameter list cut to `count` and read back by the project reader (the
  3458. // parameters a newer LYNX added after them take their defaults)
  3459. const auto oldState = [songWith] (const lynx::EffectSlot& fx, std::size_t count) -> std::optional<lynx::Song> {
  3460. auto json = juce::JSON::parse (lynx::ProjectFile::toJson (songWith (fx)));
  3461. if (auto* mixer = json["mixer"].getArray(); mixer != nullptr && mixer->size() > 1)
  3462. if (auto* effects = (*mixer)[1]["effects"].getArray(); effects != nullptr && ! effects->isEmpty())
  3463. if (auto* params = (*effects)[0]["params"].getArray())
  3464. params->removeRange ((int) count, params->size());
  3465. juce::String error;
  3466. return lynx::ProjectFile::fromJson (juce::JSON::toString (json), error);
  3467. };
  3468. auto& steps = test->steps;
  3469. juce::Random random (157);
  3470. for (int k = 0; k <= (int) lynx::lastEffectKind; ++k)
  3471. {
  3472. const auto kind = (lynx::EffectKind) k;
  3473. if (! lynx::NativeEffectWindows::canOpen (kind) || kind == lynx::EffectKind::patcher)
  3474. continue;
  3475. const auto& info = lynx::effectInfo (kind);
  3476. const auto base = lynx::natives::newEffect (kind, lynx::flStudioAccess()).value_or (lynx::makeEffectSlot (kind));
  3477. const auto n = info.params.size();
  3478. std::vector<std::pair<juce::String, std::function<std::optional<lynx::Song>()>>> variants;
  3479. variants.push_back ({ "default", [=] { return std::optional<lynx::Song> (songWith (base)); } });
  3480. for (const auto value : { 0.0f, 1.0f })
  3481. variants.push_back ({ value == 0.0f ? "all 0" : "all 1", [=] {
  3482. auto fx = base;
  3483. for (std::size_t p = 0; p < n; ++p) fx.params[p] = value;
  3484. return std::optional<lynx::Song> (songWith (fx));
  3485. } });
  3486. const auto seed = random.nextInt64();
  3487. variants.push_back ({ "random", [=] {
  3488. juce::Random r (seed);
  3489. auto fx = base;
  3490. for (std::size_t p = 0; p < n; ++p) fx.params[p] = r.nextFloat();
  3491. return std::optional<lynx::Song> (songWith (fx));
  3492. } });
  3493. std::vector<std::size_t> cuts { n / 2 };
  3494. 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)
  3495. if (c < n) cuts.push_back (c);
  3496. for (const auto c : cuts)
  3497. variants.push_back ({ "old project (" + juce::String ((int) c) + " of " + juce::String ((int) n) + " params)", [=] { return oldState (base, c); } });
  3498. for (const auto& [variant, makeSong] : variants)
  3499. {
  3500. const auto label = juce::String::fromUTF8 (info.name) + " / " + variant;
  3501. steps.push_back ({ label + ": open", [test, &engine, label, makeSong = makeSong] {
  3502. auto song = makeSong();
  3503. if (! song)
  3504. {
  3505. test->report << "FAIL " << label << ": project reader refused the state\n";
  3506. test->ok = false;
  3507. return;
  3508. }
  3509. engine.setSong (std::move (*song));
  3510. engine.dispatchPendingMessages();
  3511. lynx::NativeEffectWindows::open (engine, 1, 0);
  3512. ++test->opened;
  3513. test->touchWindows (false, false);
  3514. } });
  3515. steps.push_back ({ label + ": run", [test, &engine] {
  3516. for (const auto rate : { 44100.0, 48000.0, 96000.0 })
  3517. engine.renderOffline (0.03, rate);
  3518. test->touchWindows (false, false);
  3519. } });
  3520. steps.push_back ({ label + ": small", [test] { test->touchWindows (true, false); } });
  3521. steps.push_back ({ label + ": large", [test] { test->touchWindows (true, true); } });
  3522. steps.push_back ({ label + ": close", [test, label] {
  3523. lynx::NativeEffectWindows::closeAll();
  3524. test->report << label << ": OK\n";
  3525. test->write ("(running)\n");
  3526. } });
  3527. }
  3528. }
  3529. // instruments: the channel window the Channel rack opens (Patcher: its graph window, not here)
  3530. for (int k = 0; k <= (int) lynx::InstrumentKind::soundfont; ++k)
  3531. {
  3532. const auto kind = (lynx::InstrumentKind) k;
  3533. if (kind == lynx::InstrumentKind::plugin || kind == lynx::InstrumentKind::patcher)
  3534. continue;
  3535. for (const auto* variant : { "default", "old project (saved and read back)", "odd settings" })
  3536. {
  3537. if (juce::String (variant) == "odd settings" && kind != lynx::InstrumentKind::soundfont)
  3538. continue;
  3539. const auto label = "instrument " + juce::String (k) + " / " + variant;
  3540. steps.push_back ({ label + ": open", [test, &engine, kind, label, variant = juce::String (variant), old = juce::String (variant) != "default"] {
  3541. auto song = lynx::Song::makeDefault();
  3542. auto channel = lynx::natives::makeChannel (kind, lynx::flStudioAccess());
  3543. lynx::ChannelDef def;
  3544. def.instrument = kind;
  3545. def.name = "Test";
  3546. song.channels.push_back (channel ? *channel : def);
  3547. if (kind == lynx::InstrumentKind::soundfont && variant != "default")
  3548. {
  3549. // a real font when FL's is there; NaN / huge / truncated settings
  3550. const auto& roots = lynx::flStudioAccess().roots;
  3551. if (! roots.data.empty())
  3552. song.channels.back().samplePath = (juce::File (juce::String::fromUTF8 (roots.data.c_str()))
  3553. .getChildFile ("Patches/Soundfonts/STR_Ensemble.sf2"))
  3554. .getFullPathName().toStdString();
  3555. if (variant == "odd settings")
  3556. song.channels.back().modelParams = { NAN, 1.0e9f, -1.0e9f, 0.5f, 7.0f };
  3557. }
  3558. if (old)
  3559. {
  3560. juce::String error;
  3561. if (auto again = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), error))
  3562. song = std::move (*again);
  3563. }
  3564. const auto index = (int) song.channels.size() - 1;
  3565. engine.setSong (std::move (song));
  3566. engine.dispatchPendingMessages();
  3567. lynx::openChannelSettings (engine, index);
  3568. ++test->opened;
  3569. test->touchWindows (false, false);
  3570. } });
  3571. steps.push_back ({ label + ": run", [test, &engine] {
  3572. engine.renderOffline (0.03, 48000.0);
  3573. test->touchWindows (false, false);
  3574. } });
  3575. steps.push_back ({ label + ": small", [test] { test->touchWindows (true, false); } });
  3576. steps.push_back ({ label + ": large", [test] { test->touchWindows (true, true); } });
  3577. steps.push_back ({ label + ": close", [test, label] {
  3578. lynx::closeChannelSettings();
  3579. test->report << label << ": OK\n";
  3580. test->write ("(running)\n");
  3581. } });
  3582. }
  3583. }
  3584. test->start();
  3585. }
  3586. void runPlugWinTest (const juce::String& pluginPath, const juce::String& reportPath, const juce::String& only, int seconds)
  3587. {
  3588. struct Test final : juce::Timer
  3589. {
  3590. juce::String reportPath, report;
  3591. std::unique_ptr<lynx::AudioEngine> engine;
  3592. bool instrument = false;
  3593. int phase = 0, ticks = 0, seconds = 15, dockStep = 0;
  3594. juce::uint32 phaseStartMs = 0; // (phase 1 counts real time: the timer's ticks ran faster than 20 Hz here)
  3595. juce::AudioPluginInstance* instance = nullptr;
  3596. juce::AudioProcessorParameter* checked = nullptr;
  3597. std::unique_ptr<juce::DocumentWindow> mainWindow; // stands for LYNX's main window (window ownership)
  3598. lynx::Workspace* workspace = nullptr; // LYNX_PLUGWIN_DOCK=1: the real main window's desktop (issue #116)
  3599. int channelIndex = -1; // an instrument: its channel (added after the song's own channels)
  3600. int stepMs = 3000; // dock mode: each state held that long (screenshots)
  3601. bool keysDone = false;
  3602. bool dockOk = true;
  3603. std::function<void (bool)> done;
  3604. // issue #116 (with LYNX_DOCKED_PLUGINS=1 and LYNX_PLUGWIN_DOCK=1), FL's f116 sequence for every floating
  3605. // panel: the docked plugin window goes behind a clicked panel and comes back in front when clicked; a
  3606. // panel called by its key comes in front too; Detached reopens it as a window of its own, which stays above
  3607. // every panel clicked (it is owned by the main window).
  3608. const std::array<lynx::workspace::Panel, 4> dockPanels { lynx::workspace::Panel::channelRack, lynx::workspace::Panel::playlist,
  3609. lynx::workspace::Panel::pianoRoll, lynx::workspace::Panel::mixer };
  3610. const int dockSteps = 2 * 4 + 5;
  3611. void* panelHandle (lynx::workspace::Panel p) const { return workspace->getFrame (p).getWindowHandle(); }
  3612. void dockCheck (int at)
  3613. {
  3614. using lynx::workspace::Panel;
  3615. auto* main = mainWindow->getWindowHandle();
  3616. auto* plug = lynx::PluginWindows::hostWindowHandle (*instance);
  3617. auto expect = [this] (const juce::String& name, bool value) {
  3618. step (name + "=" + juce::String ((int) value));
  3619. dockOk = dockOk && value;
  3620. };
  3621. auto id = [] (Panel p) { return juce::String (lynx::workspace::panelId (p)); };
  3622. if (at == 0)
  3623. {
  3624. expect ("docked", lynx::PluginWindows::isDocked (*instance));
  3625. expect ("plugin_native_child", plug != nullptr && lynx::nativechild::parentOf (plug) == main);
  3626. for (auto p : dockPanels)
  3627. {
  3628. auto* h = panelHandle (p);
  3629. expect (id (p) + "_visible", workspace->isPanelVisible (p));
  3630. expect (id (p) + "_native_child", h != nullptr && h != main && lynx::nativechild::parentOf (h) == main);
  3631. expect ("plugin_above_" + id (p) + "_when_opened", lynx::nativechild::isAbove (plug, h));
  3632. }
  3633. expect ("browser_plain", ! workspace->isNativePanel (Panel::browser));
  3634. }
  3635. if (at < 2 * 4)
  3636. {
  3637. const auto p = dockPanels[at / 2];
  3638. if (at % 2 == 0)
  3639. {
  3640. workspace->activate (p); // a click on the panel
  3641. expect (id (p) + "_above_plugin_after_its_click", lynx::nativechild::isAbove (panelHandle (p), plug));
  3642. // the plugin stays above the panels nobody clicked
  3643. for (auto other : dockPanels)
  3644. if (other != p)
  3645. expect ("plugin_above_" + id (other) + "_after_" + id (p) + "_click", lynx::nativechild::isAbove (plug, panelHandle (other)));
  3646. }
  3647. else
  3648. {
  3649. lynx::PluginWindows::open ({}, *instance, {}); // (open again = a click on the plugin)
  3650. expect ("plugin_above_" + id (p) + "_after_plugin_click", lynx::nativechild::isAbove (plug, panelHandle (p)));
  3651. }
  3652. return;
  3653. }
  3654. if (at == 8)
  3655. {
  3656. // a layout change elsewhere (a panel resized, the Browser shown) keeps the plugin in front; a panel
  3657. // called by its key comes in front of it
  3658. workspace->hide (Panel::browser);
  3659. workspace->show (Panel::browser);
  3660. for (auto p : dockPanels)
  3661. expect ("plugin_above_" + id (p) + "_after_layout_change", lynx::nativechild::isAbove (plug, panelHandle (p)));
  3662. workspace->show (Panel::mixer);
  3663. expect ("mixer_above_plugin_after_show", lynx::nativechild::isAbove (panelHandle (Panel::mixer), plug));
  3664. }
  3665. else if (at == 9)
  3666. lynx::PluginWindows::setDetached (*instance, true);
  3667. else if (at == 10)
  3668. {
  3669. expect ("detached_reopened", lynx::PluginWindows::isOpen (*instance) && ! lynx::PluginWindows::isDocked (*instance));
  3670. expect ("detached_owned_by_main", plug != nullptr && lynx::nativechild::ownerOf (plug) == main);
  3671. expect ("detached_saved", find() == instance && engineRef() != nullptr && engineRef()->detached);
  3672. for (auto p : dockPanels)
  3673. workspace->activate (p);
  3674. }
  3675. else if (at == 11)
  3676. {
  3677. // (an owned top-level window: above the main window and so above all its child windows)
  3678. expect ("detached_stays_above_clicked_panels", plug != nullptr && lynx::nativechild::ownerOf (plug) == main
  3679. && lynx::nativechild::parentOf (plug) != main && lynx::PluginWindows::isOpen (*instance));
  3680. lynx::PluginWindows::setDetached (*instance, false);
  3681. }
  3682. else
  3683. {
  3684. expect ("docked_again", lynx::PluginWindows::isDocked (*instance) && engineRef() != nullptr && ! engineRef()->detached);
  3685. step (juce::String ("dock_result=") + (dockOk ? "OK" : "FAILED"));
  3686. }
  3687. }
  3688. const lynx::PluginRef* engineRef() const
  3689. {
  3690. const auto& song = engine->getSong();
  3691. if (instrument)
  3692. return channelIndex < 0 || channelIndex >= (int) song.channels.size() ? nullptr : &song.channels[(size_t) channelIndex].plugin;
  3693. return song.mixer.size() < 2 || song.mixer[1].effects.empty() ? nullptr : &song.mixer[1].effects[0].plugin;
  3694. }
  3695. void step (const juce::String& line)
  3696. {
  3697. report << line << "\n";
  3698. juce::File (reportPath).replaceWithText (report);
  3699. }
  3700. juce::AudioPluginInstance* find()
  3701. {
  3702. if (instrument)
  3703. {
  3704. if (auto* p = dynamic_cast<lynx::PluginInstrument*> (engine->getChannelInstrument (channelIndex).get()))
  3705. return &p->getInstance();
  3706. }
  3707. else if (auto* p = dynamic_cast<lynx::PluginEffect*> (engine->getEffect (1, 0).get()))
  3708. return &p->getInstance();
  3709. return nullptr;
  3710. }
  3711. void timerCallback() override
  3712. {
  3713. ++ticks;
  3714. if (phase == 0) // waiting for the engine to host the plugin
  3715. {
  3716. instance = find();
  3717. if (instance == nullptr)
  3718. {
  3719. if (ticks > 200)
  3720. {
  3721. step ("result=FAILED (not hosted)");
  3722. stopTimer();
  3723. done (false);
  3724. }
  3725. return;
  3726. }
  3727. step ("hosted=" + instance->getName() + " format=" + instance->getPluginDescription().pluginFormatName);
  3728. step ("programs=" + juce::String (instance->getNumPrograms()));
  3729. for (int p = 0; p < juce::jmin (5, instance->getNumPrograms()); ++p)
  3730. step ("program" + juce::String (p) + "=" + instance->getProgramName (p));
  3731. step ("save_formats=" + lynx::pluginpresetui::saveWildcard (*instance));
  3732. // preset round trip: save, change the first parameter, load, compare
  3733. juce::AudioProcessorParameter* param = nullptr;
  3734. for (auto* candidate : instance->getParameters())
  3735. if (candidate->isAutomatable() && ! candidate->isMetaParameter() && candidate != instance->getBypassParameter())
  3736. {
  3737. param = candidate;
  3738. break;
  3739. }
  3740. if (param != nullptr)
  3741. {
  3742. step ("param=" + param->getName (64));
  3743. checked = param;
  3744. const auto file = lynx::pluginpresetui::folderFor (instance->getName()).getChildFile ("plugwintest.lynxpreset");
  3745. juce::String error;
  3746. const auto before = param->getValue();
  3747. const auto saved = lynx::pluginpresetui::save (*instance, file, "plugwintest", error);
  3748. param->setValueNotifyingHost (before > 0.5f ? 0.1f : 0.9f);
  3749. const auto changed = param->getValue();
  3750. const auto loaded = saved && lynx::pluginpresetui::load (*instance, file, error);
  3751. step ("preset_roundtrip saved=" + juce::String ((int) saved) + " loaded=" + juce::String ((int) loaded) + " param0 before="
  3752. + juce::String (before, 4) + " changed=" + juce::String (changed, 4) + " after=" + juce::String (param->getValue(), 4)
  3753. + (error.isNotEmpty() ? " error=" + error : juce::String()));
  3754. for (const auto* ext : { "fxp", "fxb", "vstpreset" })
  3755. {
  3756. juce::String e2;
  3757. const auto f2 = file.withFileExtension (ext);
  3758. const auto ok2 = lynx::pluginpresetui::save (*instance, f2, "plugwintest", e2) && lynx::pluginpresetui::load (*instance, f2, e2);
  3759. step (juce::String ("preset_") + ext + "=" + juce::String ((int) ok2) + (e2.isNotEmpty() ? " (" + e2 + ")" : juce::String()));
  3760. f2.deleteFile();
  3761. }
  3762. step ("browser_lists=" + juce::String (lynx::pluginpresetui::userPresets (instance->getName()).size()));
  3763. }
  3764. std::shared_ptr<void> owner = instrument ? std::shared_ptr<void> (engine->getChannelInstrument (channelIndex))
  3765. : std::shared_ptr<void> (engine->getEffect (1, 0));
  3766. lynx::PluginWindows::open (owner, *instance, instance->getName(),
  3767. { engine.get(), [this] (lynx::Song& song) -> lynx::PluginRef* {
  3768. if (instrument)
  3769. return channelIndex < 0 || channelIndex >= (int) song.channels.size()
  3770. ? nullptr : &song.channels[(size_t) channelIndex].plugin;
  3771. return song.mixer.size() < 2 || song.mixer[1].effects.empty() ? nullptr : &song.mixer[1].effects[0].plugin;
  3772. }, instrument });
  3773. owner.reset();
  3774. step ("window_open=" + juce::String ((int) lynx::PluginWindows::isOpen (*instance)));
  3775. phase = 1;
  3776. ticks = 0;
  3777. phaseStartMs = juce::Time::getMillisecondCounter();
  3778. return;
  3779. }
  3780. if (phase == 1 && ticks >= 30 && ! keysDone && juce::SystemStats::getEnvironmentVariable ("LYNX_PLUGWIN_KEYS", {}).isNotEmpty() && instance->getActiveEditor() != nullptr)
  3781. keysDone = ! lynx::pluginKeysTestTick (*instance->getActiveEditor(),
  3782. [this] (bool on) {
  3783. engine->editSong ([this, on] (lynx::Song& song) {
  3784. (instrument ? song.channels[(size_t) channelIndex].plugin : song.mixer[1].effects[0].plugin).hostKeysFirst = on;
  3785. });
  3786. },
  3787. [this] (const juce::String& line) { step (line); });
  3788. const auto elapsedMs = (int) (juce::Time::getMillisecondCounter() - phaseStartMs);
  3789. if (phase == 1 && ticks == 20 && checked != nullptr)
  3790. step ("param_after_1s=" + juce::String (checked->getValue(), 4));
  3791. // (3 s apart: time for screenshots of each state)
  3792. if (phase == 1 && workspace != nullptr && dockStep < dockSteps && elapsedMs >= (dockStep + 1) * stepMs)
  3793. dockCheck (dockStep++);
  3794. if (phase == 1 && elapsedMs >= seconds * 1000 && (workspace == nullptr || dockStep >= dockSteps)) // remove the plugin from the song
  3795. {
  3796. engine->editSong ([this] (lynx::Song& song) {
  3797. if (instrument)
  3798. {
  3799. if (channelIndex >= 0 && channelIndex < (int) song.channels.size())
  3800. song.channels.erase (song.channels.begin() + channelIndex);
  3801. }
  3802. else
  3803. song.mixer[1].effects.clear();
  3804. });
  3805. step ("removed");
  3806. phase = 2;
  3807. ticks = 0;
  3808. return;
  3809. }
  3810. if (phase == 2 && ticks >= 40)
  3811. {
  3812. const auto open = lynx::PluginWindows::isOpen (*instance);
  3813. step ("window_open_after_remove=" + juce::String ((int) open));
  3814. step (open || ! dockOk ? "result=FAILED" : "result=OK");
  3815. stopTimer();
  3816. lynx::PluginWindows::closeAll();
  3817. done (! open && dockOk);
  3818. }
  3819. }
  3820. };
  3821. auto* test = new Test();
  3822. test->reportPath = reportPath;
  3823. test->seconds = seconds;
  3824. test->done = [this, test] (bool ok) {
  3825. setApplicationReturnValue (ok ? 0 : 1);
  3826. juce::MessageManager::callAsync ([this, test] {
  3827. lynx::setMainWindowForOwnership (nullptr);
  3828. lynx::PluginWindows::setDockWorkspace (nullptr);
  3829. test->workspace = nullptr;
  3830. test->mainWindow = nullptr; // (dock mode: the main component with it, before the engine)
  3831. test->engine = nullptr;
  3832. delete test;
  3833. quit();
  3834. });
  3835. };
  3836. test->engine = std::make_unique<lynx::AudioEngine> (false);
  3837. test->mainWindow = std::make_unique<juce::DocumentWindow> ("LYNX test main window", juce::Colours::darkgrey, 0);
  3838. test->mainWindow->setBounds (20, 20, 300, 200);
  3839. if (juce::SystemStats::getEnvironmentVariable ("LYNX_PLUGWIN_DOCK", {}) == "1" && lynx::nativechild::dockingEnabled())
  3840. {
  3841. // the real main window's contents (it docks plugin windows in its own desktop), so the panels are real
  3842. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  3843. auto* ui = new lynx::MainComponent (*test->engine, false);
  3844. test->mainWindow->setUsingNativeTitleBar (true);
  3845. test->mainWindow->setContentOwned (ui, false);
  3846. test->mainWindow->setBounds (20, 20, 1500, 900);
  3847. test->workspace = &ui->workspaceForTest();
  3848. if (const auto ms = juce::SystemStats::getEnvironmentVariable ("LYNX_PLUGWIN_STEP_MS", {}).getIntValue(); ms > 0)
  3849. test->stepMs = ms;
  3850. }
  3851. test->mainWindow->setVisible (true);
  3852. lynx::setMainWindowForOwnership (test->mainWindow.get());
  3853. if (test->workspace != nullptr)
  3854. {
  3855. using lynx::workspace::Panel;
  3856. for (auto p : { Panel::playlist, Panel::mixer, Panel::pianoRoll, Panel::channelRack })
  3857. test->workspace->show (p);
  3858. test->step ("dock_test=2 rack_visible=" + juce::String ((int) test->workspace->isPanelVisible (Panel::channelRack)));
  3859. }
  3860. auto& host = test->engine->getPluginHost();
  3861. test->step ("plugins_in_file=" + juce::String (host.addPluginFile (juce::File (pluginPath))));
  3862. std::optional<juce::PluginDescription> chosen;
  3863. for (const auto& type : host.getKnownPlugins().getTypes())
  3864. if ((juce::File (type.fileOrIdentifier).getFileName() == juce::File (pluginPath).getFileName() || type.fileOrIdentifier == pluginPath)
  3865. && (only.isEmpty() || type.name == only))
  3866. {
  3867. chosen = type;
  3868. break;
  3869. }
  3870. if (! chosen)
  3871. {
  3872. test->step ("result=FAILED (no plugin)");
  3873. test->done (false);
  3874. return;
  3875. }
  3876. test->instrument = chosen->isInstrument;
  3877. lynx::PluginRef ref;
  3878. ref.separateProcess = juce::SystemStats::getEnvironmentVariable ("LYNX_PLUGWIN_SEPARATE", {}) == "1"; // (issue #96's other-process check)
  3879. ref.id = chosen->createIdentifierString().toStdString();
  3880. ref.name = chosen->name.toStdString();
  3881. test->engine->editSong ([&] (lynx::Song& song) {
  3882. if (test->instrument)
  3883. {
  3884. lynx::ChannelDef c;
  3885. c.name = ref.name;
  3886. c.instrument = lynx::InstrumentKind::plugin;
  3887. c.plugin = ref;
  3888. test->channelIndex = (int) song.channels.size();
  3889. song.channels.push_back (c);
  3890. }
  3891. else
  3892. {
  3893. while (song.mixer.size() < 2)
  3894. song.mixer.emplace_back();
  3895. lynx::EffectSlot slot;
  3896. slot.kind = lynx::EffectKind::plugin;
  3897. slot.plugin = ref;
  3898. song.mixer[1].effects.push_back (slot);
  3899. }
  3900. });
  3901. test->step ("plugin=" + chosen->name + " instrument=" + juce::String ((int) test->instrument));
  3902. test->startTimerHz (20);
  3903. }
  3904. void runEditorCrashTest (const juce::String& pluginPath, const juce::String& reportPath)
  3905. {
  3906. struct CrashTest final : juce::Timer
  3907. {
  3908. juce::String reportPath, report;
  3909. std::unique_ptr<lynx::PluginHost> host;
  3910. juce::AudioPluginInstance* plugin = nullptr;
  3911. std::shared_ptr<juce::AudioPluginInstance> keep; // a window whose plugin nobody else holds is closed as orphaned
  3912. std::function<void (bool)> done;
  3913. int ticks = 0, crashesBefore = 0;
  3914. void step (const juce::String& line)
  3915. {
  3916. report << line << "\n";
  3917. juce::File (reportPath).replaceWithText (report); // at each step: a crash leaves the last one
  3918. }
  3919. void timerCallback() override
  3920. {
  3921. ++ticks;
  3922. const auto crashes = lynx::PluginWindows::editorCrashCount() - crashesBefore;
  3923. const auto open = lynx::PluginWindows::isOpen (*plugin);
  3924. if ((crashes > 0 && ! open) || ticks >= 50) // 100 ms ticks: up to 5 s
  3925. {
  3926. stopTimer();
  3927. step ("editor_crashes=" + juce::String (crashes) + " window_open=" + juce::String ((int) open) + " ticks=" + juce::String (ticks));
  3928. bool traced = false;
  3929. if (crashes > 0)
  3930. {
  3931. const auto last = lynx::PluginWindows::editorCrashes().back();
  3932. traced = last.traceFile.existsAsFile() && last.traceFile.loadFileAsString().contains ("LYNX Test Crash");
  3933. step ("plugin=" + last.plugin + " detail=" + last.detail + " trace=" + last.traceFile.getFileName() + " traced="
  3934. + juce::String ((int) traced));
  3935. last.traceFile.deleteFile();
  3936. }
  3937. // still alive: one more message through the loop after the fault
  3938. juce::MessageManager::callAsync ([this, ok = crashes == 1 && ! open && traced] {
  3939. step ("message_loop_after_fault=1");
  3940. step (juce::String ("result=") + (ok ? "OK" : "FAILED"));
  3941. done (ok);
  3942. });
  3943. }
  3944. }
  3945. };
  3946. auto* test = new CrashTest();
  3947. test->reportPath = reportPath;
  3948. test->done = [this, test] (bool ok)
  3949. {
  3950. setApplicationReturnValue (ok ? 0 : 1);
  3951. juce::MessageManager::callAsync ([this, test] { lynx::PluginWindows::closeAll(); delete test; quit(); });
  3952. };
  3953. #if ! JUCE_WINDOWS
  3954. test->step ("result=SKIPPED (Windows only: on macOS / Linux a plugin fault is a signal, see docs/analise/REA_rodada174a.md)");
  3955. test->done (true);
  3956. return;
  3957. #else
  3958. _putenv_s ("LYNX_TEST_CRASH", "editor");
  3959. test->host = std::make_unique<lynx::PluginHost> (false);
  3960. test->step ("plugins_in_file=" + juce::String (test->host->addPluginFile (juce::File (pluginPath))));
  3961. std::shared_ptr<juce::AudioPluginInstance> instance;
  3962. for (const auto& type : test->host->getKnownPlugins().getTypes())
  3963. {
  3964. if (juce::File (type.fileOrIdentifier).getFileName() != juce::File (pluginPath).getFileName())
  3965. continue;
  3966. juce::String error;
  3967. instance = std::shared_ptr<juce::AudioPluginInstance> (lynx::createRightInstance (test->host->getFormats(), type, 48000.0, 512, error).release());
  3968. test->step ("plugin=" + type.name + (instance == nullptr ? " error=" + error : juce::String()));
  3969. break;
  3970. }
  3971. if (instance == nullptr || ! instance->hasEditor())
  3972. {
  3973. test->step ("result=FAILED (no plugin with an editor)");
  3974. test->done (false);
  3975. return;
  3976. }
  3977. lynx::preparePlugin (*instance, 48000.0, 512);
  3978. test->plugin = instance.get();
  3979. test->keep = instance;
  3980. test->crashesBefore = lynx::PluginWindows::editorCrashCount();
  3981. lynx::PluginWindows::open (instance, *instance, instance->getName()); // (the window keeps the plugin alive)
  3982. test->step ("window_open=" + juce::String ((int) lynx::PluginWindows::isOpen (*instance)));
  3983. test->startTimer (100);
  3984. #endif
  3985. }
  3986. void runEditorTest (const juce::String& pluginPath, const juce::String& reportPath, const juce::String& only)
  3987. {
  3988. struct EditorTest final : juce::Timer
  3989. {
  3990. juce::String reportPath, report;
  3991. std::unique_ptr<lynx::PluginHost> host;
  3992. std::unique_ptr<juce::AudioPluginInstance> plugin;
  3993. std::unique_ptr<juce::DocumentWindow> window;
  3994. std::function<void (bool)> done;
  3995. void step (const juce::String& line)
  3996. {
  3997. report << line << "\n";
  3998. juce::File (reportPath).replaceWithText (report); // written at each step: a crash leaves the last one
  3999. }
  4000. void timerCallback() override
  4001. {
  4002. stopTimer();
  4003. window = nullptr;
  4004. step ("step=closed");
  4005. plugin = nullptr;
  4006. step ("result=OK");
  4007. done (true);
  4008. }
  4009. };
  4010. auto* test = new EditorTest();
  4011. test->reportPath = reportPath;
  4012. test->done = [this, test] (bool ok)
  4013. {
  4014. setApplicationReturnValue (ok ? 0 : 1);
  4015. juce::MessageManager::callAsync ([this, test] { delete test; quit(); });
  4016. };
  4017. test->host = std::make_unique<lynx::PluginHost> (false);
  4018. test->step ("plugins_in_file=" + juce::String (test->host->addPluginFile (juce::File (pluginPath))));
  4019. test->step ("exe=" + juce::File::getSpecialLocation (juce::File::currentExecutableFile).getFullPathName());
  4020. for (const auto& type : test->host->getKnownPlugins().getTypes())
  4021. {
  4022. if (juce::File (type.fileOrIdentifier).getFileName() != juce::File (pluginPath).getFileName()
  4023. || (only.isNotEmpty() && type.name != only))
  4024. continue;
  4025. juce::String error;
  4026. test->plugin = lynx::createRightInstance (test->host->getFormats(), type, 48000.0, 512, error);
  4027. test->step ("plugin=" + type.name + (test->plugin == nullptr ? " error=" + error : juce::String()));
  4028. break;
  4029. }
  4030. if (test->plugin == nullptr)
  4031. {
  4032. test->step ("result=FAILED");
  4033. test->done (false);
  4034. return;
  4035. }
  4036. lynx::preparePlugin (*test->plugin, 48000.0, 512);
  4037. test->step ("step=create_editor");
  4038. test->window = std::make_unique<juce::DocumentWindow> (test->plugin->getName(), juce::Colours::black, juce::DocumentWindow::closeButton);
  4039. test->window->setUsingNativeTitleBar (true);
  4040. if (auto* editor = test->plugin->createEditorIfNeeded())
  4041. test->window->setContentOwned (editor, true);
  4042. else
  4043. test->step ("no_editor");
  4044. test->step ("step=show");
  4045. test->window->centreWithSize (test->window->getWidth(), test->window->getHeight());
  4046. test->window->setVisible (true);
  4047. test->step ("step=shown");
  4048. test->startTimer (4000);
  4049. }
  4050. void runFitTest (const juce::String& reportPath, int percent)
  4051. {
  4052. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  4053. struct FitTest final : juce::Timer
  4054. {
  4055. juce::String path, report;
  4056. bool ok = true;
  4057. int step = 0, percent = 150;
  4058. std::unique_ptr<juce::DocumentWindow> tall, big;
  4059. std::function<void()> done;
  4060. // `whole`: the window must fit entirely (a resizable one); else its title bar and close button must be on the screen
  4061. void check (const juce::String& what, juce::Component& w, bool whole)
  4062. {
  4063. juce::BorderSize<int> frame;
  4064. if (auto* peer = w.getPeer())
  4065. if (const auto f = peer->getFrameSizeIfPresent())
  4066. frame = *f;
  4067. auto outer = frame.addedTo (w.getBounds());
  4068. const auto* display = juce::Desktop::getInstance().getDisplays().getDisplayForRect (outer);
  4069. const auto area = display != nullptr ? display->userArea : outer;
  4070. #if JUCE_LINUX
  4071. // round 164: a compositor that draws the frame itself (WSLg's Weston) reports its invisible shadow in
  4072. // the frame (59 px on top, 38 around at 100%): only what is visible is checked, give or take 4 px
  4073. const auto shadow = frame.getLeft() >= 16 ? frame.getLeft() : 0;
  4074. outer = outer.reduced (shadow);
  4075. const auto slack = shadow > 0 ? 4 : 0;
  4076. #else
  4077. const auto slack = 0;
  4078. #endif
  4079. const auto passed = outer.getY() >= area.getY() - slack && outer.getRight() <= area.getRight() + slack && outer.getX() >= area.getX() - slack
  4080. && (! whole || outer.getBottom() <= area.getBottom() + 1 + slack);
  4081. report << (passed ? "ok " : "FAIL ") << what << " window=" << outer.toString() << " (frame " << frame.getTop() << ","
  4082. << frame.getLeft() << ") screen=" << area.toString() << "\n";
  4083. ok = ok && passed;
  4084. }
  4085. void start()
  4086. {
  4087. report << "scale=" << percent << "%\n";
  4088. juce::Desktop::getInstance().setGlobalScaleFactor ((float) percent / 100.0f);
  4089. // a tool window taller than the screen, centred (its title bar would be above the screen)
  4090. tall = std::make_unique<juce::DocumentWindow> ("LYNX fit test - tall", lynx::theme::colour::bg2, juce::DocumentWindow::closeButton);
  4091. tall->setUsingNativeTitleBar (true);
  4092. auto* content = new juce::Component();
  4093. const auto area = juce::Desktop::getInstance().getDisplays().getPrimaryDisplay()->userArea;
  4094. content->setSize (500, area.getHeight() + 200);
  4095. tall->setContentOwned (content, true);
  4096. tall->setCentrePosition (area.getCentre());
  4097. tall->setVisible (true);
  4098. lynx::keepAboveMainWindow (*tall);
  4099. // LYNX_FITTEST_MS: how long each window stays (default 700 ms; longer to take screenshots of them)
  4100. startTimer (juce::jlimit (300, 60000, juce::SystemStats::getEnvironmentVariable ("LYNX_FITTEST_MS", "700").getIntValue()));
  4101. }
  4102. void timerCallback() override
  4103. {
  4104. ++step;
  4105. if (step == 1)
  4106. {
  4107. check ("tall tool window: title bar and close button on the screen", *tall, false);
  4108. tall.reset();
  4109. // round 164: a fixed-size LYNX tool window whose content is taller than the screen: it scrolls
  4110. auto content = std::make_unique<juce::Component>();
  4111. const auto screen = juce::Desktop::getInstance().getDisplays().getPrimaryDisplay()->userArea;
  4112. content->setSize (520, screen.getHeight() + 300);
  4113. lynx::openToolWindow (std::move (content), "LYNX fit test - fixed size", "fittest-fixed");
  4114. return;
  4115. }
  4116. if (step == 2)
  4117. {
  4118. if (auto* w = lynx::findToolWindow ("fittest-fixed"))
  4119. {
  4120. check ("fixed-size tool window taller than the screen: fits (its content scrolls)", *w, true);
  4121. const auto scrolls = w->getContentComponent() != nullptr && w->getContentComponent()->getNumChildComponents() > 0
  4122. && dynamic_cast<juce::Viewport*> (w->getContentComponent()->getChildComponent (0)) != nullptr;
  4123. report << (scrolls ? "ok " : "FAIL ") << "its content is in a scrolling viewport\n";
  4124. ok = ok && scrolls;
  4125. }
  4126. else
  4127. {
  4128. report << "FAIL fixed-size tool window not found\n";
  4129. ok = false;
  4130. }
  4131. lynx::closeAllToolWindows();
  4132. // a resizable window that fits at 100%, then the zoom goes up (the main window's case)
  4133. juce::Desktop::getInstance().setGlobalScaleFactor (1.0f);
  4134. big = std::make_unique<juce::DocumentWindow> ("LYNX fit test - zoom", lynx::theme::colour::bg2, juce::DocumentWindow::allButtons);
  4135. big->setUsingNativeTitleBar (true);
  4136. big->setResizable (true, false);
  4137. big->setResizeLimits (400, 300, 10000, 10000);
  4138. const auto area = juce::Desktop::getInstance().getDisplays().getPrimaryDisplay()->userArea;
  4139. big->setBounds (area.getX() + 40, area.getY() + 60, area.getWidth() * 9 / 10 - 40, area.getHeight() * 9 / 10 - 60);
  4140. big->setVisible (true);
  4141. return;
  4142. }
  4143. if (step == 3)
  4144. {
  4145. juce::Desktop::getInstance().setGlobalScaleFactor ((float) percent / 100.0f);
  4146. juce::Timer::callAfterDelay (200, [] { lynx::fitAllWindowsOnScreen(); });
  4147. return;
  4148. }
  4149. if (step == 4)
  4150. {
  4151. check ("resizable window after the zoom change: fits the screen", *big, true);
  4152. big.reset();
  4153. report << "result=" << (ok ? "OK" : "FAILED") << "\n";
  4154. juce::File (path).replaceWithText (report);
  4155. stopTimer();
  4156. if (done)
  4157. done();
  4158. }
  4159. }
  4160. };
  4161. static std::unique_ptr<FitTest> test;
  4162. test = std::make_unique<FitTest>();
  4163. test->path = reportPath;
  4164. test->percent = juce::jlimit (50, 300, percent);
  4165. test->done = [this] { juce::MessageManager::callAsync ([this] { test.reset(); quit(); }); };
  4166. test->start();
  4167. }
  4168. void runWindowTest (const juce::String& reportPath)
  4169. {
  4170. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  4171. struct WindowTest final : juce::Timer
  4172. {
  4173. juce::String reportPath, report;
  4174. bool ok = true;
  4175. int stepIndex = 0;
  4176. std::unique_ptr<lynx::AudioEngine> engine;
  4177. lynx::MainComponent* ui = nullptr;
  4178. std::unique_ptr<juce::DocumentWindow> main, pluginLike;
  4179. juce::TextEditor* pluginField = nullptr;
  4180. std::unique_ptr<juce::AlertWindow> nameDialog;
  4181. std::function<void()> done;
  4182. void line (const juce::String& text)
  4183. {
  4184. report << text << "\n";
  4185. juce::File (reportPath).replaceWithText (report);
  4186. }
  4187. void check (const juce::String& what, bool passed)
  4188. {
  4189. line ((passed ? "ok " : "FAIL ") + what);
  4190. ok = ok && passed;
  4191. }
  4192. bool isAbove (juce::Component* w) { return w != nullptr && lynx::isAboveMainWindow (*w); }
  4193. bool focusIn (juce::Component* w)
  4194. {
  4195. auto* f = juce::Component::getCurrentlyFocusedComponent();
  4196. return w != nullptr && f != nullptr && (f == w || w->isParentOf (f));
  4197. }
  4198. void timerCallback() override
  4199. {
  4200. switch (stepIndex++)
  4201. {
  4202. case 0:
  4203. line ("foreground=" + juce::String (juce::Process::isForegroundProcess() ? 1 : 0));
  4204. ui->openQuickAddForTest();
  4205. break;
  4206. case 1:
  4207. {
  4208. auto* w = lynx::findToolWindow ("quickadd");
  4209. check ("quick-add palette open", w != nullptr);
  4210. check ("quick-add palette active", w != nullptr && w->isActiveWindow());
  4211. check ("quick-add palette owned by the main window", w != nullptr && lynx::isOwnedByMainWindow (*w));
  4212. check ("quick-add palette above the main window", isAbove (w));
  4213. auto* f = juce::Component::getCurrentlyFocusedComponent();
  4214. check ("quick-add search box has the keyboard focus", focusIn (w) && dynamic_cast<juce::TextEditor*> (f) != nullptr && f->hasKeyboardFocus (false) && w->isActiveWindow());
  4215. lynx::closeAllToolWindows();
  4216. lynx::openAudioEditor (*engine);
  4217. break;
  4218. }
  4219. case 2:
  4220. {
  4221. auto* w = lynx::findToolWindow ("audioeditor");
  4222. check ("audio editor open", w != nullptr);
  4223. check ("audio editor active", w != nullptr && w->isActiveWindow());
  4224. check ("audio editor owned by the main window", w != nullptr && lynx::isOwnedByMainWindow (*w));
  4225. check ("audio editor above the main window", isAbove (w));
  4226. lynx::forceForegroundForTest (*main); // the user clicks the main window
  4227. break;
  4228. }
  4229. case 3:
  4230. {
  4231. auto* w = lynx::findToolWindow ("audioeditor");
  4232. check ("audio editor stays above the main window after clicking it", isAbove (w));
  4233. lynx::closeAllToolWindows();
  4234. // a plugin editor's window: its own controls keep the keyboard focus
  4235. pluginLike = std::make_unique<juce::DocumentWindow> ("Plugin", juce::Colours::black, juce::DocumentWindow::closeButton);
  4236. pluginLike->setUsingNativeTitleBar (true);
  4237. auto* field = new juce::TextEditor();
  4238. field->setSize (300, 120);
  4239. pluginLike->setContentOwned (field, true);
  4240. pluginLike->centreWithSize (300, 120);
  4241. pluginLike->setVisible (true);
  4242. lynx::keepAboveMainWindow (*pluginLike);
  4243. pluginLike->toFront (true);
  4244. field->grabKeyboardFocus();
  4245. pluginField = field;
  4246. break;
  4247. }
  4248. case 4:
  4249. check ("plugin window active", pluginLike->isActiveWindow());
  4250. check ("plugin window keeps the keyboard focus", pluginField->hasKeyboardFocus (false) && pluginLike->isActiveWindow());
  4251. check ("plugin window above the main window", isAbove (pluginLike.get()));
  4252. pluginLike = nullptr;
  4253. lynx::forceForegroundForTest (*main);
  4254. juce::Component::unfocusAllComponents();
  4255. break;
  4256. case 5:
  4257. check ("main window takes the keyboard focus back when it is active", ui->hasKeyboardFocus (true));
  4258. // round 165q: a name dialog (F4's next empty pattern, Rename and color...) opens ready to type
  4259. nameDialog = lynx::makeNameAndColourDialog ("Rename pattern", "Pattern 2", 0xff808080u);
  4260. nameDialog->enterModalState (true, nullptr, false);
  4261. lynx::keepAboveMainWindow (*nameDialog);
  4262. break;
  4263. case 6:
  4264. {
  4265. auto* f = juce::Component::getCurrentlyFocusedComponent();
  4266. auto* field = dynamic_cast<juce::TextEditor*> (f);
  4267. check ("name dialog: its text field has the keyboard focus", field != nullptr && focusIn (nameDialog.get()));
  4268. if (field != nullptr)
  4269. field->keyPressed (juce::KeyPress ('x', {}, 'x'));
  4270. check ("name dialog: typing replaces the name", nameDialog->getTextEditorContents ("name") == "x");
  4271. nameDialog->exitModalState (0);
  4272. nameDialog = nullptr;
  4273. line (ok ? "result=OK" : "result=FAILED");
  4274. stopTimer();
  4275. done();
  4276. break;
  4277. }
  4278. default:
  4279. break;
  4280. }
  4281. }
  4282. };
  4283. auto* test = new WindowTest();
  4284. test->reportPath = reportPath;
  4285. test->engine = std::make_unique<lynx::AudioEngine> (false);
  4286. test->main = std::make_unique<juce::DocumentWindow> ("LYNX window test", lynx::theme::window, juce::DocumentWindow::allButtons);
  4287. test->main->setUsingNativeTitleBar (true);
  4288. test->ui = new lynx::MainComponent (*test->engine, false);
  4289. test->main->setContentOwned (test->ui, true);
  4290. test->main->setResizable (true, true);
  4291. test->main->centreWithSize (1280, 760);
  4292. test->main->setVisible (true);
  4293. lynx::setMainWindowForOwnership (test->main.get());
  4294. lynx::forceForegroundForTest (*test->main);
  4295. test->main->toFront (true);
  4296. test->done = [this, test] {
  4297. setApplicationReturnValue (test->ok ? 0 : 1);
  4298. juce::MessageManager::callAsync ([this, test] {
  4299. lynx::closeAllToolWindows();
  4300. lynx::setMainWindowForOwnership (nullptr);
  4301. test->main = nullptr;
  4302. delete test;
  4303. quit();
  4304. });
  4305. };
  4306. test->startTimer (1500);
  4307. }
  4308. // LYNX.exe --plugintest plugin.vst3 report.txt ["name"]: loads the plugin (or the one named in a shell), plays notes if it is an
  4309. // instrument (and runs audio through it if it is an effect) and measures the audio.
  4310. void runPluginTest (const juce::String& pluginPath, const juce::String& reportPath, const juce::String& only = {})
  4311. {
  4312. juce::String report;
  4313. bool ok = false;
  4314. {
  4315. lynx::AudioEngine offline (false);
  4316. auto& host = offline.getPluginHost();
  4317. const auto added = host.addPluginFile (juce::File (pluginPath));
  4318. report << "plugins_in_file=" << added << "\n";
  4319. juce::PluginDescription instrument, effect;
  4320. bool hasInstrument = false, hasEffect = false;
  4321. for (const auto& type : host.getKnownPlugins().getTypes())
  4322. {
  4323. if (juce::File (type.fileOrIdentifier).getFileName() != juce::File (pluginPath).getFileName()
  4324. || (only.isNotEmpty() && type.name != only))
  4325. continue;
  4326. report << " " << (type.isInstrument ? "instrument: " : "effect: ") << type.name << " (" << type.manufacturerName
  4327. << ") in " << type.fileOrIdentifier << "\n";
  4328. if (type.isInstrument && ! hasInstrument) { instrument = type; hasInstrument = true; }
  4329. if (! type.isInstrument && ! hasEffect) { effect = type; hasEffect = true; }
  4330. }
  4331. auto song = lynx::Song::makeDefault();
  4332. if (hasInstrument)
  4333. {
  4334. auto& c = song.channels[4]; // the "Synth" channel becomes the plugin
  4335. c.instrument = lynx::InstrumentKind::plugin;
  4336. c.plugin.id = instrument.createIdentifierString().toStdString();
  4337. c.plugin.name = instrument.name.toStdString();
  4338. c.volume = 1.0f;
  4339. for (int i = 0; i < 4; ++i) // one chord per beat
  4340. for (int key : { 60, 64, 67 })
  4341. song.patterns[0].notes.push_back ({ (std::int64_t) i * lynx::ppq, lynx::ppq / 2, 4, key, 0.9f });
  4342. song.patterns[0].sortNotes();
  4343. }
  4344. if (hasEffect)
  4345. {
  4346. lynx::EffectSlot slot;
  4347. slot.kind = lynx::EffectKind::plugin;
  4348. slot.plugin.id = effect.createIdentifierString().toStdString();
  4349. slot.plugin.name = effect.name.toStdString();
  4350. song.mixer[0].effects.push_back (slot);
  4351. }
  4352. const auto effectSlot = (int) song.mixer[0].effects.size() - 1; // (the default master may hold effects already)
  4353. offline.setSong (song);
  4354. // after a render: the rack (and its plugins) is built when the engine is prepared
  4355. const auto peak = offline.renderOffline (3.0, 48000.0);
  4356. const auto* loadedInstrument = dynamic_cast<lynx::PluginInstrument*> (offline.getChannelInstrument (4).get());
  4357. const auto* loadedEffect = dynamic_cast<lynx::PluginEffect*> (offline.getEffect (0, effectSlot).get());
  4358. report << "instrument_loaded=" << (loadedInstrument != nullptr ? "yes" : "no") << "\n"
  4359. << "effect_loaded=" << (loadedEffect != nullptr ? "yes" : "no") << "\n";
  4360. if (host.getLoadFailures().size() > 0) // why: the host's own message (license, missing file, load failure)
  4361. report << "load_failures=" << host.getLoadFailures().joinIntoString (" | ") << "\n";
  4362. report << "peak=" << peak << "\n";
  4363. // plugins that crashed inside a call, were caught and switched off (round 111)
  4364. report << "plugin_crashes=" << lynx::pluginCrashCount() << "\n";
  4365. for (const auto& c : lynx::pluginCrashes())
  4366. report << " crashed: " << c.plugin << " (" << lynx::crashguard::describe (c.code) << ")\n";
  4367. offline.capturePluginStates();
  4368. const auto stateSize = hasInstrument ? offline.getSong().channels[4].plugin.state.size() : (size_t) 0;
  4369. report << "state_bytes_base64=" << (int) stateSize << "\n";
  4370. ok = (hasInstrument || hasEffect) && (! hasInstrument || loadedInstrument != nullptr)
  4371. && (! hasEffect || loadedEffect != nullptr) && peak > 0.001f && peak < 10.0f;
  4372. }
  4373. report << "result=" << (ok ? "OK" : "FAILED") << "\n";
  4374. juce::File (reportPath).replaceWithText (report);
  4375. setApplicationReturnValue (ok ? 0 : 1);
  4376. quit();
  4377. }
  4378. // LYNX.exe --claprestarttest "LYNX Test Restart.clap" report.txt (tools/testplugin/lynx_test_restart.c, PR #29): a
  4379. // CLAP effect on the Master that asks for a restart every 8 blocks while an export renders on a thread of its own
  4380. // (the message thread is free to run the restarts, as with the Export window). The plugin aborts the process when
  4381. // start / stop_processing run off the audio thread or activate / deactivate off the main thread (issue #46, as u-he
  4382. // Presswerk does; an export at 44.1 kHz and prepare calls from the export's thread check the latter) and counts deactivations that
  4383. // landed inside its process() call (must be none), the restarts must happen, and the delay compensation must end on
  4384. // the latency the plugin reports after its last restart.
  4385. void runClapRestartTest (const juce::String& pluginPath, const juce::String& reportPath)
  4386. {
  4387. struct Run
  4388. {
  4389. std::unique_ptr<lynx::AudioEngine> engine;
  4390. juce::String report;
  4391. int slot = -1;
  4392. std::thread render;
  4393. std::atomic<bool> done { false };
  4394. double renderSeconds = 0.0;
  4395. };
  4396. auto run = std::make_shared<Run>();
  4397. const auto counters = juce::File (reportPath).getSiblingFile (juce::File (reportPath).getFileNameWithoutExtension() + "-plugin.txt");
  4398. counters.deleteFile();
  4399. #if JUCE_WINDOWS
  4400. _putenv_s ("LYNX_TEST_RESTART_REPORT", counters.getFullPathName().toRawUTF8());
  4401. #else
  4402. setenv ("LYNX_TEST_RESTART_REPORT", counters.getFullPathName().toRawUTF8(), 1);
  4403. #endif
  4404. const auto fail = [this, reportPath] (juce::String report) {
  4405. report << "result=FAILED\n";
  4406. juce::File (reportPath).replaceWithText (report);
  4407. setApplicationReturnValue (1);
  4408. quit();
  4409. };
  4410. run->engine = std::make_unique<lynx::AudioEngine> (false);
  4411. auto& host = run->engine->getPluginHost();
  4412. run->report << "plugins_in_file=" << host.addPluginFile (juce::File (pluginPath)) << "\n";
  4413. std::optional<juce::PluginDescription> clap;
  4414. for (const auto& type : host.getKnownPlugins().getTypes())
  4415. if (type.pluginFormatName == "CLAP" && juce::File (type.fileOrIdentifier).getFileName() == juce::File (pluginPath).getFileName())
  4416. clap = type;
  4417. if (! clap)
  4418. {
  4419. fail (run->report + "no CLAP plugin in the file\n");
  4420. return;
  4421. }
  4422. auto song = lynx::Song::makeDefault();
  4423. lynx::EffectSlot slot;
  4424. slot.kind = lynx::EffectKind::plugin;
  4425. slot.plugin.id = clap->createIdentifierString().toStdString();
  4426. slot.plugin.name = clap->name.toStdString();
  4427. slot.smartDisable = false; // (processed every block, as with music playing: the export itself is silent)
  4428. song.mixer[0].effects = { slot }; // alone on the Master: the delay compensation is the plugin's latency
  4429. run->slot = (int) song.mixer[0].effects.size() - 1;
  4430. run->engine->setSong (song);
  4431. run->engine->renderOffline (0.1, 48000.0); // builds the rack (and the plugin) on the message thread
  4432. if (dynamic_cast<lynx::PluginEffect*> (run->engine->getEffect (0, run->slot).get()) == nullptr)
  4433. {
  4434. fail (run->report + "effect_loaded=no\n");
  4435. return;
  4436. }
  4437. auto effect = std::dynamic_pointer_cast<lynx::PluginEffect> (run->engine->getEffect (0, run->slot));
  4438. run->render = std::thread ([run, effect] {
  4439. const auto start = juce::Time::getMillisecondCounterHiRes();
  4440. run->engine->renderOffline (30.0, 48000.0);
  4441. run->renderSeconds = (juce::Time::getMillisecondCounterHiRes() - start) * 0.001;
  4442. // issue #46: an export at another rate / block size prepares the plugin from the export's thread; the
  4443. // plugin aborts unless activate / deactivate reach the main thread
  4444. auto& instance = effect->getInstance();
  4445. instance.prepareToPlay (44100.0, 1024);
  4446. instance.releaseResources();
  4447. instance.prepareToPlay (48000.0, 512);
  4448. run->engine->renderOffline (3.0, 44100.0); // (the engine rebuilds its rack at that rate)
  4449. run->done = true;
  4450. });
  4451. // after the render: a second for the restarts still queued and the engine's timer (the new PDC plan)
  4452. auto finish = std::make_shared<std::function<void()>>();
  4453. *finish = [this, run, counters, reportPath, fail, finish] {
  4454. if (! run->done)
  4455. {
  4456. juce::Timer::callAfterDelay (50, *finish);
  4457. return;
  4458. }
  4459. run->render.join();
  4460. juce::Timer::callAfterDelay (1000, [this, run, counters, reportPath, fail] {
  4461. auto report = run->report;
  4462. int pluginLatency = -1;
  4463. if (const auto effect = run->engine->getEffect (0, run->slot)) // (not held past the engine's reset)
  4464. pluginLatency = effect->latencySamples();
  4465. const auto pdc = run->engine->getLatencySamples();
  4466. report << "render_seconds=" << juce::String (run->renderSeconds, 2) << "\n"
  4467. << "plugin_latency=" << pluginLatency << "\npdc_total=" << pdc << "\n"
  4468. << "plugin_crashes=" << lynx::pluginCrashCount() << "\n";
  4469. run->engine.reset(); // destroys the plugin: it writes its counters
  4470. // one line per plugin instance (the engine may have made more than one): none may have been
  4471. // deactivated inside process(), and the one that rendered must have restarted
  4472. int overlapped = 0, inactive = 0, requests = 0, activations = 0, lines = 0, wrongThread = 0, misordered = 0, unstopped = 0;
  4473. bool otherRate = false;
  4474. for (const auto& line : juce::StringArray::fromLines (counters.loadFileAsString()))
  4475. {
  4476. juce::StringPairArray values;
  4477. for (const auto& token : juce::StringArray::fromTokens (line, " ", ""))
  4478. if (token.contains ("="))
  4479. values.set (token.upToFirstOccurrenceOf ("=", false, false), token.fromFirstOccurrenceOf ("=", false, false));
  4480. if (values.size() == 0)
  4481. continue;
  4482. ++lines;
  4483. report << "instance: " << line << "\n";
  4484. overlapped += values["overlapped"].getIntValue();
  4485. inactive += values["inactive_blocks"].getIntValue();
  4486. // issue #46: activate / deactivate on the main thread, start / stop_processing on the audio thread
  4487. // (the plugin aborts the process otherwise, as u-he's do), in order, every start stopped
  4488. wrongThread += values["wrong_thread"].getIntValue();
  4489. misordered += values["misordered"].getIntValue();
  4490. unstopped += values["starts"].getIntValue() - values["stops"].getIntValue();
  4491. otherRate = otherRate || values["last_rate"].getIntValue() == 44100;
  4492. if (values["requests"].getIntValue() > requests)
  4493. {
  4494. requests = values["requests"].getIntValue();
  4495. activations = values["activations"].getIntValue();
  4496. }
  4497. }
  4498. report << "wrong_thread=" << wrongThread << "\nmisordered=" << misordered << "\nunstopped=" << unstopped
  4499. << "\nactivated_at_44100=" << (otherRate ? "yes" : "no") << "\n";
  4500. const auto ok = lines > 0 && requests > 0 && activations > requests / 2 && overlapped == 0 && inactive == 0
  4501. && wrongThread == 0 && misordered == 0 && unstopped == 0 && otherRate
  4502. && pluginLatency > 0 && pdc == pluginLatency && lynx::pluginCrashCount() == 0;
  4503. if (! ok)
  4504. {
  4505. fail (report);
  4506. return;
  4507. }
  4508. report << "result=OK\n";
  4509. juce::File (reportPath).replaceWithText (report);
  4510. setApplicationReturnValue (0);
  4511. quit();
  4512. });
  4513. };
  4514. juce::Timer::callAfterDelay (50, *finish);
  4515. }
  4516. // LYNX.exe --vst2test "LYNX Test Synth.dll" report.txt (tools/testplugin/lynx_test_vst2.c): LYNX's own VST2 host.
  4517. // Scans the DLL, imports it the way an .flp holds it (Fruity Wrapper VST2 state with a chunk, REA_rodada89 §2),
  4518. // renders with two saved gains (the level must follow the restored state) and checks the plugin saw the song tempo.
  4519. void runVst2Test (const juce::String& pluginPath, const juce::String& reportPath)
  4520. {
  4521. juce::String report;
  4522. bool ok = false;
  4523. {
  4524. lynx::AudioEngine offline (false);
  4525. auto& host = offline.getPluginHost();
  4526. report << "plugins_in_file=" << host.addPluginFile (juce::File (pluginPath)) << "\n";
  4527. std::optional<juce::PluginDescription> vst2;
  4528. for (const auto& type : host.getKnownPlugins().getTypes())
  4529. if (type.pluginFormatName == "VST")
  4530. vst2 = type;
  4531. auto render = [&] (float gain, float& tempoSeen, int& adopted) {
  4532. lynx::FlVst2State state;
  4533. state.flags = 8;
  4534. state.chunk = { 'L', 'X', 'V', '2', 0, 0, 0, 0 };
  4535. std::memcpy (state.chunk.data() + 4, &gain, 4);
  4536. auto song = lynx::Song::makeDefault();
  4537. song.bpm = 137.0;
  4538. auto& f = song.channels[4].plugin.foreign;
  4539. f.format = lynx::ForeignPlugin::Format::vst2;
  4540. f.vst2Id = (std::uint32_t) vst2->uniqueId;
  4541. f.name = "Some other name"; // found by the VST2 ID
  4542. f.state = lynx::writeFlVst2State (state);
  4543. song.channels[4].volume = 1.0f;
  4544. song.patterns[0].notes.clear();
  4545. song.patterns[0].notes.push_back ({ 0, 4 * lynx::ppq, 4, 69, 1.0f });
  4546. for (std::size_t c = 0; c < song.channels.size(); ++c)
  4547. if (c != 4)
  4548. song.channels[c].muted = true;
  4549. adopted = host.adoptFlPlugins (song);
  4550. offline.setSong (song);
  4551. const auto peak = offline.renderOffline (1.0, 48000.0);
  4552. offline.capturePluginStates();
  4553. juce::MemoryBlock saved;
  4554. saved.fromBase64Encoding (juce::String (offline.getSong().channels[4].plugin.state));
  4555. lynx::FlVst2State back;
  4556. tempoSeen = 0.0f;
  4557. if (lynx::parseFlVst2State (std::vector<std::uint8_t> ((const std::uint8_t*) saved.getData(), (const std::uint8_t*) saved.getData() + saved.getSize()), back)
  4558. && back.chunk.size() >= 12)
  4559. std::memcpy (&tempoSeen, back.chunk.data() + 8, 4);
  4560. return peak;
  4561. };
  4562. if (vst2)
  4563. {
  4564. report << "plugin=" << vst2->name << " id=" << vst2->uniqueId << " instrument=" << (int) vst2->isInstrument << "\n";
  4565. float tempoA = 0, tempoB = 0;
  4566. int adoptedA = 0, adoptedB = 0;
  4567. const auto quiet = render (0.1f, tempoA, adoptedA);
  4568. const auto loud = render (0.4f, tempoB, adoptedB);
  4569. report << "adopted=" << adoptedA << "," << adoptedB << " peak_gain_0.1=" << quiet << " peak_gain_0.4=" << loud
  4570. << " tempo_seen=" << tempoB * 1000.0f << "\n";
  4571. ok = adoptedA == 1 && adoptedB == 1 && quiet > 0.01f && std::abs (loud / quiet - 4.0f) < 0.2f
  4572. && std::abs (tempoB * 1000.0f - 137.0f) < 0.01f;
  4573. }
  4574. }
  4575. report << "result=" << (ok ? "OK" : "FAILED") << "\n";
  4576. juce::File (reportPath).replaceWithText (report);
  4577. setApplicationReturnValue (ok ? 0 : 1);
  4578. quit();
  4579. }
  4580. // Round 181c: a wrapper MIDI option changed on a running plugin must act like the same option on a new one. For each
  4581. // option: a control engine whose plugin is created with the option set (proves the test can see it), then an engine
  4582. // whose plugin is already running when the option changes through editSong, as the wrapper page does it. What the
  4583. // plugin received comes from the test plugin's own log. The running instance must also stay the same one.
  4584. void runWrapperMidiTest (const juce::String& pluginPath, const juce::String& reportPath)
  4585. {
  4586. juce::String report;
  4587. auto ok = true;
  4588. const juce::File logFile (juce::SystemStats::getEnvironmentVariable ("LYNX_TEST_VST2_MIDILOG", {}));
  4589. struct Event { juce::String instance; int status, data1, data2; };
  4590. auto take = [&] {
  4591. std::vector<Event> out;
  4592. juce::StringArray lines;
  4593. logFile.readLines (lines);
  4594. for (const auto& line : lines)
  4595. {
  4596. const auto p = juce::StringArray::fromTokens (line, " ", {});
  4597. if (p.size() == 4)
  4598. out.push_back ({ p[0], p[1].getIntValue(), p[2].getIntValue(), p[3].getIntValue() });
  4599. }
  4600. logFile.deleteFile();
  4601. return out;
  4602. };
  4603. auto count = [] (const std::vector<Event>& events, int status, int data1, int data2) {
  4604. int n = 0;
  4605. for (const auto& e : events)
  4606. n += (e.status & 0xF0) == status && (data1 < 0 || e.data1 == data1) && (data2 < 0 || e.data2 == data2) ? 1 : 0;
  4607. return n;
  4608. };
  4609. struct Option
  4610. {
  4611. const char* name;
  4612. std::function<void (lynx::PluginRef&)> before, change;
  4613. std::function<juce::String (const std::vector<Event>&)> seen;
  4614. };
  4615. const Option options[] = {
  4616. { "Send note release velocity off", {}, [] (lynx::PluginRef& r) { r.releaseVelocity = false; },
  4617. [&] (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)); } },
  4618. { "Send pitch bend range on", {}, [] (lynx::PluginRef& r) { r.sendBendRange = true; },
  4619. [&] (const std::vector<Event>& e) { return "rpn_range_12=" + juce::String (count (e, 0xB0, 6, 12)); } },
  4620. { "Pitch bend range 24", [] (lynx::PluginRef& r) { r.sendBendRange = true; }, [] (lynx::PluginRef& r) { r.bendRange = 24; },
  4621. [&] (const std::vector<Event>& e) { return "rpn_range_24=" + juce::String (count (e, 0xB0, 6, 24)); } },
  4622. { "Send MOD X as polyphonic aftertouch on", {}, [] (lynx::PluginRef& r) { r.modXAftertouch = true; },
  4623. [&] (const std::vector<Event>& e) { return "aftertouch=" + juce::String (count (e, 0xA0, 69, -1)); } },
  4624. { "Send All Notes Off when playback stops off", {}, [] (lynx::PluginRef& r) { r.allNotesOffOnStop = false; },
  4625. [&] (const std::vector<Event>& e) { return "cc123=" + juce::String (count (e, 0xB0, 123, -1)); } },
  4626. };
  4627. // each phase has its own engine: an engine keeps the running instance across setSong, so one engine would
  4628. // carry the control's plugin into the "before" phase
  4629. lynx::AudioEngine scanner (false);
  4630. auto& host = scanner.getPluginHost();
  4631. report << "plugins_in_file=" << host.addPluginFile (juce::File (pluginPath)) << "\n";
  4632. std::optional<juce::PluginDescription> vst2;
  4633. for (const auto& type : host.getKnownPlugins().getTypes())
  4634. if (type.pluginFormatName == "VST")
  4635. vst2 = type;
  4636. if (! vst2 || logFile.getFullPathName().isEmpty())
  4637. ok = false;
  4638. else
  4639. for (const auto& option : options)
  4640. {
  4641. auto makeSong = [&] (bool changed) {
  4642. auto song = lynx::Song::makeDefault();
  4643. auto& channel = song.channels[0];
  4644. channel.instrument = lynx::InstrumentKind::plugin;
  4645. channel.plugin = {};
  4646. channel.plugin.id = vst2->createIdentifierString().toStdString();
  4647. channel.plugin.name = vst2->name.toStdString();
  4648. if (option.before)
  4649. option.before (channel.plugin);
  4650. if (changed)
  4651. option.change (channel.plugin);
  4652. song.patterns[0].notes.clear();
  4653. lynx::Note note;
  4654. note.start = 0;
  4655. note.length = lynx::ppq;
  4656. note.channel = 0;
  4657. note.key = 69;
  4658. note.velocity = 1.0f;
  4659. note.release = 0.25f; // 32 of 127
  4660. note.modX = 0.75f;
  4661. song.patterns[0].notes.push_back (note);
  4662. for (std::size_t c = 1; c < song.channels.size(); ++c)
  4663. song.channels[c].muted = true;
  4664. return song;
  4665. };
  4666. // a block of the song, then a note held across "playback stopped", as the options act on either
  4667. auto play = [&] (lynx::AudioEngine& engine) {
  4668. logFile.deleteFile();
  4669. engine.renderOffline (1.0, 48000.0);
  4670. if (auto instrument = engine.getChannelInstrument (0))
  4671. {
  4672. instrument->noteOn (60, 1.0f);
  4673. instrument->transportStopped();
  4674. }
  4675. engine.renderOffline (0.1, 48000.0);
  4676. return take();
  4677. };
  4678. auto newEngine = [&] {
  4679. auto engine = std::make_unique<lynx::AudioEngine> (false);
  4680. engine->getPluginHost().addPluginFile (juce::File (pluginPath));
  4681. return engine;
  4682. };
  4683. std::vector<Event> control;
  4684. {
  4685. auto engine = newEngine();
  4686. engine->setSong (makeSong (true));
  4687. control = play (*engine);
  4688. }
  4689. auto engine = newEngine();
  4690. engine->setSong (makeSong (false));
  4691. const auto before = play (*engine);
  4692. const auto instrumentBefore = engine->getChannelInstrument (0).get();
  4693. engine->capturePluginStates(); // as the wrapper page does
  4694. engine->editSong ([&] (lynx::Song& song) { option.change (song.channels[0].plugin); });
  4695. const auto after = play (*engine);
  4696. const auto sameInstance = engine->getChannelInstrument (0).get() == instrumentBefore;
  4697. // the counts differ between phases (how many blocks the note spans, how many instances the phase made):
  4698. // what matters is whether each kind of event is there at all
  4699. auto shape = [] (const juce::String& seen) {
  4700. juce::String out;
  4701. for (const auto& token : juce::StringArray::fromTokens (seen, " ", {}))
  4702. out << token.upToFirstOccurrenceOf ("=", false, false) << (token.fromFirstOccurrenceOf ("=", false, false).getIntValue() > 0 ? "=yes " : "=no ");
  4703. return out;
  4704. };
  4705. auto instances = [] (const std::vector<Event>& events) {
  4706. std::set<juce::String> made;
  4707. for (const auto& e : events)
  4708. made.insert (e.instance);
  4709. return (int) made.size();
  4710. };
  4711. const auto a = option.seen (control) + " instances=" + juce::String (instances (control)),
  4712. b = option.seen (before) + " instances=" + juce::String (instances (before)),
  4713. c = option.seen (after) + " instances=" + juce::String (instances (after));
  4714. const auto visible = shape (option.seen (control)) != shape (option.seen (before));
  4715. const auto works = shape (option.seen (after)) == shape (option.seen (control));
  4716. report << option.name << ": control " << a << " | before " << b << " | after the change " << c << " | same_instance=" << (int) sameInstance
  4717. << " | test_sees_the_option=" << (int) visible << " | " << (! visible ? "NOT PROVEN" : works ? "acts on the plugin" : "DEAD until re-created") << "\n";
  4718. ok = ok && visible && works;
  4719. }
  4720. report << "result=" << (ok ? "OK" : "FAILED") << "\n";
  4721. juce::File (reportPath).replaceWithText (report);
  4722. setApplicationReturnValue (ok ? 0 : 1);
  4723. quit();
  4724. }
  4725. // LYNX.exe --wrappertest plugin.vst3 report.txt: builds a VST3 state the way FL's Fruity
  4726. // Wrapper stores it (REA_rodada5 §3.2), runs it through the import (adoptFlPlugins) and checks
  4727. // that the plugin comes back with the changed parameter.
  4728. void runWrapperTest (const juce::String& pluginPath, const juce::String& reportPath)
  4729. {
  4730. juce::String report;
  4731. bool ok = false;
  4732. {
  4733. lynx::AudioEngine offline (false);
  4734. auto& host = offline.getPluginHost();
  4735. host.addPluginFile (juce::File (pluginPath));
  4736. const juce::PluginDescription* vst3 = nullptr;
  4737. const auto types = host.getKnownPlugins().getTypes(); // copy: the pointer below points into it
  4738. for (const auto& type : types)
  4739. if (type.pluginFormatName == "VST3" && type.isInstrument)
  4740. vst3 = &type;
  4741. if (vst3 != nullptr)
  4742. {
  4743. juce::String error;
  4744. auto plugin = host.getFormats().createPluginInstance (*vst3, 48000.0, 512, error);
  4745. auto* parameter = plugin != nullptr && ! plugin->getParameters().isEmpty() ? plugin->getParameters()[0] : nullptr;
  4746. if (parameter != nullptr)
  4747. {
  4748. const auto target = parameter->getValue() > 0.5f ? 0.13f : 0.87f;
  4749. parameter->setValueNotifyingHost (target);
  4750. juce::MemoryBlock juceState;
  4751. plugin->getStateInformation (juceState);
  4752. report << "parameter=" << parameter->getName (64) << " target=" << target << "\n";
  4753. // JUCE state -> FL container: u32 1 + records 1 (flags), 3 (component), 2 (controller)
  4754. std::vector<std::uint8_t> flState;
  4755. auto put32 = [&] (std::uint32_t v) { for (int b = 0; b < 4; ++b) flState.push_back ((std::uint8_t) (v >> (8 * b))); };
  4756. auto record = [&] (std::uint32_t id, const juce::MemoryBlock& data) {
  4757. put32 (id);
  4758. put32 ((std::uint32_t) data.getSize());
  4759. put32 (0);
  4760. flState.insert (flState.end(), (const std::uint8_t*) data.getData(), (const std::uint8_t*) data.getData() + data.getSize());
  4761. };
  4762. put32 (1);
  4763. record (1, juce::MemoryBlock (64, true));
  4764. // record 4 (REA_rodada22 §2.3): slots 0/1 hold the ParamIDs of parameters 2 and 0, so FL's
  4765. // automations k = 0, 1, 2 mean positions 2, 0 and 1 (the first parameter without a slot)
  4766. juce::MemoryBlock slots;
  4767. const auto paramId = [&] (int i) {
  4768. const auto* hosted = dynamic_cast<const juce::HostedAudioProcessorParameter*> (plugin->getParameters()[i]);
  4769. return hosted != nullptr ? (std::uint32_t) hosted->getParameterID().getLargeIntValue() : 0u;
  4770. };
  4771. const bool reorder = plugin->getParameters().size() >= 3;
  4772. if (reorder)
  4773. {
  4774. for (auto v : { 2u, paramId (2), paramId (0) })
  4775. slots.append (&v, 4);
  4776. report << "slot_param_ids=" << (juce::int64) paramId (2) << "," << (juce::int64) paramId (0) << "\n";
  4777. }
  4778. if (auto xml = juce::AudioProcessor::getXmlFromBinary (juceState.getData(), (int) juceState.getSize()))
  4779. for (auto [tag, id] : { std::pair { "IComponent", 3u }, { "IEditController", 2u } })
  4780. if (auto* child = xml->getChildByName (tag))
  4781. {
  4782. juce::MemoryBlock data;
  4783. data.fromBase64Encoding (child->getAllSubText());
  4784. record (id, data);
  4785. report << tag << "_bytes=" << (int) data.getSize() << "\n";
  4786. }
  4787. if (reorder)
  4788. record (4, slots);
  4789. plugin.reset();
  4790. auto song = lynx::Song::makeDefault();
  4791. auto& f = song.channels[4].plugin.foreign;
  4792. f.format = lynx::ForeignPlugin::Format::vst3;
  4793. f.name = vst3->name.toStdString(); // no class ID: find it by name (fallback)
  4794. f.state = flState;
  4795. {
  4796. std::vector<std::uint8_t> comp, ctrl;
  4797. report << "split=" << (int) lynx::splitFlVst3State (flState, comp, ctrl) << " component=" << (int) comp.size()
  4798. << " saved_slots=" << (int) lynx::flVst3ParamSlots (flState).size() << "\n";
  4799. }
  4800. for (int k = 0; k < 3; ++k)
  4801. {
  4802. lynx::Automation a;
  4803. a.target = { lynx::AutomationTargetKind::channelParam, 4, 0, k };
  4804. song.automations.push_back (a);
  4805. }
  4806. const auto adopted = host.adoptFlPlugins (song);
  4807. report << "adopted=" << adopted << "\n";
  4808. juce::String mapped;
  4809. for (const auto& a : song.automations)
  4810. if (a.target.kind == lynx::AutomationTargetKind::channelParam && a.target.index == 4)
  4811. mapped << (mapped.isEmpty() ? "" : ",") << a.target.param;
  4812. report << "slot_positions=" << mapped << "\n";
  4813. const auto slotsOk = ! reorder || mapped == "2,0,1";
  4814. offline.setSong (song);
  4815. if (auto* loaded = dynamic_cast<lynx::PluginInstrument*> (offline.getChannelInstrument (4).get()))
  4816. {
  4817. const auto value = loaded->getInstance().getParameters()[0]->getValue();
  4818. report << "restored_value=" << value << "\n";
  4819. ok = adopted == 1 && std::abs (value - target) < 0.02f && slotsOk;
  4820. }
  4821. }
  4822. }
  4823. }
  4824. report << "result=" << (ok ? "OK" : "FAILED") << "\n";
  4825. juce::File (reportPath).replaceWithText (report);
  4826. setApplicationReturnValue (ok ? 0 : 1);
  4827. quit();
  4828. }
  4829. void runShowcase (const juce::String& outputPath, int currentPattern)
  4830. {
  4831. using namespace lynx;
  4832. Song song;
  4833. song.bpm = 124.0;
  4834. song.mixer = Song::defaultMixer();
  4835. const auto presets = synthPresets();
  4836. auto preset = [&] (const char* name) {
  4837. for (const auto& [n, sset] : presets)
  4838. if (n == name)
  4839. return sset;
  4840. return SynthSettings {};
  4841. };
  4842. auto channel = [&] (const char* name, InstrumentKind kind, float volume, int track, std::uint32_t colour) {
  4843. ChannelDef c;
  4844. c.name = name;
  4845. c.instrument = kind;
  4846. c.volume = volume;
  4847. c.mixerTrack = track;
  4848. c.colour = colour;
  4849. song.channels.push_back (c);
  4850. return (int) song.channels.size() - 1;
  4851. };
  4852. const auto kick = channel ("Kick", InstrumentKind::kick, 0.9f, 1, 0xffd9534f);
  4853. const auto clap = channel ("Clap", InstrumentKind::clap, 0.75f, 2, 0xfff0ad4e);
  4854. const auto hat = channel ("Hat", InstrumentKind::hat, 0.6f, 3, 0xfff7d774);
  4855. const auto snare = channel ("Snare", InstrumentKind::snare, 0.7f, 4, 0xffe8835a);
  4856. const auto bass = channel ("Reese Bass", InstrumentKind::synth, 0.8f, 5, 0xff5bc0de);
  4857. song.channels[(std::size_t) bass].synth = preset ("Reese Bass"); // preset name as defined in core/SynthPresets
  4858. const auto pad = channel ("Pad", InstrumentKind::synth, 0.7f, 6, 0xff9b7fd6);
  4859. song.channels[(std::size_t) pad].synth = preset ("Pad");
  4860. const auto pluck = channel ("Pluck", InstrumentKind::synth, 0.72f, 7, 0xff5cb85c);
  4861. song.channels[(std::size_t) pluck].synth = preset ("Pluck");
  4862. const auto lead = channel ("Supersaw", InstrumentKind::synth, 0.6f, 8, 0xff4fc3a1);
  4863. song.channels[(std::size_t) lead].synth = preset ("Supersaw");
  4864. auto addPattern = [&] (const char* name, std::uint32_t colour) {
  4865. auto& p = song.patterns.emplace_back();
  4866. p.name = name;
  4867. p.colour = colour;
  4868. return (int) song.patterns.size() - 1;
  4869. };
  4870. auto note = [&] (int pattern, int ch, double beat, double beats, int key, float velocity = 0.8f) {
  4871. Note n;
  4872. n.channel = ch;
  4873. n.start = (std::int64_t) (beat * ppq);
  4874. n.length = (std::int64_t) (beats * ppq);
  4875. n.key = key;
  4876. n.velocity = velocity;
  4877. song.patterns[(std::size_t) pattern].notes.push_back (n);
  4878. };
  4879. const auto beat = addPattern ("Beat", 0xffd9534f);
  4880. for (int s = 0; s < 16; s += 4)
  4881. song.patterns[(std::size_t) beat].toggleStep (kick, s);
  4882. for (int s : { 4, 12 })
  4883. song.patterns[(std::size_t) beat].toggleStep (clap, s);
  4884. for (int s = 2; s < 16; s += 4)
  4885. song.patterns[(std::size_t) beat].toggleStep (hat, s);
  4886. for (int s : { 7, 15 })
  4887. song.patterns[(std::size_t) beat].toggleStep (snare, s);
  4888. const auto groove = addPattern ("Groove", 0xfff0ad4e);
  4889. for (int s = 0; s < 16; ++s)
  4890. song.patterns[(std::size_t) groove].toggleStep (hat, s);
  4891. for (int s : { 4, 12 })
  4892. song.patterns[(std::size_t) groove].toggleStep (clap, s);
  4893. // Am – F – C – G, one bar each
  4894. const int roots[4] = { 45, 41, 48, 43 };
  4895. const int chords[4][3] = { { 57, 60, 64 }, { 53, 57, 60 }, { 55, 60, 64 }, { 55, 59, 62 } };
  4896. const auto bassline = addPattern ("Bass", 0xff5bc0de);
  4897. for (int bar = 0; bar < 4; ++bar)
  4898. for (int e = 0; e < 8; ++e)
  4899. if (e != 3)
  4900. note (bassline, bass, bar * 4 + e * 0.5, 0.4, roots[bar] - 12 + (e == 6 ? 12 : 0), e % 2 == 0 ? 0.9f : 0.65f);
  4901. const auto chordsPattern = addPattern ("Chords", 0xff9b7fd6);
  4902. for (int bar = 0; bar < 4; ++bar)
  4903. for (int k = 0; k < 3; ++k)
  4904. note (chordsPattern, pad, bar * 4, 3.9, chords[bar][k], 0.7f);
  4905. const auto melody = addPattern ("Melody", 0xff5cb85c);
  4906. const int line[] = { 69, 72, 76, 74, 72, 69, 67, 69, 65, 69, 72, 74, 72, 69, 67, 64,
  4907. 72, 76, 79, 76, 74, 72, 74, 76, 71, 74, 79, 78, 76, 74, 71, 67 };
  4908. for (int k = 0; k < 32; ++k)
  4909. if (k % 8 != 7)
  4910. note (melody, pluck, k * 0.5, k % 4 == 3 ? 0.9 : 0.4, line[k], k % 2 == 0 ? 0.85f : 0.65f);
  4911. const auto hook = addPattern ("Hook", 0xff4fc3a1);
  4912. for (int bar = 0; bar < 4; ++bar)
  4913. for (int k = 0; k < 3; ++k)
  4914. note (hook, lead, bar * 4 + k * 1.5, k == 2 ? 1.0 : 1.4, chords[bar][2] + 12 - k * 3, 0.8f);
  4915. // Playlist: intro, verse, drop, breakdown, final drop
  4916. song.playlistTracks = { { "Drums" }, { "Groove" }, { "Bass" }, { "Chords" }, { "Melody" }, { "Hook" }, { "Automation" } };
  4917. const auto bar = (std::int64_t) ppq * 4;
  4918. auto clip = [&] (int pattern, int track, int fromBar, int bars) {
  4919. const auto length = song.patterns[(std::size_t) pattern].effectiveLength (song.beatsPerBar);
  4920. for (int b = fromBar; b < fromBar + bars;)
  4921. {
  4922. Clip c;
  4923. c.pattern = pattern;
  4924. c.track = track;
  4925. c.start = b * bar;
  4926. c.length = length;
  4927. song.playlist.push_back (c);
  4928. b += (int) std::max<std::int64_t> (1, length / bar);
  4929. }
  4930. };
  4931. clip (chordsPattern, 3, 0, 8);
  4932. clip (melody, 4, 4, 4);
  4933. clip (beat, 0, 8, 16);
  4934. clip (groove, 1, 12, 12);
  4935. clip (bassline, 2, 8, 8);
  4936. clip (melody, 4, 8, 8);
  4937. clip (chordsPattern, 3, 16, 4);
  4938. clip (bassline, 2, 20, 4);
  4939. clip (hook, 5, 20, 4);
  4940. clip (melody, 4, 20, 4);
  4941. song.addMarker ({ 0, "Intro" });
  4942. song.addMarker ({ 8 * bar, "Drop" });
  4943. song.addMarker ({ 16 * bar, "Breakdown" });
  4944. song.addMarker ({ 20 * bar, "Final" });
  4945. // automation: the pad volume opens up during the intro
  4946. Automation a;
  4947. a.name = "Pad Volume";
  4948. a.target = { AutomationTargetKind::mixerVolume, 6, 0, 0 };
  4949. a.points = { { 0, 0.15f, 0.4f }, { 8 * bar, 0.8f, 0.0f } };
  4950. song.automations.push_back (a);
  4951. Clip ac;
  4952. ac.kind = ClipKind::automation;
  4953. ac.automation = 0;
  4954. ac.track = 6;
  4955. ac.start = 0;
  4956. ac.length = 8 * bar;
  4957. song.playlist.push_back (ac);
  4958. // mixer: names, colours and effects (bass compressor sidechained to the kick)
  4959. const char* names[] = { "Master", "Kick", "Clap", "Hat", "Snare", "Bass", "Pad", "Pluck", "Lead" };
  4960. for (int t = 0; t < 9; ++t)
  4961. {
  4962. song.mixer[(std::size_t) t].name = names[t];
  4963. if (t > 0)
  4964. song.mixer[(std::size_t) t].colour = song.channels[(std::size_t) t - 1].colour;
  4965. }
  4966. auto fx = [&] (int track, EffectKind kind) -> EffectSlot& {
  4967. song.mixer[(std::size_t) track].effects.push_back (makeEffectSlot (kind));
  4968. return song.mixer[(std::size_t) track].effects.back();
  4969. };
  4970. {
  4971. // kick EQ: cut below 30 Hz, weight at 60 Hz, remove the "boxiness" at 350 Hz, brightness at 4 kHz
  4972. auto& eq = fx (1, EffectKind::parametricEq);
  4973. auto band = [&] (int b, peq::BandType type, double hz, double db, double q) {
  4974. eq.params[(std::size_t) peq::param (b, 0)] = peq::typeValue (type);
  4975. eq.params[(std::size_t) peq::param (b, 1)] = peq::hzValue (hz);
  4976. eq.params[(std::size_t) peq::param (b, 2)] = peq::gainValue (db);
  4977. eq.params[(std::size_t) peq::param (b, 3)] = peq::qValue (q);
  4978. };
  4979. band (0, peq::BandType::lowCut, 30.0, 0.0, 0.7);
  4980. band (1, peq::BandType::peak, 62.0, 5.0, 1.2);
  4981. band (2, peq::BandType::peak, 350.0, -6.0, 2.0);
  4982. band (3, peq::BandType::peak, 4200.0, 3.5, 1.5);
  4983. band (4, peq::BandType::highCut, 14000.0, 0.0, 0.7);
  4984. for (int b = 5; b < peq::bands; ++b)
  4985. eq.params[(std::size_t) peq::param (b, 0)] = peq::typeValue (peq::BandType::off);
  4986. }
  4987. fx (1, EffectKind::distortion).mix = 0.3f;
  4988. auto& comp = fx (5, EffectKind::compressor);
  4989. comp.params[0] = 0.55f;
  4990. comp.params[1] = 0.8f;
  4991. comp.sidechain = 1;
  4992. fx (5, EffectKind::parametricEq);
  4993. fx (6, EffectKind::chorus);
  4994. fx (6, EffectKind::reverb);
  4995. fx (7, EffectKind::delay);
  4996. fx (7, EffectKind::reverb).mix = 0.4f;
  4997. fx (8, EffectKind::effector);
  4998. fx (8, EffectKind::delay);
  4999. fx (0, EffectKind::parametricEq);
  5000. auto& limiter = fx (0, EffectKind::limiter);
  5001. limiter.params = { 11.7f / 12.0f, 0.1f, 0.5f };
  5002. song.mixer[1].volume = 0.78f;
  5003. song.mixer[5].volume = 0.72f;
  5004. song.mixer[6].volume = 0.6f;
  5005. song.mixer[6].pan = -0.2f;
  5006. song.mixer[7].pan = 0.25f;
  5007. song.mode = PlayMode::song;
  5008. song.currentPattern = std::clamp (currentPattern, 0, (int) song.patterns.size() - 1);
  5009. juce::String error;
  5010. const auto ok = ProjectFile::save (song, juce::File (outputPath), error);
  5011. setApplicationReturnValue (ok ? 0 : 1);
  5012. quit();
  5013. }
  5014. // LYNX.exe --sandboxtest plugin.vst3 report.txt: opens the instrument in a separate process, plays a
  5015. // note, changes a parameter, checks the state (back in an in-process plugin) and makes the child hang
  5016. // to check that LYNX keeps going (silence, without waiting longer than the timeout).
  5017. // --sandboxtest: plays an instrument (a note) or an effect (a 440 Hz tone through it); render() adds into l / r
  5018. struct TestVoice
  5019. {
  5020. explicit TestVoice (std::unique_ptr<juce::AudioPluginInstance> p)
  5021. {
  5022. if (p->acceptsMidi() && p->getTotalNumInputChannels() == 0)
  5023. instrument = std::make_unique<lynx::PluginInstrument> (std::move (p), 512);
  5024. else
  5025. effect = std::move (p);
  5026. }
  5027. void noteOn()
  5028. {
  5029. if (instrument != nullptr)
  5030. instrument->noteOn (60, 0.9f);
  5031. }
  5032. void render (float* l, float* r, int n, float gainLeft, float gainRight)
  5033. {
  5034. if (instrument != nullptr)
  5035. {
  5036. instrument->render (l, r, n, gainLeft, gainRight);
  5037. return;
  5038. }
  5039. const auto channels = juce::jmax (2, effect->getTotalNumInputChannels(), effect->getTotalNumOutputChannels());
  5040. juce::AudioBuffer<float> block (channels, 512);
  5041. juce::MidiBuffer midi;
  5042. for (int done = 0; done < n; done += 512)
  5043. {
  5044. const auto k = juce::jmin (512, n - done);
  5045. block.setSize (channels, k, false, false, true);
  5046. for (int i = 0; i < k; ++i)
  5047. {
  5048. const auto v = 0.25f * (float) std::sin (phase);
  5049. phase += 2.0 * juce::MathConstants<double>::pi * 440.0 / 48000.0;
  5050. for (int c = 0; c < channels; ++c)
  5051. block.setSample (c, i, v);
  5052. }
  5053. effect->processBlock (block, midi);
  5054. for (int i = 0; i < k; ++i)
  5055. {
  5056. l[done + i] += gainLeft * block.getSample (0, i);
  5057. r[done + i] += gainRight * block.getSample (1, i);
  5058. }
  5059. }
  5060. }
  5061. std::unique_ptr<lynx::PluginInstrument> instrument;
  5062. std::unique_ptr<juce::AudioPluginInstance> effect;
  5063. double phase = 0.0;
  5064. };
  5065. void runSandboxTest (const juce::String& pluginPath, const juce::String& reportPath)
  5066. {
  5067. juce::String report;
  5068. bool ok = false;
  5069. lynx::setPluginSandboxAlerts (false);
  5070. const juce::File log (reportPath + ".log");
  5071. auto step = [&] (const char* what) { log.appendText (juce::String (what) + "\n"); };
  5072. log.deleteFile();
  5073. {
  5074. lynx::PluginHost host (false);
  5075. host.addPluginFile (juce::File (pluginPath));
  5076. const auto types = host.getKnownPlugins().getTypes(); // getTypes() returns a copy
  5077. // the file's instrument, else its first effect (round 161: effects too, e.g. a Windows effect through yabridge)
  5078. const juce::PluginDescription* instrument = nullptr;
  5079. for (const auto& type : types)
  5080. if (type.isInstrument)
  5081. instrument = &type;
  5082. for (const auto& type : types)
  5083. if (instrument == nullptr && ! type.isInstrument)
  5084. instrument = &type;
  5085. step ("host");
  5086. juce::String error;
  5087. auto remote = instrument != nullptr ? lynx::createSandboxedPlugin (*instrument, 48000.0, 512, {}, error) : nullptr;
  5088. report << "opened=" << (remote != nullptr ? 1 : 0) << " error=" << error << "\n";
  5089. step ("created");
  5090. if (remote != nullptr)
  5091. {
  5092. auto& proxy = *remote;
  5093. TestVoice voice (std::move (remote));
  5094. std::vector<float> l (48000), r (48000);
  5095. auto peakOf = [&] {
  5096. float peak = 0.0f;
  5097. for (std::size_t k = 0; k < l.size(); ++k)
  5098. peak = std::max ({ peak, std::abs (l[k]), std::abs (r[k]) });
  5099. return peak;
  5100. };
  5101. const auto start = juce::Time::getMillisecondCounterHiRes();
  5102. voice.noteOn();
  5103. voice.render (l.data(), r.data(), 48000, 1.0f, 1.0f);
  5104. const auto renderMs = juce::Time::getMillisecondCounterHiRes() - start;
  5105. const auto peak = peakOf();
  5106. step ("played");
  5107. if (juce::JUCEApplication::getCommandLineParameters().contains ("--expect-crash"))
  5108. {
  5109. // a plugin that crashes while playing (round 161 test plugin): LYNX notices, mutes it and keeps running
  5110. const auto dead = lynx::isSandboxedPluginDead (proxy);
  5111. std::fill (l.begin(), l.end(), 0.0f);
  5112. std::fill (r.begin(), r.end(), 0.0f);
  5113. voice.render (l.data(), r.data(), 4096, 1.0f, 1.0f);
  5114. report << "peak=" << peak << " render_1s_ms=" << renderMs << " dead=" << (dead ? 1 : 0) << " peak_after=" << peakOf() << "\n";
  5115. ok = dead && peak > 1e-4f && renderMs < 2000.0 && peakOf() == 0.0f;
  5116. report << "result=" << (ok ? "OK" : "FAILED") << "\n";
  5117. juce::File (reportPath).replaceWithText (report);
  5118. setApplicationReturnValue (ok ? 0 : 1);
  5119. quit();
  5120. return;
  5121. }
  5122. report << "plugin=" << proxy.getName() << (instrument->isInstrument ? " (instrument)" : " (effect)") << " parameters="
  5123. << proxy.getParameters().size() << " peak=" << peak << " render_1s_ms=" << renderMs << "\n";
  5124. if (juce::JUCEApplication::getCommandLineParameters().contains ("--editor") && proxy.hasEditor())
  5125. {
  5126. // the plugin's own window, opened by the child process (4 s on screen); the child must stay responsive
  5127. std::unique_ptr<juce::AudioProcessorEditor> editor (proxy.createEditorIfNeeded());
  5128. juce::Thread::sleep (4000);
  5129. juce::MemoryBlock state;
  5130. const auto t0 = juce::Time::getMillisecondCounterHiRes();
  5131. proxy.getStateInformation (state);
  5132. report << "editor_shown=1 state_with_editor_ms=" << (juce::Time::getMillisecondCounterHiRes() - t0) << " dead=" << (lynx::isSandboxedPluginDead (proxy) ? 1 : 0) << "\n";
  5133. editor.reset();
  5134. }
  5135. // parameter -> state -> in-process plugin
  5136. bool stateOk = false;
  5137. if (! proxy.getParameters().isEmpty())
  5138. {
  5139. auto* p = proxy.getParameters()[0];
  5140. const auto target = p->getValue() > 0.5f ? 0.13f : 0.87f;
  5141. p->setValue (target);
  5142. std::fill (l.begin(), l.end(), 0.0f);
  5143. voice.render (l.data(), r.data(), 512, 1.0f, 1.0f); // carries the change to the child
  5144. juce::MemoryBlock state;
  5145. proxy.getStateInformation (state);
  5146. if (auto local = host.getFormats().createPluginInstance (*instrument, 48000.0, 512, error))
  5147. {
  5148. local->setStateInformation (state.getData(), (int) state.getSize());
  5149. const auto back = local->getParameters()[0]->getValue();
  5150. // the same steps without the sandbox: some plugins quantise the value or keep it out of their state
  5151. auto control = target;
  5152. if (auto a = host.getFormats().createPluginInstance (*instrument, 48000.0, 512, error))
  5153. {
  5154. a->enableAllBuses();
  5155. a->prepareToPlay (48000.0, 512);
  5156. a->getParameters()[0]->setValue (target);
  5157. juce::AudioBuffer<float> block (juce::jmax (2, a->getTotalNumInputChannels(), a->getTotalNumOutputChannels()), 512);
  5158. block.clear();
  5159. juce::MidiBuffer none;
  5160. a->processBlock (block, none);
  5161. juce::MemoryBlock direct;
  5162. a->getStateInformation (direct);
  5163. if (auto b = host.getFormats().createPluginInstance (*instrument, 48000.0, 512, error))
  5164. {
  5165. b->setStateInformation (direct.getData(), (int) direct.getSize());
  5166. control = b->getParameters()[0]->getValue();
  5167. }
  5168. a->releaseResources();
  5169. }
  5170. report << "state_bytes=" << (int) state.getSize() << " target=" << target << " in_process=" << back << " in_process_control=" << control << "\n";
  5171. stateOk = std::abs (back - control) < 0.02f;
  5172. }
  5173. }
  5174. step ("state");
  5175. // hung child: the block returns in ~0.5 s, muted, and the plugin is marked dead
  5176. lynx::hangSandboxedPluginForTest (proxy);
  5177. juce::Thread::sleep (200);
  5178. std::fill (l.begin(), l.end(), 1.0f);
  5179. std::fill (r.begin(), r.end(), 1.0f);
  5180. const auto hangStart = juce::Time::getMillisecondCounterHiRes();
  5181. voice.render (l.data(), r.data(), 4096, 0.0f, 0.0f);
  5182. std::fill (l.begin(), l.end(), 0.0f);
  5183. std::fill (r.begin(), r.end(), 0.0f);
  5184. voice.render (l.data(), r.data(), 4096, 1.0f, 1.0f);
  5185. const auto hangMs = juce::Time::getMillisecondCounterHiRes() - hangStart;
  5186. const auto dead = lynx::isSandboxedPluginDead (proxy);
  5187. const auto hangPeak = peakOf();
  5188. report << "hung_ms=" << hangMs << " dead=" << (dead ? 1 : 0) << " peak_after=" << hangPeak << "\n";
  5189. // crashed child (round 161): a second instance aborts; LYNX notices, mutes it and keeps running
  5190. bool crashOk = false;
  5191. if (auto second = lynx::createSandboxedPlugin (*instrument, 48000.0, 512, {}, error))
  5192. {
  5193. auto& proxy2 = *second;
  5194. TestVoice voice2 (std::move (second));
  5195. voice2.noteOn();
  5196. voice2.render (l.data(), r.data(), 512, 1.0f, 1.0f);
  5197. lynx::crashSandboxedPluginForTest (proxy2);
  5198. const auto crashStart = juce::Time::getMillisecondCounterHiRes();
  5199. while (! lynx::isSandboxedPluginDead (proxy2) && juce::Time::getMillisecondCounterHiRes() - crashStart < 5000.0)
  5200. {
  5201. voice2.render (l.data(), r.data(), 512, 1.0f, 1.0f);
  5202. juce::Thread::sleep (5);
  5203. }
  5204. const auto crashMs = juce::Time::getMillisecondCounterHiRes() - crashStart;
  5205. std::fill (l.begin(), l.end(), 0.0f);
  5206. std::fill (r.begin(), r.end(), 0.0f);
  5207. voice2.render (l.data(), r.data(), 4096, 1.0f, 1.0f);
  5208. const auto crashDead = lynx::isSandboxedPluginDead (proxy2);
  5209. report << "crash_ms=" << crashMs << " crash_dead=" << (crashDead ? 1 : 0) << " crash_peak_after=" << peakOf() << "\n";
  5210. crashOk = crashDead && crashMs < 3000.0;
  5211. }
  5212. step ("crash");
  5213. ok = peak > 1e-4f && stateOk && dead && hangMs < 1500.0 && hangPeak == 0.0f && crashOk;
  5214. }
  5215. }
  5216. report << "result=" << (ok ? "OK" : "FAILED") << "\n";
  5217. juce::File (reportPath).replaceWithText (report);
  5218. setApplicationReturnValue (ok ? 0 : 1);
  5219. quit();
  5220. }
  5221. // --timertest (round 174f): a view's polling timer follows the view and its parents, and survives a minimised window
  5222. void runTimerTest (const juce::File& report)
  5223. {
  5224. struct Ticks final : juce::Timer
  5225. {
  5226. void timerCallback() override {}
  5227. } timer;
  5228. juce::Component top, parent, view;
  5229. parent.addChildComponent (view);
  5230. top.addChildComponent (parent);
  5231. top.setSize (320, 200);
  5232. lynx::ui::TimerWhileShowing watch (view, timer, 30);
  5233. juce::String text;
  5234. auto failures = 0;
  5235. auto expect = [&] (const char* step, bool running) {
  5236. const auto ok = timer.isTimerRunning() == running;
  5237. failures += ok ? 0 : 1;
  5238. text << step << ": timer " << (timer.isTimerRunning() ? "running" : "stopped") << (ok ? "" : " FAIL") << "\n";
  5239. };
  5240. expect ("never shown", false);
  5241. view.setVisible (true);
  5242. parent.setVisible (true);
  5243. expect ("view and parent visible, not on the desktop", false);
  5244. top.addToDesktop (juce::ComponentPeer::windowHasTitleBar);
  5245. top.setVisible (true);
  5246. expect ("window shown", true);
  5247. parent.setVisible (false);
  5248. expect ("parent hidden", false);
  5249. parent.setVisible (true);
  5250. expect ("parent shown", true);
  5251. view.setVisible (false);
  5252. expect ("view hidden", false);
  5253. top.getPeer()->setMinimised (true);
  5254. view.setVisible (true);
  5255. expect ("view shown while minimised", true);
  5256. top.getPeer()->setMinimised (false);
  5257. expect ("window restored", true);
  5258. top.setVisible (false);
  5259. expect ("window hidden", false);
  5260. top.setVisible (true);
  5261. expect ("window shown again", true);
  5262. top.removeFromDesktop();
  5263. text << "failures: " << failures << "\nresult=" << (failures == 0 ? "OK" : "FAIL") << "\n";
  5264. report.replaceWithText (text);
  5265. setApplicationReturnValue (failures == 0 ? 0 : 1);
  5266. quit();
  5267. }
  5268. // --cachetest (round 174f): PlaylistComponent::cacheSelfTest on the project, the Playlist off screen at 1466 x 930
  5269. void runCacheTest (const juce::File& project, const juce::File& report)
  5270. {
  5271. engine = std::make_unique<lynx::AudioEngine>();
  5272. juce::String error;
  5273. auto ok = false;
  5274. if (project.hasFileExtension ("flp"))
  5275. ok = engine->importFlpFile (project, error);
  5276. else if (auto song = lynx::ProjectFile::load (project, error))
  5277. {
  5278. engine->setSong (std::move (*song));
  5279. ok = true;
  5280. }
  5281. juce::String text = "project: " + project.getFullPathName() + "\n";
  5282. if (ok)
  5283. {
  5284. auto playlist = std::make_unique<lynx::PlaylistComponent> (*engine);
  5285. playlist->setBounds (0, 0, 1466, 930);
  5286. playlist->setVisible (true);
  5287. text << playlist->cacheSelfTest ([] { lynx::ui::WaveformCache::getInstance()->waitUntilIdle (60000); }, report.getParentDirectory());
  5288. }
  5289. else
  5290. text << "result=ERROR " << error << "\n";
  5291. report.replaceWithText (text);
  5292. setApplicationReturnValue (ok && text.contains ("result=OK") ? 0 : 1);
  5293. quit();
  5294. }
  5295. // --uiperf (round 161): opens the project in the normal window, plays it, and drives the heavy UI cases of round 151
  5296. // through the window's own event path — the default layout, the Mixer maximised (meters while playing, then
  5297. // scrolled), the Playlist maximised (scroll down, scroll sideways, zoom in and out) and the Channel rack scrolled.
  5298. // Every frame is painted right after its event (ComponentPeer::performAnyPendingRepaintsNow) and timed; the report
  5299. // has, per case, the time to show it and the frames' mean / p95 / max, how many took longer than 16 ms, and the
  5300. // process CPU. The same on every OS, so Linux (X11, XWayland) and Windows numbers can be put side by side.
  5301. void runUiPerf (const juce::File& project, const juce::File& report)
  5302. {
  5303. if (const auto profile = juce::SystemStats::getEnvironmentVariable ("LYNX_PROFILE_MAIN", {}); profile.isNotEmpty())
  5304. lynx::crashguard::startMainProfiler (profile.toStdString()); // (stopped in shutdown)
  5305. startupOptions = lynx::StartupOptions::load();
  5306. engine = std::make_unique<lynx::AudioEngine>();
  5307. lynx::videoview::install (*engine); // (Fruity Video Player channels: their sound tracks)
  5308. crashEngine = engine.get();
  5309. createMainWindow();
  5310. mainWindow->reveal();
  5311. // LYNX_UIPERF_SIZE=WxH, LYNX_UIPERF_SCALE=<percent> (round 179a): a large window, a HiDPI desktop's scale
  5312. if (const auto scale = juce::SystemStats::getEnvironmentVariable ("LYNX_UIPERF_SCALE", {}).getIntValue(); scale > 0)
  5313. juce::Desktop::getInstance().setGlobalScaleFactor ((float) scale / 100.0f);
  5314. if (const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_UIPERF_SIZE", {}), "x", ""); size.size() == 2)
  5315. mainWindow->setBounds (0, 0, size[0].getIntValue(), size[1].getIntValue());
  5316. juce::String error;
  5317. auto ok = false;
  5318. const auto loadStart = juce::Time::getMillisecondCounterHiRes();
  5319. if (project.hasFileExtension ("flp"))
  5320. ok = engine->importFlpFile (project, error);
  5321. else if (auto song = lynx::ProjectFile::load (project, error))
  5322. {
  5323. engine->setSong (std::move (*song));
  5324. ok = true;
  5325. }
  5326. const auto loadMs = juce::Time::getMillisecondCounterHiRes() - loadStart;
  5327. if (! ok)
  5328. {
  5329. report.replaceWithText ("project: " + project.getFullPathName() + "\nresult=ERROR " + error + "\n");
  5330. setApplicationReturnValue (1);
  5331. quit();
  5332. return;
  5333. }
  5334. // LYNX_UIPERF_MUTE=1: the Master fader down (the meters of the inserts still move): a run on a desktop someone uses
  5335. if (juce::SystemStats::getEnvironmentVariable ("LYNX_UIPERF_MUTE", {}) == "1")
  5336. engine->editSong ([] (lynx::Song& s) { if (! s.mixer.empty()) s.mixer[0].volume = 0.0f; }, false);
  5337. struct Step
  5338. {
  5339. juce::String name;
  5340. std::function<void()> setup;
  5341. std::function<void (int)> action; // per frame; none: the step watches the window for `frames` ms
  5342. int frames;
  5343. std::function<juce::String()> finish = {}; // round 173f: after the step, its own lines for the report
  5344. };
  5345. struct UiPerf final : juce::Timer
  5346. {
  5347. LynxApplication& app;
  5348. juce::File report;
  5349. juce::String text;
  5350. std::vector<Step> steps;
  5351. std::size_t step = 0;
  5352. int frame = -1;
  5353. std::vector<double> times, rendered; // whole frames (event + paint + blit, when this timer paints) / the window's paints
  5354. std::vector<double> frames; // round 173f: the time of every frame the window painted (ui/FrameProbe.h)
  5355. double setupMs = 0.0, wallStart = 0.0;
  5356. double cpuStart = 0.0; // process CPU seconds (std::clock is wall time on Windows)
  5357. double messageCpuStart = 0.0; // the message thread's CPU seconds
  5358. double audioLoadSum = 0.0; // the device's CPU use (AudioDeviceManager::getCpuUsage), summed per tick
  5359. int audioLoadTicks = 0;
  5360. UiPerf (LynxApplication& a, juce::File r) : app (a), report (std::move (r)) {}
  5361. juce::ComponentPeer* peer() const { return app.mainWindow != nullptr ? app.mainWindow->getPeer() : nullptr; }
  5362. double paintNow() const
  5363. {
  5364. const auto t0 = juce::Time::getMillisecondCounterHiRes();
  5365. if (auto* p = peer())
  5366. p->performAnyPendingRepaintsNow();
  5367. return juce::Time::getMillisecondCounterHiRes() - t0;
  5368. }
  5369. void timerCallback() override
  5370. {
  5371. if (step >= steps.size())
  5372. {
  5373. stopTimer();
  5374. finish();
  5375. return;
  5376. }
  5377. auto& s = steps[step];
  5378. if (frame < 0)
  5379. {
  5380. const auto t0 = juce::Time::getMillisecondCounterHiRes();
  5381. if (s.setup)
  5382. s.setup();
  5383. paintNow();
  5384. setupMs = juce::Time::getMillisecondCounterHiRes() - t0;
  5385. times.clear();
  5386. rendered.clear();
  5387. frames.clear();
  5388. wallStart = juce::Time::getMillisecondCounterHiRes();
  5389. cpuStart = lynx::processCpuSeconds();
  5390. messageCpuStart = lynx::threadCpuSeconds();
  5391. audioLoadSum = 0.0;
  5392. audioLoadTicks = 0;
  5393. frame = 0;
  5394. return;
  5395. }
  5396. audioLoadSum += app.engine->getDeviceManager().getCpuUsage();
  5397. ++audioLoadTicks;
  5398. if (s.action)
  5399. s.action (frame);
  5400. if (const auto ms = paintNow(); ms > 0.25) // (nothing to paint: not a frame)
  5401. times.push_back (ms);
  5402. ++frame;
  5403. if (s.action ? frame < s.frames : juce::Time::getMillisecondCounterHiRes() - wallStart < (double) s.frames)
  5404. return;
  5405. const auto wall = juce::Time::getMillisecondCounterHiRes() - wallStart;
  5406. const auto cpu = 1000.0 * (lynx::processCpuSeconds() - cpuStart);
  5407. const auto messageCpu = 1000.0 * (lynx::threadCpuSeconds() - messageCpuStart);
  5408. text << s.name << ": show " << juce::String (setupMs, 1) << " ms\n"
  5409. << " painted frames: " << stats (rendered) << "\n"
  5410. << " timed here (event + paint + blit): " << stats (times)
  5411. << "\n window frames (probe): " << lynx::ui::FrameStats::of (frames, wall).describe()
  5412. << "\n CPU " << juce::String (wall > 0.0 ? 100.0 * cpu / wall : 0.0, 0) << "% (process, " << juce::String (wall / 1000.0, 1) << " s), message thread "
  5413. << juce::String (wall > 0.0 ? 100.0 * messageCpu / wall : 0.0, 1) << "%, audio device "
  5414. << juce::String (audioLoadTicks > 0 ? 100.0 * audioLoadSum / audioLoadTicks : 0.0, 1) << "%\n";
  5415. if (s.finish)
  5416. text << s.finish();
  5417. juce::File (report).replaceWithText (text);
  5418. ++step;
  5419. frame = -1;
  5420. }
  5421. static juce::String stats (std::vector<double> sorted)
  5422. {
  5423. std::sort (sorted.begin(), sorted.end());
  5424. 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()))]; };
  5425. double sum = 0.0;
  5426. int over = 0;
  5427. for (auto t : sorted)
  5428. {
  5429. sum += t;
  5430. over += t > 16.0 ? 1 : 0;
  5431. }
  5432. return juce::String ((int) sorted.size()) + ", mean " + juce::String (sorted.empty() ? 0.0 : sum / (double) sorted.size(), 1)
  5433. + " ms, p95 " + juce::String (at (0.95), 1) + " ms, max " + juce::String (sorted.empty() ? 0.0 : sorted.back(), 1)
  5434. + " ms, >16 ms " + juce::String (over);
  5435. }
  5436. void finish()
  5437. {
  5438. // the cost of asking where the mouse is (X11: a round trip to the display server)
  5439. const auto q0 = juce::Time::getMillisecondCounterHiRes();
  5440. for (int i = 0; i < 100; ++i)
  5441. juce::ignoreUnused (juce::Desktop::getInstance().getMainMouseSource().getScreenPosition());
  5442. text << "mouse position query: " << juce::String ((juce::Time::getMillisecondCounterHiRes() - q0) / 100.0, 3) << " ms\n";
  5443. app.mainWindow->onFrame = nullptr;
  5444. app.mainWindow->watchFrames ({});
  5445. app.engine->stop();
  5446. text << "result=OK\n";
  5447. report.replaceWithText (text);
  5448. app.setApplicationReturnValue (0);
  5449. app.quit();
  5450. }
  5451. };
  5452. auto* ui = &mainWindow->getContent();
  5453. auto wheelAt = [this] (juce::Component& target, float dx, float dy, juce::ModifierKeys mods) {
  5454. auto* peer = mainWindow->getPeer();
  5455. if (peer == nullptr || ! target.isShowing())
  5456. return;
  5457. juce::ModifierKeys::currentModifiers = mods;
  5458. const auto local = peer->globalToLocal (target.localPointToGlobal (target.getLocalBounds().getCentre()).toFloat());
  5459. juce::MouseWheelDetails wheel { dx, dy, false, false, false };
  5460. peer->handleMouseWheel (juce::MouseInputSource::InputSourceType::mouse, local, juce::Time::currentTimeMillis(), wheel);
  5461. juce::ModifierKeys::currentModifiers = {};
  5462. };
  5463. auto run = std::make_unique<UiPerf> (*this, report);
  5464. mainWindow->onFrame = [r = run.get()] (double ms) { if (r->frame >= 0) r->rendered.push_back (ms); };
  5465. // round 173f: every frame the window paints; a fader drag's moves count as shown when a frame covers the fader
  5466. auto drag = std::make_shared<UiPerfDrag>();
  5467. mainWindow->watchFrames ([r = run.get(), drag] (double now, juce::Rectangle<int> area) {
  5468. if (r->frame >= 0)
  5469. r->frames.push_back (now);
  5470. drag->framePainted (now, area);
  5471. });
  5472. run->text << "project: " << project.getFullPathName() << "\n"
  5473. << "LYNX " << getApplicationVersion() << ", " << juce::SystemStats::getOperatingSystemName() << ", "
  5474. << juce::SystemStats::getCpuModel() << ", window " << mainWindow->getWidth() << "x" << mainWindow->getHeight()
  5475. << ", scale " << juce::String (juce::Desktop::getInstance().getDisplays().getPrimaryDisplay() != nullptr
  5476. ? juce::Desktop::getInstance().getDisplays().getPrimaryDisplay()->scale : 1.0, 2)
  5477. << ", audio device " << (engine->getDeviceManager().getCurrentAudioDevice() != nullptr ? engine->getDeviceManager().getCurrentAudioDevice()->getName() : juce::String ("none")) << "\n"
  5478. << "load " << juce::String (loadMs / 1000.0, 2) << " s\n";
  5479. const auto none = juce::ModifierKeys();
  5480. // discussion #10 (round 173f): the reporter's screen — the Channel Rack and the Mixer open, the pattern playing —
  5481. // watched as it is, then insert 3's fader dragged up and down with the mouse (125 moves a second through the
  5482. // window's own mouse path, the frames painted as the window paints them)
  5483. const auto dragTrack = engine->getSong().mixer.size() > 3 ? 3 : 1;
  5484. run->steps.push_back ({ "rack + mixer, pattern playing", [this, ui] {
  5485. ui->showPanelsForSnapshot ({ lynx::workspace::Panel::channelRack, lynx::workspace::Panel::mixer });
  5486. engine->getTransport().songMode = false;
  5487. engine->rewind();
  5488. engine->play();
  5489. }, {}, 4000 });
  5490. run->steps.push_back ({ "fader drag by mouse, rack + mixer, pattern playing", [this, ui, drag, dragTrack] {
  5491. auto& strips = ui->getMixerForSnapshot().getStripsForSnapshot();
  5492. const auto rail = strips.faderRailForSnapshot (dragTrack);
  5493. drag->start (*mainWindow, strips, rail, engine.get(), dragTrack);
  5494. }, {}, 3000, [drag] { return drag->stop(); } });
  5495. run->steps.push_back ({ "song stopped during the drag", {}, {}, 500, [drag] { return drag->release(); } });
  5496. run->steps.push_back ({ "after the drag (released)", {}, {}, 600, [drag] { return drag->released(); } });
  5497. run->steps.push_back ({ "desktop, playing", [this, ui] { ui->showDesktopForSnapshot (false); engine->rewind(); engine->play(); }, {}, 3000 });
  5498. run->steps.push_back ({ "mixer maximised, playing", [ui] { ui->selectTabForSnapshot (3); }, {}, 3000 });
  5499. // round 177a: only the meters move, so the strips' picture must stay valid, also with a folded group's tab and VCA
  5500. // strips on screen (their levels are drawn over the picture, like the inserts' meters)
  5501. run->steps.push_back ({ "mixer meters over the picture, playing", [this, ui] {
  5502. ui->selectTabForSnapshot (3);
  5503. engine->getTransport().songMode = false;
  5504. engine->rewind();
  5505. engine->play();
  5506. ui->getMixerForSnapshot().getStripsForSnapshot().cacheCountersForPerf();
  5507. }, {}, 6000, [this, ui, report] {
  5508. const auto [spoiled, refills] = ui->getMixerForSnapshot().getStripsForSnapshot().cacheCountersForPerf();
  5509. if (juce::FileOutputStream out (report.withFileExtension ("png")); out.openedOk())
  5510. {
  5511. out.setPosition (0);
  5512. out.truncate();
  5513. juce::PNGImageFormat().writeImageToStream (mainWindow->createComponentSnapshot (mainWindow->getLocalBounds()), out);
  5514. }
  5515. return juce::String (" mixer picture: spoiled ") + juce::String (spoiled) + " times, drawn again " + juce::String (refills) + " times\n";
  5516. } });
  5517. run->steps.push_back ({ "mixer scroll", {}, [wheelAt, ui, none] (int f) { wheelAt (ui->getMixerForSnapshot(), 0.0f, f < 30 ? -0.25f : 0.25f, none); }, 60 });
  5518. // a fader dragged while the song plays (round 171c, discussion #10): 4 mouse moves per frame on insert 1's fader,
  5519. // through the old path (a whole snapshot per move) and through editLevels
  5520. auto faderMove = [this] (bool levels, int f) {
  5521. for (int k = 0; k < 4; ++k)
  5522. {
  5523. const auto v = 0.5f + 0.3f * std::sin ((float) (f * 4 + k) * 0.05f);
  5524. const auto edit = [v] (lynx::Song& s) { if (s.mixer.size() > 1) s.mixer[1].volume = v; };
  5525. if (levels)
  5526. engine->editLevels (edit, false); // (no undo step: in a real drag only the press saves one)
  5527. else
  5528. engine->editSong (edit, false);
  5529. }
  5530. };
  5531. run->steps.push_back ({ "mixer fader drag, playing, rebuild per move (before 171c)", {}, [faderMove] (int f) { faderMove (false, f); }, 60 });
  5532. run->steps.push_back ({ "mixer fader drag, playing, live levels (171c)", {}, [faderMove, this] (int f) { faderMove (true, f); if (f == 59) engine->flushLevels(); }, 60 });
  5533. // F8's Plugin picker (round 171c): opening it (the "show" time = building it + its first paint), its pictures
  5534. // loading while it stays open, pointing at the tiles, then closing it
  5535. run->steps.push_back ({ "plugin picker open (F8)", [ui] { ui->togglePluginPickerForSnapshot(); }, {}, 2500 });
  5536. run->steps.push_back ({ "plugin picker, pointing at tiles", {}, [ui] (int f) {
  5537. // (round 175b: the picker is its own window)
  5538. if (auto* picker = ui->pluginPickerForSnapshot(); picker != nullptr && picker->getPeer() != nullptr)
  5539. {
  5540. const auto p = picker->localPointToGlobal (juce::Point<int> (60 + (f * 37) % juce::jmax (1, picker->getWidth() - 120),
  5541. 90 + (f * 53) % juce::jmax (1, picker->getHeight() - 200)));
  5542. const auto local = picker->getPeer()->globalToLocal (p.toFloat());
  5543. picker->getPeer()->handleMouseEvent (juce::MouseInputSource::InputSourceType::mouse, local, {}, 0.0f, 0.0f,
  5544. juce::Time::currentTimeMillis());
  5545. }
  5546. }, 60 });
  5547. run->steps.push_back ({ "plugin picker close", [ui] { ui->togglePluginPickerForSnapshot(); }, {}, 300 });
  5548. run->steps.push_back ({ "playlist maximised, playing", [ui] { ui->selectTabForSnapshot (2); }, {}, 3000 });
  5549. run->steps.push_back ({ "playlist scroll down/up", [this] { engine->stop(); },
  5550. [wheelAt, ui, none] (int f) { wheelAt (ui->getPlaylistForSnapshot(), 0.0f, f < 40 ? -0.15f : 0.15f, none); }, 80 });
  5551. run->steps.push_back ({ "playlist scroll sideways", {},
  5552. [wheelAt, ui, none] (int f) { wheelAt (ui->getPlaylistForSnapshot(), f < 40 ? -0.15f : 0.15f, 0.0f, none); }, 80 });
  5553. // round 174f: Ctrl+wheel zoom, a notch every third frame (~20 a second), three in then three out, as dupmon drives it
  5554. run->steps.push_back ({ "playlist zoom (Ctrl+wheel)", {},
  5555. [wheelAt, ui] (int f) {
  5556. if (f % 3 == 0)
  5557. wheelAt (ui->getPlaylistForSnapshot(), 0.0f, (f / 9) % 2 == 0 ? 0.15f : -0.15f, juce::ModifierKeys (juce::ModifierKeys::ctrlModifier));
  5558. }, 120 });
  5559. run->steps.push_back ({ "playlist after the zoom (settles)", {}, {}, 500 });
  5560. run->steps.push_back ({ "whole window repainted", {}, [this] (int) { mainWindow->repaint(); }, 40 });
  5561. run->steps.push_back ({ "channel rack scroll", [ui] { ui->selectTabForSnapshot (0); },
  5562. [wheelAt, ui, none] (int f) { wheelAt (ui->getRackViewportForSnapshot(), 0.0f, f < 30 ? -0.25f : 0.25f, none); }, 60 });
  5563. // LYNX_UIPERF_ONLY=text: only the steps whose name has that text
  5564. if (const auto only = juce::SystemStats::getEnvironmentVariable ("LYNX_UIPERF_ONLY", {}); only.isNotEmpty())
  5565. 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());
  5566. // let the window draw the project first
  5567. perf = std::move (run);
  5568. juce::Timer::callAfterDelay (1500, [this] { if (perf != nullptr) perf->startTimer (16); });
  5569. }
  5570. // --rtstress: opens the project in the normal window with the saved audio device, plays it from the start for
  5571. // `seconds` and writes the real-time statistics (deadline misses, late device calls, load histogram, heaviest units)
  5572. // --rtstress --backuptest N (round 177d): while the project plays, a device's MIDI clock (10/s) and active sensing
  5573. // (3/s) arrive, and the project counts as changed. N > 0 also forces a backup every N seconds on top of the timed ones.
  5574. // The report tells how many backups were written, when, and what the MIDI counters did.
  5575. struct BackupTest final : juce::Timer
  5576. {
  5577. lynx::AudioEngine* engine = nullptr;
  5578. lynx::MainComponent* ui = nullptr;
  5579. double everyMs = 0.0, startMs = 0.0, lastForcedMs = 0.0, longestCallMs = 0.0;
  5580. int ticks = 0, forced = 0;
  5581. std::uint64_t seenOver = 0, seenNear = 0;
  5582. juce::String misses; // each callback over (or near) its deadline: how long after the last forced backup
  5583. void timerCallback() override
  5584. {
  5585. engine->injectMidiInput (juce::MidiMessage (0xf8));
  5586. if (++ticks % 3 == 0)
  5587. engine->injectMidiInput (juce::MidiMessage (0xfe));
  5588. const auto now = juce::Time::getMillisecondCounterHiRes();
  5589. const auto s = engine->getRtStats().snapshot();
  5590. if (s.overBudget != seenOver || s.nearBudget != seenNear)
  5591. {
  5592. misses << " +" << juce::String ((now - lastForcedMs) / 1000.0, 1) << " s after the last forced backup (or the start): over +"
  5593. << (juce::int64) (s.overBudget - seenOver) << ", near +" << (juce::int64) (s.nearBudget - seenNear) << "\n";
  5594. seenOver = s.overBudget;
  5595. seenNear = s.nearBudget;
  5596. }
  5597. if (everyMs > 0.0 && now - lastForcedMs >= everyMs)
  5598. {
  5599. lastForcedMs = now;
  5600. ++forced;
  5601. ui->backupNowForTest();
  5602. longestCallMs = juce::jmax (longestCallMs, juce::Time::getMillisecondCounterHiRes() - now);
  5603. }
  5604. }
  5605. };
  5606. std::unique_ptr<BackupTest> backupTest;
  5607. void startBackupTest()
  5608. {
  5609. const auto& cli = juce::JUCEApplication::getCommandLineParameterArray();
  5610. const auto at = cli.indexOf ("--backuptest");
  5611. auto* ui = mainWindow != nullptr ? dynamic_cast<lynx::MainComponent*> (mainWindow->getContentComponent()) : nullptr;
  5612. if (at < 0 || ui == nullptr)
  5613. return;
  5614. backupTest = std::make_unique<BackupTest>();
  5615. backupTest->engine = engine.get();
  5616. backupTest->ui = ui;
  5617. backupTest->everyMs = cli[at + 1].getDoubleValue() * 1000.0;
  5618. backupTest->startMs = backupTest->lastForcedMs = juce::Time::getMillisecondCounterHiRes();
  5619. // (the project counts as changed, so a backup has something to write; the Master's fader is down, so a long run
  5620. // makes no sound: everything else is processed as usual)
  5621. engine->editSong ([] (lynx::Song& s) {
  5622. if (! s.mixer.empty())
  5623. s.mixer[0].volume = 0.0f;
  5624. });
  5625. backupTest->startTimer (100);
  5626. }
  5627. juce::String finishBackupTest()
  5628. {
  5629. if (backupTest == nullptr)
  5630. return {};
  5631. backupTest->stopTimer();
  5632. juce::String text;
  5633. const auto played = engine->getMidiPlayed();
  5634. text << " backup test: MIDI light count " << (int) engine->getMidiActivity() << ", played count " << (int) played << " (clock and active sensing only)\n";
  5635. text << " backup test: " << backupTest->forced << " forced, longest forced call on the message thread "
  5636. << juce::String (backupTest->longestCallMs, 1) << " ms\n";
  5637. if (backupTest->misses.isNotEmpty())
  5638. text << " backup test: callbacks over or near the deadline (seen within 100 ms):\n" << backupTest->misses;
  5639. auto files = lynx::autosaveFolder().findChildFiles (juce::File::findFiles, false, "*.lynx");
  5640. text << " backup test: " << files.size() << " file(s) in the backup folder:\n";
  5641. for (const auto& f : files)
  5642. text << " " << juce::String ((f.getLastModificationTime().toMilliseconds() - juce::Time::getCurrentTime().toMilliseconds()) / 1000) << " s before the end: "
  5643. << f.getFileName() << " (" << f.getSize() << " bytes)\n";
  5644. engine->injectMidiInput (juce::MidiMessage::noteOn (1, 60, (juce::uint8) 1));
  5645. engine->injectMidiInput (juce::MidiMessage::noteOff (1, 60));
  5646. text << " backup test: after a played note, played count " << (int) engine->getMidiPlayed() << "\n";
  5647. backupTest.reset();
  5648. return text;
  5649. }
  5650. void runRealtimeStress (const juce::File& project, const juce::File& report, double seconds, int bufferSize,
  5651. const juce::String& deviceType, const juce::String& deviceName, const juce::String& recordTo = {})
  5652. {
  5653. startupOptions = lynx::StartupOptions::load();
  5654. engine = std::make_unique<lynx::AudioEngine>();
  5655. lynx::videoview::install (*engine); // (Fruity Video Player channels: their sound tracks)
  5656. crashEngine = engine.get();
  5657. // the user's saved device stays as it was: this run's choices are undone before quitting
  5658. savedDeviceState = engine->getDeviceManager().createStateXml();
  5659. auto& devices = engine->getDeviceManager();
  5660. const auto driverFile = addDriverFileDeviceType();
  5661. const auto type = deviceType.isEmpty() && driverFile ? juce::String (lynx::dllAsioTypeName) : deviceType;
  5662. if (type.isNotEmpty() && devices.getCurrentAudioDeviceType() != type)
  5663. devices.setCurrentAudioDeviceType (type, true);
  5664. if (bufferSize > 0 || deviceName.isNotEmpty())
  5665. {
  5666. auto setup = devices.getAudioDeviceSetup();
  5667. if (bufferSize > 0)
  5668. setup.bufferSize = bufferSize;
  5669. if (deviceName.isNotEmpty())
  5670. setup.outputDeviceName = deviceName;
  5671. const auto error = devices.setAudioDeviceSetup (setup, true);
  5672. if (error.isNotEmpty())
  5673. report.replaceWithText ("device error: " + error + "\n");
  5674. }
  5675. createMainWindow();
  5676. if (! juce::JUCEApplication::getCommandLineParameters().contains ("--no-window")) // --no-window: is it the UI?
  5677. mainWindow->reveal();
  5678. juce::String error;
  5679. auto ok = false;
  5680. const auto loadStart = juce::Time::getMillisecondCounterHiRes();
  5681. if (project.hasFileExtension ("flp"))
  5682. ok = engine->importFlpFile (project, error);
  5683. else if (auto song = lynx::ProjectFile::load (project, error))
  5684. {
  5685. engine->setSong (std::move (*song));
  5686. ok = true;
  5687. }
  5688. const auto loadMs = juce::Time::getMillisecondCounterHiRes() - loadStart;
  5689. if (! ok)
  5690. {
  5691. report.replaceWithText ("project: " + project.getFullPathName() + "\nresult=ERROR " + error + "\n");
  5692. restoreSavedDeviceState();
  5693. setApplicationReturnValue (1);
  5694. quit();
  5695. return;
  5696. }
  5697. if (recordTo.isNotEmpty())
  5698. engine->setAudioRecordingArmed (true); // opens the input of the driver
  5699. // let the window draw the project, then play from the start with fresh statistics
  5700. juce::Timer::callAfterDelay (1500, [this, project, report, seconds, loadMs, recordTo] {
  5701. if (engine == nullptr)
  5702. return;
  5703. engine->stop();
  5704. engine->rewind();
  5705. engine->getRtStats().reset();
  5706. engine->takeUiPulse();
  5707. if (recordTo.isNotEmpty())
  5708. engine->setRecording (true);
  5709. // --log folder: the audio logger records what the Master plays during the run (realtime vs export checks)
  5710. const auto& cli = juce::JUCEApplication::getCommandLineParameterArray();
  5711. if (const auto at = cli.indexOf ("--log"); at >= 0 && at + 1 < cli.size())
  5712. engine->getAudioLogger().start (juce::File (cli[at + 1].unquoted()), engine->getDeviceManager().getCurrentAudioDevice() != nullptr
  5713. ? engine->getDeviceManager().getCurrentAudioDevice()->getCurrentSampleRate() : 44100.0);
  5714. engine->play();
  5715. startBackupTest();
  5716. juce::Timer::callAfterDelay ((int) (seconds * 1000.0), [this, project, report, seconds, loadMs, recordTo] {
  5717. if (engine == nullptr)
  5718. return;
  5719. const auto backupReport = finishBackupTest();
  5720. engine->stop();
  5721. juce::String recording;
  5722. if (engine->getAudioLogger().isLogging())
  5723. {
  5724. recording << " logged: " << engine->getAudioLogger().currentFile().getFullPathName() << "\n";
  5725. engine->getAudioLogger().stop();
  5726. }
  5727. if (recordTo.isNotEmpty())
  5728. recording = finishStressTake (juce::File (recordTo), seconds);
  5729. const auto& cli = juce::JUCEApplication::getCommandLineParameterArray();
  5730. const auto s = engine->getRtStats().snapshot();
  5731. juce::String text;
  5732. text << "project: " << project.getFullPathName() << "\n"
  5733. << "LYNX " << getApplicationVersion() << ", " << juce::SystemStats::getOperatingSystemName() << ", "
  5734. << juce::SystemStats::getNumCpus() << " logical CPUs (" << juce::SystemStats::getNumPhysicalCpus() << " cores), "
  5735. << juce::SystemStats::getCpuModel() << "\n"
  5736. << "load " << juce::String (loadMs / 1000.0, 1) << " s, played " << juce::String (seconds, 0) << " s\n"
  5737. << engine->describeRealtime();
  5738. const auto pulse = engine->takeUiPulse();
  5739. text << " UI: the 30 Hz engine timer ran " << pulse.calls << " times (" << juce::String (pulse.calls / seconds, 1)
  5740. << "/s), longest gap " << juce::String (pulse.maxGapMs, 0) << " ms" << (mainWindow == nullptr || ! mainWindow->isVisible() ? " (window hidden)" : "") << "\n";
  5741. text << " load histogram (share of the deadline: callbacks):";
  5742. for (std::size_t b = 0; b < s.histogram.size(); ++b)
  5743. if (s.histogram[b] > 0)
  5744. text << " " << (int) (b * 10) << (b + 1 == s.histogram.size() ? juce::String ("+") : "-" + juce::String ((int) (b * 10 + 10))) << "%:" << (juce::int64) s.histogram[b];
  5745. text << "\n";
  5746. text << recording << backupReport;
  5747. // --settingsshot file.png (round 161): Options > Audio settings of this run's device, as a picture
  5748. if (const auto at = cli.indexOf ("--settingsshot"); at >= 0 && at + 1 < cli.size())
  5749. {
  5750. auto page = lynx::makeSettingsPanel (*engine, lynx::SettingsPage::audio);
  5751. juce::Image image (juce::Image::ARGB, page->getWidth(), page->getHeight(), true);
  5752. {
  5753. juce::Graphics g (image);
  5754. g.fillAll (lynx::theme::panel);
  5755. page->paintEntireComponent (g, false);
  5756. }
  5757. const juce::File shot (cli[at + 1].unquoted());
  5758. shot.deleteFile();
  5759. if (auto out = shot.createOutputStream())
  5760. juce::PNGImageFormat().writeImageToStream (image, *out);
  5761. }
  5762. text << "result=" << (s.callbacks == 0 ? "ERROR no audio callbacks" : s.overBudget == 0 && s.lateCalls == 0 ? "OK" : "GLITCHES") << "\n";
  5763. report.replaceWithText (text);
  5764. restoreSavedDeviceState();
  5765. setApplicationReturnValue (s.callbacks == 0 ? 1 : 0);
  5766. quit();
  5767. });
  5768. });
  5769. }
  5770. // --bendrectest (round 167a): see the command line above
  5771. void runBendRecordTest (const juce::File& report, bool songMode)
  5772. {
  5773. engine = std::make_unique<lynx::AudioEngine>();
  5774. auto text = std::make_shared<juce::String>();
  5775. auto step = [report, text] (const juce::String& line) { *text << line << "\n"; report.replaceWithText (*text); };
  5776. auto finish = [this] (int code) {
  5777. setApplicationReturnValue (code);
  5778. quit();
  5779. };
  5780. auto* device = engine->getDeviceManager().getCurrentAudioDevice();
  5781. if (device == nullptr)
  5782. {
  5783. step ("result=ERROR no audio device");
  5784. finish (1);
  5785. return;
  5786. }
  5787. step ("device=" + device->getTypeName() + " | " + device->getName() + " | mode " + (songMode ? "song" : "pattern"));
  5788. auto song = lynx::Song::makeDefault();
  5789. song.bpm = 120.0;
  5790. song.mode = songMode ? lynx::PlayMode::song : lynx::PlayMode::pattern;
  5791. engine->setSong (std::move (song));
  5792. auto o = engine->getRecordOptions();
  5793. o.mode = lynx::RecordMode::overdub;
  5794. o.recordNotes = true;
  5795. o.recordAutomation = true;
  5796. o.countInBars = 0;
  5797. o.waitForInput = false;
  5798. o.quantiseAutomation = false;
  5799. o.punchLoopRegion = false;
  5800. o.preRollBars = o.postRollBars = 0;
  5801. engine->setRecordOptions (o);
  5802. engine->stop();
  5803. engine->rewind();
  5804. engine->setRecording (true);
  5805. engine->startPlayback();
  5806. // 2 s of wheel at ~100 messages a second: 0 → +1 (0.5 s), +1 → −1 (1 s), −1 → 0 (0.5 s)
  5807. auto sent = std::make_shared<std::vector<std::pair<double, float>>>();
  5808. auto t0 = std::make_shared<double> (juce::Time::getMillisecondCounterHiRes());
  5809. engine->injectMidiInput (juce::MidiMessage::noteOn (1, 60, (juce::uint8) 100));
  5810. auto tick = std::make_shared<std::function<void()>>();
  5811. *tick = [this, sent, t0, tick, step, finish, songMode] {
  5812. if (engine == nullptr)
  5813. return;
  5814. const auto ms = juce::Time::getMillisecondCounterHiRes() - *t0;
  5815. if (ms < 2000.0)
  5816. {
  5817. const auto x = ms / 1000.0;
  5818. 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);
  5819. const auto wheel = juce::jlimit (0, 16383, 8192 + juce::roundToInt (v * 8191.0f));
  5820. engine->injectMidiInput (juce::MidiMessage::pitchWheel (1, wheel));
  5821. sent->push_back ({ ms, (float) (wheel - 8192) / 8192.0f });
  5822. juce::Timer::callAfterDelay (10, *tick);
  5823. return;
  5824. }
  5825. engine->injectMidiInput (juce::MidiMessage::pitchWheel (1, 8192));
  5826. engine->injectMidiInput (juce::MidiMessage::noteOff (1, 60));
  5827. juce::Timer::callAfterDelay (400, [this, sent, step, finish, songMode] {
  5828. if (engine == nullptr)
  5829. return;
  5830. engine->stop();
  5831. juce::Timer::callAfterDelay (600, [this, sent, step, finish, songMode] {
  5832. if (engine == nullptr)
  5833. return;
  5834. engine->setRecording (false);
  5835. const auto& s = engine->getSong();
  5836. // the channel's pitch bend (MIDI channel 1), recorded as a lane or a clip
  5837. std::vector<std::pair<std::int64_t, float>> got;
  5838. juce::String where = "nothing";
  5839. for (const auto& a : s.automations)
  5840. if (a.target.kind == lynx::AutomationTargetKind::channelParam && lynx::midictl::isPitchBend (a.target.param))
  5841. {
  5842. where = "automation clip \"" + juce::String (a.name) + "\"";
  5843. for (const auto& pt : a.points)
  5844. got.push_back ({ pt.tick, pt.value });
  5845. }
  5846. for (const auto& p : s.patterns)
  5847. for (const auto& lane : p.events)
  5848. if (lane.target.kind == lynx::AutomationTargetKind::channelParam && lynx::midictl::isPitchBend (lane.target.param))
  5849. {
  5850. where = "pattern \"" + juce::String (p.name) + "\" event lane";
  5851. for (const auto& e : lane.events)
  5852. got.push_back ({ e.tick, e.value });
  5853. }
  5854. int notes = 0;
  5855. for (const auto& p : s.patterns)
  5856. notes += (int) p.notes.size();
  5857. float lo = 1.0f, hi = 0.0f;
  5858. for (const auto& [t, v] : got)
  5859. lo = std::min (lo, v), hi = std::max (hi, v);
  5860. // ticks: in order, spread over the ~2 s sweep (8 beats of 96 ticks at 120 bpm ≈ 4 beats)
  5861. const auto span = got.empty() ? 0 : got.back().first - got.front().first;
  5862. const auto sorted = std::is_sorted (got.begin(), got.end(), [] (const auto& a, const auto& b) { return a.first < b.first; });
  5863. step ("sent=" + juce::String ((int) sent->size()) + " wheel messages over 2 s");
  5864. step ("recorded=" + juce::String ((int) got.size()) + " points in " + where + ", value " + juce::String (lo, 3) + " .. "
  5865. + juce::String (hi, 3) + " (0.5 = centre), ticks " + juce::String (span) + " apart, " + (sorted ? "in order" : "OUT OF ORDER")
  5866. + ", notes " + juce::String (notes));
  5867. if (! got.empty())
  5868. step ("last=" + juce::String (got.back().second, 3));
  5869. // song mode: a clip over the take, ending back at the centre. Pattern mode: the take loops the 1-bar pattern
  5870. // (4.6 beats of take), so the lane spans the bar and the last wheel message (the centre) lands inside it
  5871. const auto centred = std::any_of (got.begin(), got.end(), [] (const auto& p) { return std::abs (p.second - 0.5f) < 0.02f; });
  5872. const auto ok = got.size() >= 20 && hi > 0.97f && lo < 0.03f && sorted && notes >= 1
  5873. && (songMode ? span > lynx::ppq * 3 && span < lynx::ppq * 6 && std::abs (got.back().second - 0.5f) < 0.02f
  5874. : span > lynx::ppq * 2 && span <= lynx::ppq * 4 && centred);
  5875. step (ok ? "result=OK" : "result=FAILED");
  5876. finish (ok ? 0 : 1);
  5877. });
  5878. });
  5879. };
  5880. juce::Timer::callAfterDelay (300, *tick);
  5881. }
  5882. // --countinrectest (round 170d): see the command line above.
  5883. void runCountInRecordTest (const juce::File& report)
  5884. {
  5885. engine = std::make_unique<lynx::AudioEngine>();
  5886. engine->getDeviceManager().closeAudioDevice(); // the engine's callback is driven by hand below
  5887. struct StandIn final : juce::AudioIODevice
  5888. {
  5889. StandIn() : juce::AudioIODevice ("countin", "test") {}
  5890. juce::StringArray getOutputChannelNames() override { return { "L", "R" }; }
  5891. juce::StringArray getInputChannelNames() override { return {}; }
  5892. juce::Array<double> getAvailableSampleRates() override { return { 48000.0 }; }
  5893. juce::Array<int> getAvailableBufferSizes() override { return { 512 }; }
  5894. int getDefaultBufferSize() override { return 512; }
  5895. juce::String open (const juce::BigInteger&, const juce::BigInteger&, double, int) override { return {}; }
  5896. void close() override {}
  5897. bool isOpen() override { return true; }
  5898. void start (juce::AudioIODeviceCallback*) override {}
  5899. void stop() override {}
  5900. bool isPlaying() override { return true; }
  5901. juce::String getLastError() override { return {}; }
  5902. int getCurrentBufferSizeSamples() override { return 512; }
  5903. double getCurrentSampleRate() override { return 48000.0; }
  5904. int getCurrentBitDepth() override { return 32; }
  5905. juce::BigInteger getActiveOutputChannels() const override
  5906. {
  5907. juce::BigInteger b;
  5908. b.setRange (0, 2, true);
  5909. return b;
  5910. }
  5911. juce::BigInteger getActiveInputChannels() const override { return {}; }
  5912. int getOutputLatencyInSamples() override { return 256; }
  5913. int getInputLatencyInSamples() override { return 0; }
  5914. };
  5915. auto device = std::make_shared<StandIn>();
  5916. auto text = std::make_shared<juce::String>();
  5917. auto step = [report, text] (const juce::String& line) { *text << line << "\n"; report.replaceWithText (*text); };
  5918. auto finish = [this] (int code) {
  5919. setApplicationReturnValue (code);
  5920. quit();
  5921. };
  5922. constexpr std::int64_t bar = 4 * lynx::ppq; // 120 BPM, 4/4
  5923. lynx::Song song; // (as --cliplooptest: one synth channel on insert 1, an empty pattern)
  5924. song.bpm = 120.0;
  5925. song.mixer = lynx::Song::defaultMixer (2);
  5926. song.channels.resize (1);
  5927. song.channels[0].mixerTrack = 1;
  5928. song.patterns.emplace_back();
  5929. song.mode = lynx::PlayMode::song;
  5930. song.currentPattern = 0;
  5931. engine->setSong (song);
  5932. engine->getTransport().metronome.store (true);
  5933. auto o = engine->getRecordOptions();
  5934. o.mode = lynx::RecordMode::overdub;
  5935. o.countInBars = 1;
  5936. o.catchWindow = lynx::ppq / 4;
  5937. o.compensateOutput = true;
  5938. o.recordNotes = true;
  5939. o.recordAudio = false;
  5940. o.recordAutomation = false;
  5941. o.waitForInput = false;
  5942. o.quantise = 0;
  5943. o.placeSongClip = true;
  5944. o.recordingMarkers = false;
  5945. o.punchLoopRegion = false;
  5946. o.preRollBars = o.postRollBars = 0;
  5947. engine->setRecordOptions (o);
  5948. engine->deviceCallback().audioDeviceAboutToStart (device.get());
  5949. 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");
  5950. // an event heard at output sample `heard` (counted from the first block after Play), sent as MIDI input
  5951. struct Event
  5952. {
  5953. std::int64_t heard;
  5954. juce::MidiMessage message;
  5955. };
  5956. struct Pass
  5957. {
  5958. std::vector<float> out;
  5959. std::vector<Event> events;
  5960. std::int64_t playingAt = -1; // the first sample of the block the song started in
  5961. int block = 0, blocks = 0;
  5962. std::function<void()> done;
  5963. };
  5964. constexpr int n = 512;
  5965. constexpr double rate = 48000.0;
  5966. // one pass: the take recorded from bar 3, `blocks` blocks driven by hand, 8 at a time between the engine's timer
  5967. // ticks (the take is committed there); then stopped and its results left to the timer
  5968. auto runPass = std::make_shared<std::function<void (std::shared_ptr<Pass>)>>();
  5969. *runPass = [this] (std::shared_ptr<Pass> pass) {
  5970. auto& cb = engine->deviceCallback();
  5971. std::vector<float> l (n), r (n);
  5972. float* outs[] = { l.data(), r.data() };
  5973. juce::AudioIODeviceCallbackContext context;
  5974. if (pass->block == 0)
  5975. {
  5976. engine->stop();
  5977. engine->seek ((double) (2 * bar));
  5978. cb.audioDeviceIOCallbackWithContext (nullptr, 0, outs, 2, n, context); // (the seek, stopped)
  5979. engine->setRecording (true);
  5980. engine->startPlayback(); // the count-in starts
  5981. }
  5982. for (int k = 0; k < 8 && pass->block < pass->blocks; ++k, ++pass->block)
  5983. {
  5984. // the events heard in this block: stamped the way the engine's clock maps time to heard samples
  5985. const auto blockStart = (std::int64_t) pass->block * n;
  5986. const auto clock = engine->liveClock();
  5987. const auto compMs = 1000.0 * (n + 256) / rate;
  5988. for (auto& e : pass->events)
  5989. if (e.heard >= blockStart && e.heard < blockStart + n)
  5990. {
  5991. auto m = e.message;
  5992. m.setTimeStamp ((clock.timeMs + compMs + (double) (e.heard - blockStart) * 1000.0 / rate) * 0.001);
  5993. engine->injectMidiInput (m);
  5994. }
  5995. cb.audioDeviceIOCallbackWithContext (nullptr, 0, outs, 2, n, context);
  5996. pass->out.insert (pass->out.end(), l.begin(), l.end());
  5997. if (pass->playingAt < 0 && engine->getTransport().playing.load())
  5998. pass->playingAt = blockStart;
  5999. }
  6000. };
  6001. // (the recursion through the message loop; written out so each step lets the engine's timer run)
  6002. auto drive = std::make_shared<std::function<void (std::shared_ptr<Pass>)>>();
  6003. *drive = [this, runPass, drive, device] (std::shared_ptr<Pass> pass) { // (the stand-in lives while the passes run)
  6004. if (engine == nullptr)
  6005. return;
  6006. (*runPass) (pass);
  6007. if (pass->block < pass->blocks)
  6008. {
  6009. juce::Timer::callAfterDelay (40, [pass, drive] { (*drive) (pass); });
  6010. return;
  6011. }
  6012. engine->stop();
  6013. juce::Timer::callAfterDelay (300, [this, pass] {
  6014. if (engine == nullptr)
  6015. return;
  6016. engine->setRecording (false);
  6017. juce::Timer::callAfterDelay (200, [pass] { pass->done(); });
  6018. });
  6019. };
  6020. auto onsets = [] (const std::vector<float>& out) {
  6021. std::vector<std::int64_t> at;
  6022. std::int64_t last = -100000;
  6023. for (std::size_t i = 0; i < out.size(); ++i)
  6024. if (std::abs (out[i]) > 0.02f && (std::int64_t) i - last > 4000)
  6025. {
  6026. at.push_back ((std::int64_t) i);
  6027. last = (std::int64_t) i;
  6028. }
  6029. else if (std::abs (out[i]) > 0.02f)
  6030. last = (std::int64_t) i;
  6031. return at;
  6032. };
  6033. // the graph is (re)built on the message thread: start once it has settled
  6034. juce::Timer::callAfterDelay (1500, [this, step, finish, drive, onsets] {
  6035. if (engine == nullptr)
  6036. return;
  6037. auto first = std::make_shared<Pass>();
  6038. first->blocks = (int) (rate * 18.0 / n); // count-in + 8 bars
  6039. first->done = [this, first, step, finish, drive, onsets] {
  6040. const auto clicks = onsets (first->out);
  6041. juce::String list;
  6042. for (std::size_t i = 0; i < std::min<std::size_t> (clicks.size(), 8); ++i)
  6043. list << clicks[i] << " ";
  6044. step ("pass 1: clicks heard at samples " + list + "…, the song started in the block at " + juce::String (first->playingAt));
  6045. // the bar-3 downbeat: the click at the block the song started in
  6046. std::int64_t down = -1;
  6047. for (auto c : clicks)
  6048. if (std::abs (c - first->playingAt) < n)
  6049. down = c;
  6050. if (down < 0 || engine->getSong().patterns[0].notes.size() != 0)
  6051. {
  6052. step ("result=FAILED no downbeat click found (or notes recorded without input)");
  6053. finish (1);
  6054. return;
  6055. }
  6056. const auto ms = [down] (double t) { return down + (std::int64_t) std::llround (t * rate / 1000.0); };
  6057. auto second = std::make_shared<Pass>();
  6058. second->blocks = first->blocks;
  6059. auto add = [&second] (std::int64_t at, int key, bool on) {
  6060. second->events.push_back ({ at, on ? juce::MidiMessage::noteOn (1, key, (juce::uint8) 100) : juce::MidiMessage::noteOff (1, key) });
  6061. };
  6062. for (int key : { 60, 64, 67 }) // the chord, 15 ms early, held half a second
  6063. {
  6064. add (ms (-15.0), key, true);
  6065. add (ms (500.0), key, false);
  6066. }
  6067. add (ms (-1500.0), 62, true); // beat 2 of the count-in bar (bar 2)
  6068. add (ms (-1250.0), 62, false);
  6069. add (ms (503.0), 77, true); // 3 ms after beat 2
  6070. add (ms (603.0), 77, false);
  6071. for (int b = 1; b <= 6; ++b) // a note a bar ("it stopped after two bars")
  6072. {
  6073. add (ms (b * 2000.0), 70 + b, true);
  6074. add (ms (b * 2000.0 + 250.0), 70 + b, false);
  6075. }
  6076. second->done = [this, step, finish] {
  6077. const auto& s = engine->getSong();
  6078. const auto& p = s.patterns[0];
  6079. const lynx::Clip* clip = nullptr;
  6080. for (const auto& c : s.playlist)
  6081. if (c.kind == lynx::ClipKind::pattern && c.pattern == 0)
  6082. clip = &c;
  6083. const auto origin = clip != nullptr ? clip->start - clip->offset : -1;
  6084. step ("pass 2: " + juce::String ((int) p.notes.size()) + " notes recorded, clip at " + juce::String (clip != nullptr ? clip->start : -1));
  6085. auto ok = clip != nullptr && origin == bar && p.notes.size() == 11;
  6086. // where each one was heard (song ticks): 0.5 ms = ~1 tick
  6087. const std::vector<std::pair<int, double>> want = { { 60, 2.0 * bar }, { 64, 2.0 * bar }, { 67, 2.0 * bar },
  6088. { 62, 2.0 * bar - 3 * lynx::ppq }, { 77, 2.0 * bar + lynx::ppq + 3.0 * 1.92 },
  6089. { 71, 3.0 * bar }, { 72, 4.0 * bar }, { 73, 5.0 * bar },
  6090. { 74, 6.0 * bar }, { 75, 7.0 * bar }, { 76, 8.0 * bar } };
  6091. for (const auto& [key, tick] : want)
  6092. {
  6093. const lynx::Note* found = nullptr;
  6094. for (const auto& note : p.notes)
  6095. if (note.key == key)
  6096. found = &note;
  6097. const auto at = found != nullptr ? (double) (origin + found->start) : -1.0;
  6098. const auto good = found != nullptr && std::abs (at - tick) <= 2.0;
  6099. ok = ok && good;
  6100. step ("key " + juce::String (key) + ": heard at tick " + juce::String (tick, 2) + ", recorded at " + juce::String (at, 0)
  6101. + (good ? " ok" : " WRONG"));
  6102. }
  6103. const auto* chord = [&p] () -> const lynx::Note* {
  6104. for (const auto& note : p.notes)
  6105. if (note.key == 60)
  6106. return &note;
  6107. return nullptr;
  6108. }();
  6109. if (chord != nullptr)
  6110. step ("chord length " + juce::String (chord->length) + " ticks (caught 15 ms early, released 500 ms after bar 3: 960)");
  6111. step (ok ? "result=OK" : "result=FAILED");
  6112. finish (ok ? 0 : 1);
  6113. };
  6114. (*drive) (second);
  6115. };
  6116. (*drive) (first);
  6117. });
  6118. }
  6119. // --cliplooptest (round 167q): see the command line above.
  6120. void runClipLoopTest (const juce::File& report, const juce::File& wavFile)
  6121. {
  6122. engine = std::make_unique<lynx::AudioEngine>();
  6123. engine->getDeviceManager().closeAudioDevice(); // the engine's callback is driven by hand below
  6124. struct StandIn final : juce::AudioIODevice
  6125. {
  6126. StandIn() : juce::AudioIODevice ("cliploop", "test") {}
  6127. juce::StringArray getOutputChannelNames() override { return { "L", "R" }; }
  6128. juce::StringArray getInputChannelNames() override { return {}; }
  6129. juce::Array<double> getAvailableSampleRates() override { return { 48000.0 }; }
  6130. juce::Array<int> getAvailableBufferSizes() override { return { 512 }; }
  6131. int getDefaultBufferSize() override { return 512; }
  6132. juce::String open (const juce::BigInteger&, const juce::BigInteger&, double, int) override { return {}; }
  6133. void close() override {}
  6134. bool isOpen() override { return true; }
  6135. void start (juce::AudioIODeviceCallback*) override {}
  6136. void stop() override {}
  6137. bool isPlaying() override { return true; }
  6138. juce::String getLastError() override { return {}; }
  6139. int getCurrentBufferSizeSamples() override { return 512; }
  6140. double getCurrentSampleRate() override { return 48000.0; }
  6141. int getCurrentBitDepth() override { return 32; }
  6142. juce::BigInteger getActiveOutputChannels() const override
  6143. {
  6144. juce::BigInteger b;
  6145. b.setRange (0, 2, true);
  6146. return b;
  6147. }
  6148. juce::BigInteger getActiveInputChannels() const override { return {}; }
  6149. int getOutputLatencyInSamples() override { return 0; }
  6150. int getInputLatencyInSamples() override { return 0; }
  6151. };
  6152. auto device = std::make_shared<StandIn>();
  6153. auto text = std::make_shared<juce::String>();
  6154. auto step = [report, text] (const juce::String& line) { *text << line << "\n"; report.replaceWithText (*text); };
  6155. constexpr int bar = 96000, beat = bar / 4; // 120 BPM, 48 kHz
  6156. const auto ppq = (double) lynx::ppq;
  6157. lynx::Song song;
  6158. song.bpm = 120.0;
  6159. song.mixer = lynx::Song::defaultMixer (2);
  6160. song.channels.resize (1); // the synth of a new channel: deterministic
  6161. song.channels[0].mixerTrack = 1;
  6162. auto& pattern = song.patterns.emplace_back(); // 1 bar: C5 on beat 0, C6 on beat 2
  6163. for (auto [b, key] : { std::pair { 0, 60 }, std::pair { 2, 72 } })
  6164. {
  6165. lynx::Note n;
  6166. n.start = b * lynx::ppq;
  6167. n.length = lynx::ppq / 4;
  6168. n.key = key;
  6169. pattern.notes.push_back (n);
  6170. }
  6171. lynx::Clip clip;
  6172. clip.pattern = 0;
  6173. clip.length = 16 * lynx::ppq; // stretched to 4 bars
  6174. song.playlist.push_back (clip);
  6175. song.mode = lynx::PlayMode::song;
  6176. {
  6177. // the Windows GUI check's project: the same song with a 1-bar clip, to stretch with the mouse
  6178. auto gui = song;
  6179. gui.playlist[0].length = 4 * lynx::ppq;
  6180. juce::String error;
  6181. lynx::ProjectFile::save (gui, report.getSiblingFile ("cliploop-gui.lynx"), error);
  6182. }
  6183. engine->setSong (song);
  6184. auto& callback = engine->deviceCallback();
  6185. callback.audioDeviceAboutToStart (device.get());
  6186. step ("song=1-bar synth pattern, clip stretched to 4 bars, 120 BPM, 48 kHz, blocks of 512");
  6187. // the graph is (re)built on the message thread: the scenarios run once it has settled
  6188. juce::Timer::callAfterDelay (1500, [this, device, step, wavFile, ppq] {
  6189. if (engine == nullptr)
  6190. return;
  6191. auto& cb = engine->deviceCallback();
  6192. // plays `samples` from tick `from` through the device callback; `between` runs after each block (block index)
  6193. auto play = [this, &cb] (double from, int samples, const std::function<void (int)>& between = {}) {
  6194. engine->stop();
  6195. engine->seek (from);
  6196. std::vector<float> l (512), r (512), out;
  6197. float* outs[] = { l.data(), r.data() };
  6198. juce::AudioIODeviceCallbackContext context;
  6199. cb.audioDeviceIOCallbackWithContext (nullptr, 0, outs, 2, 512, context); // (the seek, stopped)
  6200. engine->play();
  6201. for (int k = 0; (int) out.size() < samples; ++k)
  6202. {
  6203. cb.audioDeviceIOCallbackWithContext (nullptr, 0, outs, 2, 512, context);
  6204. out.insert (out.end(), l.begin(), l.end());
  6205. if (between)
  6206. between (k);
  6207. }
  6208. engine->stop();
  6209. for (int k = 0; k < 400; ++k) // the tails of the scenario die out
  6210. cb.audioDeviceIOCallbackWithContext (nullptr, 0, outs, 2, 512, context);
  6211. out.resize ((std::size_t) samples);
  6212. return out;
  6213. };
  6214. auto rms = [] (const std::vector<float>& x, int from, int count) {
  6215. double sum = 0.0;
  6216. for (int i = from; i < from + count && i < (int) x.size(); ++i)
  6217. sum += (double) x[(std::size_t) i] * x[(std::size_t) i];
  6218. return std::sqrt (sum / juce::jmax (1, count));
  6219. };
  6220. auto diff = [] (const std::vector<float>& a, int aFrom, const std::vector<float>& b, int bFrom, int count) {
  6221. double m = 0.0;
  6222. for (int i = 0; i < count && aFrom + i < (int) a.size() && bFrom + i < (int) b.size(); ++i)
  6223. m = juce::jmax (m, (double) std::abs (a[(std::size_t) (aFrom + i)] - b[(std::size_t) (bFrom + i)]));
  6224. return m;
  6225. };
  6226. auto num = [] (double v) { return juce::String (v, 6); };
  6227. bool ok = true;
  6228. auto check = [&ok, step] (bool good, const juce::String& what) {
  6229. ok = ok && good;
  6230. step ((good ? "ok " : "FAIL ") + what);
  6231. };
  6232. lynx::setStretchedClipsLoop (true);
  6233. const auto a = play (0.0, 4 * bar);
  6234. const auto bar1 = rms (a, 0, bar);
  6235. check (bar1 > 0.01, "play from the start: bar 1 RMS " + num (bar1));
  6236. for (int k = 1; k < 4; ++k)
  6237. {
  6238. const auto rk = rms (a, k * bar, bar), d = diff (a, k * bar, a, 0, bar);
  6239. check (std::abs (rk / bar1 - 1.0) < 1.0e-3 && d < 1.0e-4,
  6240. "bar " + juce::String (k + 1) + " RMS " + num (rk) + " (x" + num (rk / bar1) + " of bar 1), max |bar - bar 1| " + juce::String (d, 9));
  6241. }
  6242. {
  6243. const auto x = play (10 * ppq, bar + bar / 2);
  6244. const auto d = juce::jmax (diff (x, 0, a, 2 * beat, bar / 2), diff (x, bar / 2, a, 0, bar));
  6245. check (rms (x, 0, bar / 2) > 0.01 && d < 1.0e-4,
  6246. "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));
  6247. }
  6248. {
  6249. // a seek while playing, after 6.99 beats, to bar 4 beat 3 (a ruler click)
  6250. const auto jumpBlock = 7 * beat / 512 - 1;
  6251. const auto x = play (0.0, 2 * bar, [this, jumpBlock, ppq] (int k) {
  6252. if (k == jumpBlock)
  6253. engine->seek (14 * ppq);
  6254. });
  6255. // (the best of 0-2 samples late: anything but 0 fails)
  6256. const auto at = (jumpBlock + 1) * 512;
  6257. int lag = 0;
  6258. auto d = 1.0e9;
  6259. for (int l = 0; l <= 2; ++l)
  6260. if (const auto dl = diff (x, at + l, a, 2 * beat, beat - 2); dl < d)
  6261. d = dl, lag = l;
  6262. d = lag == 0 ? d : 1.0;
  6263. const auto ratio = rms (x, at, beat) / rms (a, 2 * beat, beat);
  6264. check (std::abs (ratio - 1.0) < 1.0e-3 && d < 1.0e-4,
  6265. "jump mid-clip to bar 4 beat 3: RMS " + num (rms (x, at, beat)) + " (x" + num (ratio) + " of bar 1 beat 3), max diff "
  6266. + juce::String (d, 9) + " (" + juce::String (lag) + " sample(s) late)");
  6267. }
  6268. {
  6269. engine->editSong ([ppq] (lynx::Song& s) {
  6270. s.loopStart = (std::int64_t) (4 * ppq);
  6271. s.loopEnd = (std::int64_t) (12 * ppq);
  6272. }, false);
  6273. const auto x = play (0.0, 7 * bar);
  6274. double d = 0.0;
  6275. juce::String lags;
  6276. for (int k = 1; k < 7; ++k) // (the best of 0-2 samples late after a wrap, as after a jump)
  6277. {
  6278. auto best = 1.0e9;
  6279. int lag = 0;
  6280. for (int l = 0; l <= 2; ++l)
  6281. if (const auto dl = diff (x, k * bar + l, a, 0, bar - 2); dl < best)
  6282. best = dl, lag = l;
  6283. d = juce::jmax (d, lag == 0 ? best : 1.0); // a sample gained at a wrap fails (round 167q loopwrap)
  6284. lags << (k > 1 ? "," : "") << lag;
  6285. }
  6286. const auto r = rms (x, bar, 6 * bar);
  6287. check (std::abs (r / bar1 - 1.0) < 1.0e-3 && d < 1.0e-4,
  6288. "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)
  6289. + " (samples late, bars 2-7: " + lags + ")");
  6290. engine->editSong ([] (lynx::Song& s) { s.loopStart = s.loopEnd = 0; }, false);
  6291. }
  6292. {
  6293. // 100 wraps of a 1-bar loop region (bar 2): every pass on its sample, none gained (round 167q loopwrap: each
  6294. // wrap used to play one sample more)
  6295. engine->editSong ([ppq] (lynx::Song& s) {
  6296. s.loopStart = (std::int64_t) (4 * ppq);
  6297. s.loopEnd = (std::int64_t) (8 * ppq);
  6298. }, false);
  6299. const auto x = play (0.0, 101 * bar);
  6300. double d = 0.0;
  6301. int worst = 0;
  6302. for (int k = 1; k <= 100; ++k)
  6303. if (const auto dk = diff (x, k * bar, a, 0, bar); dk > d)
  6304. d = dk, worst = k + 1;
  6305. check (d < 1.0e-4, "loop region bar 2, 100 wraps: max diff of every pass vs bar 1 " + juce::String (d, 9)
  6306. + (d < 1.0e-4 ? juce::String() : " (worst: bar " + juce::String (worst) + ")"));
  6307. engine->editSong ([] (lynx::Song& s) { s.loopStart = s.loopEnd = 0; }, false);
  6308. }
  6309. lynx::setStretchedClipsLoop (false);
  6310. {
  6311. const auto x = play (0.0, 4 * bar);
  6312. const auto r = juce::jmax (rms (x, bar, bar), juce::jmax (rms (x, 2 * bar, bar), rms (x, 3 * bar, bar)));
  6313. 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));
  6314. }
  6315. lynx::setStretchedClipsLoop (true);
  6316. cb.audioDeviceStopped();
  6317. // the export: a WAV of the 4 bars, read back from the file
  6318. if (wavFile != juce::File())
  6319. {
  6320. for (const auto loops : { true, false })
  6321. {
  6322. lynx::setStretchedClipsLoop (loops);
  6323. const auto file = loops ? wavFile : wavFile.getSiblingFile (wavFile.getFileNameWithoutExtension() + "-off.wav");
  6324. file.deleteFile();
  6325. {
  6326. juce::WavAudioFormat wav;
  6327. std::unique_ptr<juce::AudioFormatWriter> writer (wav.createWriterFor (file.createOutputStream().release(), 48000.0, 2, 32, {}, 0));
  6328. engine->stop();
  6329. engine->seek (0.0);
  6330. lynx::AudioEngine::RenderOptions o;
  6331. o.seconds = 8.0;
  6332. o.sampleRate = 48000.0;
  6333. o.output = writer.get();
  6334. engine->renderOffline (o);
  6335. }
  6336. juce::WavAudioFormat wav;
  6337. std::unique_ptr<juce::AudioFormatReader> reader (wav.createReaderFor (file.createInputStream().release(), true));
  6338. std::vector<float> x;
  6339. if (reader != nullptr)
  6340. {
  6341. juce::AudioBuffer<float> buffer (2, (int) reader->lengthInSamples);
  6342. reader->read (&buffer, 0, (int) reader->lengthInSamples, 0, true, true);
  6343. x.assign (buffer.getReadPointer (0), buffer.getReadPointer (0) + buffer.getNumSamples());
  6344. }
  6345. const auto b1 = rms (x, 0, bar);
  6346. juce::String line = juce::String (loops ? "export" : "export, option off") + " (" + file.getFileName() + ", " + juce::String ((int) x.size()) + " samples): bar 1 RMS " + num (b1);
  6347. bool good = x.size() >= (std::size_t) 4 * bar && b1 > 0.01;
  6348. for (int k = 1; k < 4; ++k)
  6349. {
  6350. const auto rk = rms (x, k * bar, bar);
  6351. line << ", bar " << (k + 1) << " " << num (rk);
  6352. 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);
  6353. }
  6354. if (loops)
  6355. 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);
  6356. check (good, line);
  6357. }
  6358. lynx::setStretchedClipsLoop (true);
  6359. }
  6360. step (ok ? "result=OK" : "result=FAILED");
  6361. setApplicationReturnValue (ok ? 0 : 1);
  6362. quit();
  6363. });
  6364. }
  6365. // --rectest (round 163): see the command line above. Writes report lines step by step (a driver that ends the
  6366. // process leaves what was done).
  6367. void runRecordTest (const juce::File& report, double seconds, const juce::String& deviceType, const juce::String& deviceName,
  6368. const juce::String& inputName, int mode, int pdcSamples, int bufferSize)
  6369. {
  6370. engine = std::make_unique<lynx::AudioEngine>();
  6371. lynx::videoview::install (*engine); // (Fruity Video Player channels: their sound tracks)
  6372. savedDeviceState = engine->getDeviceManager().createStateXml();
  6373. auto text = std::make_shared<juce::String>();
  6374. auto step = [report, text] (const juce::String& line) { *text << line << "\n"; report.replaceWithText (*text); };
  6375. auto finish = [this, step] (int code) {
  6376. restoreSavedDeviceState();
  6377. setApplicationReturnValue (code);
  6378. quit();
  6379. };
  6380. auto& devices = engine->getDeviceManager();
  6381. if (deviceType.isNotEmpty() && devices.getCurrentAudioDeviceType() != deviceType)
  6382. devices.setCurrentAudioDeviceType (deviceType, true);
  6383. {
  6384. auto setup = devices.getAudioDeviceSetup();
  6385. if (deviceName.isNotEmpty())
  6386. setup.outputDeviceName = deviceName;
  6387. if (bufferSize > 0)
  6388. setup.bufferSize = bufferSize;
  6389. if (const auto error = devices.setAudioDeviceSetup (setup, true); error.isNotEmpty())
  6390. step ("device_error=" + error);
  6391. }
  6392. if (const auto r = engine->openAudioInput (inputName.isNotEmpty() ? inputName : deviceName); r.issue != lynx::AudioEngine::InputIssue::none)
  6393. step ("input_error=" + juce::String ((int) r.issue) + " " + r.detail);
  6394. // takes go next to the report, not into the user's recordings folder
  6395. engine->setRecordingTarget (report.getSiblingFile (report.getFileNameWithoutExtension() + "-takes"), {});
  6396. auto* device = devices.getCurrentAudioDevice();
  6397. if (device == nullptr || engine->getInputChannelNames().empty())
  6398. {
  6399. step ("result=ERROR no device / no input");
  6400. finish (1);
  6401. return;
  6402. }
  6403. const auto rate = device->getCurrentSampleRate();
  6404. step ("device=" + device->getTypeName() + " | " + device->getName() + " | " + juce::String (rate) + " Hz | block " + juce::String (device->getCurrentBufferSizeSamples())
  6405. + " | driver latency in " + juce::String (device->getInputLatencyInSamples()) + " out " + juce::String (device->getOutputLatencyInSamples()));
  6406. // a click (the ping's pulse) on every beat at 120 bpm: beat k at sample k * rate / 2
  6407. const auto beats = (int) std::ceil (seconds * 2.0) + 8;
  6408. const auto clickFile = report.getSiblingFile (report.getFileNameWithoutExtension() + "-clicks.wav");
  6409. {
  6410. lynx::takes::WavTakeWriter w;
  6411. w.open (clickFile.getFullPathName().toStdString(), rate, 1, lynx::takes::SampleFormat::float32);
  6412. const auto total = (juce::int64) std::llround ((double) beats * rate / 2.0);
  6413. std::vector<float> block (4096);
  6414. for (juce::int64 at = 0; at < total; at += (juce::int64) block.size())
  6415. {
  6416. std::fill (block.begin(), block.end(), 0.0f);
  6417. for (int k = 0; k < (int) block.size(); ++k)
  6418. {
  6419. const auto f = at + k;
  6420. const auto beat = (juce::int64) std::floor ((double) f / (rate / 2.0));
  6421. const auto rel = f - (juce::int64) std::llround ((double) beat * rate / 2.0);
  6422. static constexpr float shape[] { 0.25f, 0.75f, 1.0f, 0.75f, 0.25f };
  6423. if (rel >= 0 && rel < 5)
  6424. block[(std::size_t) k] = 0.5f * shape[rel];
  6425. }
  6426. const float* d[] { block.data() };
  6427. w.write (d, (int) std::min<juce::int64> ((juce::int64) block.size(), total - at));
  6428. }
  6429. w.close();
  6430. }
  6431. lynx::Song song = lynx::Song::makeDefault();
  6432. song.bpm = 120.0;
  6433. song.mode = lynx::PlayMode::song;
  6434. song.playlist.clear();
  6435. lynx::ChannelDef c;
  6436. c.name = "Clicks";
  6437. c.instrument = lynx::InstrumentKind::audioClip;
  6438. c.samplePath = clickFile.getFullPathName().toStdString();
  6439. c.mixerTrack = 0;
  6440. c.volume = 1.0f;
  6441. song.channels.push_back (c);
  6442. lynx::Clip clip;
  6443. clip.kind = lynx::ClipKind::audio;
  6444. clip.channel = (int) song.channels.size() - 1;
  6445. clip.track = 0;
  6446. clip.start = 0;
  6447. clip.length = (std::int64_t) beats * lynx::ppq;
  6448. song.playlist.push_back (clip);
  6449. if (mode == 1) // loop recording, bars 2-4
  6450. {
  6451. song.loopStart = 4 * lynx::ppq;
  6452. song.loopEnd = 16 * lynx::ppq;
  6453. }
  6454. else if (mode == 2) // punch in/out, bars 3-4
  6455. {
  6456. song.loopStart = 8 * lynx::ppq;
  6457. song.loopEnd = 16 * lynx::ppq;
  6458. }
  6459. if (song.mixer.size() > 1)
  6460. {
  6461. song.mixer[1].name = "Loop In";
  6462. song.mixer[1].monitor = lynx::InputMonitor::off; // (the loopback must not hear itself)
  6463. }
  6464. engine->setSong (std::move (song));
  6465. engine->setInsertInput (1, 0, false);
  6466. juce::ignoreUnused (pdcSamples);
  6467. // 1) the ping
  6468. if (const auto error = engine->startLatencyPing(); error.isNotEmpty())
  6469. step ("ping_error=" + error);
  6470. juce::Timer::callAfterDelay (3500, [this, step, finish, seconds, rate, report, mode] {
  6471. if (engine == nullptr)
  6472. return;
  6473. if (engine->isPinging())
  6474. engine->cancelLatencyPing();
  6475. const auto r = engine->finishLatencyPing();
  6476. step ("ping=" + juce::String (r.ok ? "ok" : "FAILED " + juce::String (r.problem)) + " samples " + juce::String (r.samples) + " spread " + juce::String (r.spread)
  6477. + " found " + juce::String (r.found) + "/" + juce::String (r.sent) + " peak " + juce::String (juce::Decibels::gainToDecibels (r.peak, -150.0f), 1) + " dB");
  6478. const auto l = engine->currentLatency();
  6479. step ("compensation=" + juce::String (l.total()) + " (round trip " + juce::String (l.roundTrip()) + ", manual " + juce::String (l.manual) + ", pdc " + juce::String (l.pdc) + ")");
  6480. // 2) record
  6481. engine->setInsertArmed (1, true);
  6482. auto o = engine->getRecordOptions();
  6483. o.recordAudio = true;
  6484. o.countInBars = 0;
  6485. o.waitForInput = false;
  6486. o.punchLoopRegion = mode == 2;
  6487. o.preRollBars = mode == 2 ? 1 : 0;
  6488. o.postRollBars = mode == 2 ? 1 : 0;
  6489. // (round 177c: LYNX_RECTEST_BLEND_OFF=1: Blend off; LYNX_RECTEST_LAST_PASS=1: "only the last pass plays")
  6490. o.mode = juce::SystemStats::getEnvironmentVariable ("LYNX_RECTEST_BLEND_OFF", {}) == "1" ? lynx::RecordMode::replace
  6491. : lynx::RecordMode::overdub;
  6492. o.lastLoopPassPlays = juce::SystemStats::getEnvironmentVariable ("LYNX_RECTEST_LAST_PASS", {}) == "1";
  6493. engine->setRecordOptions (o);
  6494. engine->stop();
  6495. engine->rewind();
  6496. engine->setRecording (true);
  6497. juce::Timer::callAfterDelay (300, [this, step, finish, seconds, rate, report, mode] {
  6498. if (engine == nullptr)
  6499. return;
  6500. engine->startPlayback(); // (as the Play button: pre-roll / punch)
  6501. juce::Timer::callAfterDelay ((int) (seconds * 1000.0), [this, step, finish, seconds, rate, report, mode] {
  6502. if (engine == nullptr)
  6503. return;
  6504. if (mode == 2)
  6505. step (juce::String ("stopped_by_post_roll=") + (engine->getTransport().playing.load() ? "no" : "yes"));
  6506. engine->stop();
  6507. juce::Timer::callAfterDelay (500, [this, step, finish, seconds, rate, report, mode] {
  6508. if (engine == nullptr)
  6509. return;
  6510. engine->setRecording (false);
  6511. const auto& s = engine->getSong();
  6512. const auto tps = 120.0 * lynx::ppq / (60.0 * rate);
  6513. int take = -1;
  6514. for (int ch = 0; ch < (int) s.channels.size(); ++ch)
  6515. if (s.channels[(std::size_t) ch].instrument == lynx::InstrumentKind::audioClip && s.channels[(std::size_t) ch].name != "Clicks")
  6516. take = ch;
  6517. if (take < 0)
  6518. {
  6519. step ("result=ERROR no take (" + engine->getLastRecordingError() + ")");
  6520. finish (1);
  6521. return;
  6522. }
  6523. std::vector<std::vector<float>> audio;
  6524. double takeRate = 0.0;
  6525. const auto& path = s.channels[(std::size_t) take].samplePath;
  6526. lynx::takes::readWav (path, audio, &takeRate);
  6527. const auto frames = audio.empty() ? (juce::int64) 0 : (juce::int64) audio[0].size();
  6528. step ("take=" + juce::String::fromUTF8 (path.c_str()) + " frames " + juce::String (frames) + " (" + juce::String ((double) frames / rate, 3)
  6529. + " s of " + juce::String (seconds, 1) + " s played) lost " + juce::String (engine->getLostRecordingFrames()));
  6530. // the clicks in the file (peaks above -12 dBFS, one per 1/8 s at most)
  6531. std::vector<juce::int64> peaks;
  6532. if (! audio.empty())
  6533. for (juce::int64 f = 1; f + 1 < frames; ++f)
  6534. {
  6535. const auto x = std::abs (audio[0][(std::size_t) f]);
  6536. if (x > 0.25f && x >= std::abs (audio[0][(std::size_t) f - 1]) && x > std::abs (audio[0][(std::size_t) f + 1])
  6537. && (peaks.empty() || f - peaks.back() > (juce::int64) (rate / 8)))
  6538. peaks.push_back (f);
  6539. }
  6540. // every clip of the take: each click inside it against the nearest beat
  6541. int clips = 0, checked = 0, muted = 0;
  6542. double worst = 0.0, sum = 0.0;
  6543. for (const auto& c : s.playlist)
  6544. {
  6545. if (c.kind != lynx::ClipKind::audio || c.channel != take)
  6546. continue;
  6547. ++clips;
  6548. muted += c.muted ? 1 : 0;
  6549. const auto skip = ((double) c.offset + (double) c.offsetFraction) / tps; // file samples before the clip start
  6550. for (const auto f : peaks)
  6551. {
  6552. const auto intoClip = (double) f - skip;
  6553. if (intoClip < 0.0 || intoClip * tps >= (double) c.length)
  6554. continue;
  6555. const auto songTick = (double) c.start + intoClip * tps - 2.0 * tps; // (the pulse's peak is its 3rd sample)
  6556. const auto beat = std::round (songTick / lynx::ppq) * lynx::ppq;
  6557. const auto error = (songTick - beat) / tps;
  6558. worst = std::max (worst, std::abs (error));
  6559. sum += error;
  6560. ++checked;
  6561. }
  6562. step ("clip track " + juce::String (c.track) + " start " + juce::String ((juce::int64) c.start) + " length " + juce::String ((juce::int64) c.length)
  6563. + " offset " + juce::String ((juce::int64) c.offset) + juce::String (c.offsetFraction >= 0.0f ? "+" : "") + juce::String (c.offsetFraction, 4)
  6564. + (c.muted ? " (muted lane)" : ""));
  6565. }
  6566. step ("clicks_in_file=" + juce::String ((int) peaks.size()) + " checked=" + juce::String (checked) + " clips=" + juce::String (clips)
  6567. + " muted_lanes=" + juce::String (muted));
  6568. step ("placement_error_samples=max " + juce::String (worst, 3) + " mean " + juce::String (checked > 0 ? sum / checked : 0.0, 3));
  6569. auto ok = checked > 0 && worst <= 1.0 && engine->getLostRecordingFrames() == 0;
  6570. if (mode == 2) // one clip, exactly the punch range, its 8 beats
  6571. {
  6572. const auto& sp = engine->getSong();
  6573. bool exact = false;
  6574. for (const auto& c : sp.playlist)
  6575. if (c.kind == lynx::ClipKind::audio && c.channel == take)
  6576. exact = c.start == sp.loopStart && c.start + c.length == sp.loopEnd;
  6577. step (juce::String ("punch_clip_matches_range=") + (exact ? "yes" : "no"));
  6578. ok = ok && clips == 1 && exact && checked == 8;
  6579. }
  6580. report.getSiblingFile (report.getFileNameWithoutExtension() + "-project.lynx").replaceWithText (lynx::ProjectFile::toJson (engine->getSong()));
  6581. step (juce::String ("result=") + (ok ? "OK" : "FAILED"));
  6582. finish (ok ? 0 : 1);
  6583. });
  6584. });
  6585. });
  6586. });
  6587. }
  6588. // --hwinserttest (round 164d): see the command line above.
  6589. void runHwInsertTest (const juce::File& report, double seconds, const juce::String& deviceType, const juce::String& deviceName,
  6590. const juce::String& inputName, int bufferSize, bool inPatcher = false, juce::File bounceFile = {})
  6591. {
  6592. engine = std::make_unique<lynx::AudioEngine>();
  6593. lynx::videoview::install (*engine); // (Fruity Video Player channels: their sound tracks)
  6594. savedDeviceState = engine->getDeviceManager().createStateXml();
  6595. auto text = std::make_shared<juce::String>();
  6596. auto step = [report, text] (const juce::String& line) { *text << line << "\n"; report.replaceWithText (*text); };
  6597. auto finish = [this] (int code) {
  6598. if (engine != nullptr)
  6599. engine->getMeters().capture.setSource (lynx::AudioCapture::off);
  6600. restoreSavedDeviceState();
  6601. setApplicationReturnValue (code);
  6602. quit();
  6603. };
  6604. auto& devices = engine->getDeviceManager();
  6605. if (deviceType.isNotEmpty() && devices.getCurrentAudioDeviceType() != deviceType)
  6606. devices.setCurrentAudioDeviceType (deviceType, true);
  6607. {
  6608. auto setup = devices.getAudioDeviceSetup();
  6609. if (deviceName.isNotEmpty())
  6610. setup.outputDeviceName = deviceName;
  6611. if (bufferSize > 0)
  6612. setup.bufferSize = bufferSize;
  6613. if (const auto error = devices.setAudioDeviceSetup (setup, true); error.isNotEmpty())
  6614. step ("device_error=" + error);
  6615. }
  6616. if (const auto r = engine->openAudioInput (inputName.isNotEmpty() ? inputName : deviceName); r.issue != lynx::AudioEngine::InputIssue::none)
  6617. step ("input_error=" + juce::String ((int) r.issue) + " " + r.detail);
  6618. auto* device = devices.getCurrentAudioDevice();
  6619. if (device == nullptr || engine->getInputChannelNames().empty())
  6620. {
  6621. step ("result=ERROR no device / no input");
  6622. finish (1);
  6623. return;
  6624. }
  6625. const auto rate = device->getCurrentSampleRate();
  6626. step ("device=" + device->getTypeName() + " | " + device->getName() + " | " + juce::String (rate) + " Hz | block " + juce::String (device->getCurrentBufferSizeSamples()));
  6627. // the click track: the ping's pulse on every beat at 120 bpm
  6628. const auto beats = (int) std::ceil (seconds * 2.0) + 8;
  6629. const auto clickFile = report.getSiblingFile (report.getFileNameWithoutExtension() + "-clicks.wav");
  6630. {
  6631. lynx::takes::WavTakeWriter w;
  6632. w.open (clickFile.getFullPathName().toStdString(), rate, 1, lynx::takes::SampleFormat::float32);
  6633. const auto total = (juce::int64) std::llround ((double) beats * rate / 2.0);
  6634. std::vector<float> block (4096);
  6635. for (juce::int64 at = 0; at < total; at += (juce::int64) block.size())
  6636. {
  6637. std::fill (block.begin(), block.end(), 0.0f);
  6638. for (int k = 0; k < (int) block.size(); ++k)
  6639. {
  6640. const auto f = at + k;
  6641. const auto beat = (juce::int64) std::floor ((double) f / (rate / 2.0));
  6642. const auto rel = f - (juce::int64) std::llround ((double) beat * rate / 2.0);
  6643. static constexpr float shape[] { 0.25f, 0.75f, 1.0f, 0.75f, 0.25f };
  6644. if (rel >= 0 && rel < 5)
  6645. block[(std::size_t) k] = 0.5f * shape[rel];
  6646. }
  6647. const float* d[] { block.data() };
  6648. w.write (d, (int) std::min<juce::int64> ((juce::int64) block.size(), total - at));
  6649. }
  6650. w.close();
  6651. }
  6652. lynx::Song song = lynx::Song::makeDefault();
  6653. song.bpm = 120.0;
  6654. song.mode = lynx::PlayMode::song;
  6655. song.playlist.clear();
  6656. song.channels.clear();
  6657. for (int k = 0; k < 2; ++k)
  6658. {
  6659. lynx::ChannelDef c;
  6660. c.name = k == 0 ? "Wet" : "Dry";
  6661. c.instrument = lynx::InstrumentKind::audioClip;
  6662. c.samplePath = clickFile.getFullPathName().toStdString();
  6663. c.mixerTrack = k + 1;
  6664. c.volume = 1.0f;
  6665. song.channels.push_back (c);
  6666. lynx::Clip clip;
  6667. clip.kind = lynx::ClipKind::audio;
  6668. clip.channel = k;
  6669. clip.track = k;
  6670. clip.start = 0;
  6671. clip.length = (std::int64_t) beats * lynx::ppq;
  6672. song.playlist.push_back (clip);
  6673. }
  6674. song.mixer[0].outputChannel = lynx::outputNone; // (the cable carries the send only)
  6675. for (auto& fx : song.mixer[0].effects) // (no Master effects: the default limiter's PDC would hide nothing, but keep it plain)
  6676. fx.enabled = false;
  6677. song.mixer[1].pan = -1.0f;
  6678. song.mixer[2].pan = 1.0f;
  6679. auto hw = lynx::makeEffectSlot (lynx::EffectKind::hardwareInsert);
  6680. hw.params[lynx::hwinsert::output] = lynx::hwinsert::channelValue (0);
  6681. hw.params[lynx::hwinsert::input] = lynx::hwinsert::channelValue (0);
  6682. hw.params[lynx::hwinsert::inputStereo] = 1.0f;
  6683. song.mixer[1].effects.clear();
  6684. lynx::AudioEngine::HardwareInsertRef ref { false, 1, 0, {} };
  6685. if (inPatcher) // (round 165c) From LYNX -> Hardware Insert -> To LYNX
  6686. {
  6687. auto slot = lynx::makeEffectSlot (lynx::EffectKind::patcher);
  6688. lynx::PatchNode node;
  6689. node.effect = hw;
  6690. slot.patcher.nodes = { node };
  6691. lynx::PatchWire in, out;
  6692. in.from = lynx::patchFromHost;
  6693. in.to = 0;
  6694. out.from = 0;
  6695. out.to = lynx::patchToHost;
  6696. slot.patcher.wires = { in, out };
  6697. song.mixer[1].effects.push_back (slot);
  6698. ref.nodes = { 0 };
  6699. }
  6700. else
  6701. song.mixer[1].effects.push_back (hw);
  6702. engine->setSong (std::move (song));
  6703. step (juce::String ("insert=") + (inPatcher ? "inside a Patcher on Insert 1" : "Insert 1 slot 1"));
  6704. const auto meter = [this, ref] (int output) {
  6705. const auto fx = engine->runningHardwareInsert (ref);
  6706. return fx != nullptr ? fx->controlOutput (output) : 0.0f;
  6707. };
  6708. // 1) the insert's ping (as its Ping button: a momentary value flipped)
  6709. juce::Timer::callAfterDelay (500, [this, report, step, finish, seconds, rate, meter, ref, inPatcher, bounceFile] {
  6710. if (engine == nullptr)
  6711. return;
  6712. engine->pingHardwareInserts ({ ref });
  6713. juce::Timer::callAfterDelay (3500, [this, report, step, finish, seconds, rate, meter, ref, inPatcher, bounceFile] {
  6714. if (engine == nullptr)
  6715. return;
  6716. // (round 165c) the engine makes a ping's result the slot's round trip with the device setup it belongs to; the
  6717. // new round trip rebuilds the insert (its latency), so the result is read from the slot
  6718. const auto* slot = lynx::AudioEngine::locateHardwareInsert (const_cast<lynx::Song&> (engine->getSong()), ref);
  6719. const auto samples = slot != nullptr ? lynx::hwinsert::roundTripOf (slot->params[lynx::hwinsert::roundTrip]) : 0;
  6720. const auto setup = slot != nullptr ? lynx::hwinsert::measuredSetup (*slot) : std::string();
  6721. const auto state = meter (lynx::hwinsert::pingState);
  6722. const auto ok = samples > 0 && setup == engine->currentSetupKey();
  6723. step ("ping_round_trip=" + juce::String (samples) + " measured_setup=" + juce::String (setup) + (ok ? " (ok)" : " (FAILED)")
  6724. + " live_ping_state=" + juce::String (state, 3) + " status_flags=" + juce::String (juce::roundToInt (meter (lynx::hwinsert::status) * 16.0f)));
  6725. if (! ok)
  6726. {
  6727. step ("result=FAILED ping");
  6728. finish (1);
  6729. return;
  6730. }
  6731. // a stale setup is noticed: another setup key on the slot gives the notice, the real one none
  6732. step ("stale_now=" + juce::String ((int) engine->staleHardwareInserts().size()));
  6733. // 2) play, capturing the Master
  6734. juce::Timer::callAfterDelay (500, [this, report, step, finish, seconds, rate, samples, ref, inPatcher, bounceFile] {
  6735. if (engine == nullptr)
  6736. return;
  6737. step ("pdc_total=" + juce::String (engine->getLatencySamples()) + " (expected " + juce::String (samples) + ")");
  6738. // saved in the project: the slot comes back the same (routing, round trip), and its latency with it — also an
  6739. // odd round trip (12345 samples: the project keeps it to the sample)
  6740. if (! inPatcher)
  6741. {
  6742. auto odd = engine->getSong();
  6743. odd.mixer[1].effects[0].params[lynx::hwinsert::roundTrip] = lynx::hwinsert::roundTripValue (12345);
  6744. juce::String error;
  6745. auto same = true;
  6746. for (const auto* song : { &engine->getSong(), (const lynx::Song*) &odd })
  6747. {
  6748. const auto file = report.getSiblingFile (report.getFileNameWithoutExtension() + (song == &odd ? "-odd.lynx" : ".lynx"));
  6749. const auto saved = lynx::ProjectFile::save (*song, file, error);
  6750. const auto loaded = saved ? lynx::ProjectFile::load (file, error) : std::nullopt;
  6751. same = same && loaded && loaded->mixer.size() > 1 && ! loaded->mixer[1].effects.empty()
  6752. && loaded->mixer[1].effects[0].kind == lynx::EffectKind::hardwareInsert
  6753. && loaded->mixer[1].effects[0].params == song->mixer[1].effects[0].params
  6754. && lynx::makeEffect (loaded->mixer[1].effects[0])->latencySamples() == (song == &odd ? 12345 : samples);
  6755. }
  6756. const auto file = report.getSiblingFile (report.getFileNameWithoutExtension() + ".lynx");
  6757. step (juce::String ("project_round_trip=") + (same ? "same" : "DIFFERENT " + error) + " (" + file.getFileName() + ")");
  6758. if (! same)
  6759. {
  6760. step ("result=FAILED project");
  6761. finish (1);
  6762. return;
  6763. }
  6764. }
  6765. auto left = std::make_shared<std::vector<float>>(), right = std::make_shared<std::vector<float>>();
  6766. engine->stop();
  6767. engine->rewind();
  6768. engine->getMeters().capture.setSource (0);
  6769. engine->play();
  6770. auto pulls = std::make_shared<int> ((int) (seconds * 5.0));
  6771. auto pull = std::make_shared<std::function<void()>>();
  6772. *pull = [this, report, step, finish, seconds, rate, samples, left, right, pulls, pull, ref, inPatcher, bounceFile] {
  6773. if (engine == nullptr)
  6774. return;
  6775. engine->getMeters().capture.pull (*left, *right);
  6776. if (*pulls == 10) // the insert's editor while it plays (next to the report)
  6777. for (const auto scale : { 1.0f, 1.5f })
  6778. {
  6779. auto editor = inPatcher ? lynx::makeNodeEffectEditor (
  6780. *engine, [ref] (lynx::Song& s) { return lynx::AudioEngine::locateHardwareInsert (s, ref); },
  6781. [this, ref] { return engine->runningHardwareInsert (ref); }, "Insert 1 (Patcher)", scale)
  6782. : lynx::makeNativeEffectEditor (*engine, 1, 0, scale, 0);
  6783. juce::Image image (juce::Image::ARGB, editor->getWidth(), editor->getHeight(), true);
  6784. {
  6785. juce::Graphics g (image);
  6786. g.fillAll (lynx::theme::panel);
  6787. editor->paintEntireComponent (g, false);
  6788. }
  6789. const auto file = report.getSiblingFile (report.getFileNameWithoutExtension() + (scale > 1.0f ? "-editor150.png" : "-editor.png"));
  6790. file.deleteFile();
  6791. juce::PNGImageFormat png;
  6792. if (auto stream = file.createOutputStream())
  6793. png.writeImageToStream (image, *stream);
  6794. }
  6795. if (--*pulls > 0)
  6796. {
  6797. juce::Timer::callAfterDelay (200, *pull);
  6798. return;
  6799. }
  6800. engine->stop();
  6801. const auto dropped = engine->getMeters().capture.droppedFrames();
  6802. engine->getMeters().capture.setSource (lynx::AudioCapture::off);
  6803. // the clicks of each side (peaks above -12 dBFS, one per 1/8 s at most)
  6804. auto peaksOf = [rate] (const std::vector<float>& x) {
  6805. std::vector<juce::int64> peaks;
  6806. for (std::size_t f = 1; f + 1 < x.size(); ++f)
  6807. 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])
  6808. && (peaks.empty() || (juce::int64) f - peaks.back() > (juce::int64) (rate / 8)))
  6809. peaks.push_back ((juce::int64) f);
  6810. return peaks;
  6811. };
  6812. const auto wet = peaksOf (*left), dry = peaksOf (*right);
  6813. int pairs = 0;
  6814. juce::int64 worst = 0;
  6815. double gainSum = 0.0, residual = 0.0, energy = 0.0;
  6816. for (const auto w : wet)
  6817. {
  6818. 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); });
  6819. if (best == dry.end() || std::abs (*best - w) > (juce::int64) (rate / 8))
  6820. continue;
  6821. ++pairs;
  6822. worst = std::max (worst, std::abs (*best - w));
  6823. gainSum += (*left)[(std::size_t) w] / (*right)[(std::size_t) *best];
  6824. }
  6825. const auto gain = pairs > 0 ? gainSum / pairs : 1.0;
  6826. // dry clicks with no wet click beside them (a dropout of the cable / device), listed
  6827. juce::String unmatched;
  6828. for (const auto d : dry)
  6829. if (std::none_of (wet.begin(), wet.end(), [d, rate] (juce::int64 w) { return std::abs (w - d) <= (juce::int64) (rate / 8); }))
  6830. unmatched << " " << (juce::int64) d << " (" << juce::String ((*left)[(std::size_t) d], 3) << ")";
  6831. if (unmatched.isNotEmpty())
  6832. step ("dry_clicks_without_wet=" + unmatched);
  6833. // the null test: left − gain · right around each click (both sides aligned → only the cable's colour remains)
  6834. for (const auto w : wet)
  6835. for (juce::int64 f = std::max<juce::int64> (0, w - 16); f < std::min<juce::int64> ((juce::int64) left->size(), w + 16); ++f)
  6836. {
  6837. const auto d = (double) (*left)[(std::size_t) f] - gain * (double) (*right)[(std::size_t) f];
  6838. residual += d * d;
  6839. energy += (double) (*left)[(std::size_t) f] * (*left)[(std::size_t) f];
  6840. }
  6841. const auto nullDb = energy > 0.0 ? 10.0 * std::log10 (std::max (1e-30, residual / energy)) : 0.0;
  6842. step ("captured=" + juce::String ((int) left->size()) + " frames dropped=" + juce::String (dropped) + " wet_clicks=" + juce::String ((int) wet.size())
  6843. + " dry_clicks=" + juce::String ((int) dry.size()) + " pairs=" + juce::String (pairs));
  6844. step ("alignment_error_samples=max " + juce::String ((int) worst) + " cable_gain=" + juce::String (gain, 4) + " null_residual_db=" + juce::String (nullDb, 1));
  6845. auto* dev = engine->getDeviceManager().getCurrentAudioDevice();
  6846. const auto xruns = dev != nullptr ? dev->getXRunCount() : -1;
  6847. step ("device_xruns=" + juce::String (xruns) + " (a dropout loses what was on the cable then: its clicks are excused)");
  6848. const auto excused = xruns > 0 ? 2 * xruns : 0;
  6849. const auto ok = pairs >= (int) (seconds * 2.0) - 2 - excused && worst == 0 && dropped == 0 && engine->getLatencySamples() == samples;
  6850. step (juce::String ("result=") + (ok ? "OK" : "FAILED"));
  6851. // (round 165c) then the re-ping notice after a buffer size change
  6852. auto then = [this, ref, step, finish] (int code) {
  6853. if (code != 0)
  6854. finish (code);
  6855. else
  6856. runRepingCheck (ref, step, finish);
  6857. };
  6858. if (! ok)
  6859. {
  6860. finish (1);
  6861. return;
  6862. }
  6863. if (bounceFile == juce::File())
  6864. then (0);
  6865. else
  6866. runBounceCheck (bounceFile, step, then);
  6867. };
  6868. juce::Timer::callAfterDelay (200, *pull);
  6869. });
  6870. });
  6871. });
  6872. }
  6873. // --hwinserttest --bounce (round 165c): Export › "Render through the hardware in real time" of the test song next to
  6874. // the offline export of the same song. Through the loopback cable (gain 1) the return is the send delayed by the
  6875. // pinged round trip, so the real-time file must equal the offline one (which passes the dry signal at that delay)
  6876. // to float rounding, with the wet clicks (left) on the dry clicks' samples (right).
  6877. // --hwinserttest (round 165c): the buffer size changes (another round trip on the device): the engine notices the
  6878. // insert measured for the old setup (the app's "Ping now?" prompt), "Ping now" measures it again for the new one
  6879. void runRepingCheck (lynx::AudioEngine::HardwareInsertRef ref, std::function<void (const juce::String&)> step, std::function<void (int)> finish)
  6880. {
  6881. auto& devices = engine->getDeviceManager();
  6882. auto setup = devices.getAudioDeviceSetup();
  6883. const auto before = setup.bufferSize;
  6884. setup.bufferSize = before == 512 ? 256 : 512;
  6885. if (const auto error = devices.setAudioDeviceSetup (setup, true); error.isNotEmpty())
  6886. step ("reping_device_error=" + error);
  6887. engine->takeHardwareInsertNotice(); // (whatever was pending before the change)
  6888. juce::Timer::callAfterDelay (1500, [this, ref, step, finish, before] {
  6889. if (engine == nullptr)
  6890. return;
  6891. auto* device = engine->getDeviceManager().getCurrentAudioDevice();
  6892. const auto block = device != nullptr ? device->getCurrentBufferSizeSamples() : 0;
  6893. const auto notice = engine->takeHardwareInsertNotice();
  6894. step ("reping_buffer=" + juce::String (before) + "->" + juce::String (block) + " notice=" + juce::String ((int) notice.size())
  6895. + " stale=" + juce::String ((int) engine->staleHardwareInserts().size()));
  6896. if (notice.size() != 1 || ! (notice[0] == ref))
  6897. {
  6898. step ("result_reping=FAILED (no notice)");
  6899. finish (1);
  6900. return;
  6901. }
  6902. engine->pingHardwareInserts (notice); // ("Ping now")
  6903. juce::Timer::callAfterDelay (3500, [this, ref, step, finish, block] {
  6904. if (engine == nullptr)
  6905. return;
  6906. const auto* slot = lynx::AudioEngine::locateHardwareInsert (const_cast<lynx::Song&> (engine->getSong()), ref);
  6907. const auto samples = slot != nullptr ? lynx::hwinsert::roundTripOf (slot->params[lynx::hwinsert::roundTrip]) : 0;
  6908. const auto stale = (int) engine->staleHardwareInserts().size();
  6909. step ("reping_round_trip=" + juce::String (samples) + " pdc_total=" + juce::String (engine->getLatencySamples()) + " stale=" + juce::String (stale));
  6910. const auto ok = stale == 0 && samples > 0 && engine->getLatencySamples() == samples;
  6911. step (juce::String ("result_reping=") + (ok ? "OK" : "FAILED") + " (device block " + juce::String (block) + ")");
  6912. finish (ok ? 0 : 1);
  6913. });
  6914. });
  6915. }
  6916. void runBounceCheck (const juce::File& bounceFile, std::function<void (const juce::String&)> step, std::function<void (int)> finish)
  6917. {
  6918. // the Export window as the user sees it with the real-time option ticked (next to the report)
  6919. lynx::showExportDialog (*engine, bounceFile.getParentDirectory(), "bounce", 0);
  6920. for (int k = 0; k < juce::TopLevelWindow::getNumTopLevelWindows(); ++k)
  6921. if (auto* w = juce::TopLevelWindow::getTopLevelWindow (k))
  6922. {
  6923. std::function<juce::ToggleButton* (juce::Component&)> find = [&find] (juce::Component& c) -> juce::ToggleButton* {
  6924. if (auto* t = dynamic_cast<juce::ToggleButton*> (&c); t != nullptr && t->getButtonText() == lynx::tr ("Render through the hardware in real time"))
  6925. return t;
  6926. for (auto* child : c.getChildren())
  6927. if (auto* t = find (*child))
  6928. return t;
  6929. return nullptr;
  6930. };
  6931. if (auto* toggle = find (*w))
  6932. {
  6933. step (juce::String ("export_option_visible=") + (toggle->isVisible() ? "yes" : "NO"));
  6934. toggle->setToggleState (true, juce::sendNotificationSync); // (calls its onClick, as a click)
  6935. auto* c = dynamic_cast<juce::DocumentWindow*> (w) != nullptr ? static_cast<juce::DocumentWindow*> (w)->getContentComponent() : w;
  6936. if (c != nullptr)
  6937. {
  6938. const auto file = bounceFile.getSiblingFile (bounceFile.getFileNameWithoutExtension() + "-export.png");
  6939. file.deleteFile();
  6940. juce::FileOutputStream out (file);
  6941. juce::PNGImageFormat png;
  6942. if (out.openedOk())
  6943. png.writeImageToStream (c->createComponentSnapshot (c->getLocalBounds()), out);
  6944. }
  6945. delete w;
  6946. break;
  6947. }
  6948. }
  6949. lynx::exportopts::Options o;
  6950. o.format = lynx::exportopts::Format::wav;
  6951. o.wavBits = 32;
  6952. o.dither = lynx::exportopts::DitherMode::none;
  6953. o.tail = lynx::exportopts::TailMode::cut;
  6954. o.range = lynx::exportopts::Range::song;
  6955. o.trimPdc = true;
  6956. o.hqAllPlugins = false;
  6957. o.pluginWarmUp = false;
  6958. const auto offlineFile = bounceFile.getSiblingFile (bounceFile.getFileNameWithoutExtension() + "-offline.wav");
  6959. auto realtimeJob = std::make_shared<lynx::ExportJob> (*engine, o, bounceFile);
  6960. o.sampleRate = engine->getTransport().sampleRate.load();
  6961. auto offlineJob = std::make_shared<lynx::ExportJob> (engine->getSong(), o, offlineFile);
  6962. struct Shared
  6963. {
  6964. std::atomic<int> done { 0 };
  6965. bool okRealtime = false, okOffline = false;
  6966. juce::String errorRealtime, errorOffline;
  6967. double lastProgress = 0.0;
  6968. double started = juce::Time::getMillisecondCounterHiRes();
  6969. };
  6970. auto shared = std::make_shared<Shared>();
  6971. // (the jobs stay owned by the message thread's poll below: they are destroyed there)
  6972. juce::Thread::launch ([rt = realtimeJob.get(), off = offlineJob.get(), shared] {
  6973. shared->okRealtime = rt->run ([shared] (double p) { shared->lastProgress = p; return true; }, shared->errorRealtime);
  6974. shared->okOffline = off->run ({}, shared->errorOffline);
  6975. shared->done.store (1);
  6976. });
  6977. auto poll = std::make_shared<std::function<void()>>();
  6978. *poll = [this, poll, shared, realtimeJob, offlineJob, bounceFile, offlineFile, step, finish] {
  6979. if (shared->done.load() == 0)
  6980. {
  6981. juce::Timer::callAfterDelay (100, *poll);
  6982. return;
  6983. }
  6984. const auto seconds = (juce::Time::getMillisecondCounterHiRes() - shared->started) / 1000.0;
  6985. step ("bounce_realtime=" + juce::String (shared->okRealtime ? "ok" : "FAILED " + shared->errorRealtime) + " offline="
  6986. + juce::String (shared->okOffline ? "ok" : "FAILED " + shared->errorOffline) + " took=" + juce::String (seconds, 1) + " s (music "
  6987. + juce::String (realtimeJob->getMusicSeconds(), 1) + " s)" + (realtimeJob->getNotice().isNotEmpty() ? " notice=" + realtimeJob->getNotice() : juce::String()));
  6988. juce::AudioFormatManager formats;
  6989. formats.registerBasicFormats();
  6990. std::unique_ptr<juce::AudioFormatReader> a (formats.createReaderFor (bounceFile)), b (formats.createReaderFor (offlineFile));
  6991. if (! shared->okRealtime || ! shared->okOffline || a == nullptr || b == nullptr)
  6992. {
  6993. step ("result=FAILED bounce");
  6994. finish (1);
  6995. return;
  6996. }
  6997. const auto frames = (int) std::min (a->lengthInSamples, b->lengthInSamples);
  6998. juce::AudioBuffer<float> x (2, frames), y (2, frames);
  6999. a->read (&x, 0, frames, 0, true, true);
  7000. b->read (&y, 0, frames, 0, true, true);
  7001. double residual = 0.0, energy = 0.0, wetDry = 0.0;
  7002. for (int ch = 0; ch < 2; ++ch)
  7003. for (int i = 0; i < frames; ++i)
  7004. {
  7005. const double d = x.getSample (ch, i) - y.getSample (ch, i);
  7006. residual += d * d;
  7007. energy += (double) y.getSample (ch, i) * y.getSample (ch, i);
  7008. }
  7009. for (int i = 0; i < frames; ++i) // the wet side against the dry side of the real-time file
  7010. wetDry += std::pow ((double) x.getSample (0, i) - x.getSample (1, i), 2.0);
  7011. const auto db = [energy] (double r) { return energy > 0.0 ? 10.0 * std::log10 (std::max (1e-30, r / energy)) : 0.0; };
  7012. step ("bounce_frames=" + juce::String ((juce::int64) a->lengthInSamples) + " offline_frames=" + juce::String ((juce::int64) b->lengthInSamples)
  7013. + " rate=" + juce::String (a->sampleRate) + " bounce_vs_offline_db=" + juce::String (db (residual), 1)
  7014. + " wet_vs_dry_db=" + juce::String (db (2.0 * wetDry), 1) + " peak=" + juce::String (realtimeJob->getPeak(), 3));
  7015. const auto ok = std::abs (a->lengthInSamples - b->lengthInSamples) <= 1 && db (residual) < -100.0 && realtimeJob->getPeak() > 0.1f;
  7016. step (juce::String ("result_bounce=") + (ok ? "OK" : "FAILED"));
  7017. finish (ok ? 0 : 1);
  7018. };
  7019. juce::Timer::callAfterDelay (100, *poll);
  7020. }
  7021. // --rtstress --record: stops recording (the take becomes a clip of the song, as in the app), moves the take's WAV to
  7022. // `target` and describes it: length against the time played, channels, peak, the latencies the driver reported.
  7023. juce::String finishStressTake (const juce::File& target, double seconds)
  7024. {
  7025. juce::String text;
  7026. auto* device = engine->getDeviceManager().getCurrentAudioDevice();
  7027. text << " recording: input " << (device != nullptr ? device->getActiveInputChannels().countNumberOfSetBits() : 0) << " channel(s)";
  7028. if (device != nullptr)
  7029. text << ", input latency " << device->getInputLatencyInSamples() << " + output latency " << device->getOutputLatencyInSamples() << " samples";
  7030. engine->setRecording (false); // closes the take: a clip of the song
  7031. juce::File take;
  7032. for (const auto& c : engine->getSong().channels)
  7033. if (c.instrument == lynx::InstrumentKind::audioClip)
  7034. take = juce::File (juce::String::fromUTF8 (c.samplePath.c_str()));
  7035. if (! take.existsAsFile())
  7036. return text + "\n recording: no take (" + engine->getLastRecordingError() + ")\n";
  7037. target.deleteFile();
  7038. if (! take.moveFileTo (target))
  7039. take.copyFileTo (target);
  7040. juce::AudioFormatManager formats;
  7041. formats.registerBasicFormats();
  7042. if (std::unique_ptr<juce::AudioFormatReader> reader (formats.createReaderFor (target)); reader != nullptr)
  7043. {
  7044. juce::AudioBuffer<float> audio ((int) reader->numChannels, (int) reader->lengthInSamples);
  7045. reader->read (&audio, 0, (int) reader->lengthInSamples, 0, true, true);
  7046. const auto peak = audio.getMagnitude (0, audio.getNumSamples());
  7047. const auto length = (double) reader->lengthInSamples / reader->sampleRate;
  7048. text << "\n recording: take " << juce::String (length, 3) << " s of " << juce::String (seconds, 0) << " s played, "
  7049. << (int) reader->numChannels << " ch @ " << (int) reader->sampleRate << " Hz, peak "
  7050. << juce::String (juce::Decibels::gainToDecibels (peak, -150.0f), 1) << " dBFS -> " << target.getFullPathName() << "\n";
  7051. }
  7052. else
  7053. text << "\n recording: take unreadable (" << target.getFullPathName() << ")\n";
  7054. return text;
  7055. }
  7056. // LYNX.exe --render project.(flp|lynx) output.wav [seconds]
  7057. // Exports the current pattern to 24-bit WAV (for an imported .flp, the one with the most notes).
  7058. void runRender (const juce::String& inputPath, const juce::String& outputPath, double seconds)
  7059. {
  7060. lynx::AudioEngine offline (false);
  7061. const juce::File input (inputPath);
  7062. juce::String error, report;
  7063. bool ok = false;
  7064. if (input.hasFileExtension ("flp;als;flm;songtmpl"))
  7065. ok = offline.importFlpFile (input, error);
  7066. else if (auto song = lynx::ProjectFile::load (input, error))
  7067. {
  7068. offline.setSong (std::move (*song));
  7069. ok = true;
  7070. }
  7071. int samplers = 0, samplersLoaded = 0;
  7072. if (ok)
  7073. {
  7074. for (const auto& c : offline.getSong().channels)
  7075. if (c.instrument == lynx::InstrumentKind::sampler || c.instrument == lynx::InstrumentKind::audioClip)
  7076. {
  7077. ++samplers;
  7078. samplersLoaded += offline.getSampleLibrary().load (juce::String::fromUTF8 (c.samplePath.c_str())) != nullptr;
  7079. }
  7080. const juce::File output (outputPath);
  7081. output.deleteFile();
  7082. juce::WavAudioFormat wav;
  7083. std::unique_ptr<juce::AudioFormatWriter> writer (
  7084. wav.createWriterFor (output.createOutputStream().release(), 44100.0, 2, 24, {}, 0));
  7085. if (writer == nullptr)
  7086. {
  7087. ok = false;
  7088. error = lynx::utf8 ("could not create ") + outputPath;
  7089. }
  7090. else
  7091. {
  7092. const auto peak = offline.renderOffline (seconds > 0.0 ? seconds : 10.0, 44100.0, writer.get());
  7093. report << "peak=" << peak << "\n";
  7094. ok = peak > 0.001f;
  7095. }
  7096. }
  7097. report << "samples=" << samplersLoaded << "/" << samplers << "\n"
  7098. << "result=" << (ok ? "OK" : "ERROR " + error) << "\n";
  7099. juce::File (outputPath + ".txt").replaceWithText (report);
  7100. setApplicationReturnValue (ok ? 0 : 1);
  7101. quit();
  7102. }
  7103. // LYNX.exe --export-flp project.(lynx|flp|als) output.(flp|zip) [--substitute] (round 171e): File › Export › FL Studio
  7104. // project without the window (option A unless --substitute; the renders next to a .flp in "<name> audio"); the
  7105. // report goes to output.txt
  7106. void runAlsExport (const juce::String& inputPath, const juce::String& folderPath, bool live11, bool reference)
  7107. {
  7108. juce::String error;
  7109. juce::StringArray notes;
  7110. juce::File als;
  7111. {
  7112. lynx::AudioEngine loader (false);
  7113. const juce::File input (inputPath);
  7114. bool ok = false;
  7115. // --scan: the targeted plugin scan an open runs first (child processes), so the set's plugins load
  7116. if (juce::JUCEApplication::getCommandLineParameterArray().contains ("--scan") && input.hasFileExtension ("flp;als;flm;songtmpl"))
  7117. {
  7118. juce::MemoryBlock data;
  7119. if (input.loadFileAsData (data))
  7120. {
  7121. const std::vector<std::uint8_t> bytes (static_cast<const std::uint8_t*> (data.getData()),
  7122. static_cast<const std::uint8_t*> (data.getData()) + data.getSize());
  7123. try
  7124. {
  7125. const auto uses = input.hasFileExtension ("als") ? lynx::alsForeignPlugins (bytes)
  7126. : lynx::flpForeignPlugins (flp::parseProject ({ bytes.data(), bytes.size() }));
  7127. loader.getPluginHost().scanFiles (loader.getPluginHost().filesToScanFor (uses), {});
  7128. }
  7129. catch (const std::exception&)
  7130. {
  7131. }
  7132. }
  7133. }
  7134. if (input.hasFileExtension ("flp;als;flm;songtmpl"))
  7135. ok = loader.importFlpFile (input, error);
  7136. else if (auto song = lynx::ProjectFile::load (input, error))
  7137. {
  7138. loader.setSong (std::move (*song));
  7139. ok = true;
  7140. }
  7141. if (ok)
  7142. {
  7143. loader.capturePluginStates();
  7144. const juce::File folder (folderPath);
  7145. folder.createDirectory();
  7146. als = lynx::writeAlsProject (loader.getSong(), &loader.getPluginHost(), live11 ? lynx::AlsVersion::live11 : lynx::AlsVersion::live12, ! reference, folder,
  7147. input.getFileNameWithoutExtension(), notes, error);
  7148. }
  7149. }
  7150. juce::String report;
  7151. report << (als != juce::File() ? "ok " + als.getFullPathName() : "error=" + error) << "\n" << notes.joinIntoString ("\n") << "\n";
  7152. juce::File (folderPath).getChildFile ("export-als.txt").replaceWithText (report);
  7153. setApplicationReturnValue (als != juce::File() ? 0 : 1);
  7154. quit();
  7155. }
  7156. void runGamepadShot (const juce::String& prefix)
  7157. {
  7158. juce::String report;
  7159. int failures = 0;
  7160. {
  7161. lynx::AudioEngine engine (false);
  7162. auto hints = lynx::makeGamepadHints();
  7163. savePng (hints->createComponentSnapshot (hints->getLocalBounds()), prefix + "-hints.png");
  7164. auto prefs = engine.getMidiPrefs();
  7165. prefs.gamepad = true;
  7166. engine.setMidiPrefs (prefs, false);
  7167. auto page = lynx::makeMidiPage (engine, {}, false);
  7168. page->setSize (760, 1400);
  7169. savePng (page->createComponentSnapshot (page->getLocalBounds()), prefix + "-settings.png");
  7170. // the poller with fake states: what the handler gets
  7171. using namespace lynx::gamepad;
  7172. std::vector<std::string> got;
  7173. lynx::GamepadInput input ([&got] (const Changes& c, const State&, double dt) {
  7174. for (int i = 0; i < c.pressedCount; ++i)
  7175. got.push_back (std::string ("press ") + buttonName (c.pressed[(std::size_t) i]));
  7176. for (int i = 0; i < c.releasedCount; ++i)
  7177. got.push_back (std::string ("release ") + buttonName (c.released[(std::size_t) i]));
  7178. for (int i = 0; i < c.controllerCount; ++i)
  7179. got.push_back ("cc " + std::to_string (c.controller[(std::size_t) i]) + "=" + std::to_string (c.value[(std::size_t) i]));
  7180. if (c.connectedChanged)
  7181. got.push_back ("connected changed");
  7182. got.push_back ("dt " + std::to_string ((int) std::lround (dt * 1000)));
  7183. });
  7184. State pad;
  7185. pad.connected = true;
  7186. input.inject (pad, 1.0 / 60.0);
  7187. pad.buttons = mask (Button::a);
  7188. pad.rightTrigger = 255;
  7189. input.inject (pad, 1.0 / 60.0);
  7190. pad.buttons = 0;
  7191. input.inject (pad, 1.0 / 60.0);
  7192. const std::vector<std::string> expected { "connected changed", "dt 17", "press A", "cc 102=127", "cc 21=127", "dt 17",
  7193. "release A", "cc 102=0", "dt 17" };
  7194. for (const auto& line : got)
  7195. report << line << "\n";
  7196. if (got != expected)
  7197. {
  7198. ++failures;
  7199. report << "FAILED: the poller's changes differ from the expected ones\n";
  7200. }
  7201. report << "xinput " << (input.available() ? "loaded" : "not available") << "\n";
  7202. }
  7203. report << (failures == 0 ? "gamepad OK" : "gamepad FAILED") << "\n";
  7204. juce::File (prefix + "-gamepad.txt").replaceWithText (report);
  7205. setApplicationReturnValue (failures == 0 ? 0 : 1);
  7206. quit();
  7207. }
  7208. void runBundleExport (const juce::String& inputPath, const juce::String& folderPath, bool zip, bool mixdown, const juce::String& shotPrefix)
  7209. {
  7210. juce::String error;
  7211. bool ok = false;
  7212. lynx::otherapps::Result result;
  7213. {
  7214. lynx::AudioEngine loader (false);
  7215. const juce::File input (inputPath);
  7216. if (input.hasFileExtension ("flp;als"))
  7217. ok = loader.importFlpFile (input, error);
  7218. else if (auto song = lynx::ProjectFile::load (input, error))
  7219. {
  7220. loader.setSong (std::move (*song));
  7221. ok = true;
  7222. }
  7223. if (ok)
  7224. {
  7225. loader.capturePluginStates();
  7226. lynx::otherapps::Context context;
  7227. context.host = &loader.getPluginHost();
  7228. context.flOptions = lynx::flstudio::optionsFor (context.host, lynx::flpexport::LynxOnly::renderAudio, loader.getSong());
  7229. context.render = [] (const lynx::Song& s, const lynx::exportopts::Options& o, const juce::File& file,
  7230. const std::function<bool (double)>& progress, juce::String& err) {
  7231. lynx::ExportJob job (s, o, file);
  7232. return job.run (progress, err);
  7233. };
  7234. context.onMessageThread = [] (std::function<void()> f) { f(); };
  7235. lynx::exportbundle::Options options;
  7236. options.zip = zip;
  7237. options.mixdown = mixdown;
  7238. const auto name = input.getFileNameWithoutExtension();
  7239. const auto shot = [&shotPrefix] (juce::Component& c, const juce::String& suffix) {
  7240. if (shotPrefix.isNotEmpty())
  7241. savePng (c.createComponentSnapshot (c.getLocalBounds()), shotPrefix + suffix);
  7242. };
  7243. if (auto panel = lynx::makeOtherAppsExportPanel (loader, name))
  7244. shot (*panel, "-panel.png");
  7245. ok = lynx::otherapps::write (loader.getSong(), name, options, juce::File (folderPath), context, result);
  7246. if (auto report = lynx::makeOtherAppsReportPanel (result.folder, result.written, result.failed))
  7247. shot (*report, "-report.png");
  7248. }
  7249. }
  7250. juce::String report;
  7251. report << (ok ? "ok " + result.folder.getFullPathName() : "error=" + error) << "\n";
  7252. for (const auto& w : result.written)
  7253. report << "written " << w << "\n";
  7254. for (const auto& f : result.failed)
  7255. report << "failed " << f << "\n";
  7256. juce::File (folderPath).getChildFile ("export-bundle.txt").replaceWithText (report);
  7257. setApplicationReturnValue (ok && result.failed.isEmpty() ? 0 : 1);
  7258. quit();
  7259. }
  7260. void runFlExport (const juce::String& inputPath, const juce::String& outputPath, bool substitute)
  7261. {
  7262. juce::String error;
  7263. bool ok = false;
  7264. lynx::flstudio::Written written;
  7265. {
  7266. lynx::AudioEngine loader (false);
  7267. const juce::File input (inputPath);
  7268. // a Live set opens through the same import as an .flp (as File › Open does, and --export-als accepts an .flp)
  7269. if (input.hasFileExtension ("flp;als"))
  7270. ok = loader.importFlpFile (input, error);
  7271. else if (auto song = lynx::ProjectFile::load (input, error))
  7272. {
  7273. loader.setSong (std::move (*song));
  7274. ok = true;
  7275. }
  7276. if (ok)
  7277. {
  7278. const juce::File output (outputPath);
  7279. const auto zip = output.hasFileExtension ("zip");
  7280. const auto mode = substitute ? lynx::flpexport::LynxOnly::substitute : lynx::flpexport::LynxOnly::renderAudio;
  7281. loader.capturePluginStates();
  7282. auto options = lynx::flstudio::optionsFor (&loader.getPluginHost(), mode, loader.getSong());
  7283. // --flp-ppq N: the file's PPQ (tests; default: 96 when the notes and clips fit it)
  7284. if (const auto args = juce::JUCEApplication::getCommandLineParameterArray(); args.contains ("--flp-ppq"))
  7285. options.ppq = juce::jlimit (0, 960, args[args.indexOf ("--flp-ppq") + 1].getIntValue());
  7286. const auto renderDir = zip ? juce::File::getSpecialLocation (juce::File::tempDirectory).getNonexistentChildFile ("LYNX FL export", {}, false)
  7287. : output.getSiblingFile (output.getFileNameWithoutExtension() + " audio");
  7288. ok = lynx::flstudio::exportProject (loader.getSong(), options, output, zip, renderDir, 44100.0,
  7289. [] (const lynx::Song& s, const lynx::ExportSettings& settings, const juce::File& wav,
  7290. const std::function<bool (double)>& progress, juce::String& err) {
  7291. lynx::ExportJob job (s, settings, wav);
  7292. return job.run (progress, err);
  7293. },
  7294. {}, written, error);
  7295. if (zip)
  7296. renderDir.deleteRecursively();
  7297. }
  7298. }
  7299. juce::String report;
  7300. report << (ok ? "ok" : "error=" + error) << "\n"
  7301. << "exact=" << (int) written.report.exact.size() << " rendered=" << (int) written.report.rendered.size()
  7302. << " substituted=" << (int) written.report.substituted.size() << " dropped=" << (int) written.report.dropped.size()
  7303. << " samples=" << written.samples << "\n\n"
  7304. << lynx::flstudio::reportText (written) << "\n";
  7305. juce::File (outputPath + ".txt").replaceWithText (report);
  7306. setApplicationReturnValue (ok ? 0 : 1);
  7307. quit();
  7308. }
  7309. // LYNX.exe --export project.(flp|als|lynx) output.(wav|flac|ogg|mp3) [--pattern] [--insert N] [--rate N]
  7310. // Same path as "Export" in the UI: the whole song (or the current pattern) with its tail.
  7311. void runExport (const juce::String& inputPath, const juce::String& outputPath, bool patternOnly, int insert)
  7312. {
  7313. juce::String error, report;
  7314. bool ok = false;
  7315. const auto started = juce::Time::getMillisecondCounterHiRes();
  7316. lynx::loadtrace::begin (inputPath.toStdString()); // phase times (round 112): report lines + load.log
  7317. {
  7318. lynx::AudioEngine loader (false);
  7319. const juce::File input (inputPath);
  7320. // --find-plugins: first the targeted scan opening the project in the app runs (its plugins not known yet)
  7321. if (input.hasFileExtension ("flp") && juce::JUCEApplication::getCommandLineParameters().contains ("--find-plugins"))
  7322. {
  7323. juce::MemoryBlock data;
  7324. if (input.loadFileAsData (data))
  7325. try
  7326. {
  7327. const auto uses = lynx::flpForeignPlugins (flp::parseProject ({ static_cast<const std::uint8_t*> (data.getData()), data.getSize() }));
  7328. auto& host = loader.getPluginHost();
  7329. const auto listed = std::chrono::steady_clock::now();
  7330. const auto files = host.filesToScanFor (uses);
  7331. lynx::loadtrace::add ("plugin_scan_list", lynx::loadtrace::msSince (listed));
  7332. report << "scanned=" << files.joinIntoString (";") << "\n";
  7333. const auto scanned = std::chrono::steady_clock::now();
  7334. host.scanFiles (files, {});
  7335. lynx::loadtrace::add ("plugin_scan", lynx::loadtrace::msSince (scanned), files.size());
  7336. }
  7337. catch (const flp::Error&)
  7338. {
  7339. }
  7340. }
  7341. if (input.hasFileExtension ("flp;als")) // a Live set opens through the same import (round 182b)
  7342. ok = loader.importFlpFile (input, error);
  7343. else if (auto song = lynx::ProjectFile::load (input, error))
  7344. {
  7345. loader.setSong (std::move (*song));
  7346. ok = true;
  7347. }
  7348. if (ok)
  7349. {
  7350. const juce::File output (outputPath);
  7351. lynx::ExportSettings settings;
  7352. settings.wholeSong = ! patternOnly;
  7353. settings.format = output.hasFileExtension ("flac") ? lynx::ExportSettings::Format::flac24
  7354. : output.hasFileExtension ("ogg") ? lynx::ExportSettings::Format::ogg
  7355. : lynx::ExportSettings::Format::wav24;
  7356. // --insert N: only that insert's output (what "Render to audio" records)
  7357. if (juce::JUCEApplication::getCommandLineParameters().contains ("--no-effects")
  7358. || juce::JUCEApplication::getCommandLineParameters().contains ("--sem-efeitos")) // performance diagnostics; --sem-efeitos: legacy alias
  7359. loader.editSong ([] (lynx::Song& s) {
  7360. for (auto& t : s.mixer)
  7361. t.effects.clear();
  7362. }, false);
  7363. if (juce::JUCEApplication::getCommandLineParameters().contains ("--no-automation")
  7364. || juce::JUCEApplication::getCommandLineParameters().contains ("--sem-automacao")) // --sem-automacao: legacy alias
  7365. loader.editSong ([] (lynx::Song& s) { s.automations.clear(); }, false);
  7366. const auto loaded = juce::Time::getMillisecondCounterHiRes();
  7367. // .mp3: the Export window's MP3 (320 kbps); everything else as before
  7368. auto options = settings.toOptions();
  7369. // --save-tempo: FL's "Tempo information" (acid chunk) on (round 167l: compare with FL's AcidBox render; --export)
  7370. if (juce::JUCEApplication::getCommandLineParameters().contains ("--save-tempo"))
  7371. options.saveTempo = true;
  7372. // --no-warmup: the export's plugin warm-up off (round 155: compare the start of the file)
  7373. if (juce::JUCEApplication::getCommandLineParameters().contains ("--no-warmup"))
  7374. options.pluginWarmUp = false;
  7375. // --rate N: render at another sample rate (round 157b: samples resampled as at a 48 kHz device)
  7376. if (const auto args = juce::JUCEApplication::getCommandLineParameterArray(); args.contains ("--rate"))
  7377. if (const auto rate = args[args.indexOf ("--rate") + 1].getDoubleValue(); rate >= 8000.0 && rate <= 384000.0)
  7378. options.sampleRate = rate;
  7379. if (output.hasFileExtension ("mp3"))
  7380. {
  7381. options.format = lynx::exportopts::Format::mp3;
  7382. options.mp3Kbps = 320;
  7383. }
  7384. lynx::ExportJob job (insert > 0 ? lynx::makeBounceSong (loader.getSong(), insert) : loader.getSong(), options, output);
  7385. job.setExtraData (true);
  7386. const auto prepared = juce::Time::getMillisecondCounterHiRes();
  7387. lynx::loadtrace::end();
  7388. int lastPercent = -1;
  7389. ok = job.run ([&lastPercent] (double p) {
  7390. lastPercent = (int) (p * 100.0);
  7391. return true;
  7392. }, error);
  7393. auto joined = [] (const std::map<std::string, int>& items) {
  7394. juce::StringArray names;
  7395. for (const auto& [name, count] : items)
  7396. names.add (juce::String::fromUTF8 (name.c_str()) + "x" + juce::String (count));
  7397. return names.joinIntoString (", ");
  7398. };
  7399. const auto& importReport = loader.getImportReport();
  7400. report << "converted=" << joined (importReport.converted) << "\n"
  7401. << "approximated=" << joined (importReport.approximated) << "\n"
  7402. << "unsupported=" << joined (importReport.unsupported) << "\n"
  7403. << "dropped_effects=" << joined (importReport.droppedEffects) << "\n"
  7404. << "partial_effects=" << joined (importReport.partialEffects) << "\n"
  7405. << "missing_samples=" << importReport.missingSamples << "\n";
  7406. // third-party plugins: how each was found, or what plays in its place (diagnostics for level differences)
  7407. for (const auto& line : loader.getMatchedPlugins())
  7408. report << "plugin_found=" << line << "\n";
  7409. for (const auto& m : loader.getMissingPluginDetails())
  7410. report << "plugin_missing=" << juce::String::fromUTF8 (m.name.c_str()) << " -> "
  7411. << juce::String::fromUTF8 (m.replacement.c_str()).replace ("{0}", juce::String::fromUTF8 (m.replacementArg.c_str())) << "\n";
  7412. {
  7413. const auto& song = loader.getSong();
  7414. for (std::size_t t = 0; t < song.mixer.size(); ++t)
  7415. {
  7416. const auto& track = song.mixer[t];
  7417. if (track.effects.empty() && track.sends.empty())
  7418. continue;
  7419. report << "insert " << (int) t << " vol=" << juce::String (track.volume / lynx::unityFader, 3)
  7420. << (track.muted ? " muted" : "") << (track.toMaster ? "" : " noMaster");
  7421. for (const auto& s : track.sends)
  7422. report << " send>" << s.target << "@" << juce::String (s.level, 3);
  7423. report << " |";
  7424. for (const auto& fx : track.effects)
  7425. report << " [" << (fx.kind == lynx::EffectKind::plugin ? juce::String::fromUTF8 (fx.plugin.name.c_str())
  7426. : juce::String::fromUTF8 (lynx::effectInfo (fx.kind).name))
  7427. << (fx.isSubstitute() ? " (substitute)" : "") << (fx.enabled ? "" : " off")
  7428. << (fx.mix < 0.999f ? " mix=" + juce::String (fx.mix, 2) : juce::String()) << "]";
  7429. report << "\n";
  7430. }
  7431. }
  7432. report << juce::String (lynx::loadtrace::reportLines());
  7433. lynx::PluginHost::settingsFolder().getChildFile ("load.log").replaceWithText (juce::String (lynx::loadtrace::table()));
  7434. report << "open_ms=" << juce::roundToInt (loaded - started) << "\n"
  7435. << "prepare_ms=" << juce::roundToInt (prepared - loaded) << "\n"
  7436. << "render_ms=" << juce::roundToInt (juce::Time::getMillisecondCounterHiRes() - prepared) << "\n"
  7437. << "graph_ms=" << juce::roundToInt (job.getEngine().getLastRenderStats().graphMs) << "\n"
  7438. << "write_ms=" << juce::roundToInt (job.getEngine().getLastRenderStats().writeMs) << "\n"
  7439. << "warmup_blocks=" << job.getEngine().getLastRenderStats().warmUp.blocks << "\n"
  7440. << "warmup_ms=" << juce::roundToInt (job.getEngine().getLastRenderStats().warmUp.wallSeconds * 1000.0) << "\n"
  7441. << "warmup_changes=" << job.getEngine().getLastRenderStats().warmUp.signatureChanges << "\n"
  7442. << "warmup_timed_out=" << (job.getEngine().getLastRenderStats().warmUp.timedOut ? 1 : 0) << "\n"
  7443. << "pdc_trim=" << job.getEngine().getLastRenderStats().trimmedSamples << "\n"
  7444. << "song_seconds=" << job.getMusicSeconds() << "\n"
  7445. << "peak=" << job.getPeak() << "\n"
  7446. << "final_progress=" << lastPercent << "\n"
  7447. << "bytes=" << output.getSize() << "\n";
  7448. ok = ok && job.getPeak() > 0.001f;
  7449. }
  7450. }
  7451. report << "result=" << (ok ? "OK" : "ERROR " + error) << "\n";
  7452. juce::File (outputPath + ".txt").replaceWithText (report);
  7453. setApplicationReturnValue (ok ? 0 : 1);
  7454. quit();
  7455. }
  7456. // LYNX.exe --snapshot prefix [project]: draws the window off-screen and writes
  7457. // prefix-rack.png, -pianoroll.png and -playlist.png (to check the UI without touching the screen).
  7458. // --editorcpu: one editor after another; each phase runs 2 s to settle and 8 s measured
  7459. struct EditorCpuRun final : juce::Timer
  7460. {
  7461. struct Case { lynx::EffectKind kind; const char* name; int type; bool demo; }; // type 0 native, 1 display-first, 2 Facet EQ
  7462. std::vector<Case> cases;
  7463. std::size_t at = 0;
  7464. int phase = 0;
  7465. double t0 = 0.0, c0 = 0.0;
  7466. juce::String report;
  7467. juce::File out;
  7468. std::unique_ptr<lynx::AudioEngine> engine;
  7469. std::unique_ptr<juce::DocumentWindow> window;
  7470. std::function<void()> done;
  7471. void start()
  7472. {
  7473. engine = std::make_unique<lynx::AudioEngine> (false);
  7474. report << "editor\tmode\tcpu % of one core\n";
  7475. open();
  7476. startTimer (250);
  7477. }
  7478. void open()
  7479. {
  7480. window.reset();
  7481. if (at >= cases.size()) { out.replaceWithText (report); stopTimer(); if (done) done(); return; }
  7482. const auto& c = cases[at];
  7483. lynx::Song song;
  7484. song.mixer.resize (2);
  7485. song.mixer[0].name = "Master";
  7486. song.mixer[1].name = "Insert 1";
  7487. song.mixer[1].effects.push_back (lynx::makeEffectSlot (c.kind));
  7488. engine->setSong (std::move (song));
  7489. engine->dispatchPendingMessages();
  7490. lynx::setNativeEditorDemo (c.demo);
  7491. auto editor = c.type == 1 ? lynx::makeProEditor (*engine, 1, 0, c.demo) : c.type == 2 ? lynx::makeFacetEqEditor (*engine, 1, 0, c.demo)
  7492. : lynx::makeNativeEffectEditor (*engine, 1, 0, 1.0f, 0);
  7493. window = std::make_unique<juce::DocumentWindow> (juce::String ("LYNX editor CPU - ") + c.name, lynx::theme::colour::bg1, 0);
  7494. window->setUsingNativeTitleBar (true);
  7495. window->setContentOwned (editor.release(), true);
  7496. const auto area = juce::Desktop::getInstance().getDisplays().getPrimaryDisplay()->userArea;
  7497. window->setTopLeftPosition (area.getRight() - window->getWidth() - 8, area.getBottom() - window->getHeight() - 8);
  7498. window->setVisible (true);
  7499. phase = 0;
  7500. t0 = juce::Time::getMillisecondCounterHiRes();
  7501. }
  7502. void timerCallback() override
  7503. {
  7504. const auto now = juce::Time::getMillisecondCounterHiRes();
  7505. if (phase == 0 && now - t0 > 2000.0) { phase = 1; t0 = now; c0 = lynx::processCpuSeconds(); return; }
  7506. if (phase == 1 && now - t0 > 8000.0)
  7507. {
  7508. const auto cpu = (lynx::processCpuSeconds() - c0) / ((now - t0) * 0.001) * 100.0;
  7509. const auto& c = cases[at];
  7510. report << c.name << "\t" << (c.demo ? "animating" : "idle") << "\t" << juce::String (cpu, 2) << "\n";
  7511. ++at;
  7512. open();
  7513. }
  7514. }
  7515. };
  7516. std::unique_ptr<EditorCpuRun> editorCpu;
  7517. void runEditorCpu (const juce::String& path)
  7518. {
  7519. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  7520. editorCpu = std::make_unique<EditorCpuRun>();
  7521. editorCpu->out = juce::File (path);
  7522. using K = lynx::EffectKind;
  7523. for (const auto demo : { false, true })
  7524. for (const auto& c : std::vector<EditorCpuRun::Case> { { K::facetEq, "Facet EQ", 2, demo }, { K::crestCompressor, "Crest Compressor", 1, demo },
  7525. { K::apexLimiter, "Apex Limiter", 1, demo }, { K::prismMultiband, "Prism Multiband", 1, demo },
  7526. { K::epochVerb, "Epoch Verb", 0, demo }, { K::glowLeveler, "Glow Leveler", 0, demo },
  7527. { K::fruityLimiter, "Fruity Limiter", 0, demo }, { K::lynxTune, "LYNX Tune", 0, demo } })
  7528. editorCpu->cases.push_back (c);
  7529. editorCpu->done = [this] { juce::MessageManager::callAsync ([this] { editorCpu.reset(); quit(); }); };
  7530. editorCpu->start();
  7531. }
  7532. struct ParityShow
  7533. {
  7534. std::unique_ptr<lynx::AudioEngine> engine;
  7535. std::unique_ptr<juce::Component> editor;
  7536. std::unique_ptr<juce::DocumentWindow> window;
  7537. ~ParityShow() { window.reset(); editor.reset(); engine.reset(); }
  7538. };
  7539. std::shared_ptr<ParityShow> parityShow;
  7540. bool parityShotFailed = false; // --parityshot: the effect name matched no built-in effect
  7541. void runParityShot (const juce::String& path, const juce::String& effectName, const juce::String& paramsFile)
  7542. {
  7543. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  7544. int kindIndex = -1;
  7545. for (int k = 0; k <= (int) lynx::lastEffectKind; ++k)
  7546. if (juce::String::fromUTF8 (lynx::effectInfo ((lynx::EffectKind) k).name).equalsIgnoreCase (effectName))
  7547. kindIndex = k;
  7548. if (kindIndex < 0)
  7549. {
  7550. // round tp172b7: say so and fail (a silent exit 0 hid a split effect name in a launch script)
  7551. std::fprintf (stderr, "unknown effect: %s\n", effectName.toRawUTF8());
  7552. std::fflush (stderr);
  7553. parityShotFailed = true;
  7554. return;
  7555. }
  7556. const auto kind = (lynx::EffectKind) kindIndex;
  7557. auto fx = lynx::makeEffectSlot (kind);
  7558. if (paramsFile.isNotEmpty())
  7559. for (const auto& line : juce::StringArray::fromLines (juce::File (paramsFile).loadFileAsString()))
  7560. {
  7561. const auto t = juce::StringArray::fromTokens (line, " \t", "");
  7562. const auto index = t.size() >= 2 ? t[0].getIntValue() : -1;
  7563. if (index >= 0 && index < lynx::maxEffectParams)
  7564. fx.params[(std::size_t) index] = t[1].getFloatValue();
  7565. }
  7566. auto offlineOwner = std::make_unique<lynx::AudioEngine> (false); // (kept alive by LYNX_PARITYSHOT_SHOW's window)
  7567. auto& offline = *offlineOwner;
  7568. auto song = lynx::Song::makeDefault();
  7569. song.mixer.resize (2);
  7570. song.mixer[0].name = "Master";
  7571. song.mixer[1].name = "Insert 1";
  7572. song.mixer[1].effects.assign (1, fx);
  7573. for (auto& c : song.channels)
  7574. c.mixerTrack = 1;
  7575. offline.setSong (std::move (song));
  7576. offline.dispatchPendingMessages();
  7577. const bool facet = kind == lynx::EffectKind::facetEq;
  7578. // round tp172b4: the originals are pictured idle (nothing playing), so the display-first editors are too: no demo
  7579. // history unless LYNX_PARITYSHOT_DEMO=1 asks for the running display
  7580. const bool demoDisplay = juce::SystemStats::getEnvironmentVariable ("LYNX_PARITYSHOT_DEMO", {}) == "1";
  7581. // (Ember in its Classic voicing: the Classic panel, as the mixer opens it)
  7582. const bool pro = lynx::ProEditorWindows::handles (kind)
  7583. && ! (kind == lynx::EffectKind::ember && fx.params[(std::size_t) lynx::mixsuite::ember::voicing] > 0.5f);
  7584. auto editor = facet ? lynx::makeFacetEqEditor (offline, 1, 0, false)
  7585. : pro ? lynx::makeProEditor (offline, 1, 0, demoDisplay) : lynx::makeNativeEffectEditor (offline, 1, 0, 1.0f, 0);
  7586. if (editor == nullptr)
  7587. return;
  7588. if (! pro) // the demo song through the effect, the editor ticked 30 times a second of audio as its timer would
  7589. {
  7590. lynx::AudioEngine::RenderOptions o;
  7591. o.seconds = 3.0;
  7592. o.sampleRate = 48000.0;
  7593. o.pluginWarmUp = false;
  7594. int sinceTick = 0;
  7595. o.capture = [&] (const float*, const float*, int n) {
  7596. sinceTick += n;
  7597. if (sinceTick < 1600) return;
  7598. sinceTick = 0;
  7599. if (facet) lynx::tickFacetEqEditor (*editor);
  7600. else lynx::tickNativeEffectEditor (*editor);
  7601. };
  7602. offline.renderOffline (o);
  7603. }
  7604. // round tp172b5: LYNX_PARITYSHOT_CLICKS drives the editor before the picture (the originals' pictures have their
  7605. // panels open), tokens in order: "x,y" a click, then the pointer leaves; "h:x,y" the pointer rests there (a hover);
  7606. // "d:x,y,x2,y2" a drag from there to there, the button still down in the picture
  7607. for (const auto& token : juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_PARITYSHOT_CLICKS", {}), " ", ""))
  7608. {
  7609. const auto hover = token.startsWith ("h:"), drag = token.startsWith ("d:");
  7610. const auto xy = juce::StringArray::fromTokens (hover || drag ? token.substring (2) : token, ",", "");
  7611. if (xy.size() < (drag ? 4 : 2))
  7612. continue;
  7613. const juce::Point<int> at (xy[0].getIntValue(), xy[1].getIntValue());
  7614. editor->setVisible (true); // (getComponentAt finds nothing in a hidden component; it never goes on screen)
  7615. auto* target = editor->getComponentAt (at);
  7616. if (target == nullptr)
  7617. continue;
  7618. const auto local = target->getLocalPoint (editor.get(), at).toFloat();
  7619. const auto now = juce::Time::getCurrentTime();
  7620. auto source = juce::Desktop::getInstance().getMainMouseSource();
  7621. const juce::ModifierKeys left (juce::ModifierKeys::leftButtonModifier);
  7622. const auto event = [&] (juce::Point<float> p, juce::ModifierKeys mods, bool dragged) {
  7623. return juce::MouseEvent (source, p, mods, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, target, target, now, local, now, 1, dragged);
  7624. };
  7625. target->mouseMove (event (local, {}, false));
  7626. if (hover)
  7627. continue;
  7628. target->mouseDown (event (local, left, false));
  7629. if (drag)
  7630. {
  7631. const auto end = target->getLocalPoint (editor.get(), juce::Point<int> (xy[2].getIntValue(), xy[3].getIntValue())).toFloat();
  7632. target->mouseDrag (event (end, left, true));
  7633. continue;
  7634. }
  7635. target->mouseUp (event (local, {}, false));
  7636. target->mouseExit (event ({ -1000.0f, -1000.0f }, {}, false));
  7637. }
  7638. // round tp172b6: LYNX_PARITYSHOT_SHOW=1 puts the same editor in a real window and keeps it open (for a guarded GUI check
  7639. // of its pop-up menus, which the offscreen picture cannot hold); closing the window quits
  7640. if (juce::SystemStats::getEnvironmentVariable ("LYNX_PARITYSHOT_SHOW", {}) == "1")
  7641. {
  7642. struct ShowWindow final : juce::DocumentWindow
  7643. {
  7644. ShowWindow() : juce::DocumentWindow ("LYNX parity check", juce::Colours::black, juce::DocumentWindow::closeButton) {}
  7645. void closeButtonPressed() override { juce::JUCEApplication::getInstance()->systemRequestedQuit(); }
  7646. };
  7647. parityShow = std::make_shared<ParityShow>();
  7648. parityShow->engine = std::move (offlineOwner);
  7649. parityShow->editor = std::move (editor);
  7650. auto window = std::make_unique<ShowWindow>();
  7651. window->setUsingNativeTitleBar (true);
  7652. window->setContentNonOwned (parityShow->editor.get(), true);
  7653. window->setTopLeftPosition (80, 80);
  7654. window->setVisible (true);
  7655. parityShow->window = std::move (window);
  7656. return;
  7657. }
  7658. juce::Image image (juce::Image::ARGB, editor->getWidth(), editor->getHeight(), true);
  7659. {
  7660. juce::Graphics g (image);
  7661. g.fillAll (lynx::theme::panel);
  7662. editor->paintEntireComponent (g, false);
  7663. }
  7664. const juce::File file (path);
  7665. file.deleteFile();
  7666. juce::PNGImageFormat png;
  7667. if (auto stream = file.createOutputStream())
  7668. png.writeImageToStream (image, *stream);
  7669. }
  7670. void runEq166fShots (const juce::String& folder)
  7671. {
  7672. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  7673. const juce::File out (folder);
  7674. out.createDirectory();
  7675. lynx::AudioEngine offline (false);
  7676. auto save = [&] (juce::Component& editor, const juce::String& name) {
  7677. juce::Image image (juce::Image::ARGB, editor.getWidth(), editor.getHeight(), true);
  7678. {
  7679. juce::Graphics g (image);
  7680. g.fillAll (lynx::theme::panel);
  7681. editor.paintEntireComponent (g, false);
  7682. }
  7683. const auto f = out.getChildFile (name);
  7684. f.deleteFile();
  7685. juce::PNGImageFormat png;
  7686. if (auto stream = f.createOutputStream())
  7687. png.writeImageToStream (image, *stream);
  7688. };
  7689. // a song whose demo beat plays into insert 1 (the source) and, for Facet's target, its other half into insert 2
  7690. auto songWith = [] (const lynx::EffectSlot& fx, bool split) {
  7691. auto song = lynx::Song::makeDefault();
  7692. song.mixer.resize (3);
  7693. song.mixer[0].name = "Master";
  7694. song.mixer[1].name = "Vocal";
  7695. song.mixer[2].name = "Reference mix";
  7696. song.mixer[1].effects.assign (1, fx);
  7697. for (std::size_t c = 0; c < song.channels.size(); ++c)
  7698. song.channels[c].mixerTrack = split && c % 2 == 1 ? 2 : 1;
  7699. return song;
  7700. };
  7701. auto feed = [&] (juce::Component& editor, bool facet, int frames) {
  7702. // one continuous render of the song, the editor ticked 30 times a second of audio, as its timer would
  7703. lynx::AudioEngine::RenderOptions o;
  7704. o.seconds = frames / 30.0;
  7705. o.sampleRate = 48000.0;
  7706. o.pluginWarmUp = false;
  7707. int sinceTick = 0;
  7708. o.capture = [&] (const float*, const float*, int n) {
  7709. sinceTick += n;
  7710. if (sinceTick < 1600) return;
  7711. sinceTick = 0;
  7712. if (facet) lynx::tickFacetEqEditor (editor);
  7713. else lynx::tickNativeEffectEditor (editor);
  7714. };
  7715. offline.renderOffline (o);
  7716. if (facet) lynx::tickFacetEqEditor (editor);
  7717. else lynx::tickNativeEffectEditor (editor);
  7718. };
  7719. // Parametric EQ 2: spectrum + heatmap (Full), flat / band 4 +12 dB / band 4 -12 dB, then the Top position
  7720. auto& display = lynx::peqview::displaySettings();
  7721. const auto kept = display;
  7722. display.spectrum = display.heatmap = true;
  7723. display.position = 0;
  7724. 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" },
  7725. { 0.0, "peq2-heatmap-top.png" } })
  7726. {
  7727. auto eq = lynx::makeEffectSlot (lynx::EffectKind::parametricEq);
  7728. eq.params[(std::size_t) lynx::peq::param (3, 2)] = lynx::peq::gainValue (gain);
  7729. eq.params[(std::size_t) lynx::peq::param (3, 1)] = lynx::peq::hzValue (900.0);
  7730. display.position = juce::String (name).contains ("top") ? 1 : 0;
  7731. offline.setSong (songWith (eq, false));
  7732. offline.dispatchPendingMessages();
  7733. auto editor = lynx::makeNativeEffectEditor (offline, 1, 0, 1.25f, 0);
  7734. feed (*editor, false, 120);
  7735. save (*editor, name);
  7736. }
  7737. display = kept;
  7738. // Facet EQ's comparative EQ: listening to the target (insert 2) with its spectrum over the source's
  7739. {
  7740. using namespace lynx::facet;
  7741. auto eq = lynx::makeEffectSlot (lynx::EffectKind::facetEq);
  7742. eq.params[(std::size_t) param (0, 0)] = shapeValue (Shape::bell);
  7743. eq.params[(std::size_t) param (0, 1)] = hzValue (250.0);
  7744. eq.params[(std::size_t) param (0, 2)] = gainValue (-4.0);
  7745. eq.params[(std::size_t) param (1, 0)] = shapeValue (Shape::highShelf);
  7746. eq.params[(std::size_t) param (1, 1)] = hzValue (6000.0);
  7747. eq.params[(std::size_t) param (1, 2)] = gainValue (3.0);
  7748. eq.params[(std::size_t) analyzerParam] = analyzerValue (Analyzer::both);
  7749. eq.sidechain = 2;
  7750. for (const auto& [l, name] : { std::pair { Listen::target, "facet-compare-target.png" }, { Listen::eq, "facet-compare-eq.png" } })
  7751. {
  7752. eq.params[(std::size_t) listenParam] = listenValue (l);
  7753. offline.setSong (songWith (eq, true));
  7754. offline.dispatchPendingMessages();
  7755. auto editor = lynx::makeFacetEqEditor (offline, 1, 0, false);
  7756. feed (*editor, true, 90);
  7757. save (*editor, name);
  7758. }
  7759. }
  7760. }
  7761. void runDesign168rShots (const juce::String& folder)
  7762. {
  7763. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  7764. const juce::File out (folder);
  7765. out.createDirectory();
  7766. lynx::AudioEngine offline (false);
  7767. using K = lynx::EffectKind;
  7768. for (const auto kind : { K::pitchCorrect, K::lovePhilter, K::peakController, K::spreader, K::fruityFastLP, K::flFrequencyShifter,
  7769. K::flLowLifter, K::distructor, K::flBassBoost, K::flDelay1, K::fl7BandEq, K::flCenter, K::flPhaseInverter,
  7770. K::eq, K::delay, K::reverb, K::limiter, K::filter, K::distortion, K::chorus, K::utility, K::lofi,
  7771. K::crossover, K::pitchShift, K::freqShift, K::rhythmGain, K::volumeGate })
  7772. {
  7773. const auto& bank = lynx::presets::factory (kind);
  7774. // Love Philter / Distructor play FL's state: their second picture is FL's default preset (when installed)
  7775. std::optional<lynx::EffectSlot> flPreset;
  7776. if (kind == K::lovePhilter || kind == K::distructor)
  7777. {
  7778. const auto roots = lynx::findFlStudioRoots();
  7779. const auto file = juce::File (juce::String::fromUTF8 (roots.data.c_str()))
  7780. .getChildFile ("Patches/Plugin presets/Effects")
  7781. .getChildFile (kind == K::lovePhilter ? "Fruity Love Philter/Default.fst" : "Distructor/Default.fst");
  7782. juce::MemoryBlock bytes;
  7783. if (file.loadFileAsData (bytes))
  7784. flPreset = lynx::effectFromFlPreset (std::vector<std::uint8_t> ((const std::uint8_t*) bytes.getData(),
  7785. (const std::uint8_t*) bytes.getData() + bytes.getSize()));
  7786. }
  7787. for (int pass = 0; pass < (bank.empty() && ! flPreset ? 1 : 2); ++pass)
  7788. {
  7789. auto fx = lynx::makeEffectSlot (kind);
  7790. if (pass == 1 && flPreset)
  7791. fx = *flPreset;
  7792. else if (pass == 1)
  7793. {
  7794. fx.params = lynx::presets::apply (kind, bank.front(), 120.0);
  7795. fx.presetName = bank.front().name;
  7796. }
  7797. lynx::Song song;
  7798. song.mixer.resize (2);
  7799. song.mixer[0].name = "Master";
  7800. song.mixer[1].name = "Insert 1";
  7801. song.mixer[1].effects.push_back (fx);
  7802. offline.setSong (std::move (song));
  7803. offline.dispatchPendingMessages();
  7804. const auto pages = juce::jmax (1, (int) lynx::plugui::layoutFor (kind).pages.size());
  7805. for (const auto scale : { 1.0f, 2.0f })
  7806. for (int page = 0; page < pages; ++page)
  7807. {
  7808. auto editor = lynx::makeNativeEffectEditor (offline, 1, 0, scale, page);
  7809. if (editor == nullptr)
  7810. continue;
  7811. juce::Image image (juce::Image::ARGB, juce::jmax (1, editor->getWidth()), juce::jmax (1, editor->getHeight()), true);
  7812. {
  7813. juce::Graphics g (image);
  7814. g.fillAll (lynx::theme::panel);
  7815. editor->paintEntireComponent (g, false);
  7816. }
  7817. // (FL's "Frequency Shifter" and LYNX's "Frequency shifter" differ only in case: FL editors get "FL ")
  7818. const auto file = out.getChildFile ((lynx::plugui::hasFlLayout (kind) ? "FL " : "")
  7819. + juce::String (lynx::effectInfo (kind).name).replaceCharacters ("/\\:", "---")
  7820. + (pass == 1 ? "-preset" : "") + (page > 0 ? "-p" + juce::String (page + 1) : juce::String())
  7821. + (scale > 1.5f ? "-200" : "-100") + ".png");
  7822. file.deleteFile();
  7823. juce::PNGImageFormat png;
  7824. if (auto stream = file.createOutputStream())
  7825. png.writeImageToStream (image, *stream);
  7826. }
  7827. }
  7828. }
  7829. }
  7830. bool runInstrumentShots (const juce::File& folder, const juce::String& which, const juce::String& source)
  7831. {
  7832. folder.createDirectory();
  7833. auto key = [] (juce::String n) { return n.toLowerCase().removeCharacters (" -!._"); };
  7834. juce::StringArray wanted;
  7835. wanted.addTokens (which, ",", "");
  7836. auto ok = true;
  7837. struct Shot
  7838. {
  7839. juce::String name;
  7840. std::optional<lynx::ChannelDef> channel;
  7841. };
  7842. std::vector<Shot> shots;
  7843. for (const auto& e : lynx::natives::instrumentEngines())
  7844. {
  7845. const auto name = key (e.name);
  7846. const auto banked = which == "banks" && lynx::banks::hasBank (e.kind);
  7847. if (! banked && ! wanted.contains (name))
  7848. continue;
  7849. auto channel = source == "fl" ? lynx::natives::makeChannel (e.kind, lynx::flStudioAccess())
  7850. : lynx::banks::defaultChannel (e.kind, e.name);
  7851. if (! channel)
  7852. {
  7853. std::fprintf (stderr, "%s: no %s channel\n", e.name, source.toRawUTF8());
  7854. ok = false;
  7855. continue;
  7856. }
  7857. shots.push_back ({ name, std::move (channel) });
  7858. }
  7859. // Autogun (round 169h): not in the Add menus (no preset files); FL's own render-test channel, either source
  7860. if (wanted.contains ("autogun"))
  7861. {
  7862. if (auto channel = lynx::natives::autogunShotChannel (lynx::flStudioAccess()))
  7863. shots.push_back ({ "autogun", std::move (channel) });
  7864. else
  7865. {
  7866. std::fprintf (stderr, "Autogun: no channel (FL Studio's Render tests\\Autogun.flp)\n");
  7867. ok = false;
  7868. }
  7869. }
  7870. for (auto& shot : shots)
  7871. {
  7872. const auto& name = shot.name;
  7873. auto& channel = shot.channel;
  7874. lynx::AudioEngine offline (false);
  7875. lynx::Song song;
  7876. song.mixer = lynx::Song::defaultMixer (2);
  7877. song.channels.push_back (*channel);
  7878. song.patterns.emplace_back();
  7879. {
  7880. juce::String error; // the project too, so an older build can picture the same channel (--snapshot)
  7881. lynx::ProjectFile::save (song, folder.getChildFile (name + "-" + source + ".lynx"), error);
  7882. }
  7883. offline.setSong (std::move (song));
  7884. offline.dispatchPendingMessages();
  7885. auto frame = lynx::makeChannelFrame (offline, 0, 0);
  7886. if (frame == nullptr || frame->getWidth() <= 0)
  7887. {
  7888. ok = false;
  7889. continue;
  7890. }
  7891. for (const auto scale : { 1.0f, 1.5f, 2.0f })
  7892. {
  7893. const auto file = folder.getChildFile (name + "-" + source + "-" + juce::String (juce::roundToInt (scale * 100)) + ".png");
  7894. savePng (frame->createComponentSnapshot (frame->getLocalBounds(), true, scale), file.getFullPathName());
  7895. std::printf ("%s %dx%d\n", file.getFullPathName().toRawUTF8(), frame->getWidth(), frame->getHeight());
  7896. }
  7897. // round 169h: the layout's other pages (Toxic's MIDI / Seq …), one shot each at 1.5×
  7898. for (int page = 1; page < lynx::showChannelLayoutPage (*frame, -1); ++page)
  7899. {
  7900. lynx::showChannelLayoutPage (*frame, page);
  7901. const auto file = folder.getChildFile (name + "-" + source + "-page" + juce::String (page) + "-150.png");
  7902. savePng (frame->createComponentSnapshot (frame->getLocalBounds(), true, 1.5f), file.getFullPathName());
  7903. std::printf ("%s\n", file.getFullPathName().toRawUTF8());
  7904. }
  7905. }
  7906. return ok;
  7907. }
  7908. // --- round 170j: the pilot editors with their own art -------------------------------------------------
  7909. struct ArtPilot
  7910. {
  7911. std::string file; // the art's name as a file name: "toxic-biohazard"
  7912. bool instrument;
  7913. lynx::InstrumentKind instrumentKind;
  7914. lynx::EffectKind effectKind;
  7915. lynx::skin::Style before; // the automatic style it had before the Themed style
  7916. };
  7917. static juce::StringArray& artOnly() // --artshot / --artgui: only these (file names), all when empty
  7918. {
  7919. static juce::StringArray only;
  7920. return only;
  7921. }
  7922. // every plugin with art of its own (round 170j/170k): generators first, then effects; built from the art
  7923. // registries, so a new theme is shot without touching this list
  7924. static const std::vector<ArtPilot>& artPilots()
  7925. {
  7926. using I = lynx::InstrumentKind;
  7927. using E = lynx::EffectKind;
  7928. static const std::vector<ArtPilot> list = [] {
  7929. std::vector<ArtPilot> all;
  7930. auto slug = [] (lynx::skin::Art a) {
  7931. return juce::String (lynx::skin::artName (a)).toLowerCase().replaceCharacters (" ", "-").removeCharacters ("!.()'").toStdString();
  7932. };
  7933. for (const auto& e : lynx::natives::instrumentEngines()) // (the engines' order first)
  7934. if (const auto a = lynx::skin::artForInstrument (e.kind); a != lynx::skin::Art::none)
  7935. all.push_back ({ slug (a), true, e.kind, E::reverb, lynx::skin::Style::neon });
  7936. for (int k = 0; k <= (int) I::wavetraveller; ++k) // then every other kind with art (DrumSynth, Autogun, Wasp...)
  7937. if (const auto a = lynx::skin::artForInstrument ((I) k); a != lynx::skin::Art::none)
  7938. all.push_back ({ slug (a), true, (I) k, E::reverb, lynx::skin::Style::neon });
  7939. for (int k = 0; k <= (int) lynx::lastEffectKind; ++k)
  7940. if (const auto a = lynx::skin::artForEffect ((E) k); a != lynx::skin::Art::none)
  7941. all.push_back ({ slug (a), false, I::synth, (E) k, lynx::skin::plainStyleFor (k) });
  7942. std::vector<ArtPilot> kept;
  7943. for (auto& p : all)
  7944. if (artOnly().isEmpty() || artOnly().contains (juce::String (p.file)))
  7945. if (std::none_of (kept.begin(), kept.end(), [&] (const ArtPilot& q) { return q.file == p.file; }))
  7946. kept.push_back (p);
  7947. return kept;
  7948. }();
  7949. return list;
  7950. }
  7951. // the song and the editor of a pilot (an instrument: the channel window on its Plugin tab)
  7952. static std::unique_ptr<juce::Component> makeArtPilot (lynx::AudioEngine& engine, const ArtPilot& p)
  7953. {
  7954. lynx::Song song;
  7955. song.mixer = lynx::Song::defaultMixer (2);
  7956. if (p.instrument)
  7957. {
  7958. for (const auto& e : lynx::natives::instrumentEngines())
  7959. if (e.kind == p.instrumentKind)
  7960. {
  7961. auto channel = lynx::natives::makeChannel (e.kind, lynx::flStudioAccess());
  7962. if (! channel) channel = lynx::banks::defaultChannel (e.kind, e.name);
  7963. if (! channel) return nullptr;
  7964. song.channels.push_back (*channel);
  7965. break;
  7966. }
  7967. if (song.channels.empty()) // a kind without an engine entry: its LYNX default, else an empty channel of that kind
  7968. {
  7969. const std::string name = lynx::skin::artName (lynx::skin::artForInstrument (p.instrumentKind));
  7970. auto channel = lynx::banks::defaultChannel (p.instrumentKind, name);
  7971. if (! channel)
  7972. {
  7973. channel = lynx::ChannelDef {};
  7974. channel->instrument = p.instrumentKind;
  7975. channel->name = name;
  7976. }
  7977. song.channels.push_back (*channel);
  7978. }
  7979. song.patterns.emplace_back();
  7980. }
  7981. else
  7982. {
  7983. song.mixer[1].effects.push_back (lynx::makeEffectSlot (p.effectKind));
  7984. }
  7985. engine.setSong (std::move (song));
  7986. engine.dispatchPendingMessages();
  7987. if (p.instrument) return lynx::makeChannelFrame (engine, 0, 0);
  7988. if (p.effectKind == lynx::EffectKind::facetEq) return lynx::makeFacetEqEditor (engine, 1, 0, true);
  7989. if (lynx::ProEditorWindows::handles (p.effectKind)) return lynx::makeProEditor (engine, 1, 0, true); // display-first editors, demo signal
  7990. return lynx::makeNativeEffectEditor (engine, 1, 0, 1.0f, 0);
  7991. }
  7992. // "before": the style each pilot had (forced for its run); "after": automatic (the pilots are Themed)
  7993. static void artPilotStyle (const ArtPilot& p, const juce::String& mode)
  7994. {
  7995. lynx::skin::setForcedStyle (mode == "before" ? (int) p.before : -1);
  7996. lynx::skin::setArtMotion (mode != "still");
  7997. }
  7998. bool runArtShots (const juce::File& folder, bool before)
  7999. {
  8000. folder.createDirectory();
  8001. auto ok = true;
  8002. juce::String titles ("editor\tsize\twidth\tname width at the style's size\tbox\tsize used\tlines\tresult\n");
  8003. for (const auto& p : artPilots())
  8004. {
  8005. artPilotStyle (p, before ? "before" : "after");
  8006. lynx::AudioEngine offline (false);
  8007. auto editor = makeArtPilot (offline, p);
  8008. if (editor == nullptr || editor->getWidth() <= 0)
  8009. {
  8010. std::fprintf (stderr, "%s: no editor\n", p.file.c_str());
  8011. ok = false;
  8012. continue;
  8013. }
  8014. if (p.effectKind == lynx::EffectKind::facetEq) lynx::tickFacetEqEditor (*editor);
  8015. // round 170k2: titles.tsv, how the header's name fitted (its width at the style's size, the box, the size used)
  8016. auto fit = [&] (const juce::String& at) {
  8017. const auto f = lynx::skin::lastTitleFit();
  8018. if (f.have <= 0.0f) return; // no plugin header drawn (a generator's channel window)
  8019. titles << juce::String (p.file) << "\t" << at << "\t" << editor->getWidth() << "\t" << juce::String (f.need, 1) << "\t" << juce::String (f.have, 1)
  8020. << "\t" << juce::String (f.size, 1) << "\t" << f.lines << "\t" << (f.clipped ? "ELLIPSIS" : "full") << "\n";
  8021. };
  8022. for (const auto scale : { 1.0f, 2.0f })
  8023. {
  8024. const auto file = folder.getChildFile (juce::String (p.file) + "-" + (before ? "before" : "after") + "-" + juce::String (juce::roundToInt (scale * 100)) + ".png");
  8025. lynx::skin::resetTitleFit();
  8026. savePng (editor->createComponentSnapshot (editor->getLocalBounds(), true, scale), file.getFullPathName());
  8027. std::printf ("%s %dx%d\n", file.getFullPathName().toRawUTF8(), editor->getWidth(), editor->getHeight());
  8028. if (scale == 1.0f) fit ("100");
  8029. }
  8030. // ... and at the smallest size its window allows (effect panels; the Pro editors scale as a whole)
  8031. if (const auto smallest = lynx::nativeEditorMinimumSize (*editor); smallest.x > 0)
  8032. {
  8033. editor->setSize (smallest.x, smallest.y);
  8034. const auto file = folder.getChildFile (juce::String (p.file) + "-" + (before ? "before" : "after") + "-min.png");
  8035. lynx::skin::resetTitleFit();
  8036. savePng (editor->createComponentSnapshot (editor->getLocalBounds(), true, 1.0f), file.getFullPathName());
  8037. fit ("min");
  8038. }
  8039. }
  8040. folder.getChildFile (juce::String ("titles-") + (before ? "before" : "after") + ".tsv").replaceWithText (titles);
  8041. lynx::skin::setForcedStyle (-1);
  8042. return ok;
  8043. }
  8044. struct ArtGuiRun final : juce::Timer
  8045. {
  8046. juce::File folder;
  8047. juce::String mode, report;
  8048. std::size_t at = 0;
  8049. int phase = 0;
  8050. double t0 = 0.0, c0 = 0.0;
  8051. std::unique_ptr<lynx::AudioEngine> engine;
  8052. std::unique_ptr<juce::DocumentWindow> window;
  8053. std::function<void()> done;
  8054. void start()
  8055. {
  8056. engine = std::make_unique<lynx::AudioEngine> (false);
  8057. report << "editor\tmode\tcpu % of one core\tart layer animating\n";
  8058. open();
  8059. startTimer (100);
  8060. }
  8061. void open()
  8062. {
  8063. window.reset();
  8064. const auto& pilots = artPilots();
  8065. if (at >= pilots.size())
  8066. {
  8067. folder.getChildFile ("cpu-" + mode + ".txt").replaceWithText (report);
  8068. stopTimer();
  8069. lynx::skin::setForcedStyle (-1);
  8070. lynx::skin::setArtMotion (true);
  8071. if (done) done();
  8072. return;
  8073. }
  8074. const auto& p = pilots[at];
  8075. artPilotStyle (p, mode);
  8076. auto editor = makeArtPilot (*engine, p);
  8077. if (editor == nullptr) { ++at; open(); return; }
  8078. window = std::make_unique<juce::DocumentWindow> (juce::String ("LYNX art - ") + juce::String (p.file), lynx::theme::colour::bg1, 0);
  8079. window->setUsingNativeTitleBar (true);
  8080. window->setContentOwned (editor.release(), true);
  8081. const auto area = juce::Desktop::getInstance().getDisplays().getPrimaryDisplay()->userArea;
  8082. window->setTopLeftPosition (area.getX() + 24, area.getY() + 24);
  8083. window->setAlwaysOnTop (true);
  8084. window->setVisible (true);
  8085. phase = 0;
  8086. t0 = juce::Time::getMillisecondCounterHiRes();
  8087. }
  8088. bool animating() const
  8089. {
  8090. if (window == nullptr || window->getContentComponent() == nullptr) return false;
  8091. std::function<bool (juce::Component&)> find = [&] (juce::Component& c) {
  8092. if (auto* l = dynamic_cast<lynx::skin::ArtLayer*> (&c); l != nullptr && l->animating()) return true;
  8093. for (auto* child : c.getChildren())
  8094. if (find (*child)) return true;
  8095. return false;
  8096. };
  8097. return find (*window->getContentComponent());
  8098. }
  8099. void timerCallback() override
  8100. {
  8101. const auto now = juce::Time::getMillisecondCounterHiRes();
  8102. const auto& p = artPilots()[at];
  8103. const auto ready = folder.getChildFile (juce::String (p.file) + "-" + mode + ".ready");
  8104. const auto shotDone = folder.getChildFile (juce::String (p.file) + "-" + mode + ".done");
  8105. if (phase == 0 && now - t0 > 1500.0)
  8106. {
  8107. // the window's content on screen, in physical pixels, for the outside screenshot to crop
  8108. auto* c = window->getContentComponent();
  8109. const auto scale = juce::Desktop::getInstance().getDisplays().getPrimaryDisplay()->scale;
  8110. const auto b = c->getScreenBounds();
  8111. shotDone.deleteFile();
  8112. ready.replaceWithText (juce::String (juce::roundToInt (b.getX() * scale)) + " " + juce::String (juce::roundToInt (b.getY() * scale)) + " "
  8113. + juce::String (juce::roundToInt (b.getWidth() * scale)) + " " + juce::String (juce::roundToInt (b.getHeight() * scale)));
  8114. phase = 1;
  8115. t0 = now;
  8116. return;
  8117. }
  8118. if (phase == 1 && (shotDone.existsAsFile() || now - t0 > 10000.0))
  8119. {
  8120. ready.deleteFile();
  8121. shotDone.deleteFile();
  8122. phase = 2;
  8123. t0 = now;
  8124. c0 = lynx::processCpuSeconds();
  8125. return;
  8126. }
  8127. if (phase == 2 && now - t0 > 6000.0)
  8128. {
  8129. const auto cpu = (lynx::processCpuSeconds() - c0) / ((now - t0) * 0.001) * 100.0;
  8130. report << juce::String (p.file) << "\t" << mode << "\t" << juce::String (cpu, 2) << "\t" << (animating() ? "yes" : "no") << "\n";
  8131. ++at;
  8132. open();
  8133. }
  8134. }
  8135. };
  8136. std::unique_ptr<ArtGuiRun> artGui;
  8137. void runArtGui (const juce::File& folder, const juce::String& mode)
  8138. {
  8139. folder.createDirectory();
  8140. artGui = std::make_unique<ArtGuiRun>();
  8141. artGui->folder = folder;
  8142. artGui->mode = mode;
  8143. artGui->done = [this] { juce::MessageManager::callAsync ([this] { artGui.reset(); quit(); }); };
  8144. artGui->start();
  8145. }
  8146. void runPluginEditorSnapshots (const juce::String& folder)
  8147. {
  8148. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  8149. {
  8150. const juce::File out (folder);
  8151. out.createDirectory();
  8152. lynx::AudioEngine offline (false);
  8153. const auto roots = lynx::findFlStudioRoots();
  8154. const auto presets = juce::File (juce::String::fromUTF8 (roots.data.c_str())).getChildFile ("Patches/Plugin presets/Effects");
  8155. auto kinds = lynx::plugui::flLayoutKinds();
  8156. kinds.push_back (lynx::EffectKind::maximus); // Soundgoodizer (below)
  8157. for (const auto own : lynx::plugui::ownLayoutKinds()) // LYNX's own panels (mixing suite, round 96)
  8158. kinds.push_back (own);
  8159. kinds.push_back (lynx::EffectKind::apexLimiter); // round 114: display-first editor
  8160. kinds.push_back (lynx::EffectKind::ridgeStrip); // round 145: the second pass shows the Vocal strip voicing
  8161. kinds.push_back (lynx::EffectKind::ridgeStrip); // round 165: the third pass shows the E console voicing
  8162. kinds.push_back (lynx::EffectKind::compressor); // round 152: the RComp role's panel (vintage voicing, RComp ranges)
  8163. const auto database = juce::File (juce::String::fromUTF8 (roots.data.c_str())).getChildFile ("Patches/Plugin database/Effects");
  8164. auto maximusPasses = 0; // Maximus has its own page (first pass); the second pass shows Soundgoodizer
  8165. auto ridgePasses = 0;
  8166. // round 173d3: the parity pictures of one editor — LYNX_PLUGUI_ONLY=<effect name>, LYNX_PLUGUI_PRESET=<.fst>,
  8167. // LYNX_PLUGUI_PAGES=<page,page,…> (the page numbers as the editor encodes them)
  8168. const auto only = juce::SystemStats::getEnvironmentVariable ("LYNX_PLUGUI_ONLY", {});
  8169. const auto onlyPreset = juce::SystemStats::getEnvironmentVariable ("LYNX_PLUGUI_PRESET", {});
  8170. const auto onlyPages = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_PLUGUI_PAGES", {}), ",", "");
  8171. for (const auto kind : kinds)
  8172. {
  8173. if (only.isNotEmpty() && only != lynx::effectInfo (kind).name)
  8174. continue;
  8175. auto fx = lynx::makeEffectSlot (kind);
  8176. juce::String name (lynx::effectInfo (kind).name);
  8177. for (const auto& plugin : lynx::flPluginsForEffect (kind))
  8178. {
  8179. const auto dir = presets.getChildFile (juce::String::fromUTF8 (plugin.c_str()));
  8180. auto file = dir.getChildFile ("Default.fst");
  8181. if (! file.existsAsFile()) // plugins without presets: their entry of FL's plugin database
  8182. for (const auto& f : database.findChildFiles (juce::File::findFiles, true, juce::String::fromUTF8 (plugin.c_str()) + ".fst"))
  8183. file = f;
  8184. if (only.isNotEmpty() && onlyPreset.isNotEmpty())
  8185. file = juce::File (onlyPreset);
  8186. if (! file.existsAsFile())
  8187. {
  8188. auto files = dir.findChildFiles (juce::File::findFiles, true, "*.fst");
  8189. std::sort (files.begin(), files.end(), [] (const juce::File& a, const juce::File& b) { return a.getFullPathName().compareNatural (b.getFullPathName()) < 0; });
  8190. file = files.isEmpty() ? juce::File() : files[0];
  8191. }
  8192. juce::MemoryBlock data;
  8193. if (file.existsAsFile() && file.loadFileAsData (data))
  8194. {
  8195. const auto* bytes = static_cast<const std::uint8_t*> (data.getData());
  8196. 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)
  8197. fx = *loaded;
  8198. }
  8199. name = juce::String::fromUTF8 (plugin.c_str());
  8200. break;
  8201. }
  8202. if (kind == lynx::EffectKind::maximus && ++maximusPasses == 2) // Soundgoodizer: preset A of the installation, Amount 60 %
  8203. {
  8204. juce::MemoryBlock data;
  8205. juce::File (juce::String::fromUTF8 (roots.factoryData.c_str())).getChildFile ("Plugins/Fruity/Effects/Soundgoodizer/Data/Presets/a.dat").loadFileAsData (data);
  8206. lynx::maximusfx::Blob blob;
  8207. blob.build = lynx::hlfx::MaximusBuild::soundgoodizer;
  8208. blob.mix = 600;
  8209. const auto* b = static_cast<const std::uint8_t*> (data.getData());
  8210. blob.state.assign (b, b + data.getSize());
  8211. fx = lynx::makeEffectSlot (kind);
  8212. fx.state = lynx::maximusfx::pack (blob);
  8213. name = "Soundgoodizer";
  8214. }
  8215. if (kind == lynx::EffectKind::ridgeStrip && ++ridgePasses == 2) // round 145: her Vocalstrip 2 setting
  8216. {
  8217. for (const auto& [param, value] : { std::pair<const char*, float> { "Vocal strip", 1.0f }, { "Compander", 1.0f },
  8218. { "Compander threshold", 0.3083f }, { "Compander ratio", 0.6929f }, { "Compander attack", 0.2543f },
  8219. { "Compander release", 0.5316f }, { "Make-up", 0.2917f }, { "Soft knee", 1.0f },
  8220. { "Expander threshold", 0.2198f }, { "Vocal input", 0.6792f }, { "Vocal output", 0.3938f },
  8221. { "Process order", 0.4783f }, { "De-esser", 1.0f } })
  8222. fx.params[(std::size_t) lynx::plugui::paramIndex (kind, param)] = value;
  8223. name = "Ridge Strip (Vocal strip)";
  8224. }
  8225. else if (kind == lynx::EffectKind::ridgeStrip && ridgePasses == 3) // round 165: the E console, EQ to the side chain
  8226. {
  8227. for (const auto& [param, value] : { std::pair<const char*, float> { "Voicing", 1.0f }, { "HPF", 0.3f }, { "HF gain", 0.8f },
  8228. { "HF bell", 1.0f }, { "Ratio", 0.5f }, { "Comp. threshold", 0.4f }, { "EQ to SC", 1.0f },
  8229. { "Filter split", 1.0f }, { "Expander", 1.0f } })
  8230. fx.params[(std::size_t) lynx::plugui::paramIndex (kind, param)] = value;
  8231. name = "Ridge Strip (E console)";
  8232. }
  8233. else if (kind == lynx::EffectKind::ridgeStrip) // a vocal setting, so the graphs show something
  8234. for (const auto& [param, value] : { std::pair<const char*, float> { "HPF", 0.3f }, { "LMF gain", 0.35f }, { "HF gain", 0.7f },
  8235. { "Ratio", 0.3f }, { "Comp. threshold", 0.55f } })
  8236. fx.params[(std::size_t) lynx::plugui::paramIndex (kind, param)] = value;
  8237. if (kind == lynx::EffectKind::compressor) // round 152: the vintage voicing with the reference's ranges and meter
  8238. {
  8239. for (const auto& [param, value] : { std::pair<const char*, float> { "Voicing", 1.0f }, { "Ranges", 1.0f }, { "Limiter", 1.0f },
  8240. { "Threshold", 0.6f }, { "RC ratio", 0.4f } })
  8241. fx.params[(std::size_t) lynx::plugui::paramIndex (kind, param)] = value;
  8242. name = "Compressor (RComp role)";
  8243. }
  8244. if (kind == lynx::EffectKind::apexLimiter) // round 114: gain into the ceiling, so the display shows reduction
  8245. fx.params[0] = 0.33f;
  8246. if (kind == lynx::EffectKind::ember)
  8247. {
  8248. fx.params[(std::size_t) lynx::plugui::paramIndex (kind, "Drive")] = 0.5f;
  8249. fx.params[(std::size_t) lynx::plugui::paramIndex (kind, "Bands")] = 1.0f; // round 108: the band rows
  8250. fx.params[(std::size_t) lynx::plugui::paramIndex (kind, "B3 drive")] = 0.6f;
  8251. }
  8252. if (kind == lynx::EffectKind::crestCompressor) // round 108: a curve with a knee and a side-chain low cut
  8253. for (const auto& [param, value] : { std::pair<const char*, float> { "Threshold", 0.55f }, { "Knee", 0.15f },
  8254. { "SC1 shape", 0.5f }, { "SC1 freq.", 0.3f } })
  8255. fx.params[(std::size_t) lynx::plugui::paramIndex (kind, param)] = value;
  8256. lynx::Song song;
  8257. song.mixer.resize (2);
  8258. song.mixer[0].name = "Master";
  8259. song.mixer[1].name = "Insert 1";
  8260. song.mixer[1].effects.push_back (fx);
  8261. offline.setSong (std::move (song));
  8262. offline.dispatchPendingMessages();
  8263. if (lynx::ProEditorWindows::handles (kind)) // round 114: the display-first editors, with a demo signal
  8264. {
  8265. auto editor = lynx::makeProEditor (offline, 1, 0, true);
  8266. juce::Image image (juce::Image::ARGB, editor->getWidth(), editor->getHeight(), true);
  8267. {
  8268. juce::Graphics g (image);
  8269. editor->paintEntireComponent (g, false);
  8270. }
  8271. const auto file = out.getChildFile (name + ".png");
  8272. file.deleteFile();
  8273. juce::PNGImageFormat png;
  8274. if (auto stream = file.createOutputStream())
  8275. png.writeImageToStream (image, *stream);
  8276. continue;
  8277. }
  8278. const auto pages = name == "Soundgoodizer" ? 1 : juce::jmax (1, (int) lynx::plugui::layoutFor (kind).pages.size());
  8279. std::vector<int> pageList;
  8280. for (int page = 0; page < pages; ++page)
  8281. pageList.push_back (page);
  8282. if (only.isNotEmpty() && ! onlyPages.isEmpty())
  8283. {
  8284. pageList.clear();
  8285. for (const auto& p : onlyPages)
  8286. pageList.push_back (p.getIntValue());
  8287. }
  8288. for (const auto page : pageList)
  8289. {
  8290. auto editor = lynx::makeNativeEffectEditor (offline, 1, 0, 1.0f, page);
  8291. juce::Image image (juce::Image::ARGB, editor->getWidth(), editor->getHeight(), true);
  8292. {
  8293. juce::Graphics g (image);
  8294. g.fillAll (lynx::theme::panel);
  8295. editor->paintEntireComponent (g, false);
  8296. }
  8297. const auto file = out.getChildFile (name + (page > 0 ? "-p" + juce::String (page + 1) : juce::String()) + ".png");
  8298. file.deleteFile();
  8299. juce::PNGImageFormat png;
  8300. if (auto stream = file.createOutputStream())
  8301. png.writeImageToStream (image, *stream);
  8302. }
  8303. }
  8304. // round 137: Echoform in its Rhythm mode (EchoBoy's role) with the Present era
  8305. {
  8306. namespace ef = lynx::echosuite::echoform;
  8307. auto fx = lynx::makeEffectSlot (lynx::EffectKind::echoform);
  8308. fx.params[ef::rhythm] = 1.0f;
  8309. fx.params[ef::rhythmRepeats] = 5.0f / 15.0f;
  8310. fx.params[ef::rhythmDecay] = 0.25f;
  8311. fx.params[ef::rhythmTap1 + 2] = 0.45f;
  8312. fx.params[ef::feedback] = 0.25f;
  8313. fx.params[ef::era] = 0.5f;
  8314. for (const auto& [param, value] : ef::rhythmPresetEdits (0)) // round 144: a pattern in the rhythm editor (Grid)
  8315. fx.params[(std::size_t) param] = value;
  8316. fx.params[ef::rhythmShape] = 0.5f; // swell
  8317. lynx::Song song;
  8318. song.mixer.resize (2);
  8319. song.mixer[0].name = "Master";
  8320. song.mixer[1].name = "Insert 1";
  8321. song.mixer[1].effects.push_back (fx);
  8322. offline.setSong (std::move (song));
  8323. offline.dispatchPendingMessages();
  8324. auto editor = lynx::makeNativeEffectEditor (offline, 1, 0, 1.0f, 0);
  8325. juce::Image image (juce::Image::ARGB, editor->getWidth(), editor->getHeight(), true);
  8326. {
  8327. juce::Graphics g (image);
  8328. g.fillAll (lynx::theme::panel);
  8329. editor->paintEntireComponent (g, false);
  8330. }
  8331. const auto file = out.getChildFile ("Echoform-rhythm.png");
  8332. file.deleteFile();
  8333. juce::PNGImageFormat png;
  8334. if (auto stream = file.createOutputStream())
  8335. png.writeImageToStream (image, *stream);
  8336. }
  8337. // round 150: Echoform with a voicing (the Stereo / L/R offset controls on the Rhythm row)
  8338. {
  8339. namespace ef = lynx::echosuite::echoform;
  8340. auto fx = lynx::makeEffectSlot (lynx::EffectKind::echoform);
  8341. fx.params[ef::voicing] = ef::voicingValue (ef::voicingForEchoBoyStyle (19));
  8342. fx.params[ef::style] = ef::styleValue (ef::Style::dual);
  8343. lynx::Song song;
  8344. song.mixer.resize (2);
  8345. song.mixer[0].name = "Master";
  8346. song.mixer[1].name = "Insert 1";
  8347. song.mixer[1].effects.push_back (fx);
  8348. offline.setSong (std::move (song));
  8349. offline.dispatchPendingMessages();
  8350. auto editor = lynx::makeNativeEffectEditor (offline, 1, 0, 1.0f, 0);
  8351. juce::Image image (juce::Image::ARGB, editor->getWidth(), editor->getHeight(), true);
  8352. {
  8353. juce::Graphics g (image);
  8354. g.fillAll (lynx::theme::panel);
  8355. editor->paintEntireComponent (g, false);
  8356. }
  8357. const auto file = out.getChildFile ("Echoform-voicing.png");
  8358. file.deleteFile();
  8359. juce::PNGImageFormat png;
  8360. if (auto stream = file.createOutputStream())
  8361. png.writeImageToStream (image, *stream);
  8362. }
  8363. // round 150: Auto-pan's Rhythm voicing with its Tweak row (PanMan's role)
  8364. {
  8365. auto fx = lynx::makeEffectSlot (lynx::EffectKind::autoPan);
  8366. fx.params[lynx::autopan::count] = 1.0f; // the Rhythm voicing
  8367. fx.params[lynx::autopan::count + 13] = 0.75f; // offset mod +90°
  8368. lynx::Song song;
  8369. song.mixer.resize (2);
  8370. song.mixer[0].name = "Master";
  8371. song.mixer[1].name = "Insert 1";
  8372. song.mixer[1].effects.push_back (fx);
  8373. offline.setSong (std::move (song));
  8374. offline.dispatchPendingMessages();
  8375. auto editor = lynx::makeNativeEffectEditor (offline, 1, 0, 1.0f, 0);
  8376. juce::Image image (juce::Image::ARGB, editor->getWidth(), editor->getHeight(), true);
  8377. {
  8378. juce::Graphics g (image);
  8379. g.fillAll (lynx::theme::panel);
  8380. editor->paintEntireComponent (g, false);
  8381. }
  8382. const auto file = out.getChildFile ("Auto-pan-tweak.png");
  8383. file.deleteFile();
  8384. juce::PNGImageFormat png;
  8385. if (auto stream = file.createOutputStream())
  8386. png.writeImageToStream (image, *stream);
  8387. }
  8388. // round 165: Ember's Classic voicing (the Decapitator role) in its one-screen panel
  8389. {
  8390. namespace em = lynx::mixsuite::ember;
  8391. auto fx = lynx::makeEffectSlot (lynx::EffectKind::ember);
  8392. fx.params[em::voicing] = 1.0f;
  8393. fx.params[em::classicDrive] = 0.35f;
  8394. lynx::Song song;
  8395. song.mixer.resize (2);
  8396. song.mixer[0].name = "Master";
  8397. song.mixer[1].name = "Insert 1";
  8398. song.mixer[1].effects.push_back (fx);
  8399. offline.setSong (std::move (song));
  8400. offline.dispatchPendingMessages();
  8401. auto editor = lynx::makeNativeEffectEditor (offline, 1, 0, 1.0f, 0);
  8402. juce::Image image (juce::Image::ARGB, editor->getWidth(), editor->getHeight(), true);
  8403. {
  8404. juce::Graphics g (image);
  8405. g.fillAll (lynx::theme::panel);
  8406. editor->paintEntireComponent (g, false);
  8407. }
  8408. const auto file = out.getChildFile ("Ember Saturator-classic.png");
  8409. file.deleteFile();
  8410. juce::PNGImageFormat png;
  8411. if (auto stream = file.createOutputStream())
  8412. png.writeImageToStream (image, *stream);
  8413. }
  8414. // round 152: Foil Plate's one-knob Plate view (the Little Plate role)
  8415. {
  8416. auto fx = lynx::makeEffectSlot (lynx::EffectKind::foilPlate);
  8417. fx.params[14] = 1.0f; // the measured plate voicing
  8418. fx.params[15] = 1.0f; // View = Plate
  8419. lynx::Song song;
  8420. song.mixer.resize (2);
  8421. song.mixer[0].name = "Master";
  8422. song.mixer[1].name = "Insert 1";
  8423. song.mixer[1].effects.push_back (fx);
  8424. offline.setSong (std::move (song));
  8425. offline.dispatchPendingMessages();
  8426. auto editor = lynx::makeNativeEffectEditor (offline, 1, 0, 1.0f, 0);
  8427. juce::Image image (juce::Image::ARGB, editor->getWidth(), editor->getHeight(), true);
  8428. {
  8429. juce::Graphics g (image);
  8430. g.fillAll (lynx::theme::panel);
  8431. editor->paintEntireComponent (g, false);
  8432. }
  8433. const auto file = out.getChildFile ("Foil Plate-plate.png");
  8434. file.deleteFile();
  8435. juce::PNGImageFormat png;
  8436. if (auto stream = file.createOutputStream())
  8437. png.writeImageToStream (image, *stream);
  8438. }
  8439. // LYNX's own editors with live displays (round 103): Facet EQ (a mixing curve, one dynamic band, demo analyser)
  8440. // and LYNX Tune (demo pitch phrase)
  8441. {
  8442. lynx::setNativeEditorDemo (true);
  8443. using namespace lynx::facet;
  8444. auto eq = lynx::makeEffectSlot (lynx::EffectKind::facetEq);
  8445. const struct { Shape s; double f, g, q; int slope; double range; } bandsDemo[] = {
  8446. { Shape::lowCut, 32, 0, 1, 24, 0 }, { Shape::bell, 110, 3, 1.2, 12, 0 }, { Shape::bell, 380, -3.5, 1.6, 12, 0 },
  8447. { Shape::bell, 3200, 0, 2.5, 12, -6 }, { Shape::highShelf, 9000, 2.5, 0.8, 12, 0 }
  8448. };
  8449. for (int b = 0; b < 5; ++b)
  8450. {
  8451. eq.params[(std::size_t) param (b, 0)] = shapeValue (bandsDemo[b].s);
  8452. eq.params[(std::size_t) param (b, 1)] = hzValue (bandsDemo[b].f);
  8453. eq.params[(std::size_t) param (b, 2)] = gainValue (bandsDemo[b].g);
  8454. eq.params[(std::size_t) param (b, 3)] = qValue (bandsDemo[b].q);
  8455. eq.params[(std::size_t) param (b, 4)] = slopeValue (bandsDemo[b].slope);
  8456. eq.params[(std::size_t) (rangeParam0 + b)] = rangeValue (bandsDemo[b].range);
  8457. }
  8458. eq.params[(std::size_t) phaseParam] = phaseValue (Phase::natural);
  8459. const auto own = [&] (const lynx::EffectSlot& fx, const juce::String& file, bool facetEditor, int page = 0) {
  8460. lynx::Song song;
  8461. song.mixer.resize (2);
  8462. song.mixer[0].name = "Master";
  8463. song.mixer[1].name = "Vocal";
  8464. song.mixer[1].effects.push_back (fx);
  8465. offline.setSong (std::move (song));
  8466. offline.dispatchPendingMessages();
  8467. auto editor = facetEditor ? lynx::makeFacetEqEditor (offline, 1, 0, true) : lynx::makeNativeEffectEditor (offline, 1, 0, 1.25f, page);
  8468. juce::Image image (juce::Image::ARGB, editor->getWidth(), editor->getHeight(), true);
  8469. {
  8470. juce::Graphics g (image);
  8471. g.fillAll (lynx::theme::panel);
  8472. editor->paintEntireComponent (g, false);
  8473. }
  8474. const auto f = out.getChildFile (file);
  8475. f.deleteFile();
  8476. juce::PNGImageFormat png;
  8477. if (auto stream = f.createOutputStream())
  8478. png.writeImageToStream (image, *stream);
  8479. };
  8480. own (eq, "Facet EQ.png", true);
  8481. own (lynx::makeEffectSlot (lynx::EffectKind::lynxTune), "LYNX Tune.png", false);
  8482. {
  8483. // round 128: the ADVANCED page, with E bypassed and A removed on the keyboard and a created vibrato
  8484. auto tune = lynx::makeEffectSlot (lynx::EffectKind::lynxTune);
  8485. tune.params[(std::size_t) (lynx::lynxtune::bypassC + 4)] = 1.0f;
  8486. tune.params[(std::size_t) (lynx::lynxtune::noteC + 9)] = 0.0f;
  8487. tune.params[lynx::lynxtune::vibratoShape] = 1.0f / 3.0f;
  8488. // round 166c: the created vibrato's amplitude / formant / variation, a short throat, In scale +2
  8489. tune.params[lynx::lynxtune::vibratoAmplitude] = 1.0f / 3.0f;
  8490. tune.params[lynx::lynxtune::vibratoFormant] = 0.7f;
  8491. tune.params[lynx::lynxtune::vibratoVariation] = 0.2f;
  8492. tune.params[lynx::lynxtune::throatLength] = lynx::lynxtune::throatValue (80.0);
  8493. tune.params[lynx::lynxtune::transposeInScale] = 1.0f;
  8494. tune.params[lynx::lynxtune::scaleTranspose] = lynx::lynxtune::scaleTransposeValue (2);
  8495. own (tune, "LYNX Tune-p2.png", false, 1);
  8496. }
  8497. own (lynx::makeEffectSlot (lynx::EffectKind::lynxTune), "LYNX Tune-p3.png", false, 2); // round 135w: Real-time
  8498. lynx::setNativeEditorDemo (false);
  8499. }
  8500. // generators in FL's arrangement: the channel's plugin page with the FL preset's settings
  8501. const auto generators = juce::File (juce::String::fromUTF8 (roots.data.c_str())).getChildFile ("Patches/Plugin presets/Generators");
  8502. 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" } })
  8503. {
  8504. juce::MemoryBlock data;
  8505. if (juce::String (folder) == "Harmor") // the first preset whose state the engine reads
  8506. {
  8507. auto files = generators.getChildFile (folder).findChildFiles (juce::File::findFiles, true, "*.fst");
  8508. files.sort();
  8509. for (const auto& f : files)
  8510. {
  8511. juce::MemoryBlock block;
  8512. if (! f.loadFileAsData (block))
  8513. continue;
  8514. const auto* b = static_cast<const std::uint8_t*> (block.getData());
  8515. try
  8516. {
  8517. const auto p = flp::parseProject (std::vector<std::uint8_t> (b, b + block.getSize()), true);
  8518. if (! p.channels.empty() && lynx::harmorStateUsable (p.channels.front().pluginState))
  8519. {
  8520. preset = nullptr;
  8521. data = block;
  8522. break;
  8523. }
  8524. }
  8525. catch (const std::exception&)
  8526. {
  8527. }
  8528. }
  8529. }
  8530. auto file = preset == nullptr ? juce::File() : juce::String (preset).isEmpty() ? database.getSiblingFile ("Generators").getChildFile ("Misc").getChildFile (juce::String (folder) + ".fst")
  8531. : generators.getChildFile (folder).getChildFile (preset);
  8532. if (! file.existsAsFile())
  8533. {
  8534. auto files = generators.getChildFile (folder).findChildFiles (juce::File::findFiles, true, "*.fst");
  8535. files.sort();
  8536. file = files.isEmpty() ? juce::File() : files[0];
  8537. }
  8538. if (data.isEmpty() && ! file.loadFileAsData (data))
  8539. continue;
  8540. try
  8541. {
  8542. const auto* bytes = static_cast<const std::uint8_t*> (data.getData());
  8543. auto project = flp::parseProject (std::vector<std::uint8_t> (bytes, bytes + data.getSize()), true);
  8544. if (project.channels.empty())
  8545. continue;
  8546. project.channels.front().type = flp::ChannelType::native;
  8547. lynx::FlpImportOptions options;
  8548. options.roots = roots;
  8549. options.fileExists = [] (const std::string& path) { return lynx::platform::localFile (path).existsAsFile(); };
  8550. options.readFile = [] (const std::string& path) {
  8551. juce::MemoryBlock block;
  8552. lynx::platform::localFile (path).loadFileAsData (block);
  8553. const auto* b = static_cast<const std::uint8_t*> (block.getData());
  8554. return std::vector<std::uint8_t> (b, b + block.getSize());
  8555. };
  8556. options.saveEmbedded = [out] (const std::vector<std::uint8_t>& wav, const std::string& name) {
  8557. const auto f = out.getChildFile ("samples").getNonexistentChildFile (juce::String::fromUTF8 (name.c_str()), ".wav");
  8558. f.getParentDirectory().createDirectory();
  8559. f.replaceWithData (wav.data(), wav.size());
  8560. return f.getFullPathName().toStdString();
  8561. };
  8562. auto song = lynx::importFlp (project, options);
  8563. // the page only needs the plugin's saved state (FL Keys' sample zones need the installed wavetables)
  8564. if (! song.channels.empty() && project.channels.front().pluginName == "BooBass" && song.channels.front().instrument != lynx::InstrumentKind::boobass)
  8565. {
  8566. song.channels.front().instrument = lynx::InstrumentKind::boobass; // (its sound needs the engine DLL; the page does not)
  8567. song.channels.front().modelParams.assign (3, 32768.0f);
  8568. }
  8569. if (! song.channels.empty() && project.channels.front().pluginName == "FL Keys")
  8570. {
  8571. song.channels.front().instrument = lynx::InstrumentKind::flkeys;
  8572. song.channels.front().pluginState = project.channels.front().pluginState;
  8573. }
  8574. offline.setSong (std::move (song));
  8575. offline.dispatchPendingMessages();
  8576. if (offline.getSong().channels.empty())
  8577. continue;
  8578. auto panel = lynx::makeChannelSettingsPanel (offline, 0);
  8579. juce::Image image (juce::Image::ARGB, panel->getWidth(), panel->getHeight(), true);
  8580. {
  8581. juce::Graphics g (image);
  8582. g.fillAll (lynx::theme::panel);
  8583. panel->paintEntireComponent (g, false);
  8584. }
  8585. const auto out2 = out.getChildFile (juce::String (folder) + ".png");
  8586. out2.deleteFile();
  8587. juce::PNGImageFormat png;
  8588. if (auto stream = out2.createOutputStream())
  8589. png.writeImageToStream (image, *stream);
  8590. }
  8591. catch (const std::exception&)
  8592. {
  8593. }
  8594. }
  8595. }
  8596. quit();
  8597. }
  8598. void runVideoShot (const juce::String& prefix, const juce::String& videoPath)
  8599. {
  8600. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  8601. // the message loop runs while the frames decode (modal loops are off): a timer takes one snapshot per step
  8602. struct VideoShot final : juce::Timer
  8603. {
  8604. lynx::AudioEngine offline { false };
  8605. std::unique_ptr<juce::Component> editor;
  8606. juce::String prefix, report;
  8607. int step = 0;
  8608. std::function<void()> done;
  8609. void moveTo (double seconds)
  8610. {
  8611. offline.getTransport().positionTicks.store (seconds * offline.getSong().bpm / 60.0 * lynx::ppq);
  8612. }
  8613. void timerCallback() override
  8614. {
  8615. static constexpr double times[] = { 0.0, 1.5, 3.25 };
  8616. constexpr int typeInStep = (int) std::size (times) + 1;
  8617. if (step > 0 && step < typeInStep && editor != nullptr)
  8618. savePng (editor->createComponentSnapshot (editor->getLocalBounds()), prefix + "-" + juce::String (step - 1) + ".png");
  8619. if (editor != nullptr && step == (int) std::size (times))
  8620. {
  8621. // round 174d: FL's in-place type-in of the current time (a right click on it)
  8622. lynx::videoview::openTypeIn (*editor, 2);
  8623. ++step;
  8624. return;
  8625. }
  8626. if (editor != nullptr && step == typeInStep)
  8627. savePng (editor->createComponentSnapshot (editor->getLocalBounds()), prefix + "-typein.png");
  8628. if (editor == nullptr || step >= typeInStep)
  8629. {
  8630. stopTimer();
  8631. juce::File (prefix + "-report.txt").replaceWithText (report);
  8632. if (done)
  8633. done();
  8634. return;
  8635. }
  8636. moveTo (times[step++]);
  8637. }
  8638. };
  8639. static std::unique_ptr<VideoShot> shot;
  8640. shot = std::make_unique<VideoShot>();
  8641. shot->prefix = prefix;
  8642. auto& offline = shot->offline;
  8643. lynx::videoview::install (offline);
  8644. lynx::Song song;
  8645. song.mixer = lynx::Song::defaultMixer (2);
  8646. lynx::ChannelDef c;
  8647. c.name = "Fruity Video Player";
  8648. c.instrument = lynx::InstrumentKind::videoplayer;
  8649. lynx::video::Settings vs;
  8650. vs.path = juce::File (videoPath).getFullPathName().toStdString();
  8651. vs.delay = lynx::video::unitsPerSecond / 2; // the video starts at 0.5 s
  8652. c.pluginState = lynx::video::write (vs);
  8653. song.channels.push_back (c);
  8654. song.patterns.emplace_back();
  8655. {
  8656. // round 174d (A3): the same Video Player in a song whose tempo drops from 120 to 60 BPM at bar 5, for FL
  8657. // (LYNX.exe --export-flp <prefix>-tempo.lynx <prefix>-tempo.flp), to compare FL's video clock with LYNX's
  8658. auto fl = song;
  8659. fl.bpm = 120.0;
  8660. fl.mode = lynx::PlayMode::song;
  8661. auto settings = vs;
  8662. settings.delay = 0;
  8663. settings.timeDisplay = lynx::video::Settings {}.timeDisplay;
  8664. fl.channels[0].pluginState = lynx::video::write (settings);
  8665. fl.patterns[0].name = "Pattern 1";
  8666. lynx::Automation tempo;
  8667. tempo.name = "Tempo";
  8668. tempo.target = { lynx::AutomationTargetKind::tempo, 0, 0, 0 };
  8669. const auto bar = (std::int64_t) lynx::ppq * 4;
  8670. tempo.points = { { 0, lynx::valueFromTempo (120.0), 0.0f }, { bar * 4 - 1, lynx::valueFromTempo (120.0), 0.0f },
  8671. { bar * 4, lynx::valueFromTempo (60.0), 0.0f }, { bar * 8, lynx::valueFromTempo (60.0), 0.0f } };
  8672. fl.automations.push_back (tempo);
  8673. lynx::Clip at;
  8674. at.kind = lynx::ClipKind::automation;
  8675. at.automation = 0;
  8676. at.track = 1;
  8677. at.start = 0;
  8678. at.length = bar * 8;
  8679. fl.playlist.push_back (at);
  8680. lynx::Clip pc;
  8681. pc.pattern = 0;
  8682. pc.track = 0;
  8683. pc.start = 0;
  8684. pc.length = bar * 8;
  8685. fl.playlist.push_back (pc);
  8686. juce::String error;
  8687. lynx::ProjectFile::save (fl, juce::File (prefix + "-tempo.lynx"), error);
  8688. }
  8689. offline.setSong (std::move (song));
  8690. offline.dispatchPendingMessages();
  8691. auto& report = shot->report;
  8692. report << "ffmpeg: " << lynx::findFfmpeg().getFullPathName() << "\n";
  8693. report << lynx::videoview::report (vs.path).fromFirstOccurrenceOf ("Input #0", true, false).upToFirstOccurrenceOf ("At least", false, false) << "\n";
  8694. shot->editor = lynx::makeChannelSettingsPanel (offline, 0);
  8695. if (shot->editor != nullptr)
  8696. shot->editor->setVisible (true);
  8697. shot->done = [this] { juce::MessageManager::callAsync ([this] { shot.reset(); quit(); }); };
  8698. shot->startTimer (1500);
  8699. }
  8700. void runVideoTrackShot (const juce::String& prefix, const juce::String& videoPath, const juce::String& secondPath)
  8701. {
  8702. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  8703. struct TrackShot final : juce::Timer
  8704. {
  8705. lynx::AudioEngine offline { false };
  8706. std::unique_ptr<lynx::PlaylistComponent> playlist;
  8707. std::unique_ptr<lynx::media::FrameDecoder> decoder;
  8708. juce::String prefix, report, path;
  8709. double fps = 25.0;
  8710. int step = 0, waits = 0, adrStep = 0;
  8711. std::unique_ptr<juce::Component> adrPanel;
  8712. std::function<void()> done;
  8713. // song times (s): before, inside the first clip (on and between frame edges), across the second clip
  8714. std::vector<double> times { 0.0, 1.0, 2.0 + 1.0 / 25.0, 2.5, 4.0, 7.3 };
  8715. void timerCallback() override
  8716. {
  8717. if (step > 0 && adrStep == 0)
  8718. {
  8719. // the frame the decoder shows for the wanted file time (the clip starts at song 1.0 s, offset 0)
  8720. const auto want = times[(std::size_t) step - 1] - 1.0;
  8721. double ft = -1.0;
  8722. const auto img = decoder->frame (ft);
  8723. const auto expected = std::floor (want * fps + 1e-6) / fps;
  8724. if (want >= 0.0 && ft < expected - 1e-3 && ++waits < 20)
  8725. return; // (still decoding)
  8726. waits = 0;
  8727. report << "song " << juce::String (times[(std::size_t) step - 1], 3) << " s: wanted file time " << juce::String (want, 4)
  8728. << ", frame shown at " << juce::String (ft, 4) << " (expected " << juce::String (expected, 4) << ")"
  8729. << (want < 0.0 ? " [before the clip]" : std::abs (ft - expected) < 1e-3 ? " OK" : " MISMATCH") << "\n";
  8730. savePng (playlist->createComponentSnapshot (playlist->getLocalBounds()), prefix + "-playlist-" + juce::String (step - 1) + ".png");
  8731. if (img.isValid())
  8732. savePng (img, prefix + "-frame-" + juce::String (step - 1) + ".png");
  8733. for (int w = 0; w < juce::Desktop::getInstance().getNumComponents(); ++w)
  8734. if (auto* c = juce::Desktop::getInstance().getComponent (w); c != nullptr && c->getName().startsWith ("Picture"))
  8735. savePng (c->createComponentSnapshot (c->getLocalBounds()), prefix + "-window-" + juce::String (step - 1) + ".png");
  8736. }
  8737. if (step >= (int) times.size() && adrStep == 0)
  8738. {
  8739. // the ADR window: two cues, takes on the first; the play position inside the streamer before the in
  8740. // point (4.0 s), so the video window shows the streamer and the line
  8741. adrStep = 1;
  8742. offline.editSong ([] (lynx::Song& s) {
  8743. lynx::AdrCue a, b;
  8744. a.id = "SC1-01";
  8745. a.in = 4.0;
  8746. a.out = 6.4;
  8747. a.character = "Dr. Silva";
  8748. a.line = "We have to leave before the storm reaches the coast.";
  8749. a.notes = "softer, out of breath";
  8750. a.status = lynx::AdrCue::Status::recorded;
  8751. for (int n = 1; n <= 3; ++n)
  8752. {
  8753. lynx::AdrTake t;
  8754. t.number = n;
  8755. t.name = lynx::adr::takeName (a, n);
  8756. t.rating = n == 2 ? 4 : n;
  8757. t.circled = n == 2;
  8758. a.takes.push_back (t);
  8759. }
  8760. a.selected = 2;
  8761. lynx::adr::setCompRange (a, 4.0, 5.1, 2);
  8762. lynx::adr::setCompRange (a, 5.1, 6.4, 3);
  8763. b.id = "SC1-02";
  8764. b.in = 8.0;
  8765. b.out = 9.5;
  8766. b.character = "Marta";
  8767. b.line = "Then we go now.";
  8768. s.adr.cues = { a, b };
  8769. s.adr.current = 0;
  8770. });
  8771. adrPanel = lynx::adrwindow::makePanel (offline);
  8772. adrPanel->setSize (1200, 640);
  8773. adrPanel->setVisible (true);
  8774. offline.getTransport().positionTicks.store (3.0 * offline.getSong().bpm / 60.0 * lynx::ppq);
  8775. decoder->request (2.0, false);
  8776. return;
  8777. }
  8778. if (adrStep == 1)
  8779. {
  8780. adrStep = 2;
  8781. savePng (adrPanel->createComponentSnapshot (adrPanel->getLocalBounds()), prefix + "-adr.png");
  8782. for (int w = 0; w < juce::Desktop::getInstance().getNumComponents(); ++w)
  8783. if (auto* c = juce::Desktop::getInstance().getComponent (w); c != nullptr && c->getName().startsWith ("Picture"))
  8784. savePng (c->createComponentSnapshot (c->getLocalBounds()), prefix + "-adr-window.png");
  8785. offline.getTransport().positionTicks.store (4.5 * offline.getSong().bpm / 60.0 * lynx::ppq);
  8786. decoder->request (3.5, false);
  8787. return;
  8788. }
  8789. if (adrStep == 2)
  8790. {
  8791. for (int w = 0; w < juce::Desktop::getInstance().getNumComponents(); ++w)
  8792. if (auto* c = juce::Desktop::getInstance().getComponent (w); c != nullptr && c->getName().startsWith ("Picture"))
  8793. savePng (c->createComponentSnapshot (c->getLocalBounds()), prefix + "-adr-window-line.png");
  8794. adrPanel.reset();
  8795. // export with video: a 3 s mix under the picture, re-encoded (the clip starts at 1 s) and copied (from 1 s)
  8796. {
  8797. const juce::File wav (prefix + "-mix.wav");
  8798. wav.deleteFile();
  8799. juce::WavAudioFormat format;
  8800. if (std::unique_ptr<juce::OutputStream> os (wav.createOutputStream().release()); os != nullptr)
  8801. if (std::unique_ptr<juce::AudioFormatWriter> w (format.createWriterFor (os.get(), 48000.0, 2, 16, {}, 0)); w != nullptr)
  8802. {
  8803. os.release();
  8804. juce::AudioBuffer<float> b (2, 48000 * 3);
  8805. for (int k = 0; k < b.getNumSamples(); ++k)
  8806. 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));
  8807. w->writeFromAudioSampleBuffer (b, 0, b.getNumSamples());
  8808. }
  8809. for (const auto origin : { 0.0, 1.0 })
  8810. {
  8811. const juce::File out (prefix + "-mux-" + juce::String ((int) origin) + ".mp4");
  8812. const auto t0 = juce::Time::getMillisecondCounterHiRes();
  8813. const auto error = lynx::videotracks::muxWithVideo (offline.getSong(), origin, wav, out);
  8814. report << "export with video from " << origin << " s: " << (error.isEmpty() ? "OK " + juce::String (out.getSize()) + " bytes" : "FAILED " + error)
  8815. << " (" << juce::String ((juce::Time::getMillisecondCounterHiRes() - t0) / 1000.0, 2) << " s)\n";
  8816. }
  8817. }
  8818. stopTimer();
  8819. report << "frames decoded " << decoder->frameCount() << ", dropped " << decoder->droppedCount() << "\n";
  8820. juce::File (prefix + "-report.txt").replaceWithText (report);
  8821. if (done)
  8822. done();
  8823. return;
  8824. }
  8825. const auto t = times[(std::size_t) step++];
  8826. offline.getTransport().positionTicks.store (t * offline.getSong().bpm / 60.0 * lynx::ppq);
  8827. decoder->request (std::max (0.0, t - 1.0), false);
  8828. }
  8829. };
  8830. static std::unique_ptr<TrackShot> shot;
  8831. shot = std::make_unique<TrackShot>();
  8832. shot->prefix = prefix;
  8833. auto& offline = shot->offline;
  8834. lynx::Song song;
  8835. song.mixer = lynx::Song::defaultMixer (2);
  8836. song.patterns.emplace_back();
  8837. song.mode = lynx::PlayMode::song;
  8838. song.bpm = 120.0;
  8839. offline.setSong (std::move (song));
  8840. offline.dispatchPendingMessages();
  8841. const juce::File video (videoPath);
  8842. const auto pr = lynx::media::probe (video.getFullPathName());
  8843. auto& report = shot->report;
  8844. report << "decoder: " << (pr.backend.isEmpty() ? juce::String ("none") : pr.backend) << " (system: " << lynx::media::nativeBackendName()
  8845. << ", ffmpeg: " << lynx::findFfmpeg().getFullPathName() << ")\n";
  8846. report << "video: " << pr.info.width << "x" << pr.info.height << " " << juce::String (pr.info.fps, 3) << " fps " << juce::String (pr.info.duration, 3)
  8847. << " s, sound " << (pr.info.hasAudio ? "yes" : "no") << "\n";
  8848. shot->fps = pr.info.fps > 1.0 ? pr.info.fps : 25.0;
  8849. shot->times[2] = 2.0 + 1.0 / shot->fps; // (exactly on a frame edge)
  8850. lynx::videotracks::importVideo (offline, video, 1.0, -1);
  8851. if (secondPath.isNotEmpty())
  8852. lynx::videotracks::importVideo (offline, juce::File (secondPath), 3.0, 1);
  8853. offline.editSong ([] (lynx::Song& s) {
  8854. s.video.startTimecode = 3600.0;
  8855. s.video.burnIn = true;
  8856. if (s.videoTracks.size() < 2)
  8857. s.videoTracks.push_back ({});
  8858. s.videoTracks[0].name = "Picture";
  8859. s.videoTracks[1].name = "Reference";
  8860. });
  8861. report << "project rate: " << lynx::vtime::rateName (offline.getSong().video.rate) << ", clip 1: "
  8862. << juce::String (offline.getSong().videoTracks[0].clips.empty() ? -1.0 : offline.getSong().videoTracks[0].clips[0].length, 3) << " s\n";
  8863. // the project round trip
  8864. {
  8865. const juce::File file (prefix + "-project.lynx");
  8866. juce::String error;
  8867. lynx::ProjectFile::save (offline.getSong(), file, error);
  8868. const auto back = lynx::ProjectFile::load (file, error);
  8869. report << "project file round trip: " << (back && back->videoTracks == offline.getSong().videoTracks && back->video == offline.getSong().video ? "OK" : "MISMATCH " + error) << "\n";
  8870. }
  8871. shot->playlist = std::make_unique<lynx::PlaylistComponent> (offline);
  8872. shot->playlist->setSize (1400, 640);
  8873. shot->playlist->setVisible (true);
  8874. shot->decoder = std::make_unique<lynx::media::FrameDecoder>();
  8875. shot->decoder->setSource (video.getFullPathName(), pr.info);
  8876. shot->decoder->setSize (pr.info.width, pr.info.height);
  8877. shot->decoder->startThread (juce::Thread::Priority::low);
  8878. lynx::videotracks::showWindow (offline, 0);
  8879. shot->done = [this] { juce::MessageManager::callAsync ([this] { shot.reset(); quit(); }); };
  8880. shot->startTimer (700);
  8881. }
  8882. void runDanceShot (const juce::String& prefix)
  8883. {
  8884. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  8885. // the moves: one row each, eight moments of a cycle (both facings for Spinning; Pose ends the sheet)
  8886. {
  8887. constexpr int cell = 120, cols = 8;
  8888. juce::Image sheet (juce::Image::ARGB, 130 + cols * cell, lynx::dance::moveCount * cell + 10, true);
  8889. juce::Graphics g (sheet);
  8890. g.fillAll (lynx::theme::colour::bg0);
  8891. for (int m = 0; m < lynx::dance::moveCount; ++m)
  8892. {
  8893. g.setColour (lynx::theme::colour::textSecondary);
  8894. g.setFont (14.0f);
  8895. g.drawText (lynx::dance::moveName (m), 8, m * cell + 5, 118, cell, juce::Justification::centredLeft);
  8896. for (int k = 0; k < cols; ++k)
  8897. {
  8898. const auto pose = lynx::dance::pose (m, k / (double) cols + (m == lynx::dance::freestyle ? k * 2 : 0), 1);
  8899. lynx::dancer::draw (g, { 130.0f + (k + 0.5f) * cell, (float) (m + 1) * cell - 6.0f }, 92.0f, pose, false, juce::Colour (0xffff3048));
  8900. }
  8901. }
  8902. savePng (sheet, prefix + "-moves.png");
  8903. }
  8904. lynx::AudioEngine offline (false);
  8905. lynx::Song song;
  8906. song.mixer = lynx::Song::defaultMixer (2);
  8907. for (int d = 0; d < 2; ++d)
  8908. {
  8909. lynx::ChannelDef c;
  8910. c.name = d == 0 ? "Fruity Dance" : "Fruity Dance #2";
  8911. c.instrument = lynx::InstrumentKind::fruitydance;
  8912. lynx::dance::Settings s;
  8913. s.move = d == 0 ? lynx::dance::stepping : lynx::dance::waving;
  8914. s.x = d == 0 ? 520 : 760;
  8915. s.y = 560;
  8916. s.colour = d == 0 ? 0xffff3048 : 0xff30a8ff;
  8917. s.mirrored = d == 1;
  8918. c.pluginState = lynx::dance::toState (s);
  8919. song.channels.push_back (c);
  8920. }
  8921. song.patterns.emplace_back();
  8922. {
  8923. const juce::File demo (prefix + "-demo.lynx");
  8924. juce::String error;
  8925. lynx::ProjectFile::save (song, demo, error);
  8926. }
  8927. offline.setSong (std::move (song));
  8928. offline.dispatchPendingMessages();
  8929. if (auto editor = lynx::makeChannelSettingsPanel (offline, 0))
  8930. savePng (editor->createComponentSnapshot (editor->getLocalBounds()), prefix + "-editor.png");
  8931. if (auto frame = lynx::makeChannelFrame (offline, 1, 0))
  8932. savePng (frame->createComponentSnapshot (frame->getLocalBounds()), prefix + "-frame.png");
  8933. }
  8934. void runControllerShot (const juce::String& prefix)
  8935. {
  8936. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  8937. lynx::AudioEngine offline (false);
  8938. lynx::Song song;
  8939. song.mixer = lynx::Song::defaultMixer (2);
  8940. song.mixer[1].name = "Insert 1";
  8941. auto fx = lynx::makeEffectSlot (lynx::EffectKind::formulaController);
  8942. lynx::formula::State formula;
  8943. formula.formula = "a*Sin(SongTime*Pi*b*4)+c";
  8944. fx.state = lynx::formula::writeState (formula);
  8945. fx.params[0] = 0.5f;
  8946. fx.params[1] = 0.25f;
  8947. fx.params[2] = 0.5f;
  8948. song.mixer[1].effects.push_back (fx);
  8949. // round 164: X-Y (slot 2), X-Y-Z (slot 3) and a Control Surface (slot 4)
  8950. {
  8951. auto xyFx = lynx::makeEffectSlot (lynx::EffectKind::xyController);
  8952. xyFx.params[(std::size_t) lynx::xy::level (0)] = 0.3f;
  8953. xyFx.params[(std::size_t) lynx::xy::level (1)] = 0.7f;
  8954. xyFx.params[(std::size_t) lynx::xy::tension (0)] = 0.8f;
  8955. song.mixer[1].effects.push_back (xyFx);
  8956. auto xyzFx = lynx::makeEffectSlot (lynx::EffectKind::xyzController);
  8957. xyzFx.params[(std::size_t) lynx::xy::level (2)] = 0.8f;
  8958. song.mixer[1].effects.push_back (xyzFx);
  8959. // round 165: an X-Y-Z whose X curve is FL's "Stairs" (tension +40 %) and Y a bent single curve
  8960. xyzFx.params[(std::size_t) lynx::xy::curveMode (0)] = lynx::xy::curveModeValue (lynx::flcurve::stairs);
  8961. xyzFx.params[(std::size_t) lynx::xy::tension (0)] = 0.7f;
  8962. xyzFx.params[(std::size_t) lynx::xy::level (0)] = 0.62f;
  8963. xyzFx.params[(std::size_t) lynx::xy::tension (1)] = 0.825f;
  8964. song.mixer[1].effects.push_back (xyzFx);
  8965. auto panel = lynx::makeEffectSlot (lynx::EffectKind::controlSurface);
  8966. lynx::SurfaceControl c;
  8967. for (const auto& [kind, name, v, x, y] : std::vector<std::tuple<lynx::SurfaceControl::Kind, const char*, float, float, float>> {
  8968. { lynx::SurfaceControl::Kind::knob, "Cutoff", 0.65f, 20.0f, 20.0f },
  8969. { lynx::SurfaceControl::Kind::knob, "Reso", 0.3f, 90.0f, 20.0f },
  8970. { lynx::SurfaceControl::Kind::slider, "Mix", 0.8f, 170.0f, 20.0f },
  8971. { lynx::SurfaceControl::Kind::xy, "Space", 0.4f, 230.0f, 20.0f },
  8972. { lynx::SurfaceControl::Kind::button, "Drop", 0.0f, 20.0f, 110.0f },
  8973. { lynx::SurfaceControl::Kind::checkBox, "Bypass", 1.0f, 20.0f, 160.0f } })
  8974. {
  8975. c.kind = kind;
  8976. c.name = name;
  8977. c.value = v;
  8978. c.valueY = 0.6f;
  8979. c.x = x;
  8980. c.y = y;
  8981. lynx::surface::add (panel, c);
  8982. }
  8983. song.mixer[1].effects.push_back (panel);
  8984. }
  8985. lynx::ChannelDef env;
  8986. env.name = "Envelope Controller";
  8987. env.instrument = lynx::InstrumentKind::controller;
  8988. auto ecData = lynx::defaultEnvelopeController();
  8989. ecData[0].lfoOn = true;
  8990. ecData[0].lfoTempo = true;
  8991. ecData[0].lfoSpeed = 40898;
  8992. ecData[0].maps[lynx::mapKeyboard].count = 2;
  8993. ecData[0].maps[lynx::mapKeyboard].time = { 0.2f, 0.8f };
  8994. ecData[0].maps[lynx::mapKeyboard].level = { 0.0f, 1.0f };
  8995. ecData[0].maps[lynx::mapModX] = ecData[0].maps[lynx::mapKeyboard];
  8996. env.controllerState = lynx::writeEnvelopeController (ecData);
  8997. song.channels.push_back (env);
  8998. lynx::ChannelDef out;
  8999. out.name = "MIDI Out";
  9000. out.instrument = lynx::InstrumentKind::midiOut;
  9001. lynx::midictl::MidiOutSettings settings;
  9002. settings.port = 1;
  9003. lynx::midictl::writeMidiOut (out.pluginState, settings);
  9004. song.channels.push_back (out);
  9005. // a Layer (round 164) over three synths split across the keyboard, crossfading
  9006. for (const auto* name : { "Bass", "Pad", "Lead" })
  9007. {
  9008. lynx::ChannelDef c;
  9009. c.name = name;
  9010. c.instrument = lynx::InstrumentKind::synth;
  9011. song.channels.push_back (c);
  9012. }
  9013. {
  9014. lynx::ChannelDef layer;
  9015. layer.name = "Layer";
  9016. layer.instrument = lynx::InstrumentKind::layer;
  9017. song.channels.push_back (layer);
  9018. const auto self = (int) song.channels.size() - 1;
  9019. lynx::layer::setChildren (song, self, { 2, 3, 4 });
  9020. song.channels[2].keyLow = 0, song.channels[2].keyHigh = 47;
  9021. song.channels[3].keyLow = 36, song.channels[3].keyHigh = 83;
  9022. song.channels[4].keyLow = 72, song.channels[4].keyHigh = 127;
  9023. song.channels[(std::size_t) self].layer.crossfade = true;
  9024. song.channels[(std::size_t) self].layer.fade = 0.35f;
  9025. }
  9026. {
  9027. lynx::ChannelDef dash; // channel 6
  9028. dash.name = "Dashboard";
  9029. dash.instrument = lynx::InstrumentKind::dashboard;
  9030. dash.patcher.surface = lynx::surface::starterControls();
  9031. song.channels.push_back (dash);
  9032. }
  9033. {
  9034. lynx::ChannelDef volt; // channel 7: FL's render-test settings (main L pitch, R gate × 0.5) with Out 2 on insert 3
  9035. volt.name = "Voltage Controller";
  9036. volt.instrument = lynx::InstrumentKind::voltage;
  9037. lynx::voltage::Settings v;
  9038. v.enabled = true;
  9039. v.params[9] = 49152;
  9040. v.unipolar[2] = true;
  9041. v.tracks = { 3, 0, 0 };
  9042. v.source[6] = lynx::voltage::Source::clock;
  9043. volt.pluginState = lynx::voltage::write (v);
  9044. song.channels.push_back (volt);
  9045. }
  9046. song.patterns.emplace_back();
  9047. offline.setSong (std::move (song));
  9048. offline.dispatchPendingMessages();
  9049. auto shoot = [&] (std::unique_ptr<juce::Component> c, const juce::String& name) {
  9050. if (c == nullptr)
  9051. return;
  9052. savePng (c->createComponentSnapshot (c->getLocalBounds()), prefix + name);
  9053. };
  9054. shoot (lynx::makeChannelSettingsPanel (offline, 0), "-envelope-controller.png");
  9055. shoot (lynx::makeChannelSettingsPanel (offline, 1), "-midi-out.png");
  9056. shoot (lynx::makeChannelSettingsPanel (offline, 5), "-layer.png");
  9057. shoot (lynx::makeChannelFrame (offline, 3, -1), "-layer-child-misc.png"); // (the key-region ruler over the root keyboard)
  9058. {
  9059. const auto slotOf = [] (int k) -> lynx::SlotLocator {
  9060. return [k] (lynx::Song& s) { return &s.mixer[1].effects[(std::size_t) k]; };
  9061. };
  9062. const lynx::AutomationTarget target { lynx::AutomationTargetKind::effectParam, 1, 1, 0 };
  9063. shoot (lynx::makeXyControllerEditor (offline, slotOf (1), nullptr, target), "-xy-controller.png");
  9064. shoot (lynx::makeXyControllerEditor (offline, slotOf (2), nullptr, target), "-xyz-controller.png");
  9065. shoot (lynx::makeXyControllerEditor (offline, slotOf (3), nullptr, target), "-xyz-controller-stairs.png");
  9066. shoot (lynx::makeControlSurfaceEditor (offline, slotOf (4), target), "-control-surface.png");
  9067. shoot (lynx::makeChannelSettingsPanel (offline, 6), "-dashboard.png");
  9068. shoot (lynx::makeChannelSettingsPanel (offline, 7), "-voltage-controller.png");
  9069. }
  9070. // FL's Dashboard presets of this PC's FL Studio, imported (round 164f): one PNG each
  9071. if (const auto fl = lynx::findFlStudio(); fl.installDir.isDirectory())
  9072. for (const auto& file : fl.installDir.getChildFile ("Data/Patches/Plugin presets/Generators/Dashboard").findChildFiles (juce::File::findFiles, false, "*.fst"))
  9073. {
  9074. juce::MemoryBlock bytes;
  9075. if (! file.loadFileAsData (bytes))
  9076. continue;
  9077. const auto preset = flp::parseProject ({ (const std::uint8_t*) bytes.getData(), bytes.getSize() }, true);
  9078. const auto dash = preset.channels.empty() ? std::nullopt : lynx::surface::parseFlDashboard (preset.channels[0].pluginState);
  9079. if (! dash || dash->controls.empty())
  9080. continue;
  9081. offline.editSong ([&] (lynx::Song& s) {
  9082. s.channels[6].name = file.getFileNameWithoutExtension().toStdString();
  9083. s.channels[6].patcher.surface = dash->controls;
  9084. s.channels[6].pluginState = preset.channels[0].pluginState; // (its MIDI port, channel, program)
  9085. });
  9086. offline.dispatchPendingMessages();
  9087. const auto name = file.getFileNameWithoutExtension().replaceCharacter (' ', '-');
  9088. shoot (lynx::makeChannelSettingsPanel (offline, 6), "-dashboard-fl-" + name + ".png");
  9089. // edit mode (round 165): each control's output number and the MIDI it sends ("1 CC74")
  9090. if (auto panel = lynx::makeChannelSettingsPanel (offline, 6))
  9091. {
  9092. std::function<void (juce::Component&)> pressEdit = [&] (juce::Component& c) {
  9093. for (auto* child : c.getChildren())
  9094. {
  9095. if (auto* b = dynamic_cast<juce::TextButton*> (child); b != nullptr && b->getButtonText() == lynx::tr ("Edit"))
  9096. b->setToggleState (true, juce::sendNotificationSync);
  9097. pressEdit (*child);
  9098. }
  9099. };
  9100. pressEdit (*panel);
  9101. shoot (std::move (panel), "-dashboard-fl-" + name + "-edit.png");
  9102. }
  9103. }
  9104. // the Envelope Controller's pages (issue #7): one PNG per part of the dropdown
  9105. if (auto ec = lynx::makeEnvelopeControllerEditor (offline, 0))
  9106. for (int part = 0; part < 7; ++part)
  9107. {
  9108. for (auto* child : ec->getChildren())
  9109. if (auto* box = dynamic_cast<juce::ComboBox*> (child))
  9110. box->setSelectedItemIndex (part, juce::sendNotificationSync);
  9111. savePng (ec->createComponentSnapshot (ec->getLocalBounds()), prefix + "-ec-part" + juce::String (part) + ".png");
  9112. }
  9113. lynx::FormulaControllerWindows::open (offline, 1, 0);
  9114. for (int k = 0; k < juce::TopLevelWindow::getNumTopLevelWindows(); ++k)
  9115. if (auto* w = dynamic_cast<juce::DocumentWindow*> (juce::TopLevelWindow::getTopLevelWindow (k)))
  9116. if (w->getName().startsWith ("Formula") && w->getContentComponent() != nullptr)
  9117. savePng (w->getContentComponent()->createComponentSnapshot (w->getContentComponent()->getLocalBounds()), prefix + "-formula-controller.png");
  9118. lynx::FormulaControllerWindows::closeAll();
  9119. }
  9120. void runEdisonShot (const juce::String& prefix, const juce::String& file)
  9121. {
  9122. namespace ae = lynx::audioedit;
  9123. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  9124. lynx::AudioEngine offline (false);
  9125. ae::Document d;
  9126. if (file.isNotEmpty())
  9127. {
  9128. juce::MemoryBlock bytes;
  9129. if (! juce::File (file).loadFileAsData (bytes) || ! ae::decodeWav (static_cast<const std::uint8_t*> (bytes.getData()), bytes.getSize(), d))
  9130. {
  9131. std::fprintf (stderr, "edisonshot: cannot read %s\n", file.toRawUTF8());
  9132. return;
  9133. }
  9134. }
  9135. else
  9136. {
  9137. // a drum loop with a hum and hiss under it (something for the denoiser and the EQ to show)
  9138. d.title = "Drum loop";
  9139. d.audio.sampleRate = 44100.0;
  9140. const auto frames = (std::size_t) (44100 * 2);
  9141. d.audio.channels.assign (2, std::vector<float> (frames, 0.0f));
  9142. std::uint32_t seed = 7;
  9143. for (std::size_t i = 0; i < frames; ++i)
  9144. {
  9145. seed = seed * 1664525u + 1013904223u;
  9146. const auto hiss = ((float) (seed >> 8) / 16777216.0f - 0.5f) * 0.02f;
  9147. const auto hum = 0.01f * (float) std::sin (2.0 * 3.141592653589793 * 50.0 * (double) i / 44100.0);
  9148. d.audio.channels[0][i] = hiss + hum;
  9149. d.audio.channels[1][i] = hiss * 0.9f + hum;
  9150. }
  9151. for (int hit = 0; hit < 8; ++hit)
  9152. {
  9153. const auto at = (std::size_t) hit * frames / 8;
  9154. const auto kick = hit % 2 == 0;
  9155. double phase = 0.0;
  9156. for (std::size_t i = 0; i < 12000 && at + i < frames; ++i)
  9157. {
  9158. seed = seed * 1664525u + 1013904223u;
  9159. const auto noise = (float) (seed >> 8) / 16777216.0f - 0.5f;
  9160. const auto t = (double) i / 44100.0;
  9161. phase += 2.0 * 3.141592653589793 * (kick ? 45.0 + 160.0 * std::exp (-t * 30.0) : 190.0) / 44100.0;
  9162. const auto body = (float) std::sin (phase) * (float) std::exp (-t * (kick ? 9.0 : 22.0));
  9163. const auto v = kick ? 0.85f * body : 0.35f * body + 0.6f * noise * (float) std::exp (-t * 18.0);
  9164. d.audio.channels[0][at + i] += v;
  9165. d.audio.channels[1][at + i] += kick ? v : v * 0.8f;
  9166. }
  9167. }
  9168. for (int hit = 1; hit < 8; ++hit)
  9169. ae::addMarker (d, (std::int64_t) (hit * frames / 8));
  9170. ae::setLoop (d, { 0, (std::int64_t) frames });
  9171. }
  9172. // a volume envelope (a fade-in and a dip) to show the envelope mode and the envelope tools
  9173. 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 } };
  9174. auto editor = lynx::makeAudioEditorForSnapshot (offline, d, false);
  9175. auto shot = [&prefix] (juce::Component& c, const juce::String& name) {
  9176. juce::Image image (juce::Image::ARGB, c.getWidth(), c.getHeight(), true);
  9177. {
  9178. juce::Graphics g (image);
  9179. g.fillAll (lynx::theme::panel);
  9180. c.paintEntireComponent (g, false);
  9181. }
  9182. savePng (image, prefix + name);
  9183. };
  9184. editor->setSize (1120, 600);
  9185. lynx::setAudioEditorEnvelopeModeForSnapshot (*editor, 1);
  9186. shot (*editor, "-editor-volume-envelope.png");
  9187. lynx::setAudioEditorEnvelopeModeForSnapshot (*editor, 0);
  9188. juce::File (prefix + "-menu.txt").replaceWithText (lynx::audioEditorMenuForSnapshot (*editor).joinIntoString ("\n") + "\n");
  9189. for (int t = 0; lynx::audioToolNameForSnapshot (t) != nullptr; ++t)
  9190. {
  9191. const auto envelopeTool = t >= 10 && t <= 14; // Scale levels .. Create sequence work on the volume envelope
  9192. if (auto panel = lynx::makeAudioToolPanelForSnapshot (*editor, t, envelopeTool ? 1 : 0))
  9193. {
  9194. offline.dispatchPendingMessages();
  9195. const auto name = juce::String (lynx::audioToolNameForSnapshot (t)).toLowerCase().retainCharacters ("abcdefghijklmnopqrstuvwxyz ").trim().replaceCharacter (' ', '-');
  9196. shot (*panel, "-tool-" + juce::String (t).paddedLeft ('0', 2) + "-" + name + ".png");
  9197. if (envelopeTool)
  9198. shot (*editor, "-tool-" + juce::String (t).paddedLeft ('0', 2) + "-" + name + "-editor.png");
  9199. panel.reset(); // (puts the envelope back)
  9200. }
  9201. }
  9202. }
  9203. static juce::TextButton* findButton (juce::Component& root, const juce::String& text)
  9204. {
  9205. if (auto* b = dynamic_cast<juce::TextButton*> (&root); b != nullptr && b->getButtonText() == text)
  9206. return b;
  9207. for (auto* child : root.getChildren())
  9208. if (auto* b = findButton (*child, text))
  9209. return b;
  9210. return nullptr;
  9211. }
  9212. // a VFX Script editor's Script / Log / API reference tabs, then the Script tab of a script with an error
  9213. void shootScriptTabs (juce::Component& panel, lynx::AudioEngine& engine, int index, const juce::String& name)
  9214. {
  9215. const std::pair<const char*, const char*> tabs[] = { { "Script", "script" }, { "Log", "log" }, { "API reference", "api" } };
  9216. for (const auto& [tab, file] : tabs)
  9217. if (auto* b = findButton (panel, lynx::tr (tab)); b != nullptr && b->onClick)
  9218. {
  9219. b->onClick();
  9220. savePng (panel.createComponentSnapshot (panel.getLocalBounds()), name + "-tab-" + file + ".png");
  9221. }
  9222. engine.editSong ([&] (lynx::Song& s) {
  9223. auto st = *lynx::vfx::readState (s.channels[(std::size_t) index].pluginState);
  9224. auto settings = lynx::vfx::parseScript (st.fl).value_or (lynx::vfx::defaultScript());
  9225. settings.setSource ("import flvfx as vfx\n\ndef onTriggerVoice(incomingVoice):\n v = vfx.Voice(incomingVoice)\n"
  9226. " v.note += 7\n v.trigger(\n\ndef onReleaseVoice(incomingVoice):\n pass\n");
  9227. st.fl = lynx::vfx::writeScript (settings);
  9228. s.channels[(std::size_t) index].pluginState = lynx::vfx::writeState (st);
  9229. });
  9230. engine.dispatchPendingMessages();
  9231. if (auto broken = lynx::makeChannelSettingsPanel (engine, index))
  9232. {
  9233. engine.dispatchPendingMessages();
  9234. if (auto* b = findButton (*broken, lynx::tr ("Script")); b != nullptr && b->onClick)
  9235. b->onClick();
  9236. savePng (broken->createComponentSnapshot (broken->getLocalBounds()), name + "-error.png");
  9237. }
  9238. }
  9239. void runVfxShot (const juce::String& prefix)
  9240. {
  9241. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  9242. lynx::AudioEngine offline (false);
  9243. lynx::MainComponent ui (offline, false);
  9244. ui.setSize (1280, 720);
  9245. auto song = lynx::Song::makeDefault();
  9246. song.channels.clear();
  9247. for (const auto kind : lynx::vfx::allKinds)
  9248. {
  9249. lynx::ChannelDef c;
  9250. lynx::vfx::makeChannel (c, kind);
  9251. if (kind == lynx::vfx::Kind::keyMapper) // a chord on every key: something to see in the grid
  9252. for (const auto& p : lynx::vfx::builtInPresets (kind))
  9253. if (p.name == "Major triad")
  9254. {
  9255. auto st = *lynx::vfx::readState (c.pluginState);
  9256. st.fl = p.fl;
  9257. c.pluginState = lynx::vfx::writeState (st);
  9258. }
  9259. song.channels.push_back (c);
  9260. }
  9261. // a Patcher: its notes through a Color Mapper to three synths
  9262. lynx::ChannelDef patcher;
  9263. patcher.name = "Patcher";
  9264. patcher.instrument = lynx::InstrumentKind::patcher;
  9265. lynx::PatchNode mapper;
  9266. mapper.generator = true;
  9267. lynx::vfx::makeChannel (mapper.channel, lynx::vfx::Kind::colorMapper);
  9268. mapper.x = 260.0f;
  9269. patcher.patcher.nodes.push_back (mapper);
  9270. lynx::PatchWire notes;
  9271. notes.kind = lynx::PatchWire::Kind::midi, notes.to = 0;
  9272. patcher.patcher.wires.push_back (notes);
  9273. for (int k = 0; k < 3; ++k)
  9274. {
  9275. lynx::PatchNode synth;
  9276. synth.generator = true;
  9277. synth.channel.instrument = lynx::InstrumentKind::synth;
  9278. synth.channel.name = "Synth " + std::to_string (k + 1);
  9279. synth.x = 520.0f, synth.y = (float) k * 90.0f;
  9280. patcher.patcher.nodes.push_back (synth);
  9281. lynx::PatchWire in, out;
  9282. in.kind = lynx::PatchWire::Kind::midi, in.from = 0, in.fromPort = k, in.to = 1 + k;
  9283. out.from = 1 + k, out.to = lynx::patchToHost;
  9284. patcher.patcher.wires.push_back (in);
  9285. patcher.patcher.wires.push_back (out);
  9286. }
  9287. patcher.patcher.outputX = 760.0f;
  9288. song.channels.push_back (patcher);
  9289. offline.setSong (std::move (song));
  9290. offline.dispatchPendingMessages();
  9291. for (int c = 0; c < lynx::vfx::kindCount; ++c)
  9292. if (auto panel = lynx::makeChannelSettingsPanel (offline, c))
  9293. {
  9294. offline.dispatchPendingMessages();
  9295. savePng (panel->createComponentSnapshot (panel->getLocalBounds()),
  9296. prefix + "-" + juce::String (lynx::vfx::flName (*lynx::vfx::kindOf (offline.getSong().channels[(std::size_t) c]))).replaceCharacter (' ', '-').toLowerCase() + ".png");
  9297. }
  9298. // with FL Studio installed: the Sequencer with FL's factory bank (to compare with FL's own editor) and
  9299. // a Script with FL's "Snap To Scale"
  9300. if (const auto roots = lynx::findFlStudioRoots(); ! roots.data.empty())
  9301. {
  9302. const auto data = juce::File (juce::String::fromUTF8 (roots.data.c_str()));
  9303. const std::pair<lynx::vfx::Kind, juce::String> extra[] = {
  9304. { lynx::vfx::Kind::sequencer, "Patches/Plugin database/Effects/Patcher/VFX Sequencer.fst" },
  9305. { lynx::vfx::Kind::script, "Patches/Plugin presets/Effects/VFX Script/Snap To Scale.fst" },
  9306. };
  9307. for (const auto& [kind, path] : extra)
  9308. {
  9309. juce::MemoryBlock bytes;
  9310. if (! data.getChildFile (path).loadFileAsData (bytes))
  9311. continue;
  9312. const auto* b = static_cast<const std::uint8_t*> (bytes.getData());
  9313. const auto fl = lynx::vfx::stateFromFlPreset (std::vector<std::uint8_t> (b, b + bytes.getSize()), kind);
  9314. int index = -1;
  9315. for (int c = 0; c < lynx::vfx::kindCount; ++c)
  9316. if (lynx::vfx::kindOf (offline.getSong().channels[(std::size_t) c]) == kind)
  9317. index = c;
  9318. if (! fl || index < 0)
  9319. continue;
  9320. offline.editSong ([&] (lynx::Song& s) {
  9321. auto st = *lynx::vfx::readState (s.channels[(std::size_t) index].pluginState);
  9322. st.fl = *fl;
  9323. s.channels[(std::size_t) index].pluginState = lynx::vfx::writeState (st);
  9324. });
  9325. offline.dispatchPendingMessages();
  9326. if (auto panel = lynx::makeChannelSettingsPanel (offline, index))
  9327. {
  9328. offline.dispatchPendingMessages();
  9329. const auto name = prefix + "-" + juce::String (lynx::vfx::flName (kind)).replaceCharacter (' ', '-').toLowerCase();
  9330. savePng (panel->createComponentSnapshot (panel->getLocalBounds()), name + "-fl.png");
  9331. if (kind == lynx::vfx::Kind::script) // the editor's other tabs (round 165d)
  9332. shootScriptTabs (*panel, offline, index, name);
  9333. }
  9334. }
  9335. }
  9336. lynx::PatcherWindows::openChannel (offline, lynx::vfx::kindCount);
  9337. for (int k = 0; k < juce::TopLevelWindow::getNumTopLevelWindows(); ++k)
  9338. if (auto* w = dynamic_cast<juce::DocumentWindow*> (juce::TopLevelWindow::getTopLevelWindow (k)))
  9339. if (w->getName().startsWith (lynx::tr ("Patcher")) && w->getContentComponent() != nullptr)
  9340. {
  9341. auto* content = w->getContentComponent();
  9342. savePng (content->createComponentSnapshot (content->getLocalBounds()), prefix + "-patcher.png");
  9343. delete w;
  9344. break;
  9345. }
  9346. lynx::PatcherWindows::shootMenus (offline, true, lynx::vfx::kindCount, 0, [&] (const juce::Image& image, const juce::String& name) {
  9347. savePng (image, prefix + "-patcher-menu-" + name + ".png");
  9348. });
  9349. // a plugin renamed in the Plugin database ("1_EQ", FL): the Quick-add palette and the mixer slot show the new name
  9350. if (juce::SystemStats::getEnvironmentVariable ("LYNX_TEST_MODE", {}).isNotEmpty())
  9351. {
  9352. const auto key = std::string ("lynx:fx:") + lynx::effectInfo (lynx::EffectKind::parametricEq).name;
  9353. offline.getPluginHost().setPluginName (key, "1_EQ");
  9354. offline.editSong ([] (lynx::Song& s) {
  9355. if (s.mixer.size() > 1)
  9356. {
  9357. lynx::EffectSlot slot;
  9358. slot.kind = lynx::EffectKind::parametricEq;
  9359. s.mixer[1].effects.push_back (slot);
  9360. }
  9361. });
  9362. offline.dispatchPendingMessages();
  9363. {
  9364. lynx::QuickAddTargets targets;
  9365. targets.addInstrument = [] (lynx::ChannelDef) {};
  9366. targets.addEffect = [] (lynx::EffectSlot) {};
  9367. auto palette = lynx::makeQuickAddPalette (offline, std::move (targets));
  9368. savePng (palette->createComponentSnapshot (palette->getLocalBounds()), prefix + "-quickadd-renamed.png");
  9369. }
  9370. ui.selectTabForSnapshot (3);
  9371. ui.getMixerForSnapshot().selectTrack (1);
  9372. offline.dispatchPendingMessages();
  9373. savePng (ui.createComponentSnapshot (ui.getLocalBounds()), prefix + "-mixer-renamed.png");
  9374. offline.getPluginHost().setPluginName (key, "");
  9375. }
  9376. }
  9377. void runComp177Shot (const juce::String& prefix, const juce::String& projectPath)
  9378. {
  9379. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  9380. lynx::AudioEngine offline (false);
  9381. {
  9382. lynx::MainComponent ui (offline, false);
  9383. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1600x900"), "x", "");
  9384. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  9385. ui.openFile (juce::File (projectPath));
  9386. offline.dispatchPendingMessages();
  9387. ui.selectTabForSnapshot (2);
  9388. offline.dispatchPendingMessages();
  9389. auto& playlist = ui.getPlaylistForSnapshot();
  9390. std::int64_t last = 0;
  9391. for (const auto& c : offline.getSong().playlist)
  9392. last = std::max (last, c.end());
  9393. const auto bars = juce::jmax (1, (int) (last / (4 * lynx::ppq)) + 1);
  9394. playlist.setViewForSnapshot (juce::jmax (60.0, (ui.getWidth() - 300.0) / bars), 0, 0);
  9395. // (the first paint asks for the clips' waveforms, a worker thread loads them)
  9396. saveSnapshot (ui, prefix + "-opened.png");
  9397. juce::Thread::sleep (3000);
  9398. offline.dispatchPendingMessages();
  9399. saveSnapshot (ui, prefix + "-opened.png");
  9400. // a muted clip selected
  9401. for (int c = 0; c < (int) offline.getSong().playlist.size(); ++c)
  9402. if (offline.getSong().playlist[(std::size_t) c].muted)
  9403. {
  9404. playlist.selectClipsForSnapshot ({ c });
  9405. offline.dispatchPendingMessages();
  9406. saveSnapshot (ui, prefix + "-selected.png");
  9407. playlist.selectClipsForSnapshot ({});
  9408. break;
  9409. }
  9410. juce::String report;
  9411. const auto listTracks = [&offline, &report] (const juce::String& title) {
  9412. const auto& s = offline.getSong();
  9413. report << title << "\n";
  9414. for (int t = 0; t < (int) s.playlistTracks.size(); ++t)
  9415. {
  9416. int clips = 0, muted = 0;
  9417. for (const auto& c : s.playlist)
  9418. if (c.track == t)
  9419. ++clips, muted += c.muted ? 1 : 0;
  9420. const auto& pt = s.playlistTracks[(std::size_t) t];
  9421. if (clips > 0 || pt.grouped || ! pt.name.empty())
  9422. report << "track " << (t + 1) << " '" << juce::String::fromUTF8 (pt.name.c_str()) << "' grouped=" << (pt.grouped ? 1 : 0) << " collapsed=" << (pt.collapsed ? 1 : 0)
  9423. << " comp=" << (pt.compTrack ? 1 : 0) << " clips=" << clips << " muted=" << muted << "\n";
  9424. }
  9425. };
  9426. listTracks ("opened");
  9427. // the first group's header (a member's menu holds "Comp these takes" too)
  9428. int firstGroup = -1;
  9429. for (int t = 0; t < (int) offline.getSong().playlistTracks.size() && firstGroup < 0; ++t)
  9430. if (lynx::comp::canComp (offline.getSong(), t))
  9431. firstGroup = t;
  9432. report << "first group with takes: track " << (firstGroup + 1) << "\n";
  9433. if (firstGroup >= 0)
  9434. {
  9435. saveMenus (juce::StringArray { "Playlist track" }, std::vector<juce::PopupMenu> { playlist.getTrackMenuForSnapshot (firstGroup) }, prefix + "-trackmenu.png");
  9436. int comp = -1;
  9437. offline.editSong ([firstGroup, &comp] (lynx::Song& s) { comp = lynx::comp::compTakes (s, firstGroup); });
  9438. offline.dispatchPendingMessages();
  9439. saveSnapshot (ui, prefix + "-comped.png");
  9440. listTracks ("after Comp these takes");
  9441. const auto g = lynx::comp::groupOf (offline.getSong(), comp);
  9442. std::int64_t from = -1, to = 0;
  9443. for (const auto& c : offline.getSong().playlist)
  9444. if (c.track == g.first)
  9445. from = from < 0 ? c.start : std::min (from, c.start), to = std::max (to, c.end());
  9446. if (g.valid() && to > from)
  9447. {
  9448. offline.editSong ([&g, from, to] (lynx::Song& s) { lynx::comp::swipe (s, g.first, from + (to - from) / 4, from + (to - from) / 2); });
  9449. offline.dispatchPendingMessages();
  9450. saveSnapshot (ui, prefix + "-swiped.png");
  9451. listTracks ("after a swipe of the middle of the first lane");
  9452. // a lane auditioned; the crossfade close up; the comp flattened
  9453. offline.editSong ([&g] (lynx::Song& s) { lynx::comp::setAudition (s, g.first); }, false);
  9454. offline.dispatchPendingMessages();
  9455. saveSnapshot (ui, prefix + "-audition.png");
  9456. offline.editSong ([] (lynx::Song& s) { lynx::comp::setAudition (s, -1); }, false);
  9457. const auto switchAt = from + (to - from) / 4;
  9458. playlist.setViewForSnapshot (4.0 * 4.0 * lynx::ppq, 0, 0);
  9459. playlist.setScrollTickForSnapshot ((double) (switchAt - 100));
  9460. juce::Thread::sleep (1500);
  9461. offline.dispatchPendingMessages();
  9462. saveSnapshot (ui, prefix + "-crossfade.png");
  9463. playlist.setViewForSnapshot (juce::jmax (60.0, (ui.getWidth() - 300.0) / bars), 0, 0);
  9464. offline.editSong ([comp] (lynx::Song& s) { lynx::comp::flatten (s, comp); });
  9465. offline.dispatchPendingMessages();
  9466. saveSnapshot (ui, prefix + "-flattened.png");
  9467. listTracks ("after Flatten comp");
  9468. }
  9469. }
  9470. saveMenus (juce::StringArray { "Record" }, std::vector<juce::PopupMenu> { ui.getRecordMenuForSnapshot() }, prefix + "-recordmenu.png");
  9471. juce::File (prefix + "-tracks.txt").replaceWithText (report);
  9472. }
  9473. }
  9474. void runFeat166Shot (const juce::String& prefix, const juce::String& projectPath)
  9475. {
  9476. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  9477. lynx::AudioEngine offline (false);
  9478. {
  9479. lynx::MainComponent ui (offline, false);
  9480. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1600x900"), "x", "");
  9481. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  9482. if (projectPath.isNotEmpty())
  9483. ui.openFile (juce::File (projectPath));
  9484. offline.dispatchPendingMessages();
  9485. ui.selectTabForSnapshot (1); // the Piano Roll, on the channel with the most notes
  9486. offline.dispatchPendingMessages();
  9487. // the scale the pattern's notes fit best (major / minor, any root)
  9488. const auto& song = offline.getSong();
  9489. const auto& notes = song.patterns[(std::size_t) song.currentPattern].notes;
  9490. int bestRoot = 0, bestScale = 1, bestHits = -1;
  9491. for (int sc = 1; sc < (int) lynx::notetools::scales().size(); ++sc)
  9492. {
  9493. const juce::String name (lynx::notetools::scales()[(std::size_t) sc].name);
  9494. if (name != "Major" && name != "Minor")
  9495. continue;
  9496. for (int root = 0; root < 12; ++root)
  9497. {
  9498. int hits = 0;
  9499. for (const auto& n : notes)
  9500. hits += lynx::notetools::inScale (n.key, root, sc) ? 1 : 0;
  9501. if (hits > bestHits)
  9502. bestHits = hits, bestRoot = root, bestScale = sc;
  9503. }
  9504. }
  9505. auto& roll = ui.getPianoRollForSnapshot();
  9506. roll.setScaleForSnapshot (bestRoot, bestScale);
  9507. roll.scrollToNotes();
  9508. offline.dispatchPendingMessages();
  9509. saveSnapshot (ui, prefix + "-pr-scale.png");
  9510. roll.setFoldToScale (true);
  9511. offline.dispatchPendingMessages();
  9512. saveSnapshot (ui, prefix + "-pr-folded.png");
  9513. roll.setFoldToScale (false);
  9514. // ghost channels: only the first other channel with notes stays a ghost
  9515. const auto selected = offline.getSelectedChannel();
  9516. int keep = -1;
  9517. for (const auto& n : notes)
  9518. if (n.channel != selected && keep < 0)
  9519. keep = n.channel;
  9520. offline.editSong ([keep] (lynx::Song& s) {
  9521. for (int c = 0; c < (int) s.channels.size(); ++c)
  9522. s.channels[(std::size_t) c].ghostHidden = c != keep;
  9523. }, false);
  9524. offline.dispatchPendingMessages();
  9525. saveSnapshot (ui, prefix + "-pr-ghost-one.png");
  9526. saveMenus (juce::StringArray { "Ghost channels" }, { roll.ghostChannelsMenu() }, prefix + "-ghostmenu.png");
  9527. offline.editSong ([] (lynx::Song& s) {
  9528. for (auto& c : s.channels)
  9529. c.ghostHidden = false;
  9530. }, false);
  9531. // the Mixer at 500 inserts
  9532. const auto t0 = juce::Time::getMillisecondCounterHiRes();
  9533. offline.editSong ([] (lynx::Song& s) { lynx::mixerops::insertTracks (s, (int) s.mixer.size(), lynx::mixerops::roomForInserts (s)); }, false);
  9534. const auto t1 = juce::Time::getMillisecondCounterHiRes();
  9535. offline.dispatchPendingMessages();
  9536. ui.selectTabForSnapshot (3);
  9537. offline.dispatchPendingMessages();
  9538. auto& mixer = ui.getMixerForSnapshot();
  9539. const auto t2 = juce::Time::getMillisecondCounterHiRes();
  9540. saveSnapshot (ui, prefix + "-mixer500-start.png");
  9541. const auto t3 = juce::Time::getMillisecondCounterHiRes();
  9542. mixer.selectTrack ((int) offline.getSong().mixer.size() - 1);
  9543. offline.dispatchPendingMessages();
  9544. saveSnapshot (ui, prefix + "-mixer500-end.png");
  9545. juce::File (prefix + "-mixer500.txt")
  9546. .replaceWithText ("inserts=" + juce::String ((int) offline.getSong().mixer.size() - 1) + "\nfill_ms=" + juce::String (t1 - t0, 2)
  9547. + "\nsnapshot_ms=" + juce::String (t3 - t2, 2) + "\n");
  9548. }
  9549. }
  9550. void runGridShot (const juce::String& prefix, const juce::String& projectPath = {})
  9551. {
  9552. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  9553. lynx::AudioEngine offline (false);
  9554. lynx::MainComponent ui (offline, false);
  9555. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1600x900"), "x", "");
  9556. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  9557. const auto write = [&prefix, &ui] (const char* name) {
  9558. const auto file = juce::File (prefix + "-" + name + ".png");
  9559. file.deleteFile();
  9560. juce::FileOutputStream out (file);
  9561. juce::PNGImageFormat().writeImageToStream (ui.createComponentSnapshot (ui.getLocalBounds(), true, 1.0f), out);
  9562. };
  9563. ui.selectTabForSnapshot (2); // the Playlist panel, maximized
  9564. if (projectPath.isNotEmpty())
  9565. {
  9566. ui.openFile (juce::File (projectPath));
  9567. offline.dispatchPendingMessages();
  9568. ui.setClipLaunchWorkflow (true);
  9569. offline.dispatchPendingMessages();
  9570. write ("file-both");
  9571. ui.setClipGridView (lynx::PlaylistArea::GridView::grid);
  9572. write ("file-grid");
  9573. const auto& song = offline.getSong();
  9574. juce::String info;
  9575. info << "grid " << (song.clipGrid ? "yes" : "no") << ", clips " << (song.clipGrid ? (int) song.clipGrid->clips.size() : 0)
  9576. << ", scenes " << (song.clipGrid ? (int) song.clipGrid->scenes.size() : 0) << ", playlist clips " << (int) song.playlist.size() << "\n";
  9577. juce::File (prefix + "-file.txt").replaceWithText (info);
  9578. ui.setClipLaunchWorkflow (false);
  9579. return;
  9580. }
  9581. write ("pattern"); // Pattern workflow: nothing of the grid exists yet
  9582. const auto madeBefore = lynx::launcher::Runtime::instances.load();
  9583. offline.editSong ([] (lynx::Song& s) {
  9584. while (s.patterns.size() < 6)
  9585. s.patterns.emplace_back();
  9586. for (int p = 0; p < 6; ++p)
  9587. {
  9588. auto& pattern = s.patterns[(std::size_t) p];
  9589. const char* names[] { "Drums A", "Drums B", "Bass", "Chords", "Lead", "Pad" };
  9590. pattern.name = names[p];
  9591. pattern.lengthTicks = 4 * lynx::ppq;
  9592. }
  9593. s.playlistTracks.resize (std::max<std::size_t> (s.playlistTracks.size(), 6));
  9594. const char* tracks[] { "Drums", "Bass", "Chords", "Lead", "Vocals", "FX" };
  9595. for (int t = 0; t < 6; ++t)
  9596. s.playlistTracks[(std::size_t) t].name = tracks[t];
  9597. 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 } };
  9598. for (const auto& c : placed)
  9599. {
  9600. lynx::Clip clip;
  9601. clip.pattern = c[2];
  9602. clip.length = 4 * lynx::ppq;
  9603. lynx::launcher::setClip (s, c[0], c[1], clip);
  9604. }
  9605. auto& grid = lynx::launcher::ensureGrid (s);
  9606. const char* scenes[] { "Intro", "Verse", "Drop", "Break" };
  9607. grid.scenes.resize (6);
  9608. for (int r = 0; r < 4; ++r)
  9609. grid.scenes[(std::size_t) r].name = scenes[r];
  9610. }, false);
  9611. offline.dispatchPendingMessages();
  9612. write ("pattern-edited"); // the same song as -pattern-after: the workflow must leave no trace
  9613. ui.setClipLaunchWorkflow (true);
  9614. offline.dispatchPendingMessages();
  9615. if (auto* runtime = offline.launcherStateForSnapshot())
  9616. {
  9617. runtime->tracks[0].playing.store (2);
  9618. runtime->tracks[0].progress.store (0.4f);
  9619. runtime->tracks[0].taken.store (true);
  9620. runtime->tracks[1].playing.store (2);
  9621. runtime->tracks[1].progress.store (0.4f);
  9622. runtime->tracks[1].taken.store (true);
  9623. runtime->tracks[2].pending.store (2);
  9624. runtime->tracks[3].taken.store (true);
  9625. }
  9626. write ("both");
  9627. ui.setClipGridView (lynx::PlaylistArea::GridView::grid);
  9628. write ("grid");
  9629. ui.setClipGridView (lynx::PlaylistArea::GridView::song);
  9630. write ("song");
  9631. ui.setClipLaunchWorkflow (false);
  9632. write ("pattern-after");
  9633. juce::File (prefix + "-counts.txt").replaceWithText ("runtimes before " + juce::String (madeBefore) + ", after " + juce::String (lynx::launcher::Runtime::instances.load()) + "\n");
  9634. }
  9635. void runSimpleShot (const juce::String& prefix)
  9636. {
  9637. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  9638. lynx::AudioEngine offline (false);
  9639. lynx::MainComponent ui (offline, false);
  9640. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1600x900"), "x", "");
  9641. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  9642. const auto writeImage = [&prefix] (const juce::Image& image, const char* name) {
  9643. const auto file = juce::File (prefix + "-" + name + ".png");
  9644. file.deleteFile();
  9645. juce::FileOutputStream out (file);
  9646. juce::PNGImageFormat().writeImageToStream (image, out);
  9647. };
  9648. const auto write = [&ui, &writeImage] (const char* name) { writeImage (ui.createComponentSnapshot (ui.getLocalBounds(), true, 1.0f), name); };
  9649. // View › Layout style, with its submenu, as it is with `style` chosen
  9650. const auto viewMenu = [&ui] {
  9651. const auto names = ui.getMenuNamesForSnapshot();
  9652. const auto view = names.indexOf (lynx::tr ("View"));
  9653. return ui.getMenuForSnapshot (juce::jmax (0, view));
  9654. };
  9655. const auto saveStyleMenus = [&] (const juce::String& suffix) {
  9656. const auto view = viewMenu();
  9657. juce::StringArray names { lynx::tr ("View") };
  9658. std::vector<juce::PopupMenu> menus { view };
  9659. for (juce::PopupMenu::MenuItemIterator it (view); it.next();)
  9660. if (it.getItem().subMenu != nullptr && it.getItem().text == lynx::tr ("Layout style"))
  9661. {
  9662. names.add (lynx::tr ("Layout style"));
  9663. menus.push_back (*it.getItem().subMenu);
  9664. }
  9665. saveMenus (names, menus, prefix + "-menu-" + suffix + ".png");
  9666. };
  9667. // Settings › General with `style` selected, and its style list
  9668. const auto saveSettings = [&] (lynx::layoutstyle::Style style, const char* name) {
  9669. lynx::SettingsHooks hooks;
  9670. hooks.getGeneral = [style] {
  9671. lynx::GeneralOptions o;
  9672. o.language = lynx::i18n::current();
  9673. o.layoutStyle = (int) style;
  9674. return o;
  9675. };
  9676. auto page = lynx::makeSettingsPanel (offline, lynx::SettingsPage::general, false, hooks);
  9677. juce::Image image (juce::Image::ARGB, page->getWidth(), juce::jmin (page->getHeight(), 420), true);
  9678. {
  9679. juce::Graphics g (image);
  9680. g.fillAll (lynx::theme::panel);
  9681. page->paintEntireComponent (g, false);
  9682. }
  9683. writeImage (image, name);
  9684. std::function<juce::ComboBox* (juce::Component&)> find = [&find] (juce::Component& c) -> juce::ComboBox* {
  9685. if (c.getComponentID() == "layoutStyle")
  9686. return dynamic_cast<juce::ComboBox*> (&c);
  9687. for (auto* child : c.getChildren())
  9688. if (auto* box = find (*child))
  9689. return box;
  9690. return nullptr;
  9691. };
  9692. if (auto* box = find (*page); box != nullptr && box->getRootMenu() != nullptr)
  9693. saveMenus (juce::StringArray { lynx::tr ("Layout style") }, std::vector<juce::PopupMenu> { *box->getRootMenu() },
  9694. prefix + "-" + name + "-list.png");
  9695. };
  9696. const auto madeBefore = lynx::SimpleWorkflow::instances.load();
  9697. ui.selectTabForSnapshot (2); // the Playlist panel, maximized (as --gridshot)
  9698. write ("pattern");
  9699. saveStyleMenus ("pattern");
  9700. saveSettings (lynx::layoutstyle::Style::pattern, "settings-pattern");
  9701. const auto madePattern = lynx::SimpleWorkflow::instances.load();
  9702. ui.setLayoutStyle (lynx::layoutstyle::Style::clipLaunch);
  9703. saveStyleMenus ("cliplaunch");
  9704. ui.setLayoutStyle (lynx::layoutstyle::Style::simple);
  9705. offline.dispatchPendingMessages();
  9706. if (auto* simple = ui.getSimpleWorkflowForSnapshot())
  9707. simple->showChooser(); // (an empty project opens on it by itself; the offline project may hold the default song)
  9708. write ("simple"); // the New track chooser (slice S3)
  9709. if (auto* simple = ui.getSimpleWorkflowForSnapshot())
  9710. {
  9711. simple->showStarterPageForSnapshot();
  9712. write ("simple-starter");
  9713. simple->hideChooser();
  9714. write ("simple-closed");
  9715. }
  9716. saveStyleMenus ("simple");
  9717. saveSettings (lynx::layoutstyle::Style::simple, "settings-simple");
  9718. ui.setLayoutStyle (lynx::layoutstyle::Style::pattern);
  9719. offline.dispatchPendingMessages();
  9720. write ("pattern-after");
  9721. juce::File (prefix + "-counts.txt").replaceWithText ("simple workflows before " + juce::String (madeBefore) + ", in pattern workflow "
  9722. + juce::String (madePattern) + ", after " + juce::String (lynx::SimpleWorkflow::instances.load())
  9723. + "\nstyle after " + lynx::layoutstyle::id (ui.getLayoutStyle()) + "\n");
  9724. }
  9725. void runDetailShot (const juce::String& prefix)
  9726. {
  9727. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  9728. lynx::AudioEngine offline (false);
  9729. lynx::MainComponent ui (offline, false);
  9730. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1600x900"), "x", "");
  9731. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  9732. const auto write = [&prefix, &ui] (const char* name) {
  9733. const auto file = juce::File (prefix + "-" + name + ".png");
  9734. file.deleteFile();
  9735. juce::FileOutputStream out (file);
  9736. juce::PNGImageFormat().writeImageToStream (ui.createComponentSnapshot (ui.getLocalBounds(), true, 1.0f), out);
  9737. };
  9738. ui.setVisible (true); // (not on the desktop: only so the Clip page sees itself shown and docks the Piano roll)
  9739. lynx::DetailView::shownSetting = lynx::DetailView::devicesPage = true;
  9740. ui.selectTabForSnapshot (2); // the Playlist panel, maximized
  9741. offline.editSong ([] (lynx::Song& s) {
  9742. if (s.channels.size() < 2)
  9743. s.channels.resize (2);
  9744. s.channels[0].name = "Bass synth";
  9745. s.channels[0].mixerTrack = 2;
  9746. s.channels[1].mixerTrack = 3;
  9747. if (s.mixer.size() < 4)
  9748. s.mixer.resize (4);
  9749. s.mixer[2].name = "Bass";
  9750. s.mixer[2].effects.clear();
  9751. for (auto kind : { lynx::EffectKind::eq, lynx::EffectKind::compressor, lynx::EffectKind::reverb, lynx::EffectKind::delay })
  9752. {
  9753. lynx::EffectSlot fx;
  9754. fx.kind = kind;
  9755. const auto& info = lynx::effectInfo (kind);
  9756. for (std::size_t k = 0; k < info.params.size() && k < fx.params.size(); ++k)
  9757. fx.params[k] = info.params[k].defaultValue;
  9758. fx.enabled = kind != lynx::EffectKind::compressor; // one switched off
  9759. s.mixer[2].effects.push_back (fx);
  9760. }
  9761. while (s.patterns.size() < 2)
  9762. s.patterns.emplace_back();
  9763. s.patterns[0].name = "Bass line";
  9764. s.patterns[0].notes.clear();
  9765. for (int n = 0; n < 4; ++n)
  9766. {
  9767. lynx::Note note;
  9768. note.channel = 0;
  9769. note.start = n * lynx::ppq;
  9770. note.key = 36 + (n % 2) * 7;
  9771. s.patterns[0].notes.push_back (note);
  9772. }
  9773. s.patterns[0].lengthTicks = 4 * lynx::ppq;
  9774. lynx::PatternEvents lane; // a volume swell for the Envelopes tab (slice 3)
  9775. lane.target = lynx::AutomationTarget { lynx::AutomationTargetKind::channelVolume, 0 };
  9776. for (int e = 0; e < 16; ++e)
  9777. lane.events.push_back ({ e * lynx::ppq / 4, 0.3f + 0.6f * (float) e / 15.0f });
  9778. s.patterns[0].events = { lane };
  9779. s.playlistTracks.resize (std::max<std::size_t> (s.playlistTracks.size(), 3));
  9780. s.playlistTracks[1].name = "Bass";
  9781. }, false);
  9782. offline.dispatchPendingMessages();
  9783. write ("pattern"); // Pattern workflow: no detail view exists
  9784. ui.setClipLaunchWorkflow (true);
  9785. offline.editSong ([] (lynx::Song& s) {
  9786. lynx::Clip clip;
  9787. clip.pattern = 0;
  9788. clip.length = 4 * lynx::ppq;
  9789. lynx::launcher::setClip (s, 1, 0, clip);
  9790. }, false);
  9791. offline.dispatchPendingMessages();
  9792. juce::String counts;
  9793. if (auto* detail = ui.getDetailViewForSnapshot())
  9794. {
  9795. detail->showSelection (1, 0);
  9796. detail->setPage (lynx::DetailView::Page::devices);
  9797. write ("devices");
  9798. counts << "cards " << detail->cardCountForCheck() << ", insert " << detail->chainInsertForCheck() << ", channel " << detail->chainChannelForCheck() << "\n";
  9799. detail->toggleFoldForCheck (3); // the reverb (card 0 is the instrument)
  9800. write ("folded");
  9801. counts << "folded card 3: " << (detail->isFoldedForCheck (3) ? 1 : 0) << "\n";
  9802. detail->showSelection (2, 0); // an empty track
  9803. write ("empty-track");
  9804. detail->showSelection (1, 0);
  9805. detail->setPage (lynx::DetailView::Page::clip);
  9806. offline.dispatchPendingMessages();
  9807. ui.getPianoRollForSnapshot().scrollToNotes(); // (the app does it on the message loop, which this shot doesn't run)
  9808. write ("clip"); // slice 2: the Piano roll docked here
  9809. {
  9810. // round 190s: the Transform panel with each MIDI tool, then Arpeggiate applied (and undone again)
  9811. auto& tools = detail->midiToolsForSnapshot();
  9812. for (int t = 0; t < lynx::MidiToolsPanel::toolCount; ++t)
  9813. {
  9814. tools.setTool (t);
  9815. write (("clip-mt-" + juce::String (lynx::MidiToolsPanel::toolName (t)).toLowerCase()).toRawUTF8());
  9816. }
  9817. // round 190aa: the pages again with the settings of the Live shots they are compared with
  9818. tools.setAuto (false);
  9819. tools.setLiveShotSettingsForSnapshot();
  9820. for (int t : { (int) lynx::MidiToolsPanel::chop, (int) lynx::MidiToolsPanel::quantize, (int) lynx::MidiToolsPanel::timeWarp })
  9821. {
  9822. tools.setTool (t);
  9823. write (("clip-mt-" + juce::String (lynx::MidiToolsPanel::toolName (t)).toLowerCase() + "-set").toRawUTF8());
  9824. }
  9825. tools.setAuto (true);
  9826. tools.setTool (lynx::MidiToolsPanel::arpeggiate);
  9827. tools.transformNow();
  9828. offline.dispatchPendingMessages();
  9829. write ("clip-mt-applied");
  9830. counts << "midi tools: arpeggiate made " << (int) offline.getSong().patterns[0].notes.size() << " notes of 4\n";
  9831. offline.undo();
  9832. offline.dispatchPendingMessages();
  9833. counts << "midi tools: undo gives " << (int) offline.getSong().patterns[0].notes.size() << " notes\n";
  9834. }
  9835. counts << "piano roll docked: " << (ui.getPianoRollForSnapshot().getParentComponent() != nullptr
  9836. && ui.getPianoRollForSnapshot().getParentComponent()->getParentComponent() == detail ? 1 : 0) << "\n";
  9837. detail->setClipTab (true); // slice 3: the pattern's events in the Envelopes tab
  9838. offline.dispatchPendingMessages();
  9839. write ("envelopes");
  9840. detail->setClipTab (false);
  9841. detail->setPage (lynx::DetailView::Page::devices);
  9842. counts << "piano roll back in its panel: " << (ui.getPianoRollForSnapshot().getParentComponent() != nullptr
  9843. && ui.getPianoRollForSnapshot().getParentComponent()->getParentComponent() != detail ? 1 : 0) << "\n";
  9844. }
  9845. else
  9846. counts << "no detail view\n";
  9847. ui.setClipLaunchWorkflow (false);
  9848. offline.dispatchPendingMessages();
  9849. write ("pattern-after");
  9850. juce::File (prefix + "-counts.txt").replaceWithText (counts);
  9851. }
  9852. void runPerfShot (const juce::String& prefix, const juce::String& projectPath)
  9853. {
  9854. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  9855. lynx::AudioEngine offline (false);
  9856. {
  9857. lynx::MainComponent ui (offline, false);
  9858. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1600x900"), "x", "");
  9859. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  9860. if (projectPath.isNotEmpty())
  9861. ui.openFile (juce::File (projectPath));
  9862. offline.dispatchPendingMessages();
  9863. // LYNX_PERFSHOT_PREPARE=1: Tools › Macros › Prepare for performance mode first (16 one-bar columns)
  9864. if (juce::SystemStats::getEnvironmentVariable ("LYNX_PERFSHOT_PREPARE", {}) == "1")
  9865. offline.editSong ([] (lynx::Song& s) { lynx::perf::prepareForPerformance (s, 16, 4 * lynx::ppq); }, false);
  9866. offline.editSong ([] (lynx::Song& s) { s.performanceMode = true; s.mode = lynx::PlayMode::song; }, false);
  9867. offline.dispatchPendingMessages();
  9868. // what the Player would publish: on each of the first tracks with zone clips, one clip playing (part way)
  9869. // and on every other one the next clip waiting for its sync point
  9870. const auto& song = offline.getSong();
  9871. auto& live = offline.performanceStateForSnapshot();
  9872. const auto zone = lynx::perf::zoneClips (song);
  9873. int lastTrack = -1, launched = 0;
  9874. for (const auto index : zone)
  9875. {
  9876. const auto& c = song.playlist[(std::size_t) index];
  9877. if (c.track == lastTrack || c.track >= lynx::perf::maxTracks)
  9878. continue;
  9879. lastTrack = c.track;
  9880. std::int64_t clips[64];
  9881. const auto n = lynx::perf::trackZoneClips (song, zone, c.track, clips, 64);
  9882. auto& view = live.tracks[(std::size_t) c.track];
  9883. view.playing.store (clips[(std::size_t) ((launched % 3) % n)]);
  9884. view.progress.store (0.2f + 0.15f * (float) (launched % 5));
  9885. if (launched % 2 == 1 && n > 1)
  9886. view.pending.store (clips[(std::size_t) ((launched % 3 + 1) % n)]);
  9887. ++launched;
  9888. }
  9889. live.anyPlaying.store (launched > 0);
  9890. ui.selectTabForSnapshot (2);
  9891. offline.dispatchPendingMessages();
  9892. auto& playlist = ui.getPlaylistForSnapshot();
  9893. savePng (playlist.createComponentSnapshot (playlist.getLocalBounds()), prefix + "-playlist-song.png");
  9894. playlist.runAction ("playlist.zoomPerformance"); // as FL opens these demos: the zone fills the view
  9895. offline.dispatchPendingMessages();
  9896. saveSnapshot (ui, prefix + "-playlist.png");
  9897. savePng (playlist.createComponentSnapshot (playlist.getLocalBounds()), prefix + "-playlist-only.png");
  9898. // patcherize: the first insert with effects (all of them) and the first channel that can be
  9899. auto patched = offline.getSong();
  9900. for (int t = 0; t < (int) patched.mixer.size(); ++t)
  9901. if (lynx::patcherize::slotsForAll (patched, t).size() > 1)
  9902. {
  9903. lynx::patcherize::patcherizeSlots (patched, t, 0, true);
  9904. break;
  9905. }
  9906. for (int c = 0; c < (int) patched.channels.size(); ++c)
  9907. if (lynx::patcherize::patcherizeChannel (patched, c))
  9908. break;
  9909. juce::String error;
  9910. lynx::ProjectFile::save (patched, juce::File (prefix + "-patcherized.lynx"), error);
  9911. }
  9912. }
  9913. void runPatcherShot (const juce::String& prefix, const juce::String& projectPath)
  9914. {
  9915. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  9916. lynx::AudioEngine offline (false);
  9917. {
  9918. lynx::MainComponent ui (offline, false);
  9919. ui.setSize (1280, 720);
  9920. if (projectPath.isNotEmpty())
  9921. ui.openFile (juce::File (projectPath));
  9922. else
  9923. {
  9924. auto song = lynx::Song::makeDefault();
  9925. song.mixer.resize (4);
  9926. auto slot = lynx::makeEffectSlot (lynx::EffectKind::patcher);
  9927. slot.patcher.wires.clear();
  9928. for (auto [kind, x, y] : { std::tuple { lynx::EffectKind::frequencySplitter, 200.0f, 60.0f }, { lynx::EffectKind::reverb, 420.0f, 0.0f },
  9929. { lynx::EffectKind::fruityDelay3, 420.0f, 120.0f }, { lynx::EffectKind::peakController, 200.0f, 260.0f } })
  9930. {
  9931. lynx::PatchNode n;
  9932. n.effect = lynx::makeEffectSlot (kind);
  9933. n.x = x;
  9934. n.y = y;
  9935. slot.patcher.nodes.push_back (n);
  9936. }
  9937. { // round 165c: a Hardware Insert node (its editor opens from the node)
  9938. lynx::PatchNode n;
  9939. n.effect = lynx::makeEffectSlot (lynx::EffectKind::hardwareInsert);
  9940. n.x = 420.0f, n.y = 260.0f;
  9941. slot.patcher.nodes.push_back (n);
  9942. }
  9943. auto wire = [&] (int from, int fromPort, int to, int toPort, float gain = 1.0f, lynx::PatchWire::Kind kind = lynx::PatchWire::Kind::audio) {
  9944. lynx::PatchWire w;
  9945. w.kind = kind;
  9946. w.from = from, w.fromPort = fromPort, w.to = to, w.toPort = toPort, w.gain = gain;
  9947. slot.patcher.wires.push_back (w);
  9948. };
  9949. wire (lynx::patchFromHost, 0, 0, 0);
  9950. wire (0, 1, 1, 0);
  9951. wire (0, 3, 2, 0, 0.5f);
  9952. wire (1, 0, lynx::patchToHost, 0);
  9953. wire (2, 0, lynx::patchToHost, 0);
  9954. wire (lynx::patchFromHost, 1, 3, 0);
  9955. wire (3, 1, 2, 2, 1.0f, lynx::PatchWire::Kind::control);
  9956. wire (0, 2, lynx::patchToHost, 1, 0.7f);
  9957. // round 171b (issue #65): a Surface knob on the reverb's parameter input 1, the reverb's parameter 0 out to
  9958. // the delay's parameter input 2 (FL's Inputs / Outputs › Parameters)
  9959. {
  9960. lynx::SurfaceControl knob;
  9961. knob.name = "Knob 1";
  9962. knob.value = 0.6f;
  9963. slot.patcher.surface = { knob };
  9964. slot.patcher.surfaceX = 200.0f, slot.patcher.surfaceY = 380.0f;
  9965. lynx::patcher::setParamInput (slot.patcher, 1, 1, true, "Reverb - 2");
  9966. lynx::patcher::setParamOutput (slot.patcher, 1, 0, true);
  9967. lynx::patcher::setParamInput (slot.patcher, 2, 2, true, "Delay - 3");
  9968. wire (lynx::patchSurface, 0, 1, 1, 1.0f, lynx::PatchWire::Kind::control);
  9969. wire (1, lynx::patchParamOutput (0), 2, 2, 1.0f, lynx::PatchWire::Kind::control);
  9970. }
  9971. slot.patcher.outputTracks = { 3 };
  9972. slot.patcher.inputX = -20.0f;
  9973. slot.patcher.outputX = 660.0f;
  9974. song.mixer[1].effects = { slot };
  9975. lynx::ChannelDef ch;
  9976. ch.name = "Patcher";
  9977. ch.instrument = lynx::InstrumentKind::patcher;
  9978. lynx::PatchNode synth, chorus;
  9979. synth.generator = true;
  9980. synth.channel.instrument = lynx::InstrumentKind::synth;
  9981. synth.channel.name = "Synth";
  9982. synth.x = 220.0f;
  9983. chorus.effect = lynx::makeEffectSlot (lynx::EffectKind::chorus);
  9984. chorus.x = 420.0f;
  9985. // round 162: a MIDI Out node between the "MIDI port 5" pin and "To LYNX" MIDI port 3, an Envelope Controller
  9986. // on the notes moving the chorus
  9987. lynx::PatchNode midiOut, envelope;
  9988. midiOut.generator = envelope.generator = true;
  9989. midiOut.channel.instrument = lynx::InstrumentKind::midiOut;
  9990. midiOut.channel.name = "MIDI Out";
  9991. lynx::midictl::writeMidiOut (midiOut.channel.pluginState, { 3, 0, 0, -1, -1 });
  9992. midiOut.x = 220.0f, midiOut.y = 160.0f;
  9993. envelope.channel.instrument = lynx::InstrumentKind::controller;
  9994. envelope.channel.name = "Envelope Controller";
  9995. envelope.channel.controllerState = lynx::writeEnvelopeController (lynx::defaultEnvelopeController());
  9996. envelope.x = 220.0f, envelope.y = 260.0f;
  9997. lynx::PatchNode osc; // round 164f: an FL engine node (its editor opens from the node)
  9998. osc.generator = true;
  9999. osc.channel = lynx::natives::makeChannel (lynx::InstrumentKind::threeosc, lynx::flStudioAccess()).value_or (lynx::ChannelDef {});
  10000. osc.channel.instrument = lynx::InstrumentKind::threeosc;
  10001. osc.channel.name = "3x Osc";
  10002. osc.x = 420.0f, osc.y = 260.0f;
  10003. // round 165c: Keyboard Controller, SoundFont player, Granulizer and Dashboard nodes (their editors open from the node)
  10004. lynx::PatchNode keys, soundfont, granulizer, dashboard;
  10005. keys.generator = soundfont.generator = granulizer.generator = dashboard.generator = true;
  10006. keys.channel.instrument = lynx::InstrumentKind::controller;
  10007. keys.channel.name = "Keyboard Controller";
  10008. {
  10009. lynx::KeyboardControllerData ramp;
  10010. for (std::size_t k = 0; k < ramp.keys.size(); ++k)
  10011. ramp.keys[k] = (float) k / (float) (ramp.keys.size() - 1);
  10012. lynx::writeKeyboardController (ramp, keys.channel.controllerState);
  10013. }
  10014. soundfont.channel = lynx::sf::makeChannel();
  10015. granulizer.channel = lynx::natives::makeChannel (lynx::InstrumentKind::granulizer, lynx::flStudioAccess()).value_or (lynx::ChannelDef {});
  10016. granulizer.channel.instrument = lynx::InstrumentKind::granulizer;
  10017. granulizer.channel.name = "Fruity Granulizer";
  10018. dashboard.channel.instrument = lynx::InstrumentKind::dashboard;
  10019. dashboard.channel.name = "Dashboard";
  10020. dashboard.channel.patcher.surface = lynx::surface::starterControls();
  10021. keys.x = 20.0f, keys.y = 440.0f;
  10022. soundfont.x = 220.0f, soundfont.y = 440.0f;
  10023. granulizer.x = 420.0f, granulizer.y = 440.0f;
  10024. dashboard.x = 20.0f, dashboard.y = 540.0f;
  10025. // and a Layer node playing the SoundFont and Granulizer nodes on its Children pin (crossfaded)
  10026. lynx::PatchNode layerNode;
  10027. layerNode.generator = true;
  10028. layerNode.channel.instrument = lynx::InstrumentKind::layer;
  10029. layerNode.channel.name = "Layer";
  10030. layerNode.channel.layer.crossfade = true;
  10031. layerNode.channel.layer.fade = 0.35f;
  10032. layerNode.x = 220.0f, layerNode.y = 540.0f;
  10033. ch.patcher.nodes = { synth, chorus, midiOut, envelope, osc, keys, soundfont, granulizer, dashboard, layerNode };
  10034. lynx::PatchWire notes, a, b, portIn, portOut, envNotes, envControl;
  10035. notes.kind = lynx::PatchWire::Kind::midi, notes.to = 0;
  10036. a.from = 0, a.to = 1;
  10037. b.from = 1;
  10038. portIn.kind = lynx::PatchWire::Kind::midi, portIn.fromPort = lynx::patchMidiPortPin (5), portIn.to = 2;
  10039. portOut.kind = lynx::PatchWire::Kind::midi, portOut.from = 2, portOut.to = lynx::patchToHost, portOut.toPort = 3;
  10040. envNotes.kind = lynx::PatchWire::Kind::midi, envNotes.to = 3;
  10041. envControl.kind = lynx::PatchWire::Kind::control, envControl.from = 3, envControl.to = 1, envControl.toPort = 0;
  10042. lynx::PatchWire oscNotes, oscOut;
  10043. oscNotes.kind = lynx::PatchWire::Kind::midi, oscNotes.to = 4;
  10044. oscOut.from = 4;
  10045. lynx::PatchWire layerNotes, layerToFont, layerToGrains, fontOut, grainsOut;
  10046. layerNotes.kind = layerToFont.kind = layerToGrains.kind = lynx::PatchWire::Kind::midi;
  10047. layerNotes.to = 9;
  10048. layerToFont.from = 9, layerToFont.to = 6;
  10049. layerToGrains.from = 9, layerToGrains.to = 7;
  10050. fontOut.from = 6;
  10051. grainsOut.from = 7;
  10052. ch.patcher.wires = { notes, a, b, portIn, portOut, envNotes, envControl, oscNotes, oscOut, layerNotes, layerToFont, layerToGrains, fontOut, grainsOut };
  10053. ch.patcher.fromMidiPorts = { 1, 5 };
  10054. ch.patcher.toMidiPorts = { 3 };
  10055. ch.patcher.outputX = 640.0f;
  10056. song.channels.push_back (ch);
  10057. // LYNX_PATCHERSHOT_SAVE=file.lynx: the demo as a project (a GUI check of the same Patchers, round 164f)
  10058. if (const auto save = juce::SystemStats::getEnvironmentVariable ("LYNX_PATCHERSHOT_SAVE", {}); save.isNotEmpty())
  10059. {
  10060. if (! song.patterns.empty())
  10061. for (int k = 0; k < 4; ++k)
  10062. 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 });
  10063. juce::String error;
  10064. lynx::ProjectFile::save (song, juce::File (save), error);
  10065. // round 171b: the saved Patchers come back the same (parameter ports, event cables, published)
  10066. juce::String report;
  10067. if (const auto loaded = lynx::ProjectFile::load (juce::File (save), error))
  10068. {
  10069. const auto same = loaded->mixer.size() > 1 && ! loaded->mixer[1].effects.empty()
  10070. && loaded->mixer[1].effects[0].patcher == song.mixer[1].effects[0].patcher;
  10071. const auto& d = loaded->mixer.size() > 1 && ! loaded->mixer[1].effects.empty() ? loaded->mixer[1].effects[0].patcher : lynx::PatcherDoc {};
  10072. report << "patcher round trip: " << (same ? "OK" : "DIFFERENT") << "\n";
  10073. if (! same && loaded->mixer.size() > 1 && ! loaded->mixer[1].effects.empty())
  10074. {
  10075. const auto& a = song.mixer[1].effects[0].patcher;
  10076. report << "wires " << (a.wires == d.wires ? "same" : "differ") << ", published " << (a.published == d.published ? "same" : "differ")
  10077. << ", surface " << (a.surface == d.surface ? "same" : "differ") << "\n";
  10078. for (std::size_t n = 0; n < std::min (a.nodes.size(), d.nodes.size()); ++n)
  10079. if (! (a.nodes[n] == d.nodes[n]))
  10080. report << "node " << (int) n << " differs: ports " << (a.nodes[n].paramIns == d.nodes[n].paramIns && a.nodes[n].paramOuts == d.nodes[n].paramOuts ? "same" : "differ")
  10081. << ", effect " << (a.nodes[n].effect == d.nodes[n].effect ? "same" : "differ") << ", xy "
  10082. << (a.nodes[n].x == d.nodes[n].x && a.nodes[n].y == d.nodes[n].y ? "same" : "differ") << "\n";
  10083. }
  10084. for (int n = 0; n < (int) d.nodes.size(); ++n)
  10085. report << "node " << n << " paramIns " << (int) d.nodes[(std::size_t) n].paramIns.size() << " paramOuts "
  10086. << (int) d.nodes[(std::size_t) n].paramOuts.size() << "\n";
  10087. for (const auto& w : d.wires)
  10088. if (w.kind == lynx::PatchWire::Kind::control)
  10089. report << "control " << w.from << ":" << w.fromPort << " -> " << w.to << ":" << w.toPort << "\n";
  10090. for (const auto& p : d.published)
  10091. report << "published " << p.node << ":" << p.param << " " << juce::String::fromUTF8 (p.name.c_str()) << "\n";
  10092. }
  10093. else
  10094. report << "patcher round trip: load failed: " << error << "\n";
  10095. juce::File (prefix + "-roundtrip.txt").replaceWithText (report);
  10096. }
  10097. offline.setSong (std::move (song));
  10098. }
  10099. offline.dispatchPendingMessages();
  10100. const auto& song = offline.getSong();
  10101. auto shootOpen = [&] (const juce::String& name) {
  10102. for (int k = 0; k < juce::TopLevelWindow::getNumTopLevelWindows(); ++k)
  10103. if (auto* w = dynamic_cast<juce::DocumentWindow*> (juce::TopLevelWindow::getTopLevelWindow (k)))
  10104. if (w->getName().startsWith (lynx::tr ("Patcher")) && w->getContentComponent() != nullptr)
  10105. {
  10106. auto* c = w->getContentComponent();
  10107. savePng (c->createComponentSnapshot (c->getLocalBounds()), prefix + name);
  10108. delete w;
  10109. return;
  10110. }
  10111. };
  10112. int shots = 0;
  10113. for (int t = 0; t < (int) song.mixer.size() && shots < 12; ++t)
  10114. for (int s = 0; s < (int) song.mixer[(std::size_t) t].effects.size(); ++s)
  10115. if (song.mixer[(std::size_t) t].effects[(std::size_t) s].kind == lynx::EffectKind::patcher)
  10116. {
  10117. lynx::PatcherWindows::openSlot (offline, t, s);
  10118. shootOpen ("-insert" + juce::String (t) + "-slot" + juce::String (s) + ".png");
  10119. // each built-in node's editor, as a double-click opens it (round 165c)
  10120. lynx::PatcherWindows::shootNodeEditors (offline, false, t, s, [&] (const juce::Image& image, int n) {
  10121. savePng (image, prefix + "-insert" + juce::String (t) + "-slot" + juce::String (s) + "-node" + juce::String (n) + ".png");
  10122. });
  10123. ++shots;
  10124. if (shots == 1) // its menus (round 162)
  10125. lynx::PatcherWindows::shootMenus (offline, false, t, s, [&] (const juce::Image& image, const juce::String& name) {
  10126. savePng (image, prefix + "-menu-" + name + ".png");
  10127. });
  10128. }
  10129. for (int c = 0; c < (int) song.channels.size(); ++c)
  10130. if (song.channels[(std::size_t) c].instrument == lynx::InstrumentKind::patcher)
  10131. {
  10132. lynx::PatcherWindows::openChannel (offline, c);
  10133. shootOpen ("-channel" + juce::String (c) + ".png");
  10134. // each node's editor, as a double-click opens it (round 164f; every built-in node since round 165c)
  10135. lynx::PatcherWindows::shootNodeEditors (offline, true, c, 0, [&] (const juce::Image& image, int n) {
  10136. savePng (image, prefix + "-channel" + juce::String (c) + "-node" + juce::String (n) + ".png");
  10137. });
  10138. lynx::PatcherWindows::shootMenus (offline, true, c, 0, [&] (const juce::Image& image, const juce::String& name) {
  10139. savePng (image, prefix + "-channel" + juce::String (c) + "-menu-" + name + ".png");
  10140. });
  10141. }
  10142. }
  10143. }
  10144. // Issue #64: FL's letter keys in a plugin menu (quickpick::showMenu), checked on the real menu windows
  10145. struct TypeAheadTest final : private juce::Timer
  10146. {
  10147. juce::File out;
  10148. juce::StringArray log;
  10149. int step = 0, picked = 0;
  10150. bool ok = true, menuShown = false;
  10151. std::unique_ptr<juce::DocumentWindow> owner;
  10152. juce::PopupMenu pending;
  10153. static juce::String highlighted()
  10154. {
  10155. if (auto* window = juce::Component::getCurrentlyModalComponent())
  10156. for (auto* child : window->getChildren())
  10157. if (auto* h = child->getAccessibilityHandler(); h != nullptr && h->hasFocus (false))
  10158. return h->getTitle();
  10159. return "(none)";
  10160. }
  10161. static void press (const juce::KeyPress& key)
  10162. {
  10163. if (auto* window = juce::Component::getCurrentlyModalComponent())
  10164. if (auto* peer = window->getPeer())
  10165. peer->handleKeyPress (key);
  10166. }
  10167. void expect (const juce::String& what, const juce::String& got, const juce::String& wanted)
  10168. {
  10169. const auto good = got == wanted;
  10170. ok = ok && good;
  10171. log.add ((good ? "ok " : "FAIL ") + what + ": " + got + (good ? juce::String() : " (wanted " + wanted + ")"));
  10172. }
  10173. void start()
  10174. {
  10175. juce::PopupMenu menu, sub;
  10176. auto item = [this] (juce::PopupMenu& m, int id, const char* text, bool enabled = true) {
  10177. m.addItem (text, enabled, false, [this, id] { picked = id; });
  10178. };
  10179. menu.addSectionHeader ("LYNX SHARE");
  10180. item (menu, 1, "Echoform");
  10181. item (menu, 2, "EQ");
  10182. item (menu, 3, "Halo");
  10183. menu.addSectionHeader ("Misc");
  10184. item (menu, 4, "Effector");
  10185. item (menu, 5, "Exciter (unavailable)", false);
  10186. item (sub, 10, "Delay");
  10187. item (sub, 11, "Edison");
  10188. item (sub, 12, "Eventide");
  10189. menu.addSubMenu ("Tree", sub);
  10190. // the menu belongs to a window in the foreground, as when the user right-clicks a mixer slot (JUCE closes a
  10191. // menu of a background process at once)
  10192. owner = std::make_unique<juce::DocumentWindow> ("LYNX type-ahead test", juce::Colours::black, 0);
  10193. owner->setBounds (200, 200, 300, 200);
  10194. owner->setVisible (true);
  10195. lynx::forceForegroundForTest (*owner);
  10196. pending = menu; // shown once the window is up and active (X11 maps and activates it asynchronously)
  10197. startTimer (300);
  10198. }
  10199. void timerCallback() override
  10200. {
  10201. const auto e = juce::KeyPress ('e', {}, 'e');
  10202. if (step == 0 && owner != nullptr && ! menuShown)
  10203. {
  10204. menuShown = true;
  10205. lynx::forceForegroundForTest (*owner);
  10206. lynx::quickpick::showMenu (pending, juce::PopupMenu::Options().withTargetComponent (owner.get()), {});
  10207. return;
  10208. }
  10209. switch (step++)
  10210. {
  10211. case 0: expect ("menu open", juce::String ((int) (juce::Component::getCurrentlyModalComponent() != nullptr)), "1"); break;
  10212. case 1: press (e); expect ("e", highlighted(), "Echoform"); break;
  10213. case 2: press (e); expect ("e again", highlighted(), "EQ"); break;
  10214. case 3: press (juce::KeyPress ('E', juce::ModifierKeys::shiftModifier, 'E')); expect ("E (shift)", highlighted(), "Effector"); break;
  10215. case 4: press (e); expect ("e wraps (skips the disabled one)", highlighted(), "Echoform"); break;
  10216. case 5: press (juce::KeyPress ('m', {}, 'm')); expect ("m (only a heading starts with it: no move)", highlighted(), "Echoform"); break;
  10217. case 6: press (juce::KeyPress (juce::KeyPress::downKey)); expect ("down arrow", highlighted(), "EQ"); break;
  10218. case 7: press (e); expect ("e after the arrow", highlighted(), "Effector"); break;
  10219. case 8: press (juce::KeyPress ('t', {}, 't')); expect ("t", highlighted(), "Tree"); break;
  10220. case 9: press (juce::KeyPress (juce::KeyPress::rightKey)); break; // opens the submenu (it takes the keys)
  10221. case 10: press (e); expect ("e in the submenu", highlighted(), "Edison"); break;
  10222. case 11: press (e); expect ("e again in the submenu", highlighted(), "Eventide"); break;
  10223. case 12: expect ("nothing picked by the letters", juce::String (picked), "0"); press (juce::KeyPress (juce::KeyPress::returnKey)); break;
  10224. case 13: break;
  10225. default:
  10226. expect ("Enter closed the menu", juce::String ((int) (juce::Component::getCurrentlyModalComponent() == nullptr)), "1");
  10227. expect ("Enter picked", juce::String (picked), "12");
  10228. stopTimer();
  10229. owner.reset();
  10230. log.add (ok ? "result=OK" : "result=FAIL");
  10231. out.replaceWithText (log.joinIntoString ("\n") + "\n");
  10232. juce::JUCEApplication::getInstance()->setApplicationReturnValue (ok ? 0 : 1);
  10233. juce::JUCEApplication::quit();
  10234. return;
  10235. }
  10236. }
  10237. };
  10238. std::unique_ptr<TypeAheadTest> typeAheadTest;
  10239. struct ChooserTest final : private juce::Timer
  10240. {
  10241. juce::File out, file;
  10242. juce::StringArray log;
  10243. std::unique_ptr<juce::FileChooser> chooser;
  10244. double started = 0;
  10245. bool shot = false, done = false;
  10246. void start()
  10247. {
  10248. log.add ("LYNX_FILE_DIALOG=" + juce::SystemStats::getEnvironmentVariable ("LYNX_FILE_DIALOG", {}));
  10249. log.add ("native=" + juce::String ((int) lynx::ui::filechooser::nativeDialogs()));
  10250. chooser = lynx::ui::makeFileChooser ("Open audio file", file.getParentDirectory(), "*.wav;*.flac");
  10251. started = juce::Time::getMillisecondCounterHiRes();
  10252. lynx::ui::launchChooser (chooser, juce::FileBrowserComponent::openMode | juce::FileBrowserComponent::canSelectFiles,
  10253. [this] (const juce::FileChooser& fc) { finish (fc.getResult()); });
  10254. startTimer (200);
  10255. }
  10256. static juce::FileChooserDialogBox* builtInDialog()
  10257. {
  10258. for (int i = 0; i < juce::Desktop::getInstance().getNumComponents(); ++i)
  10259. if (auto* box = dynamic_cast<juce::FileChooserDialogBox*> (juce::Desktop::getInstance().getComponent (i)); box != nullptr && box->isShowing())
  10260. return box;
  10261. return nullptr;
  10262. }
  10263. static juce::FileBrowserComponent* findBrowser (juce::Component& c)
  10264. {
  10265. if (auto* b = dynamic_cast<juce::FileBrowserComponent*> (&c))
  10266. return b;
  10267. for (auto* child : c.getChildren())
  10268. if (auto* b = findBrowser (*child))
  10269. return b;
  10270. return nullptr;
  10271. }
  10272. void timerCallback() override
  10273. {
  10274. if (done)
  10275. return;
  10276. if (auto* box = builtInDialog(); box != nullptr && ! shot)
  10277. {
  10278. shot = true;
  10279. log.add ("built-in dialog shown after " + juce::String (juce::roundToInt (juce::Time::getMillisecondCounterHiRes() - started)) + " ms");
  10280. const auto image = box->createComponentSnapshot (box->getLocalBounds());
  10281. juce::FileOutputStream png (out.getSiblingFile (out.getFileName() + ".png"));
  10282. if (png.openedOk())
  10283. {
  10284. png.setPosition (0), png.truncate();
  10285. juce::PNGImageFormat().writeImageToStream (image, png);
  10286. }
  10287. if (auto* browser = findBrowser (*box))
  10288. {
  10289. browser->setRoot (file.getParentDirectory());
  10290. browser->setFileName (file.getFileName());
  10291. log.add ("typed " + file.getFileName());
  10292. box->exitModalState (1);
  10293. }
  10294. else
  10295. log.add ("no file browser in the dialog");
  10296. }
  10297. if (juce::Time::getMillisecondCounterHiRes() - started > 30000.0)
  10298. finish ({}, "timeout");
  10299. }
  10300. void finish (const juce::File& result, const juce::String& why = {})
  10301. {
  10302. if (done)
  10303. return;
  10304. done = true;
  10305. stopTimer();
  10306. log.add ("callback after " + juce::String (juce::roundToInt (juce::Time::getMillisecondCounterHiRes() - started)) + " ms: "
  10307. + (why.isNotEmpty() ? why : result.getFullPathName().isEmpty() ? juce::String ("(no file)") : result.getFullPathName()));
  10308. log.add ("native now=" + juce::String ((int) lynx::ui::filechooser::nativeDialogs()));
  10309. const auto ok = result == file && result.existsAsFile();
  10310. log.add (ok ? "result=OK" : "result=FAIL");
  10311. out.replaceWithText (log.joinIntoString ("\n") + "\n");
  10312. juce::JUCEApplication::getInstance()->setApplicationReturnValue (ok ? 0 : 1);
  10313. juce::MessageManager::callAsync ([] { juce::JUCEApplication::quit(); });
  10314. }
  10315. };
  10316. std::unique_ptr<ChooserTest> chooserTest;
  10317. void runChooserTest (const juce::File& out, const juce::File& file)
  10318. {
  10319. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  10320. chooserTest = std::make_unique<ChooserTest>();
  10321. chooserTest->out = out;
  10322. chooserTest->file = file;
  10323. chooserTest->start();
  10324. }
  10325. void runTypeAheadTest (const juce::File& out)
  10326. {
  10327. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  10328. typeAheadTest = std::make_unique<TypeAheadTest>();
  10329. typeAheadTest->out = out;
  10330. typeAheadTest->start();
  10331. }
  10332. void runSnapshot (const juce::String& prefix, const juce::String& projectPath)
  10333. {
  10334. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  10335. // LYNX_SNAPSHOT_THEME=file.lynxtheme: the pictures in that theme (round 162d)
  10336. if (const auto themeFile = juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_THEME", {}); themeFile.isNotEmpty())
  10337. if (const auto spec = lynx::themeui::loadFile (juce::File (themeFile)))
  10338. lynx::themeui::apply (*spec, false);
  10339. {
  10340. lynx::AudioEngine offline (false);
  10341. lynx::MainComponent ui (offline, false); // default layout and keys, nothing saved
  10342. // LYNX_SNAPSHOT_SIZE=WxH (default 1280x720)
  10343. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1280x720"), "x", "");
  10344. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  10345. if (projectPath.isNotEmpty())
  10346. ui.openFile (juce::File (projectPath));
  10347. offline.dispatchPendingMessages(); // change notifications are asynchronous
  10348. ui.waitForBrowserForSnapshot();
  10349. // the workspace desktop: the default layout, then with the Piano Roll and Mixer floating too
  10350. // (and a sample hint in the status strip, as when hovering a knob)
  10351. ui.showDesktopForSnapshot (false);
  10352. ui.setMetersForSnapshot (0.23, (std::int64_t) 412 << 20, 6);
  10353. offline.dispatchPendingMessages();
  10354. saveSnapshot (ui, prefix + "-desktop.png");
  10355. // the first start: the setup wizard over the main window (round 140), also on a small screen (it scrolls)
  10356. {
  10357. const auto size = ui.getBounds();
  10358. ui.showSetupWizard();
  10359. offline.dispatchPendingMessages();
  10360. saveSnapshot (ui, prefix + "-desktop-setup.png");
  10361. ui.setSize (1024, 600);
  10362. offline.dispatchPendingMessages();
  10363. saveSnapshot (ui, prefix + "-desktop-setup-small.png");
  10364. ui.closeSetupWizardForSnapshot();
  10365. ui.setBounds (size);
  10366. offline.dispatchPendingMessages();
  10367. }
  10368. // the start-up desktop and the toolbar at the usual window sizes: the untouched default layout
  10369. // follows the window (default rects, not scaled ones); panels drop from the toolbar by priority
  10370. {
  10371. const auto size = ui.getBounds();
  10372. for (const auto& [w, h] : std::vector<std::pair<int, int>> { { 1280, 720 }, { 1366, 768 }, { 1600, 900 }, { 1920, 1080 }, { 2560, 1440 }, { 3840, 2160 } })
  10373. {
  10374. ui.setSize (w, h);
  10375. offline.dispatchPendingMessages();
  10376. saveSnapshot (ui, prefix + "-desktop-" + juce::String (w) + ".png");
  10377. saveArea (ui, ui.getToolbarBoundsForSnapshot(), prefix + "-toolbar-" + juce::String (w) + ".png");
  10378. if (w == 1920) // the rack scrolled to its last steps: the controls column stays in view (round 90)
  10379. {
  10380. ui.scrollRackForSnapshot (100000);
  10381. offline.dispatchPendingMessages();
  10382. saveSnapshot (ui, prefix + "-desktop-rack-scrolled.png");
  10383. ui.scrollRackForSnapshot (0);
  10384. }
  10385. }
  10386. // the toolbar with small and large icons, and a customized one (groups hidden and reordered)
  10387. ui.setSize (1600, 900);
  10388. for (auto [iconSize, name] : { std::pair { lynx::toolbarlayout::IconSize::small, "small" }, { lynx::toolbarlayout::IconSize::large, "large" } })
  10389. {
  10390. auto layout = lynx::toolbarlayout::Layout::makeDefault();
  10391. layout.iconSize = iconSize;
  10392. ui.setToolbarLayoutForSnapshot (layout);
  10393. saveArea (ui, ui.getToolbarBoundsForSnapshot(), prefix + "-toolbar-" + name + "-1600.png");
  10394. }
  10395. {
  10396. auto layout = lynx::toolbarlayout::Layout::makeDefault();
  10397. layout.move (lynx::toolbarlayout::Group::windows, -3);
  10398. layout.setShown (lynx::toolbarlayout::Group::record, false);
  10399. layout.setShown (lynx::toolbarlayout::Group::meters, false);
  10400. ui.setToolbarLayoutForSnapshot (layout);
  10401. saveArea (ui, ui.getToolbarBoundsForSnapshot(), prefix + "-toolbar-custom-1600.png");
  10402. }
  10403. {
  10404. // round 170e: the toolbar after a knob was moved: the last tweaked read-out (its caption) and the snap magnet
  10405. ui.setSize (1920, 1080); // the read-out needs room beside the hint bar
  10406. ui.setToolbarLayoutForSnapshot (lynx::toolbarlayout::Layout::makeDefault());
  10407. lynx::AutomationTarget t;
  10408. t.kind = lynx::AutomationTargetKind::mixerVolume;
  10409. t.index = 0;
  10410. offline.noteTweaked (t);
  10411. ui.refreshTweakReadoutForSnapshot();
  10412. offline.dispatchPendingMessages();
  10413. saveArea (ui, ui.getToolbarBoundsForSnapshot(), prefix + "-toolbar-tweak-1920.png");
  10414. ui.setSize (1600, 900);
  10415. }
  10416. {
  10417. // the toolbar's edit mode (round 115): outlined panels and the tray of panels under it
  10418. ui.setToolbarLayoutForSnapshot (lynx::toolbarlayout::Layout::makeDefault());
  10419. auto layout = lynx::toolbarlayout::Layout::makeDefault();
  10420. layout.setShown (lynx::toolbarlayout::Group::meters, false);
  10421. ui.setToolbarLayoutForSnapshot (layout);
  10422. ui.setToolbarEditingForSnapshot (true);
  10423. offline.dispatchPendingMessages();
  10424. saveArea (ui, ui.getToolbarBoundsForSnapshot().withHeight (ui.getToolbarAndTrayHeightForSnapshot()), prefix + "-toolbar-edit-1600.png");
  10425. ui.setToolbarEditingForSnapshot (false);
  10426. // Ctrl+F11: only the menu and the hint bar
  10427. layout = lynx::toolbarlayout::Layout::makeDefault();
  10428. layout.visible = false;
  10429. ui.setToolbarLayoutForSnapshot (layout);
  10430. saveArea (ui, ui.getLocalBounds().withHeight (120), prefix + "-toolbar-hidden-1600.png");
  10431. }
  10432. ui.setToolbarLayoutForSnapshot (lynx::toolbarlayout::Layout::makeDefault());
  10433. // quick tips: the toolbar and title bars with a few name bubbles, and every tip on one sheet
  10434. offline.dispatchPendingMessages();
  10435. saveQuickTips (ui, prefix);
  10436. ui.setBounds (size);
  10437. offline.dispatchPendingMessages();
  10438. }
  10439. // the hint bar: a value control while it is dragged (live value), a gesture line with mouse and key
  10440. // glyphs, and a text too long for one line (two lines)
  10441. {
  10442. const auto toolbar = ui.getToolbarBoundsForSnapshot().withWidth (juce::jmin (ui.getWidth(), 900));
  10443. const lynx::ui::Hint hints[] = {
  10444. { lynx::tr ("Volume") + " - " + lynx::tr ("drag (Ctrl: fine), wheel, Alt+click resets"), "-3.2 dB", true, true },
  10445. { lynx::tr ("Piano Roll: [LMB] add a note, drag to move [RMB] delete [Ctrl][LMB] drag to select [Ctrl][Wheel] zoom"), {}, false, false },
  10446. { lynx::tr ("Global snap: the grid of the Piano Roll and Playlist (when they follow it) and the quantise of recorded notes "
  10447. "[LMB] choose [Wheel] step [RMB] length of new notes [Backspace] snap on/off [Alt] while dragging: no snap"), {}, false, true },
  10448. };
  10449. for (int i = 0; i < 3; ++i)
  10450. {
  10451. ui.setHintForSnapshot (hints[i], i == 0);
  10452. saveArea (ui, toolbar, prefix + "-hint-" + juce::String (i + 1) + ".png");
  10453. }
  10454. }
  10455. ui.showDesktopForSnapshot (true);
  10456. ui.setHintForSnapshot ({ lynx::tr ("Volume") + " - " + lynx::tr ("drag (Ctrl: fine), wheel, Alt+click resets"), "78%", true, true });
  10457. saveSnapshot (ui, prefix + "-desktop-all.png");
  10458. ui.selectTabForSnapshot (0);
  10459. saveSnapshot (ui, prefix + "-rack.png");
  10460. {
  10461. // a pattern with piano-roll notes: those rows show a miniature instead of steps (round 90)
  10462. int found = -1;
  10463. const auto before = offline.getSong().currentPattern;
  10464. {
  10465. const auto& song = offline.getSong();
  10466. for (int p = 0; p < (int) song.patterns.size() && found < 0; ++p)
  10467. for (int c = 0; c < (int) song.channels.size() && found < 0; ++c)
  10468. if (lynx::showsNotePreview (song.patterns[(std::size_t) p], c))
  10469. found = p;
  10470. }
  10471. if (found >= 0)
  10472. {
  10473. offline.editSong ([found] (lynx::Song& s) { s.currentPattern = found; }, false);
  10474. offline.dispatchPendingMessages();
  10475. saveSnapshot (ui, prefix + "-rack-preview.png");
  10476. offline.editSong ([before] (lynx::Song& s) { s.currentPattern = before; }, false);
  10477. offline.dispatchPendingMessages();
  10478. }
  10479. }
  10480. ui.selectTabForSnapshot (1);
  10481. saveSnapshot (ui, prefix + "-pianoroll.png");
  10482. if (const auto strip = ui.getToolStripAreaForSnapshot (false); ! strip.isEmpty())
  10483. saveArea (ui, strip, prefix + "-pianoroll-tools.png");
  10484. // the editors' mouse feel: the hovered note / clip edge (grip, outline) and its hint in the hint bar
  10485. ui.setHintForSnapshot (ui.getPianoRollForSnapshot().hoverForSnapshot());
  10486. saveSnapshot (ui, prefix + "-pianoroll-hover.png");
  10487. {
  10488. // a pattern with note Chance or a Velocity Range (round 187c): the Piano roll with those lanes
  10489. const auto& song = offline.getSong();
  10490. const auto& notes = song.patterns[(std::size_t) std::clamp (song.currentPattern, 0, (int) song.patterns.size() - 1)].notes;
  10491. if (std::any_of (notes.begin(), notes.end(), [] (const lynx::Note& n) { return n.hasChance(); }))
  10492. {
  10493. auto& roll = ui.getPianoRollForSnapshot();
  10494. ui.setHintForSnapshot ({});
  10495. for (const auto& [lane, name] : { std::pair { lynx::PianoRollComponent::laneChance, "chance" },
  10496. { lynx::PianoRollComponent::laneVelocityRange, "velrange" },
  10497. { lynx::PianoRollComponent::laneVelocity, "velocity" } })
  10498. {
  10499. roll.setLaneForSnapshot (lane);
  10500. offline.dispatchPendingMessages();
  10501. saveSnapshot (ui, prefix + "-pianoroll-" + name + ".png");
  10502. }
  10503. }
  10504. }
  10505. ui.selectTabForSnapshot (2);
  10506. saveSnapshot (ui, prefix + "-playlist.png");
  10507. if (const auto strip = ui.getToolStripAreaForSnapshot (true); ! strip.isEmpty())
  10508. saveArea (ui, strip, prefix + "-playlist-tools.png");
  10509. ui.setHintForSnapshot (ui.getPlaylistForSnapshot().hoverForSnapshot());
  10510. saveSnapshot (ui, prefix + "-playlist-hover.png");
  10511. ui.setHintForSnapshot ({ lynx::tr ("Volume") + " - " + lynx::tr ("drag (Ctrl: fine), wheel, Alt+click resets"), "78%", true, true });
  10512. // the Playlist with a time selection over bars 2-3 (it selects the clips it touches) and the Knife tool
  10513. ui.getPlaylistForSnapshot().setTimeSelectionForSnapshot (1, 3);
  10514. ui.getPlaylistForSnapshot().setToolForSnapshot (lynx::EditTool::knife);
  10515. offline.dispatchPendingMessages();
  10516. saveSnapshot (ui, prefix + "-playlist-timesel.png");
  10517. ui.getPlaylistForSnapshot().setToolForSnapshot (lynx::EditTool::pencil);
  10518. // round 177b: automation lanes on (two lanes under track 2: a volume ramp and a pan wobble)
  10519. {
  10520. const auto before = offline.getSong();
  10521. offline.editSong ([] (lynx::Song& s) {
  10522. s.loopStart = s.loopEnd = 0; // (no time selection in this one)
  10523. const auto bar = (std::int64_t) lynx::ppq * s.beatsPerBar;
  10524. const auto vol = lynx::autolanes::addLane (s, 1, { lynx::AutomationTargetKind::mixerVolume, 1, 0, 0 }, "Insert 1 - Volume", 0.3f);
  10525. s.automations[(std::size_t) vol].points = { { 0, 0.3f, 0.0f }, { bar * 2, 0.8f, 0.4f }, { bar * 4, 0.6f, 0.0f } };
  10526. const auto pan = lynx::autolanes::addLane (s, 1, { lynx::AutomationTargetKind::mixerPan, 1, 0, 0 }, "Insert 1 - Pan", 0.5f);
  10527. 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 } };
  10528. }, false);
  10529. lynx::autolanes::setShown (true);
  10530. ui.getPlaylistForSnapshot().resized();
  10531. offline.dispatchPendingMessages();
  10532. saveSnapshot (ui, prefix + "-playlist-lanes.png");
  10533. lynx::autolanes::setShown (false);
  10534. offline.editSong ([before] (lynx::Song& s) { s = before; }, false);
  10535. offline.dispatchPendingMessages();
  10536. }
  10537. // round 104: a folded track group (FL's thin member rows) and the Picker's audio tab
  10538. {
  10539. int header = -1;
  10540. for (int t = 0; t < (int) offline.getSong().playlistTracks.size() && header < 0; ++t)
  10541. if (lynx::noteedit::isGroupHeader (offline.getSong(), t))
  10542. header = t;
  10543. if (header >= 0)
  10544. {
  10545. offline.editSong ([header] (lynx::Song& s) { lynx::noteedit::setGroupCollapsed (s, header, true); }, false);
  10546. offline.dispatchPendingMessages();
  10547. saveSnapshot (ui, prefix + "-playlist-group-folded.png");
  10548. offline.editSong ([header] (lynx::Song& s) { lynx::noteedit::setGroupCollapsed (s, header, false); }, false);
  10549. }
  10550. ui.getPickerForSnapshot().setView (1);
  10551. offline.dispatchPendingMessages();
  10552. saveSnapshot (ui, prefix + "-playlist-picker-audio.png");
  10553. ui.getPickerForSnapshot().setView (0);
  10554. }
  10555. // round 104: the Channel Rack filtered to its first filter group
  10556. if (! offline.getSong().channelGroups.empty())
  10557. {
  10558. ui.selectTabForSnapshot (0);
  10559. ui.getRackForSnapshot().setFilterGroup (0);
  10560. offline.dispatchPendingMessages();
  10561. saveSnapshot (ui, prefix + "-rack-filter.png");
  10562. ui.getRackForSnapshot().setFilterGroup (-1);
  10563. }
  10564. ui.selectTabForSnapshot (3);
  10565. // LYNX_SNAPSHOT_ARRANGE=1 (round 186c): Mixer menu › "Arrange inserts like the Playlist" first
  10566. if (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_ARRANGE", {}) == "1")
  10567. {
  10568. offline.editSong ([] (lynx::Song& s) { lynx::mixerops::arrangeLikePlaylist (s); });
  10569. offline.dispatchPendingMessages();
  10570. }
  10571. // LYNX_SNAPSHOT_TRACK=n: shows the effects of that mixer track
  10572. if (const auto track = juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_TRACK", {}); track.isNotEmpty())
  10573. {
  10574. ui.selectMixerTrackForSnapshot (track.getIntValue(),
  10575. juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SLOT", "-1").getIntValue());
  10576. offline.dispatchPendingMessages();
  10577. }
  10578. saveSnapshot (ui, prefix + "-mixer.png");
  10579. // round 168h (issue #52): FL's 8 Mixer layouts
  10580. {
  10581. const auto before = lynx::MixerStrips::layout;
  10582. for (int l = 0; l < lynx::mixerlayout::layoutCount; ++l)
  10583. {
  10584. ui.getMixerForSnapshot().getStripsForSnapshot().setLayout ((lynx::mixerlayout::Layout) l);
  10585. offline.dispatchPendingMessages();
  10586. saveSnapshot (ui, prefix + "-mixer168h-" + juce::String (l) + ".png");
  10587. }
  10588. ui.getMixerForSnapshot().getStripsForSnapshot().setLayout (before);
  10589. offline.dispatchPendingMessages();
  10590. }
  10591. // round 163: the Mixer at short heights (UI zoom 150%+): the EQ folds, then the effects panel scrolls
  10592. {
  10593. const auto size = ui.getBounds();
  10594. for (auto h : { 450, 560, 680, 820 })
  10595. {
  10596. ui.setSize (size.getWidth(), h);
  10597. offline.dispatchPendingMessages();
  10598. saveSnapshot (ui, prefix + "-mixer163-" + juce::String (h) + ".png");
  10599. }
  10600. ui.setBounds (size);
  10601. offline.dispatchPendingMessages();
  10602. }
  10603. // round 170b (Busy Works Beats' review): inserts 1-3 selected and routed together to insert 4, a single effect
  10604. // moved down into slot 2 (FL's slot places), and the plugin menus grouped by category, LYNX SHARE first
  10605. {
  10606. const auto before = offline.getSong();
  10607. offline.editSong ([] (lynx::Song& s) {
  10608. if (s.mixer.size() < 5)
  10609. return;
  10610. s.mixer[1].effects.clear();
  10611. lynx::EffectSlot fx;
  10612. fx.kind = lynx::EffectKind::compressor;
  10613. s.mixer[1].effects.push_back (fx);
  10614. lynx::mixerops::moveEffectBy (s, 1, 0, 1);
  10615. lynx::mixerops::switchSelectedRoute (s, { 1, 2, 3 }, 4, true);
  10616. });
  10617. ui.selectMixerTrackForSnapshot (1);
  10618. ui.getMixerForSnapshot().getStripsForSnapshot().setSelection ({ 1, 2, 3 }, 1);
  10619. offline.dispatchPendingMessages();
  10620. saveSnapshot (ui, prefix + "-mixer170b.png");
  10621. juce::PopupMenu effects, generators;
  10622. lynx::quickpick::addFolderGroups (effects, offline, std::function<void (lynx::EffectSlot)> ([] (lynx::EffectSlot) {}));
  10623. lynx::quickpick::addFolderViewItems (effects, offline);
  10624. lynx::quickpick::addGeneratorMenu (generators, offline, [] (lynx::ChannelDef) {}, {}, nullptr, nullptr);
  10625. lynx::quickpick::addFolderViewItems (generators, offline);
  10626. saveMenus (juce::StringArray { "Mixer slot: add an effect", "Channel Rack: add" }, { effects, generators }, prefix + "-menus170b.png");
  10627. offline.setSong (before);
  10628. offline.dispatchPendingMessages();
  10629. }
  10630. // standalone windows, with the theme background
  10631. auto saveWindow = [&prefix] (std::unique_ptr<juce::Component> c, const juce::String& name) {
  10632. juce::Component frame;
  10633. frame.setSize (c->getWidth(), c->getHeight());
  10634. frame.setOpaque (true);
  10635. // an AlertWindow is built on the desktop: shown there first, it would take the foreground from whoever has it
  10636. // (TopLevelWindow::visibilityChanged calls toFront (true)). Off the desktop, its control that showing it would
  10637. // have focused (what grabKeyboardFocus picks) is marked, so the picture keeps that control's focus ring
  10638. if (c->isOnDesktop())
  10639. {
  10640. c->removeFromDesktop();
  10641. auto* focus = c.get();
  10642. for (int depth = 0; focus != nullptr && depth < 32; ++depth)
  10643. {
  10644. if (focus->getWantsKeyboardFocus() && (focus->isEnabled() || focus == c.get()))
  10645. {
  10646. focus->getProperties().set ("lynxSnapshotFocus", true);
  10647. break;
  10648. }
  10649. auto traverser = focus->createKeyboardFocusTraverser();
  10650. focus = traverser != nullptr ? traverser->getDefaultComponent (focus) : nullptr;
  10651. }
  10652. }
  10653. frame.addAndMakeVisible (*c);
  10654. c->setTopLeftPosition (0, 0);
  10655. checkTextFit (*c, name.fromFirstOccurrenceOf ("-", false, false).upToLastOccurrenceOf (".", false, false));
  10656. juce::Image image (juce::Image::ARGB, frame.getWidth(), frame.getHeight(), true);
  10657. {
  10658. juce::Graphics g (image);
  10659. g.fillAll (lynx::theme::panel);
  10660. frame.paintEntireComponent (g, false);
  10661. }
  10662. const juce::File file (prefix + name);
  10663. file.deleteFile();
  10664. juce::PNGImageFormat png;
  10665. if (auto out = file.createOutputStream())
  10666. png.writeImageToStream (image, *out);
  10667. };
  10668. saveWindow (lynx::makeExportPanel (offline), "-export.png");
  10669. saveWindow (lynx::makeExportPanel (offline, 1), "-export-mp3.png");
  10670. saveWindow (lynx::makeExportPanel (offline, 3), "-export-flac-stems.png");
  10671. {
  10672. // REA round 165f-mixer: the mixer track's Track latency / routing submenus, Disk recording, PDC, and the
  10673. // Export window for "Render selected tracks to wave file(s)"
  10674. const auto before = offline.getSong();
  10675. offline.editSong ([] (lynx::Song& s) {
  10676. if (s.mixer.size() > 3)
  10677. {
  10678. s.mixer[1].latencyMs = 5.0f;
  10679. s.mixer[1].latencyBypass = lynx::LatencyBypass::whenRecordingOrStopped;
  10680. s.mixer[2].latencyMs = -1.5f;
  10681. }
  10682. });
  10683. offline.dispatchPendingMessages();
  10684. auto& strips = ui.getMixerForSnapshot().getStripsForSnapshot();
  10685. strips.setSelection ({ 1, 2, 3 }, 1);
  10686. const auto menu = strips.buildMenu (1);
  10687. juce::StringArray names { "Mixer track" };
  10688. std::vector<juce::PopupMenu> menus { menu };
  10689. const auto latencyPrefix = lynx::tr ("Track latency: {0}", { juce::String() });
  10690. const juce::String wanted[] = { lynx::tr ("Selected tracks ⇄ this track"), lynx::tr ("Disk recording"),
  10691. lynx::tr ("Plugin delay compensation") };
  10692. for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
  10693. {
  10694. const auto& item = it.getItem();
  10695. if (item.subMenu != nullptr && (item.text.startsWith (latencyPrefix) || std::find (std::begin (wanted), std::end (wanted), item.text) != std::end (wanted)))
  10696. {
  10697. names.add (item.text.upToFirstOccurrenceOf (":", false, false));
  10698. menus.push_back (*item.subMenu);
  10699. }
  10700. }
  10701. saveMenus (names, menus, prefix + "-menus165-mixer.png");
  10702. saveWindow (lynx::makeExportPanelForTracks (offline, { 1, 2, 3 }), "-export165-tracks.png");
  10703. offline.setSong (before);
  10704. offline.dispatchPendingMessages();
  10705. }
  10706. saveSplashFrames (prefix);
  10707. saveIconSheet (prefix + "-icons.png", 1.0f);
  10708. saveIconSheet (prefix + "-icons-150.png", 1.5f);
  10709. saveWindow (lynx::MainComponent::makeHelpContent(), "-help.png");
  10710. saveWindow (lynx::ui::makeTrackIconGrid (5, {}), "-trackicons168h.png"); // round 168h: the icon picker
  10711. saveWindow (std::make_unique<lynx::toolbar::CustomizePanel> (lynx::toolbarlayout::Layout::makeDefault()), "-customize-toolbar.png");
  10712. // two moved controls: Tools › Last tweaked and Add › Automation for last tweaked parameter show them (REA round 143)
  10713. offline.noteTweaked ({ lynx::AutomationTargetKind::channelVolume, 0 });
  10714. offline.noteTweaked ({ lynx::AutomationTargetKind::mixerVolume, 0 });
  10715. saveMenus (ui, prefix + "-menus.png");
  10716. {
  10717. // the windows' own menus (title bars) and the toolbar's recording menu
  10718. juce::StringArray names;
  10719. std::vector<juce::PopupMenu> menus;
  10720. for (auto [panel, name] : { std::pair { lynx::workspace::Panel::playlist, "Playlist" }, { lynx::workspace::Panel::channelRack, "Channel Rack" },
  10721. { lynx::workspace::Panel::pianoRoll, "Piano Roll" }, { lynx::workspace::Panel::mixer, "Mixer" },
  10722. { lynx::workspace::Panel::browser, "Browser" } })
  10723. {
  10724. names.add (name);
  10725. menus.push_back (ui.getPanelMenuForSnapshot (panel));
  10726. }
  10727. names.add ("Recording");
  10728. menus.push_back (ui.getRecordMenuForSnapshot());
  10729. names.add ("Toolbar");
  10730. menus.push_back (ui.getToolbarMenuForSnapshot());
  10731. saveMenus (names, menus, prefix + "-panel-menus.png");
  10732. }
  10733. {
  10734. // REA round 143: the piano roll Tools menu, a Playlist track menu and a mixer insert menu (FL's layouts)
  10735. std::vector<juce::PopupMenu> menus { ui.getPianoRollForSnapshot().getToolsMenuForSnapshot(),
  10736. ui.getPlaylistForSnapshot().getTrackMenuForSnapshot (0),
  10737. ui.getMixerForSnapshot().getStripsForSnapshot().buildMenu (1) };
  10738. saveMenus (juce::StringArray { "Piano roll tools", "Playlist track", "Mixer track" }, menus, prefix + "-menus143.png");
  10739. // round 167l: the channel menu ("Lock active/mute state")
  10740. if (! offline.getSong().channels.empty())
  10741. saveMenus (juce::StringArray { "Channel" }, std::vector<juce::PopupMenu> { ui.getRackForSnapshot().getChannelMenuForSnapshot (0) }, prefix + "-channel-menu.png");
  10742. // round 163: menu density, compact (default) and comfortable, on a Browser folder menu
  10743. {
  10744. juce::PopupMenu folder;
  10745. folder.addSectionHeader ("Documents");
  10746. folder.addItem (1, "Expand all");
  10747. folder.addItem (2, "Collapse all");
  10748. folder.addSeparator();
  10749. folder.addItem (3, "Refresh");
  10750. folder.addSectionHeader ("System");
  10751. folder.addItem (4, "Open");
  10752. folder.addItem (5, "Copy the file path");
  10753. folder.addSectionHeader ("Tags");
  10754. folder.addItem (6, "Starred", true, true);
  10755. folder.addSeparator();
  10756. folder.addItem (7, "Add folder...");
  10757. const auto wasCompact = lynx::theme::menus::compact();
  10758. lynx::theme::menus::setCompact (true);
  10759. saveMenus (juce::StringArray { "Compact" }, { folder }, prefix + "-menu163-compact.png");
  10760. lynx::theme::menus::setCompact (false);
  10761. saveMenus (juce::StringArray { "Comfortable" }, { folder }, prefix + "-menu163-comfortable.png");
  10762. lynx::theme::menus::setCompact (wasCompact);
  10763. }
  10764. // and the clip menus of the first pattern, audio and automation clips of the project
  10765. juce::StringArray clipNames;
  10766. std::vector<juce::PopupMenu> clipMenus;
  10767. for (auto [kind, name] : { std::pair { lynx::ClipKind::pattern, "Pattern clip" }, { lynx::ClipKind::audio, "Audio clip" },
  10768. { lynx::ClipKind::automation, "Automation clip" } })
  10769. for (int c = 0; c < (int) offline.getSong().playlist.size(); ++c)
  10770. if (offline.getSong().playlist[(std::size_t) c].kind == kind)
  10771. {
  10772. clipNames.add (name);
  10773. clipMenus.push_back (ui.getPlaylistForSnapshot().getClipMenuForSnapshot (c));
  10774. break;
  10775. }
  10776. if (! clipMenus.empty())
  10777. saveMenus (clipNames, clipMenus, prefix + "-menus143-clips.png");
  10778. }
  10779. auto saveAlert = [&] (std::unique_ptr<juce::AlertWindow> alert, const juce::String& name) {
  10780. alert->setOpaque (true);
  10781. saveWindow (std::move (alert), name);
  10782. };
  10783. saveAlert (ui.makeConfirmDiscardWindow(), "-confirm.png");
  10784. saveAlert (lynx::MainComponent::makeAboutWindow(), "-about.png");
  10785. saveAlert (lynx::makeNameAndColourDialog (lynx::tr ("Rename pattern"), "Pattern 2", lynx::lynxPalette()[6]), "-rename.png");
  10786. saveAlert (lynx::makeRecordChoiceDialog(), "-record-dialog.png");
  10787. saveAlert (lynx::makeSamplePitchDialog (7.25f, true, true), "-sample-pitch.png"); // round 163c
  10788. saveAlert (lynx::makeGradientColourDialog (juce::Colour (0xffe5383b), juce::Colour (0xff3a7bd5), 8), "-gradient.png"); // round 177a
  10789. saveAlert (lynx::makeMidiImportDialog(), "-midi-import-dialog.png"); // File › Import › MIDI file (REA round 143)
  10790. // round 186c: FL's mixer "Delete" questions and its Settings › General › Manage messages menu
  10791. saveAlert (lynx::makeFlMessageDialog ({ lynx::tr ("Delete tracks"), lynx::tr ("This will |delete| {0} selected mixer track(s). Are you sure?", { "1" }),
  10792. { lynx::tr ("Yes"), lynx::tr ("No") }, true }),
  10793. "-delete-tracks.png");
  10794. saveAlert (lynx::makeFlMessageDialog ({ lynx::tr ("Playlist tracks"),
  10795. lynx::tr ("One or more mixer tracks that will be deleted are connected to instrument/audio tracks.") + "\n"
  10796. + lynx::tr ("Do you want to unlink the tracks and channels or delete them?"),
  10797. { lynx::tr ("Delete tracks and channels"), lynx::tr ("Unlink tracks and channels"), lynx::tr ("Cancel") }, false }),
  10798. "-delete-tracks-linked.png");
  10799. saveMenus (juce::StringArray { "Manage messages" }, std::vector<juce::PopupMenu> { lynx::messages::manageMenu() }, prefix + "-manage-messages.png");
  10800. saveWindow (lynx::makeSetupWizardContent (offline, {}, {}), "-setup.png");
  10801. saveWindow (lynx::crashreporter::makeDialogForSnapshot (false), "-crash-report.png"); // round 159
  10802. saveWindow (lynx::crashreporter::makeDialogForSnapshot (true), "-report-problem.png");
  10803. // round 166b: the update bar in its states (available, downloading, failed, ready) and the release notes window
  10804. {
  10805. struct Bars final : juce::Component
  10806. {
  10807. Bars()
  10808. {
  10809. constexpr int h = lynx::updater::UpdateBar::height;
  10810. setSize (1100, 4 * (h + 6));
  10811. for (int state = 0; state < 4; ++state)
  10812. {
  10813. bars[state].setBounds (0, state * (h + 6), getWidth(), h);
  10814. bars[state].showForSnapshot (state);
  10815. addAndMakeVisible (bars[state]);
  10816. }
  10817. }
  10818. lynx::updater::UpdateBar bars[4];
  10819. };
  10820. saveWindow (std::make_unique<Bars>(), "-update-bar.png");
  10821. saveWindow (lynx::updater::makeReleaseNotesForSnapshot(), "-update-notes.png");
  10822. }
  10823. saveWindow (lynx::makeMissingFilesPanel (lynx::missingFilesSnapshotInfo(), 0, 1), "-missing-files.png");
  10824. saveWindow (lynx::makeMissingFilesPanel (lynx::missingFilesSnapshotInfo(), 1), "-missing-plugins.png");
  10825. saveWindow (lynx::makeMissingFilesPanel (lynx::missingFilesSnapshotInfo(), 2), "-missing-found.png");
  10826. {
  10827. // the Settings pages, with credits like a project imported from FL would carry
  10828. offline.editSong ([] (lynx::Song& s) {
  10829. s.info = { "Night Drive", "LYNX SHARE demo", "Synthwave", "https://lynx-share.com",
  10830. "Made with LYNX SHARE.\nDrums and bass from the Channel Rack, pads from the Browser.", false };
  10831. }, false);
  10832. saveWindow (lynx::makeSettingsPanel (offline, lynx::SettingsPage::project), "-settings-project.png");
  10833. saveWindow (lynx::makeSettingsPanel (offline, lynx::SettingsPage::info), "-settings-info.png");
  10834. saveWindow (lynx::makeSettingsPanel (offline, lynx::SettingsPage::files), "-settings-files.png");
  10835. saveWindow (lynx::makeSettingsPanel (offline, lynx::SettingsPage::general), "-settings-general.png");
  10836. {
  10837. // the whole General page (round 186a: the Startup section is below the first screen)
  10838. auto tall = lynx::makeSettingsPanel (offline, lynx::SettingsPage::general);
  10839. tall->setSize (tall->getWidth(), 1500);
  10840. saveWindow (std::move (tall), "-settings-general-tall.png");
  10841. }
  10842. saveWindow (lynx::makeSettingsPanel (offline, lynx::SettingsPage::theme), "-settings-theme.png");
  10843. saveWindow (lynx::makeSettingsPanel (offline, lynx::SettingsPage::audio), "-settings-audio.png");
  10844. saveWindow (lynx::makeSettingsPanel (offline, lynx::SettingsPage::midi), "-settings-midi.png");
  10845. saveWindow (lynx::makePluginManagerPanel (offline, false), "-plugin-manager.png");
  10846. saveWindow (lynx::makeShortcutManagerPanel (false), "-shortcuts.png");
  10847. }
  10848. {
  10849. // round 84: New project, Clip properties, Arrangements, Plugin performance monitor, Touch keyboard
  10850. saveWindow (lynx::makeNewProjectPanel(), "-new-project.png");
  10851. const auto& clips = offline.getSong().playlist;
  10852. for (int i = 0; i < (int) clips.size(); ++i)
  10853. if (clips[(std::size_t) i].kind == lynx::ClipKind::pattern)
  10854. {
  10855. saveWindow (lynx::makeClipPropertiesPanel (offline, i, { i, (i + 1) % (int) clips.size() }), "-clip-properties.png");
  10856. break;
  10857. }
  10858. for (int i = 0; i < (int) clips.size(); ++i)
  10859. if (clips[(std::size_t) i].kind == lynx::ClipKind::audio)
  10860. {
  10861. saveWindow (lynx::makeClipPropertiesPanel (offline, i, { i }), "-clip-properties-audio.png");
  10862. break;
  10863. }
  10864. if (offline.getSong().arrangements.size() < 2)
  10865. offline.editSong ([] (lynx::Song& s) {
  10866. const auto current = s.currentArrangement;
  10867. s.addArrangement ("Radio edit", true);
  10868. s.addArrangement ("Intro loop");
  10869. s.selectArrangement (current);
  10870. }, false);
  10871. saveWindow (lynx::makeArrangementsPanel (offline), "-arrangements.png");
  10872. saveWindow (lynx::makePluginMonitorPanel (offline), "-plugin-monitor.png");
  10873. saveWindow (lynx::makeTouchKeyboardPanel (offline), "-touch-keyboard.png");
  10874. }
  10875. {
  10876. // round 142: the Newtone / Newtime editors on a synthetic sung line (A3 B3 C4 · E4), one note moved
  10877. const auto wav = juce::File::getSpecialLocation (juce::File::tempDirectory).getChildFile ("lynx-snapshot-newtone.wav");
  10878. {
  10879. juce::AudioBuffer<float> line (1, 44100 * 2);
  10880. const double hz[] = { 220.0, 246.94, 261.63, 0.0, 329.63 };
  10881. double ph = 0.0;
  10882. for (int i = 0; i < line.getNumSamples(); ++i)
  10883. {
  10884. const auto f0 = hz[std::min (4, i / 17640)];
  10885. 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;
  10886. float v = 0.0f;
  10887. for (int h = 1; f0 > 0.0 && h < 8; ++h)
  10888. v += (float) (0.3 / h * std::sin (h * ph));
  10889. line.setSample (0, i, v);
  10890. }
  10891. wav.deleteFile();
  10892. juce::WavAudioFormat format;
  10893. std::unique_ptr<juce::OutputStream> out (wav.createOutputStream().release());
  10894. if (auto* w = out != nullptr ? format.createWriterFor (out.get(), 44100.0, 1, 16, {}, 0) : nullptr)
  10895. {
  10896. out.release();
  10897. std::unique_ptr<juce::AudioFormatWriter> writer (w);
  10898. writer->writeFromAudioSampleBuffer (line, 0, line.getNumSamples());
  10899. }
  10900. }
  10901. if (const auto sample = offline.getSampleLibrary().load (wav.getFullPathName()))
  10902. {
  10903. auto notes = lynx::newtonefx::analyseNotes (*sample);
  10904. if (notes.pitches.size() > 1)
  10905. notes.pitches[1].shift = 2.0;
  10906. lynx::newtonefx::WarpMap warp;
  10907. warp.frames = (std::int64_t) sample->frames();
  10908. warp.markers = { { 22050, 33075 } };
  10909. int at = 0;
  10910. offline.editSong ([&] (lynx::Song& song) {
  10911. if (song.mixer.size() < 2)
  10912. song.mixer.resize (2);
  10913. auto& fx = song.mixer[1].effects;
  10914. auto tone = lynx::makeEffectSlot (lynx::EffectKind::newtone);
  10915. tone.samplePath = wav.getFullPathName().toStdString();
  10916. tone.state = lynx::newtonefx::writeNative (notes);
  10917. auto time = lynx::makeEffectSlot (lynx::EffectKind::newtime);
  10918. time.samplePath = tone.samplePath;
  10919. time.state = lynx::newtonefx::writeWarp (warp);
  10920. at = (int) fx.size();
  10921. fx.push_back (tone);
  10922. fx.push_back (time);
  10923. }, false);
  10924. saveWindow (lynx::makeNewtoneEditor (offline, 1, at), "-newtone.png");
  10925. saveWindow (lynx::makeNewtoneEditor (offline, 1, at + 1), "-newtime.png");
  10926. offline.editSong ([at] (lynx::Song& song) {
  10927. auto& fx = song.mixer[1].effects;
  10928. fx.erase (fx.begin() + at, fx.begin() + at + 2);
  10929. }, false);
  10930. }
  10931. }
  10932. if (! offline.getSong().automations.empty())
  10933. {
  10934. auto editor = lynx::makeAutomationEditor (offline, 0);
  10935. editor->setSize (760, 300);
  10936. saveWindow (std::move (editor), "-automation.png");
  10937. // round 177b: the same clip in FL's LFO mode: FL's defaults, then one shaped state (the UI gate pairs)
  10938. const auto before = offline.getSong().automations[0].lfo;
  10939. const auto lfoShot = [&offline, &saveWindow] (std::function<void (lynx::AutomationLfo&)> set, const char* suffix) {
  10940. offline.editSong ([&set] (lynx::Song& song) {
  10941. auto& lfo = song.automations[0].lfo;
  10942. lfo = lynx::AutomationLfo {};
  10943. lfo.on = true;
  10944. set (lfo);
  10945. }, false);
  10946. auto lfoEditor = lynx::makeAutomationEditor (offline, 0);
  10947. lfoEditor->setSize (760, 346);
  10948. saveWindow (std::move (lfoEditor), suffix);
  10949. };
  10950. lfoShot ([] (lynx::AutomationLfo&) {}, "-automation-lfo.png");
  10951. lfoShot ([] (lynx::AutomationLfo& lfo) {
  10952. // the state set through FL's own UI for the UI gate (TNS 50 %, SKEW 25 %, PW 25 %, two points), as FL saved it
  10953. lfo.tension = 64;
  10954. lfo.skew = 32;
  10955. lfo.pulseWidth = 28;
  10956. lfo.amp = { { 0, 0.6716f, 0.0f }, { (std::int64_t) (lynx::ppq * 1.4128), 0.9204f, 0.0f } };
  10957. }, "-automation-lfo-shape.png");
  10958. offline.editSong ([before] (lynx::Song& song) { song.automations[0].lfo = before; }, false);
  10959. }
  10960. // round 177b: LYNX's modulators window, with one routed modulator
  10961. {
  10962. offline.editSong ([] (lynx::Song& song) {
  10963. lynx::Modulator m;
  10964. m.name = "LFO 1";
  10965. m.shape = lynx::ModShape::triangle;
  10966. m.routes = { { { lynx::AutomationTargetKind::mixerVolume, 1, 0, 0 }, 0.25f }, { { lynx::AutomationTargetKind::mixerPan, 1, 0, 0 }, -0.5f } };
  10967. song.modulators.push_back (m);
  10968. lynx::Modulator r;
  10969. r.name = "LFO 2";
  10970. r.shape = lynx::ModShape::smoothRandom;
  10971. r.sync = false;
  10972. r.hz = 0.5;
  10973. song.modulators.push_back (r);
  10974. }, false);
  10975. auto mods = lynx::makeModulatorsPanel (offline);
  10976. mods->setSize (720, 360);
  10977. saveWindow (std::move (mods), "-modulators.png");
  10978. offline.editSong ([] (lynx::Song& song) { song.modulators.clear(); }, false);
  10979. }
  10980. saveWindow (lynx::makeChannelSettingsPanel (offline, 0), "-sampler.png");
  10981. // the channel window frame (REA round 143b): header strip + tabs; the Misc tab of the first channel and of a synth
  10982. saveWindow (lynx::makeChannelFrame (offline, 0), "-channel-frame.png");
  10983. saveWindow (lynx::makeChannelFrame (offline, 0, -1), "-channel-misc.png");
  10984. for (int c = 0; c < (int) offline.getSong().channels.size(); ++c)
  10985. if (offline.getSong().channels[(std::size_t) c].instrument == lynx::InstrumentKind::synth)
  10986. {
  10987. saveWindow (lynx::makeChannelSettingsPanel (offline, c), "-synth.png");
  10988. saveWindow (lynx::makeChannelModulationPanel (offline, c), "-modulation.png");
  10989. break;
  10990. }
  10991. for (int c = 0; c < (int) offline.getSong().channels.size(); ++c)
  10992. if (offline.getSong().channels[(std::size_t) c].instrument == lynx::InstrumentKind::controller)
  10993. {
  10994. saveWindow (lynx::makeChannelSettingsPanel (offline, c), "-controller.png");
  10995. break;
  10996. }
  10997. for (const auto kind : { lynx::InstrumentKind::sakura, lynx::InstrumentKind::drumpad })
  10998. for (int c = 0; c < (int) offline.getSong().channels.size(); ++c)
  10999. if (offline.getSong().channels[(std::size_t) c].instrument == kind)
  11000. {
  11001. saveWindow (lynx::makeChannelSettingsPanel (offline, c), kind == lynx::InstrumentKind::sakura ? "-sakura.png" : "-drumpad.png");
  11002. break;
  11003. }
  11004. // round 180c: Fruity Slicer's editor
  11005. for (int c = 0; c < (int) offline.getSong().channels.size(); ++c)
  11006. if (offline.getSong().channels[(std::size_t) c].instrument == lynx::InstrumentKind::fruityslicer)
  11007. {
  11008. saveWindow (lynx::makeChannelSettingsPanel (offline, c), "-fruityslicer.png");
  11009. break;
  11010. }
  11011. // parametric EQ: the one with the most pronounced curve (in an imported .flp, with FL's settings)
  11012. {
  11013. int bestTrack = -1, bestSlot = -1;
  11014. double bestShape = -1.0;
  11015. const auto& mixer = offline.getSong().mixer;
  11016. for (int t = 0; t < (int) mixer.size(); ++t)
  11017. for (int s = 0; s < (int) mixer[(std::size_t) t].effects.size(); ++s)
  11018. if (const auto& fx = mixer[(std::size_t) t].effects[(std::size_t) s]; fx.kind == lynx::EffectKind::parametricEq)
  11019. {
  11020. double shape = 0.0;
  11021. for (double hz = 30.0; hz < 18000.0; hz *= 1.5)
  11022. shape += std::abs (lynx::peq::responseDb (fx.params, 48000.0, hz));
  11023. if (shape > bestShape)
  11024. {
  11025. bestShape = shape;
  11026. bestTrack = t;
  11027. bestSlot = s;
  11028. }
  11029. }
  11030. if (bestTrack >= 0)
  11031. saveWindow (lynx::makeParametricEqEditor (offline, bestTrack, bestSlot), "-peq.png");
  11032. }
  11033. // Note inspector for the Piano Roll's notes (its selection, or all of the channel's notes)
  11034. if (auto inspector = ui.getPianoRollForSnapshot().makeNoteInspectorForSnapshot())
  11035. saveWindow (std::move (inspector), "-noteinspector.png");
  11036. if (auto inspector = ui.getPianoRollForSnapshot().makeNoteInspectorForSnapshot (true))
  11037. saveWindow (std::move (inspector), "-noteinspector-one.png");
  11038. // workflow P2: note tool dialogs (they preview on the pattern; each one puts the notes back when destroyed)
  11039. {
  11040. auto& roll = ui.getPianoRollForSnapshot();
  11041. const std::pair<lynx::NoteTool, const char*> tools[] = { { lynx::NoteTool::strum, "-tool-strum.png" },
  11042. { lynx::NoteTool::arpeggiate, "-tool-arpeggiate.png" },
  11043. { lynx::NoteTool::flip, "-tool-flip.png" },
  11044. { lynx::NoteTool::randomise, "-tool-randomise.png" },
  11045. { lynx::NoteTool::scaleLevels, "-tool-scalelevels.png" },
  11046. { lynx::NoteTool::limit, "-tool-limit.png" },
  11047. { lynx::NoteTool::quantize, "-tool-quantize.png" },
  11048. { lynx::NoteTool::chop, "-tool-chop.png" },
  11049. { lynx::NoteTool::flam, "-tool-flam.png" },
  11050. { lynx::NoteTool::lfo, "-tool-lfo.png" },
  11051. { lynx::NoteTool::claw, "-tool-claw.png" },
  11052. { lynx::NoteTool::articulate, "-tool-articulate.png" },
  11053. { lynx::NoteTool::riffMachine, "-tool-riff.png" },
  11054. { lynx::NoteTool::chordProgression, "-tool-chords.png" } };
  11055. for (const auto& [tool, name] : tools)
  11056. saveWindow (lynx::makeNoteToolPanel (offline, tool, roll.noteIndicesForSnapshot(), roll.gridForSnapshot()), name);
  11057. }
  11058. // round 83: the event editor, with sample events on the selected channel's volume (removed afterwards)
  11059. {
  11060. const lynx::AutomationTarget volume { lynx::AutomationTargetKind::channelVolume, offline.getSelectedChannel() };
  11061. const auto before = offline.getSong().patterns[(std::size_t) offline.getSong().currentPattern].events;
  11062. offline.editSong ([&] (lynx::Song& s) {
  11063. auto& lane = lynx::eventedit::laneFor (s.patterns[(std::size_t) s.currentPattern], volume);
  11064. lynx::eventedit::line (lane, 0, lynx::ppq * 2, 0.2f, 0.9f, lynx::ticksPerStep);
  11065. lynx::prtools::LfoOptions lfo;
  11066. lfo.startSpeed = 7 * 4096; // one beat
  11067. lynx::eventedit::applyLfo (lane, lynx::ppq * 2, lynx::ppq * 4, lfo, lynx::ticksPerStep);
  11068. }, false);
  11069. saveWindow (lynx::makeEventEditor (offline, volume), "-eventeditor.png");
  11070. offline.editSong ([&] (lynx::Song& s) { s.patterns[(std::size_t) s.currentPattern].events = before; }, false);
  11071. // issue #86: the same editor on the Tempo target, with the project's own Tempo events (a sample ramp if none)
  11072. const lynx::AutomationTarget tempo { lynx::AutomationTargetKind::tempo, 0 };
  11073. offline.editSong ([&] (lynx::Song& s) {
  11074. auto& lane = lynx::eventedit::laneFor (s.patterns[(std::size_t) s.currentPattern], tempo);
  11075. if (lane.events.empty())
  11076. lynx::eventedit::line (lane, 0, lynx::ppq * 2, 0.05f, 0.11f, lynx::ticksPerStep);
  11077. }, false);
  11078. saveWindow (lynx::makeEventEditor (offline, tempo), "-eventeditor-tempo.png");
  11079. {
  11080. auto compact = lynx::makeEventEditor (offline, tempo); // the toolbar in a small window
  11081. compact->setSize (640, 300);
  11082. saveWindow (std::move (compact), "-eventeditor-tempo-small.png");
  11083. auto narrowest = lynx::makeEventEditor (offline, tempo); // the tool window's lower limit
  11084. narrowest->setSize (400, 300);
  11085. saveWindow (std::move (narrowest), "-eventeditor-tempo-narrowest.png");
  11086. }
  11087. offline.editSong ([&] (lynx::Song& s) { s.patterns[(std::size_t) s.currentPattern].events = before; }, false);
  11088. }
  11089. // round 86: the audio editor with a synthetic drum loop (markers, a region, a loop), waveform and spectrogram,
  11090. // and its menu items (-audioeditor-menu.txt)
  11091. {
  11092. namespace ae = lynx::audioedit;
  11093. ae::Document d;
  11094. d.title = "Drum loop";
  11095. d.audio.sampleRate = 44100.0;
  11096. const auto frames = (std::size_t) (44100 * 2);
  11097. d.audio.channels.assign (2, std::vector<float> (frames, 0.0f));
  11098. std::uint32_t seed = 7;
  11099. for (int hit = 0; hit < 8; ++hit)
  11100. {
  11101. const auto at = (std::size_t) hit * frames / 8;
  11102. const auto kick = hit % 2 == 0;
  11103. double phase = 0.0;
  11104. for (std::size_t i = 0; i < 12000 && at + i < frames; ++i)
  11105. {
  11106. seed = seed * 1664525u + 1013904223u;
  11107. const auto noise = (float) (seed >> 8) / 16777216.0f - 0.5f;
  11108. const auto t = (double) i / 44100.0;
  11109. phase += 2.0 * 3.141592653589793 * (kick ? 45.0 + 160.0 * std::exp (-t * 30.0) : 190.0) / 44100.0;
  11110. const auto body = (float) std::sin (phase) * (float) std::exp (-t * (kick ? 9.0 : 22.0));
  11111. const auto v = kick ? 0.85f * body : 0.35f * body + 0.6f * noise * (float) std::exp (-t * 18.0);
  11112. d.audio.channels[0][at + i] += v;
  11113. d.audio.channels[1][at + i] += kick ? v : v * 0.8f + 0.1f * noise * (float) std::exp (-t * 30.0);
  11114. }
  11115. }
  11116. ae::addMarker (d, (std::int64_t) frames / 8, "Snare");
  11117. ae::addRegion (d, { (std::int64_t) frames / 2, (std::int64_t) frames * 3 / 4 }, "Fill");
  11118. ae::setLoop (d, { 0, (std::int64_t) frames });
  11119. auto wave = lynx::makeAudioEditorForSnapshot (offline, d, false);
  11120. juce::File (prefix + "-audioeditor-menu.txt").replaceWithText (lynx::audioEditorMenuForSnapshot (*wave).joinIntoString ("\n") + "\n");
  11121. saveWindow (std::move (wave), "-audioeditor.png");
  11122. saveWindow (lynx::makeAudioEditorForSnapshot (offline, d, true), "-audioeditor-spectrum.png");
  11123. }
  11124. // warp markers (round 175a, M3): the audio editor of the first audio clip whose channel has warp markers,
  11125. // opened as the Playlist opens it, with its warp lane
  11126. {
  11127. const auto& song = offline.getSong();
  11128. for (int i = 0; i < (int) song.playlist.size(); ++i)
  11129. {
  11130. const auto& c = song.playlist[(std::size_t) i];
  11131. if (c.kind == lynx::ClipKind::audio && juce::isPositiveAndBelow (c.channel, (int) song.channels.size())
  11132. && song.channels[(std::size_t) c.channel].sampler.warp.size() >= 3)
  11133. {
  11134. if (auto panel = lynx::makeAudioEditorPanel (offline, c.channel, i, true))
  11135. saveWindow (std::move (panel), "-audioeditor-warp.png");
  11136. break;
  11137. }
  11138. }
  11139. }
  11140. // the tempo tapper after five steady taps (round 132)
  11141. saveWindow (lynx::makeTempoTapperForSnapshot (offline, 5, 128.0), "-tempotapper.png");
  11142. // the Channel Rack's piano-roll view (round 132)
  11143. ui.selectTabForSnapshot (0);
  11144. ui.getRackForSnapshot().setPianoRollView (true);
  11145. offline.dispatchPendingMessages();
  11146. saveSnapshot (ui, prefix + "-rack-pianoroll-view.png");
  11147. ui.getRackForSnapshot().setPianoRollView (false);
  11148. // the Channel Rack with the step graph lane (velocity), and the Euclidean fill window
  11149. ui.selectTabForSnapshot (0);
  11150. ui.getRackForSnapshot().setGraphLevelForSnapshot (0);
  11151. offline.dispatchPendingMessages();
  11152. saveSnapshot (ui, prefix + "-rack-graph.png");
  11153. ui.getRackForSnapshot().setGraphLevelForSnapshot (1);
  11154. saveSnapshot (ui, prefix + "-rack-graph-pan.png");
  11155. ui.getRackForSnapshot().toggleGraphLanes();
  11156. saveWindow (ui.getRackForSnapshot().makeEuclideanPanel (0), "-euclidean.png");
  11157. // the Mixer with three inserts selected and one armed for recording
  11158. ui.selectTabForSnapshot (3);
  11159. if (offline.getSong().mixer.size() > 4)
  11160. {
  11161. ui.getMixerForSnapshot().getStripsForSnapshot().setSelection ({ 1, 2, 3 }, 2);
  11162. offline.setInsertArmed (3, true);
  11163. offline.dispatchPendingMessages();
  11164. saveSnapshot (ui, prefix + "-mixer-multi.png");
  11165. // the armed insert with an audio input (its input row in the side panel, the level bar on the strip)
  11166. offline.editSong ([] (lynx::Song& s) { s.mixer[3].inputChannel = 0; });
  11167. ui.getMixerForSnapshot().selectTrack (3);
  11168. offline.dispatchPendingMessages();
  11169. saveSnapshot (ui, prefix + "-mixer-input.png");
  11170. offline.undo();
  11171. offline.setInsertArmed (3, false);
  11172. ui.getMixerForSnapshot().getStripsForSnapshot().setSelection ({}, 0);
  11173. }
  11174. // the Mixer's routing lane: an insert with sends selected (send knobs and wires)
  11175. if (offline.getSong().mixer.size() > 6)
  11176. {
  11177. int source = -1;
  11178. for (int t = 1; t < (int) offline.getSong().mixer.size() && source < 0; ++t)
  11179. if (! offline.getSong().mixer[(std::size_t) t].sends.empty())
  11180. source = t;
  11181. const auto temporary = source < 0;
  11182. if (temporary) // the demo has no sends: add two for the picture
  11183. {
  11184. source = 1;
  11185. 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); });
  11186. }
  11187. ui.getMixerForSnapshot().selectTrack (source);
  11188. offline.dispatchPendingMessages();
  11189. saveSnapshot (ui, prefix + "-mixer-sends.png");
  11190. if (temporary)
  11191. offline.editSong ([] (lynx::Song& s) { s.setRoute (1, 5, false); s.setRoute (1, 6, false); s.setRoute (4, 1, false); });
  11192. ui.getMixerForSnapshot().selectTrack (0);
  11193. }
  11194. // the Playlist with ripple editing on
  11195. ui.selectTabForSnapshot (2);
  11196. ui.getPlaylistForSnapshot().setRipple (true);
  11197. saveSnapshot (ui, prefix + "-playlist-ripple.png");
  11198. ui.getPlaylistForSnapshot().setRipple (false);
  11199. // FL's legacy Pattern Blocks (round 170f, issue #60): the section under the clip tracks, a row per pattern
  11200. {
  11201. const auto saved = offline.getSong();
  11202. offline.editSong ([] (lynx::Song& s) {
  11203. s.patternBlocksOn = true;
  11204. while (s.patterns.size() < 5) // a few rows to show (Drums, Bass...: copies of the demo's pattern)
  11205. lynx::clonePattern (s, (int) s.patterns.size() - 1);
  11206. const auto rows = juce::jmin (6, (int) s.patterns.size());
  11207. for (int r = 0; r < rows; ++r)
  11208. lynx::patternblocks::paintRange (s, r, (std::int64_t) (r % 3) * 4 * lynx::ppq * 2,
  11209. (std::int64_t) (8 + r * 2) * 4 * lynx::ppq);
  11210. }, false);
  11211. offline.dispatchPendingMessages();
  11212. saveSnapshot (ui, prefix + "-playlist-blocks.png");
  11213. offline.editSong ([saved] (lynx::Song& s) { s = saved; }, false);
  11214. offline.dispatchPendingMessages();
  11215. }
  11216. // quick-add palette, and the Browser searching
  11217. saveWindow (ui.makeQuickAddForSnapshot(), "-quickadd.png");
  11218. ui.showDesktopForSnapshot (false);
  11219. ui.getBrowserForSnapshot().setSearchForSnapshot ("kick");
  11220. offline.dispatchPendingMessages();
  11221. saveSnapshot (ui, prefix + "-browser-search.png");
  11222. ui.getBrowserForSnapshot().setSearchForSnapshot ({});
  11223. ui.getBrowserForSnapshot().selectFirstSampleForSnapshot(); // the tree with a sample selected and its waveform
  11224. offline.dispatchPendingMessages();
  11225. saveSnapshot (ui, prefix + "-browser-tree.png");
  11226. // the Browser's PROJECT tab: the patterns, generators and audio files of the project in their colours
  11227. ui.getBrowserForSnapshot().showProjectForSnapshot();
  11228. offline.dispatchPendingMessages();
  11229. saveSnapshot (ui, prefix + "-browser-project.png");
  11230. ui.getBrowserForSnapshot().showPluginDatabaseForSnapshot(); // round 142: the Plugin database's FL engines
  11231. offline.dispatchPendingMessages();
  11232. saveSnapshot (ui, prefix + "-browser-plugins.png");
  11233. ui.getBrowserForSnapshot().setTab (lynx::BrowserComponent::allTab);
  11234. saveWindow (ui.getBrowserForSnapshot().makeFoldersPanelForSnapshot(), "-browser-folders.png"); // round 164
  11235. {
  11236. // round 164: the content filter leaves out the folders with nothing to list (a small library)
  11237. const auto lib = juce::File::getSpecialLocation (juce::File::tempDirectory).getChildFile ("lynx-snapshot-library");
  11238. lib.deleteRecursively();
  11239. for (const auto* path : { "Drums/Kicks/kick 1.wav", "Drums/Kicks/kick 2.wav", "Drums/snare.wav", "Keys/pad.sf2", "Presets/Synth/lead.fst",
  11240. "Projects/beat.flp", "Projects/MIDI/chords.mid", "Notes/readme.txt", "Empty/Nothing/.keep" })
  11241. lib.getChildFile (path).create();
  11242. ui.showDesktopForSnapshot (false);
  11243. ui.getBrowserForSnapshot().showFilterForSnapshot (lib, lynx::browserview::ContentFilter::all);
  11244. offline.dispatchPendingMessages();
  11245. saveSnapshot (ui, prefix + "-browser164-all.png");
  11246. ui.getBrowserForSnapshot().showFilterForSnapshot (lib, lynx::browserview::ContentFilter::samples);
  11247. offline.dispatchPendingMessages();
  11248. saveSnapshot (ui, prefix + "-browser164-samples.png");
  11249. ui.getBrowserForSnapshot().showFilterForSnapshot (lib, lynx::browserview::ContentFilter::projects);
  11250. offline.dispatchPendingMessages();
  11251. saveSnapshot (ui, prefix + "-browser164-projects.png");
  11252. lib.deleteRecursively();
  11253. ui.getBrowserForSnapshot().resetViewForSnapshot();
  11254. }
  11255. // the undo history after a few edits
  11256. offline.editSong ([] (lynx::Song& s) { s.bpm += 1.0; });
  11257. offline.editSong ([] (lynx::Song& s) { if (! s.channels.empty()) s.channels[0].muted = ! s.channels[0].muted; });
  11258. offline.editSong ([] (lynx::Song& s) { if (! s.patterns.empty()) s.patterns[(std::size_t) s.currentPattern].notes.push_back ({}); });
  11259. offline.undo();
  11260. saveWindow (lynx::makeHistoryPanel (offline), "-history.png");
  11261. // spectral waveforms: a synthetic beat (kick, hats, a chord, a noise riser) as audio clips in spectral
  11262. // colours, zoomed in, classic and stereo; the same file in the Sampler editor and the Browser preview
  11263. {
  11264. const juce::File wav (prefix + "-wavedemo.wav");
  11265. writeWaveDemo (wav, offline.getSong().bpm);
  11266. const auto path = wav.getFullPathName();
  11267. const auto pathUtf8 = path.toStdString();
  11268. int samplerChannel = -1, firstTrack = 0;
  11269. offline.editSong ([&] (lynx::Song& s) {
  11270. for (const auto& clip : s.playlist)
  11271. firstTrack = std::max (firstTrack, clip.track + 1);
  11272. lynx::ChannelDef audio;
  11273. audio.name = "Beat (audio)";
  11274. audio.instrument = lynx::InstrumentKind::audioClip;
  11275. audio.samplePath = pathUtf8;
  11276. s.channels.push_back (audio);
  11277. const auto audioChannel = (int) s.channels.size() - 1;
  11278. lynx::ChannelDef sampler = audio;
  11279. sampler.name = "Beat (sampler)";
  11280. sampler.instrument = lynx::InstrumentKind::sampler;
  11281. sampler.sampler.regionStart = 0.06f;
  11282. sampler.sampler.regionEnd = 0.94f;
  11283. s.channels.push_back (sampler);
  11284. samplerChannel = (int) s.channels.size() - 1;
  11285. const auto bar = (std::int64_t) lynx::ppq * std::max (1, s.beatsPerBar);
  11286. const auto whole = (std::int64_t) std::llround (8.0 * s.bpm / 60.0 * lynx::ppq);
  11287. lynx::Clip clip;
  11288. clip.kind = lynx::ClipKind::audio;
  11289. clip.channel = audioChannel;
  11290. clip.track = firstTrack;
  11291. clip.length = whole;
  11292. s.playlist.push_back (clip);
  11293. clip.track = firstTrack + 1; // a slice of it, later in the song
  11294. clip.start = bar;
  11295. clip.offset = bar;
  11296. clip.length = 2 * bar;
  11297. s.playlist.push_back (clip);
  11298. // taller rows for the audio (tracks can be resized: P18)
  11299. if ((int) s.playlistTracks.size() < firstTrack + 2)
  11300. s.playlistTracks.resize ((std::size_t) firstTrack + 2);
  11301. s.playlistTracks[(std::size_t) firstTrack].height = 80;
  11302. s.playlistTracks[(std::size_t) firstTrack + 1].height = 60;
  11303. });
  11304. offline.dispatchPendingMessages();
  11305. auto& cache = *lynx::ui::WaveformCache::getInstance();
  11306. cache.find (path, [&offline, path] { return offline.getSampleLibrary().load (path); });
  11307. cache.waitUntilIdle (30000);
  11308. ui.selectTabForSnapshot (2);
  11309. auto& playlist = ui.getPlaylistForSnapshot();
  11310. playlist.setTimeSelectionForSnapshot (0, 0);
  11311. {
  11312. // the Playlist alone (the floating Channel Rack would cover the clips)
  11313. auto saveSnapshot = [&playlist] (juce::Component&, const juce::String& file) { saveArea (playlist, playlist.getLocalBounds(), file); };
  11314. playlist.setViewForSnapshot (180.0, 0, std::max (0, firstTrack - 3));
  11315. saveSnapshot (ui, prefix + "-playlist-audio.png");
  11316. playlist.setViewForSnapshot (1400.0, 0, std::max (0, firstTrack - 3));
  11317. saveSnapshot (ui, prefix + "-playlist-audio-zoom.png");
  11318. lynx::ui::WaveformCache::stereo = true;
  11319. saveSnapshot (ui, prefix + "-playlist-audio-stereo.png");
  11320. lynx::ui::WaveformCache::stereo = false;
  11321. lynx::ui::WaveformCache::spectral = true;
  11322. playlist.setViewForSnapshot (180.0, 0, std::max (0, firstTrack - 3));
  11323. saveSnapshot (ui, prefix + "-playlist-audio-spectral.png");
  11324. lynx::ui::WaveformCache::spectral = false;
  11325. playlist.setViewForSnapshot (40.0, 0, 0);
  11326. saveSnapshot (ui, prefix + "-playlist-audio-far.png");
  11327. // LYNX_SNAPSHOT_AUDIO=a.wav;b.wav...: real audio as clips (default-height tracks, one tall,
  11328. // a fade, a reversed copy), at three zoom levels
  11329. if (const auto files = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_AUDIO", {}), ";", "");
  11330. ! files.isEmpty())
  11331. {
  11332. const auto realTrack = firstTrack + 2;
  11333. std::vector<juce::String> paths;
  11334. for (const auto& f : files)
  11335. if (juce::File (f.trim()).existsAsFile())
  11336. paths.push_back (f.trim());
  11337. offline.editSong ([&] (lynx::Song& s) {
  11338. const auto bar = (std::int64_t) lynx::ppq * std::max (1, s.beatsPerBar);
  11339. const std::uint32_t colours[] = { 0, 0xffd9a441, 0xff6fb36a, 0xffb06fd0, 0xff5fb7c9, 0xffd06f6f };
  11340. for (std::size_t i = 0; i < paths.size(); ++i)
  11341. {
  11342. lynx::ChannelDef audio;
  11343. audio.name = juce::File (paths[i]).getFileNameWithoutExtension().toStdString();
  11344. audio.instrument = lynx::InstrumentKind::audioClip;
  11345. audio.samplePath = paths[i].toStdString();
  11346. audio.colour = colours[i % 6];
  11347. audio.sampler.stretchBeats = i % 2 == 0 ? 16.0f : 0.0f; // fitted to 4 bars, or as recorded
  11348. audio.sampler.keepPitch = true;
  11349. s.channels.push_back (audio);
  11350. lynx::Clip clip;
  11351. clip.kind = lynx::ClipKind::audio;
  11352. clip.channel = (int) s.channels.size() - 1;
  11353. clip.track = realTrack + (int) i;
  11354. clip.length = 4 * bar;
  11355. clip.fadeIn = i == 1 ? bar / 2 : 0;
  11356. s.playlist.push_back (clip);
  11357. clip.start = 4 * bar;
  11358. clip.fadeIn = 0;
  11359. clip.fadeOut = i == 0 ? bar : 0;
  11360. s.playlist.push_back (clip);
  11361. }
  11362. if ((int) s.playlistTracks.size() < realTrack + (int) paths.size())
  11363. s.playlistTracks.resize ((std::size_t) realTrack + paths.size());
  11364. if (! paths.empty())
  11365. s.playlistTracks[(std::size_t) realTrack].height = 90;
  11366. });
  11367. offline.dispatchPendingMessages();
  11368. for (const auto& path2 : paths)
  11369. cache.find (path2, [&offline, path2] { return offline.getSampleLibrary().load (path2); });
  11370. cache.waitUntilIdle (60000);
  11371. playlist.setViewForSnapshot (160.0, 0, std::max (0, realTrack - 4));
  11372. saveSnapshot (ui, prefix + "-playlist-real.png");
  11373. playlist.setViewForSnapshot (700.0, 0, std::max (0, realTrack - 1));
  11374. saveSnapshot (ui, prefix + "-playlist-real-zoom.png");
  11375. playlist.setViewForSnapshot (2400.0, 0, std::max (0, realTrack - 1));
  11376. saveSnapshot (ui, prefix + "-playlist-real-close.png");
  11377. playlist.setViewForSnapshot (50.0, 0, std::max (0, realTrack - 4));
  11378. saveSnapshot (ui, prefix + "-playlist-real-far.png");
  11379. // the clip menu of the first real clip
  11380. if (const auto menu = playlist.getClipMenuForSnapshot ((int) offline.getSong().playlist.size() - (int) paths.size() * 2); menu.getNumItems() > 0)
  11381. saveMenus (juce::StringArray { "Audio clip" }, std::vector<juce::PopupMenu> { menu }, prefix + "-clip-menu-audio.png");
  11382. if (const auto menu = playlist.getClipMenuForSnapshot (0); menu.getNumItems() > 0)
  11383. saveMenus (juce::StringArray { "Pattern clip" }, std::vector<juce::PopupMenu> { menu }, prefix + "-clip-menu-pattern.png");
  11384. // the clip menu's actions, run through the menu itself; results in -clip-actions.txt
  11385. {
  11386. juce::StringArray log;
  11387. auto clipOf = [&offline] (const std::string& channelName, int nth) {
  11388. const auto& sg = offline.getSong();
  11389. for (int i = 0; i < (int) sg.playlist.size(); ++i)
  11390. {
  11391. const auto& c = sg.playlist[(std::size_t) i];
  11392. if (c.kind == lynx::ClipKind::audio && c.channel >= 0 && sg.channels[(std::size_t) c.channel].name == channelName && nth-- == 0)
  11393. return i;
  11394. }
  11395. return -1;
  11396. };
  11397. std::function<bool (const juce::PopupMenu&, const juce::String&)> run = [&run] (const juce::PopupMenu& m, const juce::String& text) {
  11398. for (juce::PopupMenu::MenuItemIterator it (m); it.next();)
  11399. {
  11400. auto& item = it.getItem();
  11401. if (item.subMenu != nullptr && run (*item.subMenu, text))
  11402. return true;
  11403. if (item.text.startsWith (text) && item.isEnabled && item.action)
  11404. {
  11405. item.action();
  11406. return true;
  11407. }
  11408. }
  11409. return false;
  11410. };
  11411. auto act = [&] (const std::string& name, int nth, const juce::String& text) {
  11412. const auto clip = clipOf (name, nth);
  11413. const auto ok = clip >= 0 && run (playlist.getClipMenuForSnapshot (clip), text);
  11414. offline.dispatchPendingMessages();
  11415. return ok;
  11416. };
  11417. auto channelOf = [&] (const std::string& name) -> const lynx::ChannelDef* {
  11418. for (const auto& c : offline.getSong().channels)
  11419. if (c.name == name)
  11420. return &c;
  11421. return nullptr;
  11422. };
  11423. auto check = [&log] (const juce::String& what, bool ok) { log.add ((ok ? "OK " : "FAIL ") + what); };
  11424. const auto names = [&] { std::vector<std::string> n; for (auto& p2 : paths) n.push_back (juce::File (p2).getFileNameWithoutExtension().toStdString()); return n; }();
  11425. if (names.size() >= 4)
  11426. {
  11427. const auto channelsBefore = offline.getSong().channels.size();
  11428. check ("Reverse", act (names[2], 0, lynx::tr ("Reverse")) && channelOf (names[2])->sampler.reverse);
  11429. offline.undo();
  11430. offline.dispatchPendingMessages();
  11431. check ("Reverse undone", ! channelOf (names[2])->sampler.reverse);
  11432. act (names[2], 0, lynx::tr ("Reverse"));
  11433. check ("Make unique", act (names[3], 1, lynx::tr ("Make unique")) && offline.getSong().channels.size() == channelsBefore + 1
  11434. && channelOf (names[3] + " #2") != nullptr);
  11435. check ("Fit to tempo, resample", act (names[1], 0, lynx::tr ("Fit to tempo, resample ({0})", { juce::String() }).upToFirstOccurrenceOf ("(", false, false))
  11436. && channelOf (names[1])->sampler.stretchBeats > 0.0f && ! channelOf (names[1])->sampler.keepPitch);
  11437. const auto gainBefore = offline.getSong().playlist[(std::size_t) clipOf (names[0], 1)].gain;
  11438. check ("Normalize", act (names[0], 1, lynx::tr ("Normalize"))
  11439. && offline.getSong().playlist[(std::size_t) clipOf (names[0], 1)].gain != gainBefore);
  11440. const auto clipsBefore = offline.getSong().playlist.size();
  11441. check ("Split here", act (names[3], 0, lynx::tr ("Split here")) && offline.getSong().playlist.size() == clipsBefore + 1);
  11442. check ("Mute", act (names[0], 0, lynx::tr ("Mute")) && offline.getSong().playlist[(std::size_t) clipOf (names[0], 0)].muted);
  11443. check ("Copy + Paste here", act (names[0], 0, lynx::tr ("Copy")) && act (names[0], 1, lynx::tr ("Paste here"))
  11444. && offline.getSong().playlist.size() == clipsBefore + 2);
  11445. check ("Delete", act (names[0], 2, lynx::tr ("Delete")) && offline.getSong().playlist.size() == clipsBefore + 1);
  11446. check ("Chop to grid", act (names[3], 0, lynx::tr ("Chop to grid")) && offline.getSong().playlist.size() > clipsBefore + 1);
  11447. }
  11448. playlist.setViewForSnapshot (160.0, 0, std::max (0, realTrack - 4));
  11449. saveSnapshot (ui, prefix + "-playlist-real-actions.png");
  11450. juce::File (prefix + "-clip-actions.txt").replaceWithText (log.joinIntoString ("\n") + "\n");
  11451. }
  11452. }
  11453. }
  11454. saveWindow (lynx::makeChannelSettingsPanel (offline, samplerChannel), "-sampler-wave.png");
  11455. ui.showDesktopForSnapshot (false);
  11456. ui.getBrowserForSnapshot().showPreviewForSnapshot (wav);
  11457. saveSnapshot (ui, prefix + "-browser-preview.png");
  11458. }
  11459. }
  11460. // round 165o: every Label / button / tick box whose text the drawing squeezes below its minimum scale or cuts
  11461. // (an ellipsis), per language: `LYNX --lang de --snapshot shots/de` -> shots/de-textfit.txt
  11462. juce::File (prefix + "-textfit.txt").replaceWithText (textFitLog().joinIntoString ("\n") + "\n");
  11463. juce::LookAndFeel::setDefaultLookAndFeel (nullptr);
  11464. quit();
  11465. }
  11466. // --snapshot: 8 s of a synthetic stereo beat whose parts sit in different bands (kick = low, chord = mid,
  11467. // hats and the noise riser = high), to show the spectral waveform colours
  11468. static void writeWaveDemo (const juce::File& file, double bpm)
  11469. {
  11470. constexpr double rate = 44100.0;
  11471. const auto frames = (int) (8.0 * rate);
  11472. juce::AudioBuffer<float> buffer (2, frames);
  11473. buffer.clear();
  11474. auto* l = buffer.getWritePointer (0);
  11475. auto* r = buffer.getWritePointer (1);
  11476. const auto beat = 60.0 / juce::jlimit (40.0, 300.0, bpm);
  11477. std::uint32_t noise = 0x9e3779b9u;
  11478. auto white = [&noise] {
  11479. noise ^= noise << 13;
  11480. noise ^= noise >> 17;
  11481. noise ^= noise << 5;
  11482. return (float) (noise & 0xffffff) / (float) 0x800000 - 1.0f;
  11483. };
  11484. float previous = 0.0f;
  11485. for (int i = 0; i < frames; ++i)
  11486. {
  11487. const auto t = i / rate;
  11488. const auto inBeat = std::fmod (t, beat);
  11489. const auto bar = (int) (t / (beat * 4.0));
  11490. float left = 0.0f, right = 0.0f;
  11491. // kick on every beat: a falling sine
  11492. {
  11493. const auto phase = 2.0 * juce::MathConstants<double>::pi * (48.0 * inBeat + 4.0 * (1.0 - std::exp (-inBeat * 30.0)));
  11494. const auto k = (float) (std::sin (phase) * std::exp (-inBeat * 7.0)) * 0.85f;
  11495. left += k;
  11496. right += k;
  11497. }
  11498. // hats on the off-beats: high-passed noise bursts, a little to the right
  11499. {
  11500. const auto h = std::fmod (t + beat * 0.5, beat);
  11501. const auto n = white();
  11502. const auto hp = (n - previous) * 0.5f;
  11503. previous = n;
  11504. const auto hat = hp * (float) std::exp (-h * 45.0) * 0.55f;
  11505. left += hat * 0.6f;
  11506. right += hat;
  11507. }
  11508. // a chord in the second and third bars (mid band)
  11509. if (bar == 1 || bar == 2)
  11510. {
  11511. const auto env = (float) std::min (1.0, std::min (t - beat * 4.0, beat * 12.0 - t) * 8.0);
  11512. float chord = 0.0f;
  11513. for (const auto hz : { 523.25, 659.25, 783.99 })
  11514. chord += (float) (std::sin (2.0 * juce::MathConstants<double>::pi * hz * t) + 0.3 * std::sin (4.0 * juce::MathConstants<double>::pi * hz * t));
  11515. left += chord * 0.09f * std::max (0.0f, env);
  11516. right += chord * 0.09f * std::max (0.0f, env);
  11517. }
  11518. // a white-noise riser over the last two seconds (high band)
  11519. if (t > 6.0)
  11520. {
  11521. const auto rise = (float) ((t - 6.0) / 2.0);
  11522. left += white() * 0.4f * rise * rise;
  11523. right += white() * 0.4f * rise * rise;
  11524. }
  11525. l[i] = left;
  11526. r[i] = right;
  11527. }
  11528. buffer.applyGain (0.9f / juce::jmax (1.0e-6f, buffer.getMagnitude (0, frames)));
  11529. file.deleteFile();
  11530. juce::WavAudioFormat wav;
  11531. if (std::unique_ptr<juce::AudioFormatWriter> writer { wav.createWriterFor (file.createOutputStream().release(), rate, 2, 24, {}, 0) })
  11532. writer->writeFromAudioSampleBuffer (buffer, 0, frames);
  11533. }
  11534. // the menu bar's menus side by side, drawn with the LookAndFeel as they appear when opened
  11535. static void saveMenus (lynx::MainComponent& ui, const juce::String& path)
  11536. {
  11537. const auto names = ui.getMenuNamesForSnapshot();
  11538. std::vector<juce::PopupMenu> source;
  11539. for (int m = 0; m < names.size(); ++m)
  11540. source.push_back (ui.getMenuForSnapshot (m));
  11541. saveMenus (names, source, path);
  11542. }
  11543. // menus side by side, each under its name
  11544. static void saveMenus (const juce::StringArray& names, const std::vector<juce::PopupMenu>& source, const juce::String& path)
  11545. {
  11546. auto& lf = juce::LookAndFeel::getDefaultLookAndFeel();
  11547. struct Laid
  11548. {
  11549. juce::PopupMenu menu;
  11550. int width = 0, height = 0;
  11551. };
  11552. std::vector<Laid> menus;
  11553. const auto border = lf.getPopupMenuBorderSize();
  11554. for (int m = 0; m < names.size(); ++m)
  11555. {
  11556. Laid laid { source[(std::size_t) m] };
  11557. int width = 160, height = 2 * border;
  11558. for (juce::PopupMenu::MenuItemIterator it (laid.menu); it.next();)
  11559. {
  11560. const auto& item = it.getItem();
  11561. int w = 0, h = 0;
  11562. lf.getIdealPopupMenuItemSize (item.text, item.isSeparator, item.isSectionHeader ? -1 : 0, w, h);
  11563. if (item.isSectionHeader) h += h / 2; // as JUCE does
  11564. if (item.shortcutKeyDescription.isNotEmpty() || item.text.containsChar ('\t'))
  11565. w += 90;
  11566. width = juce::jmax (width, w + 10);
  11567. height += h;
  11568. }
  11569. laid.width = width;
  11570. laid.height = height;
  11571. menus.push_back (std::move (laid));
  11572. }
  11573. int totalWidth = 16, totalHeight = 0;
  11574. for (const auto& l : menus)
  11575. {
  11576. totalWidth += l.width + 16;
  11577. totalHeight = juce::jmax (totalHeight, l.height + 32);
  11578. }
  11579. juce::Image image (juce::Image::ARGB, totalWidth, totalHeight, true);
  11580. {
  11581. juce::Graphics g (image);
  11582. g.fillAll (lynx::theme::colour::bg1);
  11583. int x = 16;
  11584. for (int m = 0; m < (int) menus.size(); ++m)
  11585. {
  11586. const auto& l = menus[(std::size_t) m];
  11587. g.setColour (lynx::theme::colour::textSecondary);
  11588. g.setFont (lynx::theme::font (lynx::theme::type::small, true));
  11589. g.drawText (names[m], x, 0, l.width, 24, juce::Justification::centredLeft);
  11590. {
  11591. juce::Graphics::ScopedSaveState state (g);
  11592. g.reduceClipRegion (x, 24, l.width, l.height);
  11593. g.setOrigin (x, 24);
  11594. lf.drawPopupMenuBackground (g, l.width, l.height);
  11595. int y = border;
  11596. bool first = true;
  11597. for (juce::PopupMenu::MenuItemIterator it (l.menu); it.next();)
  11598. {
  11599. const auto& item = it.getItem();
  11600. int w = 0, h = 0;
  11601. lf.getIdealPopupMenuItemSize (item.text, item.isSeparator, item.isSectionHeader ? -1 : 0, w, h);
  11602. if (item.isSectionHeader) h += h / 2; // as JUCE does
  11603. const juce::Rectangle<int> r (0, y, l.width, h);
  11604. auto text = item.text, shortcut = item.shortcutKeyDescription;
  11605. if (text.containsChar ('\t'))
  11606. {
  11607. shortcut = text.fromFirstOccurrenceOf ("\t", false, false);
  11608. text = text.upToFirstOccurrenceOf ("\t", false, false);
  11609. }
  11610. if (item.isSectionHeader)
  11611. lf.drawPopupMenuSectionHeader (g, r, text);
  11612. else
  11613. lf.drawPopupMenuItem (g, r, item.isSeparator, item.isEnabled, first && ! item.isSeparator && m == 0, item.isTicked,
  11614. item.subMenu != nullptr, text, shortcut, item.image.get(), nullptr);
  11615. first = false;
  11616. y += h;
  11617. }
  11618. }
  11619. x += l.width + 16;
  11620. }
  11621. }
  11622. const juce::File file (path);
  11623. file.deleteFile();
  11624. juce::PNGImageFormat png;
  11625. if (auto out = file.createOutputStream())
  11626. png.writeImageToStream (image, *out);
  11627. }
  11628. static void writePng (const juce::Image& image, const juce::String& path)
  11629. {
  11630. const juce::File file (path);
  11631. file.deleteFile();
  11632. juce::PNGImageFormat png;
  11633. if (auto out = file.createOutputStream())
  11634. png.writeImageToStream (image, *out);
  11635. }
  11636. // the splash screen: one settled frame, and a strip of frames through its animation
  11637. static void saveSplashFrames (const juce::String& prefix)
  11638. {
  11639. lynx::SplashScreen splash;
  11640. splash.setStatus (lynx::tr ("Loading the workspace..."));
  11641. splash.setTimeForSnapshot (1.6);
  11642. writePng (splash.createComponentSnapshot (splash.getLocalBounds()), prefix + "-splash.png");
  11643. const double times[] = { 0.10, 0.22, 0.29, 0.40, 0.58, 0.75, 1.00, 1.30 };
  11644. const auto w = lynx::SplashScreen::width / 2, h = lynx::SplashScreen::height / 2;
  11645. juce::Image strip (juce::Image::ARGB, 4 * (w + 8) + 8, 2 * (h + 8) + 8, true);
  11646. {
  11647. juce::Graphics g (strip);
  11648. g.fillAll (lynx::theme::colour::bg1);
  11649. for (int i = 0; i < 8; ++i)
  11650. {
  11651. splash.setTimeForSnapshot (times[i]);
  11652. const auto frame = splash.createComponentSnapshot (splash.getLocalBounds());
  11653. g.drawImage (frame, 8 + (i % 4) * (w + 8), 8 + (i / 4) * (h + 8), w, h, 0, 0, frame.getWidth(), frame.getHeight());
  11654. }
  11655. }
  11656. writePng (strip, prefix + "-splash-frames.png");
  11657. }
  11658. // every icon at 16, 20 and 24 px (at `scale`, e.g. 1.5 for a 150% display), in the toolbar's
  11659. // colours: at rest, hovered and switched on
  11660. static void saveIconSheet (const juce::String& path, float scale)
  11661. {
  11662. const int sizes[] = { 16, 20, 24 };
  11663. const int cell = 34, columns = 3 * 3, labelWidth = 110;
  11664. const auto w = labelWidth + columns * cell + 16, h = lynx::iconCount * cell + 16;
  11665. juce::Image image (juce::Image::ARGB, juce::roundToInt ((float) w * scale), juce::roundToInt ((float) h * scale), true);
  11666. {
  11667. juce::Graphics g (image); // (drawing is flushed when it goes out of scope)
  11668. g.addTransform (juce::AffineTransform::scale (scale));
  11669. g.fillAll (lynx::theme::colour::bg3);
  11670. g.setFont (lynx::theme::font (lynx::theme::type::small));
  11671. for (int i = 1; i < lynx::iconCount; ++i)
  11672. {
  11673. const auto y = 8 + (i - 1) * cell;
  11674. g.setColour (lynx::theme::colour::textDisabled);
  11675. g.drawText (juce::String (i), 8, y, labelWidth - 8, cell, juce::Justification::centredLeft);
  11676. for (int v = 0; v < 3; ++v)
  11677. for (int s = 0; s < 3; ++s)
  11678. {
  11679. const juce::Rectangle<float> box ((float) (labelWidth + (v * 3 + s) * cell), (float) y, (float) cell, (float) cell);
  11680. const auto bg = v == 2 ? lynx::theme::colour::accent : v == 1 ? lynx::theme::colour::bg5 : lynx::theme::colour::bg3;
  11681. g.setColour (bg);
  11682. g.fillRoundedRectangle (box.reduced (2.0f), 4.0f);
  11683. const auto fg = v == 2 ? lynx::theme::colour::onAccent : v == 1 ? lynx::theme::colour::textPrimary
  11684. : lynx::theme::colour::textSecondary.brighter (0.25f);
  11685. lynx::icons::draw (g, (lynx::Icon) i, box.withSizeKeepingCentre ((float) sizes[s], (float) sizes[s]), fg);
  11686. }
  11687. }
  11688. }
  11689. writePng (image, path);
  11690. }
  11691. // a part of a component (e.g. the main toolbar)
  11692. static void saveArea (juce::Component& c, juce::Rectangle<int> area, const juce::String& path)
  11693. {
  11694. const juce::File file (path);
  11695. file.deleteFile();
  11696. juce::PNGImageFormat png;
  11697. if (auto out = file.createOutputStream())
  11698. png.writeImageToStream (c.createComponentSnapshot (area), *out);
  11699. }
  11700. static void savePng (const juce::Image& image, const juce::String& path)
  11701. {
  11702. const juce::File file (path);
  11703. file.deleteFile();
  11704. juce::PNGImageFormat png;
  11705. if (auto out = file.createOutputStream())
  11706. png.writeImageToStream (image, *out);
  11707. }
  11708. // -toolbar-tips.png: the top of the window with the bubbles of a few controls as they appear under the
  11709. // mouse; -tips-sheet.png: every quick tip of the window, to check names, shortcuts and translations
  11710. static void saveQuickTips (lynx::MainComponent& ui, const juce::String& prefix)
  11711. {
  11712. const auto tips = ui.getQuickTipsForSnapshot();
  11713. const auto top = juce::Rectangle<int> (0, 0, ui.getWidth(), juce::jmin (ui.getHeight(), ui.getToolbarBoundsForSnapshot().getHeight() + 72));
  11714. auto image = ui.createComponentSnapshot (top);
  11715. {
  11716. juce::Graphics g (image);
  11717. const juce::String shown[] = { lynx::tr ("Pattern mode"), lynx::tr ("Play"), lynx::tr ("Metronome"), lynx::tr ("Mixer"), lynx::tr ("Save project"),
  11718. lynx::tr ("Window options"), lynx::tr ("Close") };
  11719. std::vector<juce::Rectangle<int>> used;
  11720. for (const auto& [area, tip] : tips)
  11721. {
  11722. const auto name = tip.upToFirstOccurrenceOf ("\t", false, false);
  11723. if (std::find (std::begin (shown), std::end (shown), name) == std::end (shown))
  11724. continue;
  11725. const auto bubble = lynx::ui::quickTipBounds (tip, area, top);
  11726. if (std::any_of (used.begin(), used.end(), [&] (const auto& r) { return r.intersects (bubble); }))
  11727. continue;
  11728. used.push_back (bubble);
  11729. g.setColour (juce::Colours::white.withAlpha (0.075f)); // the hovered control
  11730. g.fillRoundedRectangle (area.toFloat().reduced (0.5f), lynx::theme::radius::md);
  11731. lynx::ui::paintQuickTip (g, bubble.toFloat(), tip);
  11732. }
  11733. }
  11734. savePng (image, prefix + "-toolbar-tips.png");
  11735. // the sheet: bubbles in rows
  11736. const int width = 900;
  11737. int x = 12, y = 12;
  11738. std::vector<std::pair<juce::Rectangle<int>, juce::String>> placed;
  11739. for (const auto& [area, tip] : tips)
  11740. {
  11741. auto r = lynx::ui::quickTipSize (tip);
  11742. if (x + r.getWidth() > width - 12)
  11743. {
  11744. x = 12;
  11745. y += r.getHeight() + 10;
  11746. }
  11747. placed.emplace_back (r.withPosition (x, y), tip);
  11748. x += r.getWidth() + 10;
  11749. }
  11750. juce::Image sheet (juce::Image::ARGB, width, y + 20 + 12, true);
  11751. {
  11752. juce::Graphics g (sheet);
  11753. g.fillAll (lynx::theme::colour::bg3);
  11754. for (const auto& [r, tip] : placed)
  11755. lynx::ui::paintQuickTip (g, r.toFloat(), tip);
  11756. }
  11757. savePng (sheet, prefix + "-tips-sheet.png");
  11758. }
  11759. static juce::StringArray& textFitLog()
  11760. {
  11761. static juce::StringArray log;
  11762. return log;
  11763. }
  11764. // drawFittedText would shrink `text` below `minScale` or cut it: fewer visible glyphs than the text has
  11765. static bool textIsCut (const juce::Font& font, const juce::String& text, juce::Rectangle<int> area, int maxLines, float minScale)
  11766. {
  11767. if (text.trim().isEmpty() || area.getWidth() <= 4 || area.getHeight() <= 4)
  11768. return false;
  11769. auto visible = [] (juce::GlyphArrangement& ga) {
  11770. int n = 0;
  11771. for (int i = 0; i < ga.getNumGlyphs(); ++i)
  11772. n += ga.getGlyph (i).isWhitespace() ? 0 : 1;
  11773. return n;
  11774. };
  11775. juce::GlyphArrangement fitted, full;
  11776. fitted.addFittedText (font, text, 0.0f, 0.0f, (float) area.getWidth(), (float) area.getHeight(), juce::Justification::centredLeft,
  11777. juce::jmax (1, maxLines), minScale);
  11778. full.addLineOfText (font, text, 0.0f, 0.0f);
  11779. return visible (fitted) < visible (full);
  11780. }
  11781. // walks the visible components under `root` and logs the texts that don't fit (labels, text buttons, tick boxes)
  11782. static void checkTextFit (juce::Component& root, const juce::String& where)
  11783. {
  11784. std::function<void (juce::Component&)> visit = [&] (juce::Component& c) {
  11785. if (! c.isVisible() || c.getWidth() <= 0 || c.getHeight() <= 0)
  11786. return;
  11787. juce::String text;
  11788. bool cut = false;
  11789. if (auto* label = dynamic_cast<juce::Label*> (&c); label != nullptr && ! label->isBeingEdited())
  11790. {
  11791. const auto font = label->getLookAndFeel().getLabelFont (*label);
  11792. const auto area = label->getBorderSize().subtractedFrom (label->getLocalBounds());
  11793. text = label->getText();
  11794. cut = textIsCut (font, text, area, juce::jmax (1, (int) ((float) area.getHeight() / font.getHeight())),
  11795. label->getMinimumHorizontalScale());
  11796. }
  11797. else if (auto* toggle = dynamic_cast<juce::ToggleButton*> (&c))
  11798. {
  11799. const auto tick = juce::jmin (16.0f, (float) c.getHeight() - 4.0f);
  11800. text = toggle->getButtonText();
  11801. cut = textIsCut (juce::Font (lynx::theme::font (juce::jmin ((float) lynx::theme::type::body, (float) c.getHeight() * 0.75f))), text,
  11802. c.getLocalBounds().withTrimmedLeft (juce::roundToInt (tick) + 8).withTrimmedRight (2), 2, 0.85f);
  11803. }
  11804. else if (auto* button = dynamic_cast<juce::TextButton*> (&c);
  11805. button != nullptr && (int) button->getProperties().getWithDefault (lynx::theme::LookAndFeel::iconProperty, 0) == 0)
  11806. {
  11807. text = button->getButtonText();
  11808. cut = textIsCut (button->getLookAndFeel().getTextButtonFont (*button, button->getHeight()), text,
  11809. button->getLocalBounds().reduced (juce::jmin (8, button->getWidth() / 6), 0), 2, 0.85f);
  11810. }
  11811. if (cut)
  11812. {
  11813. juce::String path;
  11814. for (auto* p = &c; p != nullptr && p != &root; p = p->getParentComponent())
  11815. if (p->getName().isNotEmpty())
  11816. path = p->getName() + (path.isEmpty() ? "" : "/") + path;
  11817. const auto line = where + " | " + juce::String (c.getWidth()) + "x" + juce::String (c.getHeight()) + " | " + text.replace ("\n", "\\n")
  11818. + (path.isEmpty() ? juce::String() : " | " + path);
  11819. textFitLog().addIfNotAlreadyThere (line);
  11820. }
  11821. for (auto* child : c.getChildren())
  11822. visit (*child);
  11823. };
  11824. visit (root);
  11825. }
  11826. static void saveSnapshot (juce::Component& c, const juce::String& path)
  11827. {
  11828. checkTextFit (c, juce::File (path).getFileNameWithoutExtension());
  11829. const juce::File file (path);
  11830. file.deleteFile();
  11831. juce::PNGImageFormat png;
  11832. if (auto out = file.createOutputStream())
  11833. png.writeImageToStream (c.createComponentSnapshot (c.getLocalBounds()), *out);
  11834. }
  11835. class MainWindow final : public juce::DocumentWindow
  11836. {
  11837. public:
  11838. MainWindow (const juce::String& name, lynx::AudioEngine& engine)
  11839. : DocumentWindow (name, lynx::theme::window, DocumentWindow::allButtons)
  11840. {
  11841. setUsingNativeTitleBar (true);
  11842. setIcon (lynx::logoImage());
  11843. content = new lynx::MainComponent (engine);
  11844. setContentOwned (content, true);
  11845. setResizable (true, true);
  11846. setResizeLimits (800, 400, 10000, 10000);
  11847. // ~88% of the main display's usable area (at least the UI's design size, but never larger than the
  11848. // display: the AppImage catalog test runs on an 800x600 screen)
  11849. if (const auto* display = juce::Desktop::getInstance().getDisplays().getPrimaryDisplay())
  11850. {
  11851. const auto area = display->userArea;
  11852. const auto fit = [] (int design, int available) {
  11853. return juce::jmin (available, juce::jmax (design, (int) (available * 0.88)));
  11854. };
  11855. setSize (fit (getWidth(), area.getWidth()), fit (getHeight(), area.getHeight()));
  11856. }
  11857. centreWithSize (getWidth(), getHeight());
  11858. // where it was last time (round 167v); the first start opens maximized, the Playlist filling the screen
  11859. // with the Browser at the left and the Channel Rack above it, like FL Studio's first start
  11860. const auto saved = stateFile().loadFileAsString().trim();
  11861. // (LYNX_TEST_MODE keeps the fixed-size window scripted checks expect, unless LYNX_TEST_MAXIMIZE=1)
  11862. const auto firstStart = saved.isEmpty()
  11863. && (! lynx::platform::testMode() || juce::SystemStats::getEnvironmentVariable ("LYNX_TEST_MAXIMIZE", {}) == "1");
  11864. maximiseOnReveal = firstStart || saved.startsWithIgnoreCase ("fs");
  11865. if (saved.isNotEmpty())
  11866. restoreWindowStateFromString (saved.startsWithIgnoreCase ("fs") ? saved.substring (2).trim() : saved);
  11867. }
  11868. // Shows the window (built hidden while the splash screen is up).
  11869. void reveal()
  11870. {
  11871. if (lynx::uitrace::enabled()) // LYNX_TRACE_UI: the frames per second and the longest gap in ui.log (round 173f)
  11872. watchFrames ({});
  11873. setVisible (true);
  11874. lynx::applyWindowChrome (*this);
  11875. lynx::fitWindowOnScreen (*this); // a size saved at another UI zoom still fits (round 163)
  11876. if (maximiseOnReveal)
  11877. setFullScreen (true); // (a title-bar window: maximized, the taskbar stays)
  11878. toFront (true);
  11879. content->grabKeyboardFocus();
  11880. // issue #62: the detached panels restored with the layout (built before this window was shown): their saved
  11881. // place and above it, once the window manager has placed this one
  11882. juce::Timer::callAfterDelay (250, [safe = juce::Component::SafePointer<MainWindow> (this)] {
  11883. if (safe != nullptr)
  11884. safe->content->restoreDetachedWindows();
  11885. });
  11886. }
  11887. // The window's place and maximized state for the next start (main-window.txt in the settings folder).
  11888. void saveState() { stateFile().replaceWithText (getWindowStateAsString()); }
  11889. static juce::File stateFile() { return lynx::PluginHost::settingsFolder().getChildFile ("main-window.txt"); }
  11890. void openFile (const juce::File& file) { content->openFile (file); }
  11891. lynx::MainComponent& getContent() { return *content; }
  11892. void showSetupWizard() { content->showSetupWizard(); }
  11893. void confirmDiscard (std::function<void()> then) { content->confirmDiscard (std::move (then)); }
  11894. void closeButtonPressed() override { JUCEApplication::getInstance()->systemRequestedQuit(); }
  11895. // Every frame the window paints, with its dirty area (ui/FrameProbe.h; --uiperf, LYNX_TRACE_UI). The trace keeps
  11896. // counting when --uiperf watches too.
  11897. void watchFrames (std::function<void (double, juce::Rectangle<int>)> callback)
  11898. {
  11899. if (probe == nullptr)
  11900. {
  11901. probe = std::make_unique<lynx::ui::FrameProbe>();
  11902. Component::addAndMakeVisible (*probe); // (ResizableWindow hides the plain overload)
  11903. probe->setBounds (getLocalBounds());
  11904. }
  11905. probe->onFrame = [callback = std::move (callback)] (double now, juce::Rectangle<int> area) {
  11906. if (lynx::uitrace::enabled())
  11907. lynx::uitrace::frame (now);
  11908. if (callback)
  11909. callback (now, area);
  11910. };
  11911. }
  11912. void resized() override
  11913. {
  11914. DocumentWindow::resized();
  11915. if (probe != nullptr)
  11916. probe->setBounds (getLocalBounds());
  11917. }
  11918. // --uiperf: the time of each frame the window paints (its own paint, then every child's, up to the last)
  11919. std::function<void (double)> onFrame;
  11920. void paint (juce::Graphics& g) override
  11921. {
  11922. if (onFrame)
  11923. frameStart = juce::Time::getMillisecondCounterHiRes();
  11924. DocumentWindow::paint (g);
  11925. }
  11926. void paintOverChildren (juce::Graphics& g) override
  11927. {
  11928. DocumentWindow::paintOverChildren (g);
  11929. if (onFrame && frameStart > 0.0)
  11930. onFrame (juce::Time::getMillisecondCounterHiRes() - frameStart);
  11931. frameStart = 0.0;
  11932. }
  11933. private:
  11934. lynx::MainComponent* content = nullptr; // owned by the window
  11935. std::unique_ptr<lynx::ui::FrameProbe> probe; // (on top of the content; see watchFrames)
  11936. double frameStart = 0.0;
  11937. bool maximiseOnReveal = false;
  11938. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MainWindow)
  11939. };
  11940. lynx::theme::LookAndFeel lookAndFeel;
  11941. std::unique_ptr<lynx::AudioEngine> engine;
  11942. std::unique_ptr<juce::XmlElement> savedDeviceState; // --rtstress: the user's device before this run's --type/--buffer
  11943. // Hidden test mode --asiodll "<driver.dll>[|{CLSID}]" (REA round 97): an ASIO driver loaded straight from its file,
  11944. // without registering it, listed as the driver type "ASIO driver file". True when one was added.
  11945. bool addDriverFileDeviceType()
  11946. {
  11947. const auto args = juce::JUCEApplication::getCommandLineParameterArray();
  11948. const auto i = args.indexOf ("--asiodll");
  11949. if (i < 0 || i + 1 >= args.size() || engine == nullptr)
  11950. return false;
  11951. auto& devices = engine->getDeviceManager();
  11952. devices.getAvailableDeviceTypes(); // creates the standard types first
  11953. for (auto* t : devices.getAvailableDeviceTypes())
  11954. if (t->getTypeName() == lynx::dllAsioTypeName)
  11955. return true;
  11956. auto type = lynx::makeDllAsioDeviceType (args[i + 1].unquoted());
  11957. if (type == nullptr)
  11958. return false;
  11959. devices.addAudioDeviceType (std::move (type));
  11960. return true;
  11961. }
  11962. void restoreSavedDeviceState()
  11963. {
  11964. if (engine != nullptr)
  11965. engine->restoreAudioDeviceState (savedDeviceState.get());
  11966. }
  11967. std::unique_ptr<MainWindow> mainWindow;
  11968. std::unique_ptr<juce::Timer> perf; // --uiperf
  11969. std::unique_ptr<lynx::SplashScreen> splash;
  11970. double splashDuration = lynx::SplashScreen::minimumDuration; // seconds of its clock (round 121: from the process start)
  11971. lynx::StartupOptions startupOptions;
  11972. juce::File fileToOpen;
  11973. bool startupFileHandled = false;
  11974. juce::File openTimeReport; // --opentime
  11975. int openTimeIdleSeconds = 10;
  11976. };
  11977. START_JUCE_APPLICATION (LynxApplication)