@coderline/alphatab 1.6.0-alpha.1397 → 1.6.0-alpha.1399

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,5 +1,5 @@
1
1
  /*!
2
- * alphaTab v1.6.0-alpha.1397 (develop, build 1397)
2
+ * alphaTab v1.6.0-alpha.1399 (develop, build 1399)
3
3
  *
4
4
  * Copyright © 2025, Daniel Kuschny and Contributors, All rights reserved.
5
5
  *
@@ -48,4 +48,4 @@
48
48
  * @preserve
49
49
  * @license
50
50
  */
51
- var e,t,s,i,a,r,n,o,h,l,c,d,u,p,g,m,f,y,b,S,_,w,B,k,T,N,x,v,P,F,C,D,E,L,M,I;void 0===Symbol.dispose&&(Symbol.dispose=Symbol("Symbol.dispose")),function(e){e[e.Page=0]="Page",e[e.Horizontal=1]="Horizontal"}(e||(e={})),function(e){e[e.Default=0]="Default",e[e.ScoreTab=1]="ScoreTab",e[e.Score=2]="Score",e[e.Tab=3]="Tab",e[e.TabMixed=4]="TabMixed"}(t||(t={}));class A{static getValue(e){return A._values||(A._values=new Map),e=e.toLowerCase().replaceAll(" ",""),A._values.has(e)?A._values.get(e):0}static isPiano(e){return e<=7||e>=16&&e<=23}static isGuitar(e){return e>=24&&e<=39||105===e||43===e}}A._values=new Map([["acousticgrandpiano",0],["brightacousticpiano",1],["electricgrandpiano",2],["honkytonkpiano",3],["electricpiano1",4],["electricpiano2",5],["harpsichord",6],["clavinet",7],["celesta",8],["glockenspiel",9],["musicbox",10],["vibraphone",11],["marimba",12],["xylophone",13],["tubularbells",14],["dulcimer",15],["drawbarorgan",16],["percussiveorgan",17],["rockorgan",18],["churchorgan",19],["reedorgan",20],["accordion",21],["harmonica",22],["tangoaccordion",23],["acousticguitarnylon",24],["acousticguitarsteel",25],["electricguitarjazz",26],["electricguitarclean",27],["electricguitarmuted",28],["overdrivenguitar",29],["distortionguitar",30],["guitarharmonics",31],["acousticbass",32],["electricbassfinger",33],["electricbasspick",34],["fretlessbass",35],["slapbass1",36],["slapbass2",37],["synthbass1",38],["synthbass2",39],["violin",40],["viola",41],["cello",42],["contrabass",43],["tremolostrings",44],["pizzicatostrings",45],["orchestralharp",46],["timpani",47],["stringensemble1",48],["stringensemble2",49],["synthstrings1",50],["synthstrings2",51],["choiraahs",52],["voiceoohs",53],["synthvoice",54],["orchestrahit",55],["trumpet",56],["trombone",57],["tuba",58],["mutedtrumpet",59],["frenchhorn",60],["brasssection",61],["synthbrass1",62],["synthbrass2",63],["sopranosax",64],["altosax",65],["tenorsax",66],["baritonesax",67],["oboe",68],["englishhorn",69],["bassoon",70],["clarinet",71],["piccolo",72],["flute",73],["recorder",74],["panflute",75],["blownbottle",76],["shakuhachi",77],["whistle",78],["ocarina",79],["lead1square",80],["lead2sawtooth",81],["lead3calliope",82],["lead4chiff",83],["lead5charang",84],["lead6voice",85],["lead7fifths",86],["lead8bassandlead",87],["pad1newage",88],["pad2warm",89],["pad3polysynth",90],["pad4choir",91],["pad5bowed",92],["pad6metallic",93],["pad7halo",94],["pad8sweep",95],["fx1rain",96],["fx2soundtrack",97],["fx3crystal",98],["fx4atmosphere",99],["fx5brightness",100],["fx6goblins",101],["fx7echoes",102],["fx8scifi",103],["sitar",104],["banjo",105],["shamisen",106],["koto",107],["kalimba",108],["bagpipe",109],["fiddle",110],["shanai",111],["tinklebell",112],["agogo",113],["steeldrums",114],["woodblock",115],["taikodrum",116],["melodictom",117],["synthdrum",118],["reversecymbal",119],["guitarfretnoise",120],["breathnoise",121],["seashore",122],["birdtweet",123],["telephonering",124],["helicopter",125],["applause",126],["gunshot",127]]),function(e){e[e.NoBrackets=0]="NoBrackets",e[e.GroupStaves=1]="GroupStaves",e[e.GroupSimilarInstruments=2]="GroupSimilarInstruments"}(s||(s={})),function(e){e[e.Hidden=0]="Hidden",e[e.FirstSystem=1]="FirstSystem",e[e.AllSystems=2]="AllSystems"}(i||(i={})),function(e){e[e.FullName=0]="FullName",e[e.ShortName=1]="ShortName"}(a||(a={})),function(e){e[e.Horizontal=0]="Horizontal",e[e.Vertical=1]="Vertical"}(r||(r={}));class R{constructor(){this.hideDynamics=!1,this.bracketExtendMode=s.GroupStaves,this.useSystemSignSeparator=!1,this.globalDisplayTuning=!0,this.perTrackDisplayTuning=null,this.globalDisplayChordDiagramsOnTop=!0,this.perTrackChordDiagramsOnTop=null,this.singleTrackTrackNamePolicy=i.FirstSystem,this.multiTrackTrackNamePolicy=i.FirstSystem,this.firstSystemTrackNameMode=a.ShortName,this.otherSystemsTrackNameMode=a.ShortName,this.firstSystemTrackNameOrientation=r.Vertical,this.otherSystemsTrackNameOrientation=r.Vertical,this.multiTrackMultiBarRest=!1,this.perTrackMultiBarRest=null}}class O{constructor(){this.masterBars=[],this.opening=null,this.closings=[],this.isClosed=!1}get openings(){const e=this.opening;return e?[e]:[]}get isOpened(){return!0===this.opening?.isRepeatStart}addMasterBar(e){null===this.opening&&(this.opening=e),this.masterBars.push(e),e.repeatGroup=this,e.isRepeatEnd&&(this.closings.push(e),this.isClosed=!0)}}class H{constructor(){this.colors=new Map}}!function(e){e[e.Neutral=0]="Neutral",e[e.C3=1]="C3",e[e.C4=2]="C4",e[e.F4=3]="F4",e[e.G2=4]="G2"}(n||(n={})),function(e){e[e._15ma=0]="_15ma",e[e._8va=1]="_8va",e[e.Regular=2]="Regular",e[e._8vb=3]="_8vb",e[e._15mb=4]="_15mb"}(o||(o={})),function(e){e[e.None=0]="None",e[e.Simple=1]="Simple",e[e.FirstOfDouble=2]="FirstOfDouble",e[e.SecondOfDouble=3]="SecondOfDouble"}(h||(h={})),function(e){e[e.Cb=-7]="Cb",e[e.Gb=-6]="Gb",e[e.Db=-5]="Db",e[e.Ab=-4]="Ab",e[e.Eb=-3]="Eb",e[e.Bb=-2]="Bb",e[e.F=-1]="F",e[e.C=0]="C",e[e.G=1]="G",e[e.D=2]="D",e[e.A=3]="A",e[e.E=4]="E",e[e.B=5]="B",e[e.FSharp=6]="FSharp",e[e.CSharp=7]="CSharp"}(l||(l={})),function(e){e[e.Major=0]="Major",e[e.Minor=1]="Minor"}(c||(c={})),function(e){e[e.Down=0]="Down",e[e.Hold=1]="Hold",e[e.Up=2]="Up"}(d||(d={}));class W{constructor(){this.ratioPosition=0,this.pedalType=d.Down,this.nextPedalMarker=null,this.previousPedalMarker=null}}!function(e){e[e.StandardNotationRepeats=0]="StandardNotationRepeats",e[e.GuitarTabsRepeats=1]="GuitarTabsRepeats",e[e.SlashRepeats=2]="SlashRepeats",e[e.NumberedRepeats=3]="NumberedRepeats",e[e.StandardNotationBarNumber=4]="StandardNotationBarNumber",e[e.GuitarTabsBarNumber=5]="GuitarTabsBarNumber",e[e.SlashBarNumber=6]="SlashBarNumber",e[e.NumberedBarNumber=7]="NumberedBarNumber",e[e.StandardNotationBarLines=8]="StandardNotationBarLines",e[e.GuitarTabsBarLines=9]="GuitarTabsBarLines",e[e.SlashBarLines=10]="SlashBarLines",e[e.NumberedBarLines=11]="NumberedBarLines",e[e.StandardNotationClef=12]="StandardNotationClef",e[e.GuitarTabsClef=13]="GuitarTabsClef",e[e.StandardNotationKeySignature=14]="StandardNotationKeySignature",e[e.NumberedKeySignature=15]="NumberedKeySignature",e[e.StandardNotationTimeSignature=16]="StandardNotationTimeSignature",e[e.GuitarTabsTimeSignature=17]="GuitarTabsTimeSignature",e[e.SlashTimeSignature=18]="SlashTimeSignature",e[e.NumberedTimeSignature=19]="NumberedTimeSignature",e[e.StandardNotationStaffLine=20]="StandardNotationStaffLine",e[e.GuitarTabsStaffLine=21]="GuitarTabsStaffLine",e[e.SlashStaffLine=22]="SlashStaffLine",e[e.NumberedStaffLine=23]="NumberedStaffLine"}(u||(u={}));class V extends H{}!function(e){e[e.Automatic=0]="Automatic",e[e.Dashed=1]="Dashed",e[e.Dotted=2]="Dotted",e[e.Heavy=3]="Heavy",e[e.HeavyHeavy=4]="HeavyHeavy",e[e.HeavyLight=5]="HeavyLight",e[e.LightHeavy=6]="LightHeavy",e[e.LightLight=7]="LightLight",e[e.None=8]="None",e[e.Regular=9]="Regular",e[e.Short=10]="Short",e[e.Tick=11]="Tick"}(p||(p={}));class G{constructor(){this.id=G._globalBarId++,this.index=0,this.nextBar=null,this.previousBar=null,this.clef=n.G2,this.clefOttava=o.Regular,this.voices=[],this.simileMark=h.None,this.isMultiVoice=!1,this.displayScale=1,this.displayWidth=-1,this.sustainPedals=[],this._isEmpty=!0,this._isRestOnly=!0,this.barLineLeft=p.Automatic,this.barLineRight=p.Automatic,this.keySignature=l.C,this.keySignatureType=c.Major}static resetIds(){G._globalBarId=0}get masterBar(){return this.staff.track.score.masterBars[this.index]}get isEmpty(){return this._isEmpty}get isRestOnly(){return this._isRestOnly}getActualBarLineLeft(e){return G.actualBarLine(this,!1,e)}getActualBarLineRight(){return G.actualBarLine(this,!0,!1)}static automaticToActualType(e,t,s){let i;return i=t?e.isRepeatEnd?p.LightHeavy:e.nextMasterBar?e.isFreeTime?p.Dashed:e.isDoubleBar?p.LightLight:p.Regular:p.LightHeavy:e.isRepeatStart?p.HeavyLight:s?p.Regular:p.None,i}static actualBarLine(e,t,s){const i=e.masterBar,a=t?e.barLineRight:e.barLineLeft;let r;return r=a===p.Automatic?G.automaticToActualType(i,t,s):a,r}addVoice(e){e.bar=this,e.index=this.voices.length,this.voices.push(e)}finish(e,t=null){this.isMultiVoice=!1,this._isEmpty=!0,this._isRestOnly=!0;for(let s=0,i=this.voices.length;s<i;s++){const i=this.voices[s];i.finish(e,t),s>0&&!i.isEmpty&&(this.isMultiVoice=!0),i.isEmpty||(this._isEmpty=!1),i.isRestOnly||(this._isRestOnly=!1)}const s=this.sustainPedals;if(s.length>0){let e=null;this.sustainPedals=[],this.previousBar&&this.previousBar.sustainPedals.length>0&&(e=this.previousBar.sustainPedals[this.previousBar.sustainPedals.length-1]);const t=null!==e&&e.pedalType!==d.Up;for(const i of s){if(e&&e.pedalType!==d.Up){if(e.bar===this&&i.ratioPosition<=e.ratioPosition)continue;e.nextPedalMarker=i,i.previousPedalMarker=e}t&&i.pedalType===d.Down&&(i.pedalType=d.Hold),i.bar=this,this.sustainPedals.push(i),e=i}}else if(this.previousBar&&this.previousBar.sustainPedals.length>0){const e=this.previousBar.sustainPedals[this.previousBar.sustainPedals.length-1];if(e.pedalType!==d.Up){const t=new W;t.ratioPosition=0,t.bar=this,t.pedalType=d.Hold,this.sustainPedals.push(t),e.nextPedalMarker=t,t.previousPedalMarker=e}}}calculateDuration(){let e=0;for(const t of this.voices){const s=t.calculateDuration();s>e&&(e=s)}return e}}G._globalBarId=0,function(e){e[e.PPP=0]="PPP",e[e.PP=1]="PP",e[e.P=2]="P",e[e.MP=3]="MP",e[e.MF=4]="MF",e[e.F=5]="F",e[e.FF=6]="FF",e[e.FFF=7]="FFF",e[e.PPPP=8]="PPPP",e[e.PPPPP=9]="PPPPP",e[e.PPPPPP=10]="PPPPPP",e[e.FFFF=11]="FFFF",e[e.FFFFF=12]="FFFFF",e[e.FFFFFF=13]="FFFFFF",e[e.SF=14]="SF",e[e.SFP=15]="SFP",e[e.SFPP=16]="SFPP",e[e.FP=17]="FP",e[e.RF=18]="RF",e[e.RFZ=19]="RFZ",e[e.SFZ=20]="SFZ",e[e.SFFZ=21]="SFFZ",e[e.FZ=22]="FZ",e[e.N=23]="N",e[e.PF=24]="PF",e[e.SFZP=25]="SFZP"}(g||(g={}));class z{static ticksToMillis(e,t){return e*(6e4/(t*z.QuarterTime))|0}static millisToTicks(e,t){return e/(6e4/(t*z.QuarterTime))|0}static toTicks(e){return z.valueToTicks(e)}static valueToTicks(e){let t=e;return t<0&&(t=1/-t),z.QuarterTime*(4/t)|0}static applyDot(e,t){return t?e+3*(e/4|0):e+(e/2|0)}static applyTuplet(e,t,s){return e*s/t|0}static removeTuplet(e,t,s){return e*t/s|0}static dynamicToVelocity(e,t=0){let s=1;switch(e){case g.PPP:s=z.MinVelocity+0*z.VelocityIncrement;break;case g.PP:s=z.MinVelocity+1*z.VelocityIncrement;break;case g.P:s=z.MinVelocity+2*z.VelocityIncrement;break;case g.MP:s=z.MinVelocity+3*z.VelocityIncrement;break;case g.MF:s=z.MinVelocity+4*z.VelocityIncrement;break;case g.F:s=z.MinVelocity+5*z.VelocityIncrement;break;case g.FF:s=z.MinVelocity+6*z.VelocityIncrement;break;case g.FFF:s=z.MinVelocity+7*z.VelocityIncrement;break;case g.PPPP:s=10;break;case g.PPPPP:s=5;break;case g.PPPPPP:s=3;break;case g.FFFF:s=z.MinVelocity+8*z.VelocityIncrement;break;case g.FFFFF:s=z.MinVelocity+9*z.VelocityIncrement;break;case g.FFFFFF:s=z.MinVelocity+10*z.VelocityIncrement;break;case g.SF:case g.SFP:case g.SFZP:case g.SFPP:case g.SFZ:case g.FZ:s=z.MinVelocity+6*z.VelocityIncrement;break;case g.FP:case g.RF:case g.RFZ:case g.SFFZ:s=z.MinVelocity+5*z.VelocityIncrement;break;case g.N:s=1;break;case g.PF:s=z.MinVelocity+(4.5*z.VelocityIncrement|0)}return s+=t*z.VelocityIncrement,Math.min(Math.max(s,1),127)}}z.QuarterTime=960,z.MinVelocity=15,z.VelocityIncrement=16,function(e){e[e.Tempo=0]="Tempo",e[e.Volume=1]="Volume",e[e.Instrument=2]="Instrument",e[e.Balance=3]="Balance"}(m||(m={}));class U{constructor(){this.isLinear=!1,this.type=m.Tempo,this.value=0,this.ratioPosition=0,this.text=""}static buildTempoAutomation(e,t,s,i){(i<1||i>5)&&(i=2);const a=new Float32Array([1,.5,1,1.5,2,3]),r=new U;return r.type=m.Tempo,r.isLinear=e,r.ratioPosition=t,r.value=s*a[i],r}static buildInstrumentAutomation(e,t,s){const i=new U;return i.type=m.Instrument,i.isLinear=e,i.ratioPosition=t,i.value=s,i}}class X{constructor(e=0,t=0){this.offset=e,this.value=t}}X.MaxPosition=60,X.MaxValue=12,function(e){e[e.Default=0]="Default",e[e.Gradual=1]="Gradual",e[e.Fast=2]="Fast"}(f||(f={})),function(e){e[e.None=0]="None",e[e.Custom=1]="Custom",e[e.Bend=2]="Bend",e[e.Release=3]="Release",e[e.BendRelease=4]="BendRelease",e[e.Hold=5]="Hold",e[e.Prebend=6]="Prebend",e[e.PrebendBend=7]="PrebendBend",e[e.PrebendRelease=8]="PrebendRelease"}(y||(y={})),function(e){e[e.None=0]="None",e[e.BrushUp=1]="BrushUp",e[e.BrushDown=2]="BrushDown",e[e.ArpeggioUp=3]="ArpeggioUp",e[e.ArpeggioDown=4]="ArpeggioDown"}(b||(b={})),function(e){e[e.None=0]="None",e[e.Crescendo=1]="Crescendo",e[e.Decrescendo=2]="Decrescendo"}(S||(S={})),function(e){e[e.QuadrupleWhole=-4]="QuadrupleWhole",e[e.DoubleWhole=-2]="DoubleWhole",e[e.Whole=1]="Whole",e[e.Half=2]="Half",e[e.Quarter=4]="Quarter",e[e.Eighth=8]="Eighth",e[e.Sixteenth=16]="Sixteenth",e[e.ThirtySecond=32]="ThirtySecond",e[e.SixtyFourth=64]="SixtyFourth",e[e.OneHundredTwentyEighth=128]="OneHundredTwentyEighth",e[e.TwoHundredFiftySixth=256]="TwoHundredFiftySixth"}(_||(_={})),function(e){e[e.None=0]="None",e[e.OnBeat=1]="OnBeat",e[e.BeforeBeat=2]="BeforeBeat",e[e.BendGrace=3]="BendGrace"}(w||(w={})),function(e){e[e.None=0]="None",e[e.Normal=1]="Normal",e[e.Heavy=2]="Heavy",e[e.Tenuto=3]="Tenuto"}(B||(B={})),function(e){e[e.Unknown=-2]="Unknown",e[e.NoOrDead=-1]="NoOrDead",e[e.Thumb=0]="Thumb",e[e.IndexFinger=1]="IndexFinger",e[e.MiddleFinger=2]="MiddleFinger",e[e.AnnularFinger=3]="AnnularFinger",e[e.LittleFinger=4]="LittleFinger"}(k||(k={})),function(e){e[e.None=0]="None",e[e.Natural=1]="Natural",e[e.Artificial=2]="Artificial",e[e.Pinch=3]="Pinch",e[e.Tap=4]="Tap",e[e.Semi=5]="Semi",e[e.Feedback=6]="Feedback"}(T||(T={})),function(e){e[e.Default=0]="Default",e[e.ForceNone=1]="ForceNone",e[e.ForceNatural=2]="ForceNatural",e[e.ForceSharp=3]="ForceSharp",e[e.ForceDoubleSharp=4]="ForceDoubleSharp",e[e.ForceFlat=5]="ForceFlat",e[e.ForceDoubleFlat=6]="ForceDoubleFlat"}(N||(N={})),function(e){e[e.None=0]="None",e[e.IntoFromBelow=1]="IntoFromBelow",e[e.IntoFromAbove=2]="IntoFromAbove"}(x||(x={})),function(e){e[e.None=0]="None",e[e.Shift=1]="Shift",e[e.Legato=2]="Legato",e[e.OutUp=3]="OutUp",e[e.OutDown=4]="OutDown",e[e.PickSlideDown=5]="PickSlideDown",e[e.PickSlideUp=6]="PickSlideUp"}(v||(v={})),function(e){e[e.None=0]="None",e[e.Slight=1]="Slight",e[e.Wide=2]="Wide"}(P||(P={})),function(e){e[e.Hidden=0]="Hidden",e[e.ShowWithBeams=1]="ShowWithBeams",e[e.ShowWithBars=2]="ShowWithBars",e[e.Automatic=3]="Automatic"}(F||(F={})),function(e){e[e.ScoreDefault=0]="ScoreDefault",e[e.ScoreForcePiano=1]="ScoreForcePiano",e[e.SingleNoteEffectBand=2]="SingleNoteEffectBand",e[e.SingleNoteEffectBandForcePiano=3]="SingleNoteEffectBandForcePiano"}(C||(C={})),function(e){e[e.GuitarPro=0]="GuitarPro",e[e.SongBook=1]="SongBook"}(D||(D={})),function(e){e[e.ScoreTitle=0]="ScoreTitle",e[e.ScoreSubTitle=1]="ScoreSubTitle",e[e.ScoreArtist=2]="ScoreArtist",e[e.ScoreAlbum=3]="ScoreAlbum",e[e.ScoreWords=4]="ScoreWords",e[e.ScoreMusic=5]="ScoreMusic",e[e.ScoreWordsAndMusic=6]="ScoreWordsAndMusic",e[e.ScoreCopyright=7]="ScoreCopyright",e[e.GuitarTuning=8]="GuitarTuning",e[e.TrackNames=9]="TrackNames",e[e.ChordDiagrams=10]="ChordDiagrams",e[e.ParenthesisOnTiedBends=11]="ParenthesisOnTiedBends",e[e.TabNotesOnTiedBends=12]="TabNotesOnTiedBends",e[e.ZerosOnDiveWhammys=13]="ZerosOnDiveWhammys",e[e.EffectAlternateEndings=14]="EffectAlternateEndings",e[e.EffectCapo=15]="EffectCapo",e[e.EffectChordNames=16]="EffectChordNames",e[e.EffectCrescendo=17]="EffectCrescendo",e[e.EffectDynamics=18]="EffectDynamics",e[e.EffectFadeIn=19]="EffectFadeIn",e[e.EffectFermata=20]="EffectFermata",e[e.EffectFingering=21]="EffectFingering",e[e.EffectHarmonics=22]="EffectHarmonics",e[e.EffectLetRing=23]="EffectLetRing",e[e.EffectLyrics=24]="EffectLyrics",e[e.EffectMarker=25]="EffectMarker",e[e.EffectOttavia=26]="EffectOttavia",e[e.EffectPalmMute=27]="EffectPalmMute",e[e.EffectPickSlide=28]="EffectPickSlide",e[e.EffectPickStroke=29]="EffectPickStroke",e[e.EffectSlightBeatVibrato=30]="EffectSlightBeatVibrato",e[e.EffectSlightNoteVibrato=31]="EffectSlightNoteVibrato",e[e.EffectTap=32]="EffectTap",e[e.EffectTempo=33]="EffectTempo",e[e.EffectText=34]="EffectText",e[e.EffectTrill=35]="EffectTrill",e[e.EffectTripletFeel=36]="EffectTripletFeel",e[e.EffectWhammyBar=37]="EffectWhammyBar",e[e.EffectWideBeatVibrato=38]="EffectWideBeatVibrato",e[e.EffectWideNoteVibrato=39]="EffectWideNoteVibrato",e[e.EffectLeftHandTap=40]="EffectLeftHandTap",e[e.EffectFreeTime=41]="EffectFreeTime",e[e.EffectSustainPedal=42]="EffectSustainPedal",e[e.EffectGolpe=43]="EffectGolpe",e[e.EffectWahPedal=44]="EffectWahPedal",e[e.EffectBeatBarre=45]="EffectBeatBarre",e[e.EffectNoteOrnament=46]="EffectNoteOrnament",e[e.EffectRasgueado=47]="EffectRasgueado",e[e.EffectDirections=48]="EffectDirections",e[e.EffectBeatTimer=49]="EffectBeatTimer"}(E||(E={}));class J{constructor(){this.notationMode=D.GuitarPro,this.fingeringMode=C.ScoreDefault,this.elements=new Map,this.rhythmMode=F.Automatic,this.rhythmHeight=15,this.transpositionPitches=[],this.displayTranspositionPitches=[],this.smallGraceTabNotes=!0,this.extendBendArrowsOnTiedNotes=!0,this.extendLineEffectsToBeatEnd=!1,this.slurHeight=5}isNotationElementVisible(e){return this.elements.has(e)?this.elements.get(e):!J.defaultElements.has(e)||J.defaultElements.get(e)}}J.defaultElements=new Map([[E.ZerosOnDiveWhammys,!1]]);class Y{constructor(e){this._value=void 0,this._factory=e}get value(){return void 0===this._value&&(this._value=this._factory()),this._value}}!function(e){e[e.None=0]="None",e[e.Debug=1]="Debug",e[e.Info=2]="Info",e[e.Warning=3]="Warning",e[e.Error=4]="Error"}(L||(L={}));class ${static format(e,t){return`[AlphaTab][${e}] ${t}`}debug(e,t,...s){console.debug($.format(e,t),...s)}warning(e,t,...s){console.warn($.format(e,t),...s)}info(e,t,...s){console.info($.format(e,t),...s)}error(e,t,...s){console.error($.format(e,t),...s)}}$.logLevel=L.Info;class q{static shouldLog(e){return q.logLevel!==L.None&&e>=q.logLevel}static debug(e,t,...s){q.shouldLog(L.Debug)&&q.log.debug(e,t,...s)}static warning(e,t,...s){q.shouldLog(L.Warning)&&q.log.warning(e,t,...s)}static info(e,t,...s){q.shouldLog(L.Info)&&q.log.info(e,t,...s)}static error(e,t,...s){q.shouldLog(L.Error)&&q.log.error(e,t,...s)}}q.logLevel=L.Info,q.log=new $,function(e){e[e.NoTripletFeel=0]="NoTripletFeel",e[e.Triplet16th=1]="Triplet16th",e[e.Triplet8th=2]="Triplet8th",e[e.Dotted16th=3]="Dotted16th",e[e.Dotted8th=4]="Dotted8th",e[e.Scottish16th=5]="Scottish16th",e[e.Scottish8th=6]="Scottish8th"}(M||(M={}));class j{constructor(){this.alternateEndings=0,this.nextMasterBar=null,this.previousMasterBar=null,this.index=0,this.isDoubleBar=!1,this.isRepeatStart=!1,this.repeatCount=0,this.timeSignatureNumerator=4,this.timeSignatureDenominator=4,this.timeSignatureCommon=!1,this.isFreeTime=!1,this.tripletFeel=M.NoTripletFeel,this.section=null,this.tempoAutomations=[],this.fermata=null,this.start=0,this.isAnacrusis=!1,this.displayScale=1,this.displayWidth=-1,this.directions=null}get keySignature(){return this.score.tracks[0].staves[0].bars[this.index].keySignature}set keySignature(e){this.score.tracks[0].staves[0].bars[this.index].keySignature=e}get keySignatureType(){return this.score.tracks[0].staves[0].bars[this.index].keySignatureType}set keySignatureType(e){this.score.tracks[0].staves[0].bars[this.index].keySignatureType=e}get isRepeatEnd(){return this.repeatCount>0}get isSectionStart(){return!!this.section}get tempoAutomation(){return this.tempoAutomations.length>0?this.tempoAutomations[0]:null}calculateDuration(e=!0){if(this.isAnacrusis&&e){let e=0;for(const t of this.score.tracks)for(const s of t.staves){const t=this.index<s.bars.length?s.bars[this.index].calculateDuration():0;t>e&&(e=t)}return e}return this.timeSignatureNumerator*z.valueToTicks(this.timeSignatureDenominator)}addFermata(e,t){let s=this.fermata;null===s&&(s=new Map,this.fermata=s),s.set(e,t)}addDirection(e){null==this.directions&&(this.directions=new Set),this.directions.add(e)}getFermata(e){const t=this.fermata;return null===t?null:t.has(e.playbackStart)?t.get(e.playbackStart):null}}j.MaxAlternateEndings=8;class K{}K.DefaultChannelCount=17,K.MetronomeChannel=K.DefaultChannelCount-1,K.MetronomeKey=33,K.AudioChannels=2,K.MinVolume=0,K.MinProgram=0,K.MaxProgram=127,K.MinPlaybackSpeed=.125,K.MaxPlaybackSpeed=8,K.PercussionChannel=9,K.PercussionBank=128,K.MaxPitchWheel=16384,K.MaxPitchWheel20=4294967296,K.DefaultPitchWheel=K.MaxPitchWheel/2,K.MicroBufferCount=32,K.MicroBufferSize=64;class Q{constructor(){this.beats=[],this.id="empty",this.isComplete=!1}addBeat(e){e.graceIndex=this.beats.length,e.graceGroup=this,this.beats.push(e)}finish(){this.beats.length>0&&(this.id=`${this.beats[0].absoluteDisplayStart}_${this.beats[0].voice.index}`)}}!function(e){e[e.Glyphs=0]="Glyphs"}(I||(I={}));class Z extends H{}let ee=class e{constructor(){this._isEmpty=!0,this._isRestOnly=!0,this.id=e._globalVoiceId++,this.index=0,this.beats=[]}static resetIds(){e._globalVoiceId=0}get isEmpty(){return this._isEmpty}forceNonEmpty(){this._isEmpty=!1}get isRestOnly(){return this._isRestOnly}insertBeat(e,t){t.nextBeat=e.nextBeat,t.nextBeat&&(t.nextBeat.previousBeat=t),t.previousBeat=e,t.voice=this,e.nextBeat=t,this.beats.splice(e.index+1,0,t)}addBeat(e){e.voice=this,e.index=this.beats.length,this.beats.push(e),e.isEmpty||(this._isEmpty=!1),e.isRest||(this._isRestOnly=!1)}chain(e,t=null){if(this.bar){if(e.index<this.beats.length-1)e.nextBeat=this.beats[e.index+1],e.nextBeat.previousBeat=e;else if(e.isLastOfVoice&&e.voice.bar.nextBar){const t=this.bar.nextBar.voices[this.index];t.beats.length>0?(e.nextBeat=t.beats[0],e.nextBeat.previousBeat=e):e.nextBeat.previousBeat=e}e.chain(t)}}addGraceBeat(e){if(0===this.beats.length)return void this.addBeat(e);const t=this.beats[this.beats.length-1];this.beats.splice(this.beats.length-1,1),this.addBeat(e),this.addBeat(t),this._isEmpty=!1,this._isRestOnly=!1}getBeatAtPlaybackStart(e){return this._beatLookup.has(e)?this._beatLookup.get(e):null}finish(e,t=null){this._isEmpty=!0,this._isRestOnly=!0,this._beatLookup=new Map;let s=null;for(let e=0;e<this.beats.length;e++){const i=this.beats[e];i.index=e,this.chain(i,t),i.graceType===w.None?(i.graceGroup=s,s&&(s.isComplete=!0),s=null):(s||(s=new Q),s.addBeat(i)),i.isEmpty||(this._isEmpty=!1),i.isRest||(this._isRestOnly=!1)}let i=0,a=0;for(let s=0;s<this.beats.length;s++){const r=this.beats[s];if(r.index=s,r.finish(e,t),r.graceType===w.None){if(r.graceGroup){const e=r.graceGroup.beats[0],t=r.graceGroup.beats[r.graceGroup.beats.length-1];if(e.graceType!==w.BendGrace){const s=t.playbackStart+t.playbackDuration-e.playbackStart;switch(e.graceType){case w.BeforeBeat:e.previousBeat?(e.previousBeat.playbackDuration-=s,a=e.previousBeat.voice===this?e.previousBeat.playbackStart+e.previousBeat.playbackDuration:-s):a=-s;for(const e of r.graceGroup.beats)this._beatLookup.delete(e.playbackStart),e.playbackStart=a,this._beatLookup.set(e.playbackStart,r),a+=e.playbackDuration;break;case w.OnBeat:r.playbackDuration-=s,a=t.voice===this?t.playbackStart+t.playbackDuration:-s}}}r.displayStart=i,r.playbackStart=a,r.fermata?this.bar.masterBar.addFermata(r.playbackStart,r.fermata):r.fermata=this.bar.masterBar.getFermata(r),this._beatLookup.set(r.playbackStart,r)}else r.displayStart=i,r.playbackStart=a;r.finishTuplet(),r.graceGroup&&r.graceGroup.finish(),i+=r.displayDuration,a+=r.playbackDuration}}calculateDuration(){if(this.isEmpty||0===this.beats.length)return 0;const e=this.beats[this.beats.length-1],t=this.beats[0];return e.playbackStart+e.playbackDuration-t.playbackStart}};ee._globalVoiceId=0;class te{constructor(){this.note=null,this.tone=new se,this.octave=0}get realValue(){return 12*this.octave+this.tone.noteValue}}class se{constructor(e=0,t=N.Default){this.noteValue=e,this.accidentalMode=t}}class ie{static getIndex(e){return e<0?0:0|Math.log2(e)}static keySignatureIsFlat(e){return e<0}static keySignatureIsNatural(e){return 0===e}static keySignatureIsSharp(e){return e>0}static applyPitchOffsets(e,t){for(let s=0;s<t.tracks.length;s++){if(s<e.notation.displayTranspositionPitches.length)for(const i of t.tracks[s].staves)i.displayTranspositionPitch=-e.notation.displayTranspositionPitches[s];if(s<e.notation.transpositionPitches.length)for(const i of t.tracks[s].staves)i.transpositionPitch=-e.notation.transpositionPitches[s]}}static fingerToString(e,t,s,i){if(e.notation.fingeringMode===C.ScoreForcePiano||e.notation.fingeringMode===C.SingleNoteEffectBandForcePiano||A.isPiano(t.voice.bar.staff.track.playbackInfo.program))switch(s){case k.Unknown:case k.NoOrDead:return null;case k.Thumb:return"1";case k.IndexFinger:return"2";case k.MiddleFinger:return"3";case k.AnnularFinger:return"4";case k.LittleFinger:return"5";default:return null}if(i)switch(s){case k.Unknown:return null;case k.NoOrDead:return"0";case k.Thumb:return"t";case k.IndexFinger:return"1";case k.MiddleFinger:return"2";case k.AnnularFinger:return"3";case k.LittleFinger:return"4";default:return null}switch(s){case k.Unknown:case k.NoOrDead:return null;case k.Thumb:return"p";case k.IndexFinger:return"i";case k.MiddleFinger:return"m";case k.AnnularFinger:return"a";case k.LittleFinger:return"c";default:return null}}static isTuning(e){return!!ie.parseTuning(e)}static parseTuning(e){let t="",s="";for(let i=0;i<e.length;i++){const a=e.charCodeAt(i);if(a>=48&&a<=57){if(!t)return null;s+=String.fromCharCode(a)}else{if(!ie.TuningLetters.has(a))return null;t+=String.fromCharCode(a)}}if(!s||!t)return null;const i=new te;return i.octave=Number.parseInt(s)+1,i.note=t.toLowerCase(),i.tone=ie.getToneForText(i.note),i.tone.noteValue<0&&(i.octave--,i.tone.noteValue+=12),i}static getTuningForText(e){const t=ie.parseTuning(e);return t?t.realValue:-1}static getToneForText(e){const t=e.substring(0,1),s=e.substring(1);let i,a;switch(t.toLowerCase()){case"c":default:i=0;break;case"d":i=2;break;case"e":i=4;break;case"f":i=5;break;case"g":i=7;break;case"a":i=9;break;case"b":i=11}switch(a=ie.parseAccidentalMode(s),a){case N.Default:case N.ForceNone:case N.ForceNatural:break;case N.ForceSharp:i++;break;case N.ForceDoubleSharp:i+=2;break;case N.ForceFlat:i--;break;case N.ForceDoubleFlat:i-=2}return new se(i,a)}static parseAccidentalMode(e){const t=e.toLowerCase();return ie.accidentalModeMapping.has(t)?ie.accidentalModeMapping.get(t):N.Default}static newGuid(){return`${Math.floor(65536*(1+Math.random())).toString(16).substring(1)+Math.floor(65536*(1+Math.random())).toString(16).substring(1)}-${Math.floor(65536*(1+Math.random())).toString(16).substring(1)}-${Math.floor(65536*(1+Math.random())).toString(16).substring(1)}-${Math.floor(65536*(1+Math.random())).toString(16).substring(1)}-${Math.floor(65536*(1+Math.random())).toString(16).substring(1)}${Math.floor(65536*(1+Math.random())).toString(16).substring(1)}${Math.floor(65536*(1+Math.random())).toString(16).substring(1)}`}static isAlmostEqualTo(e,t){return Math.abs(e-t)<1e-5}static toHexString(e,t=0){let s="";do{s=String.fromCharCode("0123456789ABCDEF".charCodeAt(15&e))+s,e>>=4}while(e>0);for(;s.length<t;)s=`0${s}`;return s}static getAlternateEndingsList(e){const t=[];for(let s=0;s<j.MaxAlternateEndings;s++)e&1<<s&&t.push(s);return t}static deltaFretToHarmonicValue(e){switch(e){case 2:return 2.4;case 3:return 3.2;case 4:case 5:case 7:case 9:case 12:case 16:case 17:case 19:case 24:return e;case 8:return 8.2;case 10:return 9.6;case 14:case 15:return 14.7;case 21:case 22:return 21.7;default:return 12}}static clamp(e,t,s){return e<=t?t:e>=s?s:e}static buildMultiBarRestInfo(e,t,s){if(!e)return null;const i=e[0].score.stylesheet;if(!(e.length>1?i.multiTrackMultiBarRest:!0===i.perTrackMultiBarRest?.has(e[0].index)))return null;const a=new Map,r=e[0].score;let n=t;for(;n<=s;){const i=n;let o=null;for(;n<=s;){const s=r.masterBars[n];if(s.alternateEndings||s.isRepeatStart&&s.index!==i||s.isFreeTime||s.isAnacrusis||null!==s.section||s.index!==i&&s.tempoAutomations.length>0||null!==s.fermata&&s.fermata.size>0||null!==s.directions&&s.directions.size>0)break;if(i>t&&s.previousMasterBar&&(s.timeSignatureCommon!==s.previousMasterBar.timeSignatureCommon||s.timeSignatureNumerator!==s.previousMasterBar.timeSignatureNumerator||s.timeSignatureDenominator!==s.previousMasterBar.timeSignatureDenominator||s.tripletFeel!==s.previousMasterBar.tripletFeel))break;let a=!0;for(const t of e){for(const e of t.staves){const t=e.bars[s.index];if(!t.isRestOnly){a=!1;break}if(t.index>0&&(t.keySignature!==t.previousBar.keySignature||t.keySignatureType!==t.previousBar.keySignatureType)){a=!1;break}}if(!a)break}if(!a)break;if(n++,s.index>i&&(null===o?o=[s.index]:o.push(s.index)),s.isRepeatEnd)break}o?a.set(i,o):n++}return a}static computeFirstDisplayedBarIndex(e,t){let s=t.display.startBar;return s--,s=Math.min(e.masterBars.length-1,Math.max(0,s)),s}static computeLastDisplayedBarIndex(e,t,s){let i=t.display.barCount;return i<0&&(i=e.masterBars.length),i=s+i-1,i=Math.min(e.masterBars.length-1,Math.max(0,i)),i}static getOrCreateHeaderFooterStyle(e,t){let s,i=e.style;if(e.style||(i=new Xe,e.style=i),i.headerAndFooter.has(t))s=i.headerAndFooter.get(t);else{if(s=new Ue,Xe.defaultHeaderAndFooter.has(t)){const e=Xe.defaultHeaderAndFooter.get(t);s.template=e.template,s.textAlign=e.textAlign}i.headerAndFooter.set(t,s)}return s}static consolidate(e){if(0===e.masterBars.length){const t=new j;e.addMasterBar(t);const s=new U;s.isLinear=!1,s.type=m.Tempo,s.value=e.tempo,t.tempoAutomations.push(s);const i=new G;e.tracks[0].staves[0].addBar(i);const a=new ee;i.addVoice(a);const r=new ze;return r.isEmpty=!0,void a.addBeat(r)}const t=new Set([K.PercussionChannel]);for(const s of e.tracks){if(1===s.staves.length&&s.staves[0].isPercussion)s.playbackInfo.primaryChannel=K.PercussionChannel,s.playbackInfo.secondaryChannel=K.PercussionChannel;else{if(s.playbackInfo.primaryChannel!==K.PercussionChannel)for(;t.has(s.playbackInfo.primaryChannel);)s.playbackInfo.primaryChannel++;if(t.add(s.playbackInfo.primaryChannel),s.playbackInfo.secondaryChannel!==K.PercussionChannel)for(;t.has(s.playbackInfo.secondaryChannel);)s.playbackInfo.secondaryChannel++;t.add(s.playbackInfo.secondaryChannel)}for(const t of s.staves){for(const e of t.bars)for(const t of e.voices)if(t.isEmpty&&0===t.beats.length){const e=new ze;e.isEmpty=!0,t.addBeat(e)}const s=0===t.bars.length?1:t.bars[0].voices.length;for(;t.bars.length<e.masterBars.length;){const e=new G;t.addBar(e);const i=e.previousBar;i&&(e.clef=i.clef,e.clefOttava=i.clefOttava,e.keySignature=e.previousBar.keySignature,e.keySignatureType=e.previousBar.keySignatureType);for(let t=0;t<s;t++){const t=new ee;e.addVoice(t);const s=new ze;s.isEmpty=!0,t.addBeat(s)}}}}}}var ae,re,ne,oe,he,le,ce,de,ue,pe,ge,me,fe,ye,be,Se,_e,we,Be,ke,Te,Ne,xe,ve,Pe,Fe,Ce;ie.TuningLetters=new Set([67,68,69,70,71,65,66,99,100,101,102,103,97,98,35]),ie.accidentalModeMapping=new Map([["default",N.Default],["d",N.Default],["forcenone",N.ForceNone],["-",N.ForceNone],["forcenatural",N.ForceNatural],["n",N.ForceNatural],["forcesharp",N.ForceSharp],["#",N.ForceSharp],["forcedoublesharp",N.ForceDoubleSharp],["##",N.ForceDoubleSharp],["x",N.ForceDoubleSharp],["forceflat",N.ForceFlat],["b",N.ForceFlat],["forcedoubleflat",N.ForceDoubleFlat],["bb",N.ForceDoubleFlat]]),function(e){e[e.None=0]="None",e[e.Up=1]="Up",e[e.Down=2]="Down"}(ae||(ae={})),function(e){e[e.None=-1]="None",e[e.Space=32]="Space",e[e.Brace=57344]="Brace",e[e.BracketTop=57347]="BracketTop",e[e.BracketBottom=57348]="BracketBottom",e[e.SystemDivider=57351]="SystemDivider",e[e.GClef=57424]="GClef",e[e.CClef=57436]="CClef",e[e.FClef=57442]="FClef",e[e.UnpitchedPercussionClef1=57449]="UnpitchedPercussionClef1",e[e.SixStringTabClef=57453]="SixStringTabClef",e[e.FourStringTabClef=57454]="FourStringTabClef",e[e.TimeSig0=57472]="TimeSig0",e[e.TimeSig1=57473]="TimeSig1",e[e.TimeSig2=57474]="TimeSig2",e[e.TimeSig3=57475]="TimeSig3",e[e.TimeSig4=57476]="TimeSig4",e[e.TimeSig5=57477]="TimeSig5",e[e.TimeSig6=57478]="TimeSig6",e[e.TimeSig7=57479]="TimeSig7",e[e.TimeSig8=57480]="TimeSig8",e[e.TimeSig9=57481]="TimeSig9",e[e.TimeSigCommon=57482]="TimeSigCommon",e[e.TimeSigCutCommon=57483]="TimeSigCutCommon",e[e.NoteheadDoubleWholeSquare=57505]="NoteheadDoubleWholeSquare",e[e.NoteheadDoubleWhole=57504]="NoteheadDoubleWhole",e[e.NoteheadWhole=57506]="NoteheadWhole",e[e.NoteheadHalf=57507]="NoteheadHalf",e[e.NoteheadBlack=57508]="NoteheadBlack",e[e.NoteheadNull=57509]="NoteheadNull",e[e.NoteheadXOrnate=57514]="NoteheadXOrnate",e[e.NoteheadPlusDoubleWhole=57516]="NoteheadPlusDoubleWhole",e[e.NoteheadPlusWhole=57517]="NoteheadPlusWhole",e[e.NoteheadPlusHalf=57518]="NoteheadPlusHalf",e[e.NoteheadPlusBlack=57519]="NoteheadPlusBlack",e[e.NoteheadSquareWhite=57528]="NoteheadSquareWhite",e[e.NoteheadSquareBlack=57529]="NoteheadSquareBlack",e[e.NoteheadTriangleUpDoubleWhole=57530]="NoteheadTriangleUpDoubleWhole",e[e.NoteheadTriangleUpWhole=57531]="NoteheadTriangleUpWhole",e[e.NoteheadTriangleUpHalf=57532]="NoteheadTriangleUpHalf",e[e.NoteheadTriangleUpBlack=57534]="NoteheadTriangleUpBlack",e[e.NoteheadTriangleRightWhite=57537]="NoteheadTriangleRightWhite",e[e.NoteheadTriangleRightBlack=57538]="NoteheadTriangleRightBlack",e[e.NoteheadTriangleDownDoubleWhole=57548]="NoteheadTriangleDownDoubleWhole",e[e.NoteheadTriangleDownWhole=57540]="NoteheadTriangleDownWhole",e[e.NoteheadTriangleDownHalf=57541]="NoteheadTriangleDownHalf",e[e.NoteheadTriangleDownBlack=57543]="NoteheadTriangleDownBlack",e[e.NoteheadDiamondDoubleWhole=57559]="NoteheadDiamondDoubleWhole",e[e.NoteheadDiamondWhole=57560]="NoteheadDiamondWhole",e[e.NoteheadDiamondHalf=57561]="NoteheadDiamondHalf",e[e.NoteheadDiamondBlack=57563]="NoteheadDiamondBlack",e[e.NoteheadDiamondBlackWide=57564]="NoteheadDiamondBlackWide",e[e.NoteheadDiamondWhite=57565]="NoteheadDiamondWhite",e[e.NoteheadDiamondWhiteWide=57566]="NoteheadDiamondWhiteWide",e[e.NoteheadCircleXDoubleWhole=57520]="NoteheadCircleXDoubleWhole",e[e.NoteheadCircleXWhole=57521]="NoteheadCircleXWhole",e[e.NoteheadCircleXHalf=57522]="NoteheadCircleXHalf",e[e.NoteheadCircleX=57523]="NoteheadCircleX",e[e.NoteheadXDoubleWhole=57510]="NoteheadXDoubleWhole",e[e.NoteheadXWhole=57511]="NoteheadXWhole",e[e.NoteheadXHalf=57512]="NoteheadXHalf",e[e.NoteheadXBlack=57513]="NoteheadXBlack",e[e.NoteheadParenthesis=57550]="NoteheadParenthesis",e[e.NoteheadSlashedBlack1=57551]="NoteheadSlashedBlack1",e[e.NoteheadSlashedBlack2=57552]="NoteheadSlashedBlack2",e[e.NoteheadSlashedHalf1=57553]="NoteheadSlashedHalf1",e[e.NoteheadSlashedHalf2=57554]="NoteheadSlashedHalf2",e[e.NoteheadSlashedWhole1=57555]="NoteheadSlashedWhole1",e[e.NoteheadSlashedWhole2=57556]="NoteheadSlashedWhole2",e[e.NoteheadSlashedDoubleWhole1=57557]="NoteheadSlashedDoubleWhole1",e[e.NoteheadSlashedDoubleWhole2=57558]="NoteheadSlashedDoubleWhole2",e[e.NoteheadCircledBlack=57572]="NoteheadCircledBlack",e[e.NoteheadCircledHalf=57573]="NoteheadCircledHalf",e[e.NoteheadCircledWhole=57574]="NoteheadCircledWhole",e[e.NoteheadCircledDoubleWhole=57575]="NoteheadCircledDoubleWhole",e[e.NoteheadCircleSlash=57591]="NoteheadCircleSlash",e[e.NoteheadHeavyX=57592]="NoteheadHeavyX",e[e.NoteheadHeavyXHat=57593]="NoteheadHeavyXHat",e[e.NoteheadSlashVerticalEnds=57600]="NoteheadSlashVerticalEnds",e[e.NoteheadSlashWhiteWhole=57602]="NoteheadSlashWhiteWhole",e[e.NoteheadSlashWhiteHalf=57603]="NoteheadSlashWhiteHalf",e[e.NoteheadRoundWhiteWithDot=57621]="NoteheadRoundWhiteWithDot",e[e.NoteheadSquareBlackLarge=57626]="NoteheadSquareBlackLarge",e[e.NoteheadSquareBlackWhite=57627]="NoteheadSquareBlackWhite",e[e.NoteheadClusterDoubleWhole3rd=57640]="NoteheadClusterDoubleWhole3rd",e[e.NoteheadClusterWhole3rd=57641]="NoteheadClusterWhole3rd",e[e.NoteheadClusterHalf3rd=57642]="NoteheadClusterHalf3rd",e[e.NoteheadClusterQuarter3rd=57643]="NoteheadClusterQuarter3rd",e[e.NoteShapeRoundWhite=57776]="NoteShapeRoundWhite",e[e.NoteShapeRoundBlack=57777]="NoteShapeRoundBlack",e[e.NoteShapeSquareWhite=57778]="NoteShapeSquareWhite",e[e.NoteShapeSquareBlack=57779]="NoteShapeSquareBlack",e[e.NoteShapeTriangleRightWhite=57780]="NoteShapeTriangleRightWhite",e[e.NoteShapeTriangleRightBlack=57781]="NoteShapeTriangleRightBlack",e[e.NoteShapeTriangleLeftWhite=57782]="NoteShapeTriangleLeftWhite",e[e.NoteShapeTriangleLeftBlack=57783]="NoteShapeTriangleLeftBlack",e[e.NoteShapeDiamondWhite=57784]="NoteShapeDiamondWhite",e[e.NoteShapeDiamondBlack=57785]="NoteShapeDiamondBlack",e[e.NoteShapeTriangleUpWhite=57786]="NoteShapeTriangleUpWhite",e[e.NoteShapeTriangleUpBlack=57787]="NoteShapeTriangleUpBlack",e[e.NoteShapeMoonWhite=57788]="NoteShapeMoonWhite",e[e.NoteShapeMoonBlack=57789]="NoteShapeMoonBlack",e[e.NoteShapeTriangleRoundWhite=57790]="NoteShapeTriangleRoundWhite",e[e.NoteShapeTriangleRoundBlack=57791]="NoteShapeTriangleRoundBlack",e[e.NoteQuarterUp=57813]="NoteQuarterUp",e[e.NoteEighthUp=57815]="NoteEighthUp",e[e.TextBlackNoteLongStem=57841]="TextBlackNoteLongStem",e[e.TextBlackNoteFrac8thLongStem=57843]="TextBlackNoteFrac8thLongStem",e[e.TextBlackNoteFrac16thLongStem=57845]="TextBlackNoteFrac16thLongStem",e[e.TextBlackNoteFrac32ndLongStem=57846]="TextBlackNoteFrac32ndLongStem",e[e.TextCont8thBeamLongStem=57848]="TextCont8thBeamLongStem",e[e.TextCont16thBeamLongStem=57850]="TextCont16thBeamLongStem",e[e.TextCont32ndBeamLongStem=57851]="TextCont32ndBeamLongStem",e[e.TextAugmentationDot=57852]="TextAugmentationDot",e[e.TextTupletBracketStartLongStem=57857]="TextTupletBracketStartLongStem",e[e.TextTuplet3LongStem=57858]="TextTuplet3LongStem",e[e.TextTupletBracketEndLongStem=57859]="TextTupletBracketEndLongStem",e[e.Tremolo3=57890]="Tremolo3",e[e.Tremolo2=57889]="Tremolo2",e[e.Tremolo1=57888]="Tremolo1",e[e.FlagEighthUp=57920]="FlagEighthUp",e[e.FlagEighthDown=57921]="FlagEighthDown",e[e.FlagSixteenthUp=57922]="FlagSixteenthUp",e[e.FlagSixteenthDown=57923]="FlagSixteenthDown",e[e.FlagThirtySecondUp=57924]="FlagThirtySecondUp",e[e.FlagThirtySecondDown=57925]="FlagThirtySecondDown",e[e.FlagSixtyFourthUp=57926]="FlagSixtyFourthUp",e[e.FlagSixtyFourthDown=57927]="FlagSixtyFourthDown",e[e.FlagOneHundredTwentyEighthUp=57928]="FlagOneHundredTwentyEighthUp",e[e.FlagOneHundredTwentyEighthDown=57929]="FlagOneHundredTwentyEighthDown",e[e.FlagTwoHundredFiftySixthUp=57930]="FlagTwoHundredFiftySixthUp",e[e.FlagTwoHundredFiftySixthDown=57931]="FlagTwoHundredFiftySixthDown",e[e.AccidentalFlat=57952]="AccidentalFlat",e[e.AccidentalNatural=57953]="AccidentalNatural",e[e.AccidentalSharp=57954]="AccidentalSharp",e[e.AccidentalDoubleSharp=57955]="AccidentalDoubleSharp",e[e.AccidentalDoubleFlat=57956]="AccidentalDoubleFlat",e[e.AccidentalQuarterToneFlatArrowUp=57968]="AccidentalQuarterToneFlatArrowUp",e[e.AccidentalQuarterToneSharpArrowUp=57972]="AccidentalQuarterToneSharpArrowUp",e[e.AccidentalQuarterToneNaturalArrowUp=57970]="AccidentalQuarterToneNaturalArrowUp",e[e.Segno=57415]="Segno",e[e.Coda=57416]="Coda",e[e.ArticAccentAbove=58528]="ArticAccentAbove",e[e.ArticAccentBelow=58529]="ArticAccentBelow",e[e.ArticStaccatoAbove=58530]="ArticStaccatoAbove",e[e.ArticStaccatoBelow=58531]="ArticStaccatoBelow",e[e.ArticTenutoAbove=58532]="ArticTenutoAbove",e[e.ArticTenutoBelow=58533]="ArticTenutoBelow",e[e.ArticMarcatoAbove=58540]="ArticMarcatoAbove",e[e.ArticMarcatoBelow=58541]="ArticMarcatoBelow",e[e.FermataAbove=58560]="FermataAbove",e[e.FermataShortAbove=58564]="FermataShortAbove",e[e.FermataLongAbove=58566]="FermataLongAbove",e[e.RestLonga=58593]="RestLonga",e[e.RestDoubleWhole=58594]="RestDoubleWhole",e[e.RestWhole=58595]="RestWhole",e[e.RestHalf=58596]="RestHalf",e[e.RestQuarter=58597]="RestQuarter",e[e.RestEighth=58598]="RestEighth",e[e.RestSixteenth=58599]="RestSixteenth",e[e.RestThirtySecond=58600]="RestThirtySecond",e[e.RestSixtyFourth=58601]="RestSixtyFourth",e[e.RestOneHundredTwentyEighth=58602]="RestOneHundredTwentyEighth",e[e.RestTwoHundredFiftySixth=58603]="RestTwoHundredFiftySixth",e[e.RestHBarLeft=58607]="RestHBarLeft",e[e.RestHBarMiddle=58608]="RestHBarMiddle",e[e.RestHBarRight=58609]="RestHBarRight",e[e.Repeat1Bar=58624]="Repeat1Bar",e[e.Repeat2Bars=58625]="Repeat2Bars",e[e.Ottava=58640]="Ottava",e[e.OttavaAlta=58641]="OttavaAlta",e[e.OttavaBassaVb=58652]="OttavaBassaVb",e[e.Quindicesima=58644]="Quindicesima",e[e.QuindicesimaAlta=58645]="QuindicesimaAlta",e[e.DynamicPPPPPP=58663]="DynamicPPPPPP",e[e.DynamicPPPPP=58664]="DynamicPPPPP",e[e.DynamicPPPP=58665]="DynamicPPPP",e[e.DynamicPPP=58666]="DynamicPPP",e[e.DynamicPP=58667]="DynamicPP",e[e.DynamicPiano=58656]="DynamicPiano",e[e.DynamicMP=58668]="DynamicMP",e[e.DynamicMF=58669]="DynamicMF",e[e.DynamicPF=58670]="DynamicPF",e[e.DynamicForte=58658]="DynamicForte",e[e.DynamicFF=58671]="DynamicFF",e[e.DynamicFFF=58672]="DynamicFFF",e[e.DynamicFFFF=58673]="DynamicFFFF",e[e.DynamicFFFFF=58674]="DynamicFFFFF",e[e.DynamicFFFFFF=58675]="DynamicFFFFFF",e[e.DynamicFortePiano=58676]="DynamicFortePiano",e[e.DynamicNiente=58662]="DynamicNiente",e[e.DynamicSforzando1=58678]="DynamicSforzando1",e[e.DynamicSforzandoPiano=58679]="DynamicSforzandoPiano",e[e.DynamicSforzandoPianissimo=58680]="DynamicSforzandoPianissimo",e[e.DynamicSforzato=58681]="DynamicSforzato",e[e.DynamicSforzatoPiano=58682]="DynamicSforzatoPiano",e[e.DynamicSforzatoFF=58683]="DynamicSforzatoFF",e[e.DynamicRinforzando1=58684]="DynamicRinforzando1",e[e.DynamicRinforzando2=58685]="DynamicRinforzando2",e[e.DynamicForzando=58677]="DynamicForzando",e[e.OrnamentTrill=58726]="OrnamentTrill",e[e.OrnamentTurn=58727]="OrnamentTurn",e[e.OrnamentTurnInverted=58728]="OrnamentTurnInverted",e[e.OrnamentShortTrill=58732]="OrnamentShortTrill",e[e.OrnamentMordent=58733]="OrnamentMordent",e[e.StringsDownBow=58896]="StringsDownBow",e[e.StringsUpBow=58898]="StringsUpBow",e[e.KeyboardPedalPed=58960]="KeyboardPedalPed",e[e.KeyboardPedalUp=58965]="KeyboardPedalUp",e[e.PictEdgeOfCymbal=59177]="PictEdgeOfCymbal",e[e.GuitarString0=59443]="GuitarString0",e[e.GuitarString1=59444]="GuitarString1",e[e.GuitarString2=59445]="GuitarString2",e[e.GuitarString3=59446]="GuitarString3",e[e.GuitarString4=59447]="GuitarString4",e[e.GuitarString5=59448]="GuitarString5",e[e.GuitarString6=59449]="GuitarString6",e[e.GuitarString7=59450]="GuitarString7",e[e.GuitarString8=59451]="GuitarString8",e[e.GuitarString9=59452]="GuitarString9",e[e.GuitarOpenPedal=59453]="GuitarOpenPedal",e[e.GuitarClosePedal=59455]="GuitarClosePedal",e[e.GuitarGolpe=59458]="GuitarGolpe",e[e.GuitarFadeIn=59459]="GuitarFadeIn",e[e.GuitarFadeOut=59460]="GuitarFadeOut",e[e.GuitarVolumeSwell=59461]="GuitarVolumeSwell",e[e.FretboardX=59481]="FretboardX",e[e.FretboardO=59482]="FretboardO",e[e.WiggleTrill=60068]="WiggleTrill",e[e.WiggleVibratoMediumFast=60126]="WiggleVibratoMediumFast",e[e.OctaveBaselineM=60565]="OctaveBaselineM",e[e.OctaveBaselineB=60563]="OctaveBaselineB"}(re||(re={})),function(e){e[e.Left=0]="Left",e[e.Center=1]="Center",e[e.Right=2]="Right"}(ne||(ne={})),function(e){e[e.Top=0]="Top",e[e.Middle=1]="Middle",e[e.Bottom=2]="Bottom"}(oe||(oe={}));class De{constructor(e,t){this.width=e,this.height=t}}class Ee{constructor(e="",t=0,s=0,i=re.None,a=re.None,r=re.None,n=re.None,o=oe.Middle){this.elementType=e,this.outputMidiNumber=s,this.staffLine=t,this.noteHeadDefault=i,this.noteHeadHalf=a!==re.None?a:i,this.noteHeadWhole=r!==re.None?r:i,this.techniqueSymbol=n,this.techniqueSymbolPlacement=o}getSymbol(e){switch(e){case _.Whole:return this.noteHeadWhole;case _.Half:return this.noteHeadHalf;default:return this.noteHeadDefault}}}class Le{static articulationFromElementVariation(e,t){return e<Le.gp6ElementAndVariationToArticulation.length?(t>=Le.gp6ElementAndVariationToArticulation.length&&(t=0),Le.gp6ElementAndVariationToArticulation[e][t]):38}static getArticulation(e){const t=e.percussionArticulation;if(t<0)return null;const s=e.beat.voice.bar.staff.track.percussionArticulations;return t<s.length?s[t]:Le.getArticulationByInputMidiNumber(t)}static getElementAndVariation(e){const t=Le.getArticulation(e);if(!t)return[-1,-1];for(let e=0;e<Le.gp6ElementAndVariationToArticulation.length;e++){const s=Le.gp6ElementAndVariationToArticulation[e];for(let i=0;i<s.length;i++){const a=Le.getArticulationByInputMidiNumber(s[i]);if(a?.outputMidiNumber===t.outputMidiNumber)return[e,i]}}return[-1,-1]}static getArticulationByInputMidiNumber(e){return Le.instrumentArticulations.has(e)?Le.instrumentArticulations.get(e):null}}Le.gp6ElementAndVariationToArticulation=[[35,35,35],[38,91,37],[99,100,99],[56,100,56],[102,103,102],[43,43,43],[45,45,45],[47,47,47],[48,48,48],[50,50,50],[42,92,46],[44,44,44],[57,98,57],[49,97,49],[55,95,55],[51,93,127],[52,96,52]],Le.instrumentArticulations=new Map([[38,new Ee("snare",3,38,re.NoteheadBlack,re.NoteheadHalf,re.NoteheadWhole)],[37,new Ee("snare",3,37,re.NoteheadXBlack,re.NoteheadXBlack,re.NoteheadXBlack)],[91,new Ee("snare",3,38,re.NoteheadDiamondWhite,re.NoteheadDiamondWhite,re.NoteheadDiamondWhite)],[42,new Ee("hiHat",-1,42,re.NoteheadXBlack,re.NoteheadXBlack,re.NoteheadXBlack)],[92,new Ee("hiHat",-1,46,re.NoteheadCircleSlash,re.NoteheadCircleSlash,re.NoteheadCircleSlash)],[46,new Ee("hiHat",-1,46,re.NoteheadCircleX,re.NoteheadCircleX,re.NoteheadCircleX)],[44,new Ee("hiHat",9,44,re.NoteheadXBlack,re.NoteheadXBlack,re.NoteheadXBlack)],[35,new Ee("kickDrum",8,35,re.NoteheadBlack,re.NoteheadHalf,re.NoteheadWhole)],[36,new Ee("kickDrum",7,36,re.NoteheadBlack,re.NoteheadHalf,re.NoteheadWhole)],[50,new Ee("tom",1,50,re.NoteheadBlack,re.NoteheadHalf,re.NoteheadWhole)],[48,new Ee("tom",2,48,re.NoteheadBlack,re.NoteheadHalf,re.NoteheadWhole)],[47,new Ee("tom",4,47,re.NoteheadBlack,re.NoteheadHalf,re.NoteheadWhole)],[45,new Ee("tom",5,45,re.NoteheadBlack,re.NoteheadHalf,re.NoteheadWhole)],[43,new Ee("tom",6,43,re.NoteheadBlack,re.NoteheadHalf,re.NoteheadWhole)],[93,new Ee("ride",0,51,re.NoteheadXBlack,re.NoteheadXBlack,re.NoteheadXBlack,re.PictEdgeOfCymbal,oe.Bottom)],[51,new Ee("ride",0,51,re.NoteheadXBlack,re.NoteheadXBlack,re.NoteheadXBlack)],[53,new Ee("ride",0,53,re.NoteheadDiamondWhite,re.NoteheadDiamondWhite,re.NoteheadDiamondWhite)],[94,new Ee("ride",0,51,re.NoteheadXBlack,re.NoteheadXBlack,re.NoteheadXBlack,re.ArticStaccatoAbove,oe.Top)],[55,new Ee("splash",-2,55,re.NoteheadXBlack,re.NoteheadXBlack,re.NoteheadXBlack)],[95,new Ee("splash",-2,55,re.NoteheadXBlack,re.NoteheadXBlack,re.NoteheadXBlack,re.ArticStaccatoAbove,oe.Bottom)],[52,new Ee("china",-3,52,re.NoteheadHeavyXHat,re.NoteheadHeavyXHat,re.NoteheadHeavyXHat)],[96,new Ee("china",-3,52,re.NoteheadHeavyXHat,re.NoteheadHeavyXHat,re.NoteheadHeavyXHat)],[49,new Ee("crash",-2,49,re.NoteheadHeavyX,re.NoteheadHeavyX,re.NoteheadHeavyX)],[97,new Ee("crash",-2,49,re.NoteheadHeavyX,re.NoteheadHeavyX,re.NoteheadHeavyX,re.ArticStaccatoAbove,oe.Bottom)],[57,new Ee("crash",-1,57,re.NoteheadHeavyX,re.NoteheadHeavyX,re.NoteheadHeavyX)],[98,new Ee("crash",-1,57,re.NoteheadHeavyX,re.NoteheadHeavyX,re.NoteheadHeavyX,re.ArticStaccatoAbove,oe.Bottom)],[99,new Ee("cowbell",1,56,re.NoteheadTriangleUpBlack,re.NoteheadTriangleUpHalf,re.NoteheadTriangleUpWhole)],[100,new Ee("cowbell",1,56,re.NoteheadXBlack,re.NoteheadXHalf,re.NoteheadXWhole)],[56,new Ee("cowbell",0,56,re.NoteheadTriangleUpBlack,re.NoteheadTriangleUpHalf,re.NoteheadTriangleUpWhole)],[101,new Ee("cowbell",0,56,re.NoteheadXBlack,re.NoteheadXHalf,re.NoteheadXWhole)],[102,new Ee("cowbell",-1,56,re.NoteheadTriangleUpBlack,re.NoteheadTriangleUpHalf,re.NoteheadTriangleUpWhole)],[103,new Ee("cowbell",-1,56,re.NoteheadXBlack,re.NoteheadXHalf,re.NoteheadXWhole)],[77,new Ee("woodblock",-9,77,re.NoteheadTriangleUpBlack,re.NoteheadTriangleUpBlack,re.NoteheadTriangleUpBlack)],[76,new Ee("woodblock",-10,76,re.NoteheadTriangleUpBlack,re.NoteheadTriangleUpBlack,re.NoteheadTriangleUpBlack)],[60,new Ee("bongo",-4,60,re.NoteheadBlack,re.NoteheadHalf,re.NoteheadWhole)],[104,new Ee("bongo",-5,60,re.NoteheadBlack,re.NoteheadHalf,re.NoteheadWhole,re.NoteheadParenthesis,oe.Middle)],[105,new Ee("bongo",-6,60,re.NoteheadXBlack,re.NoteheadXBlack,re.NoteheadXBlack)],[61,new Ee("bongo",-7,61,re.NoteheadBlack,re.NoteheadHalf,re.NoteheadWhole)],[106,new Ee("bongo",-8,61,re.NoteheadBlack,re.NoteheadHalf,re.NoteheadWhole,re.NoteheadParenthesis,oe.Middle)],[107,new Ee("bongo",-16,61,re.NoteheadXBlack,re.NoteheadXBlack,re.NoteheadXBlack)],[66,new Ee("timbale",10,66,re.NoteheadBlack,re.NoteheadHalf,re.NoteheadWhole)],[65,new Ee("timbale",9,65,re.NoteheadBlack,re.NoteheadHalf,re.NoteheadWhole)],[68,new Ee("agogo",12,68,re.NoteheadBlack,re.NoteheadHalf,re.NoteheadWhole)],[67,new Ee("agogo",11,67,re.NoteheadBlack,re.NoteheadHalf,re.NoteheadWhole)],[64,new Ee("conga",17,64,re.NoteheadBlack,re.NoteheadHalf,re.NoteheadWhole)],[108,new Ee("conga",16,64,re.NoteheadXBlack,re.NoteheadXBlack,re.NoteheadXBlack)],[109,new Ee("conga",15,64,re.NoteheadBlack,re.NoteheadHalf,re.NoteheadWhole,re.NoteheadParenthesis,oe.Middle)],[63,new Ee("conga",14,63,re.NoteheadBlack,re.NoteheadHalf,re.NoteheadWhole)],[110,new Ee("conga",13,63,re.NoteheadXBlack,re.NoteheadXBlack,re.NoteheadXBlack)],[62,new Ee("conga",19,62,re.NoteheadBlack,re.NoteheadHalf,re.NoteheadWhole,re.NoteheadParenthesis,oe.Middle)],[72,new Ee("whistle",-11,72,re.NoteheadBlack,re.NoteheadHalf,re.NoteheadWhole)],[71,new Ee("whistle",-17,71,re.NoteheadBlack,re.NoteheadHalf,re.NoteheadWhole)],[73,new Ee("guiro",38,73,re.NoteheadBlack,re.NoteheadHalf,re.NoteheadWhole)],[74,new Ee("guiro",37,74,re.NoteheadBlack,re.NoteheadHalf,re.NoteheadWhole)],[86,new Ee("surdo",36,86,re.NoteheadBlack,re.NoteheadHalf,re.NoteheadWhole)],[87,new Ee("surdo",35,87,re.NoteheadXBlack,re.NoteheadXBlack,re.NoteheadXBlack,re.NoteheadParenthesis,oe.Middle)],[54,new Ee("tambourine",3,54,re.NoteheadTriangleUpBlack,re.NoteheadTriangleUpBlack,re.NoteheadTriangleUpBlack)],[111,new Ee("tambourine",2,54,re.NoteheadTriangleUpBlack,re.NoteheadTriangleUpBlack,re.NoteheadTriangleUpBlack,re.StringsUpBow,oe.Bottom)],[112,new Ee("tambourine",1,54,re.NoteheadTriangleUpBlack,re.NoteheadTriangleUpBlack,re.NoteheadTriangleUpBlack,re.StringsDownBow,oe.Bottom)],[113,new Ee("tambourine",-7,54,re.NoteheadXBlack,re.NoteheadXBlack,re.NoteheadXBlack)],[79,new Ee("cuica",30,79,re.NoteheadBlack,re.NoteheadHalf,re.NoteheadWhole)],[78,new Ee("cuica",29,78,re.NoteheadXBlack,re.NoteheadXBlack,re.NoteheadXBlack)],[58,new Ee("vibraslap",28,58,re.NoteheadBlack,re.NoteheadHalf,re.NoteheadWhole)],[81,new Ee("triangle",27,81,re.NoteheadBlack,re.NoteheadHalf,re.NoteheadWhole)],[80,new Ee("triangle",26,80,re.NoteheadXBlack,re.NoteheadXBlack,re.NoteheadXBlack,re.NoteheadParenthesis,oe.Middle)],[114,new Ee("grancassa",25,43,re.NoteheadBlack,re.NoteheadHalf,re.NoteheadWhole)],[115,new Ee("piatti",18,49,re.NoteheadBlack,re.NoteheadHalf,re.NoteheadWhole)],[116,new Ee("piatti",24,49,re.NoteheadXBlack,re.NoteheadXBlack,re.NoteheadXBlack)],[69,new Ee("cabasa",23,69,re.NoteheadBlack,re.NoteheadHalf,re.NoteheadWhole)],[117,new Ee("cabasa",22,69,re.NoteheadBlack,re.NoteheadHalf,re.NoteheadWhole,re.StringsUpBow,oe.Bottom)],[85,new Ee("castanets",21,85,re.NoteheadBlack,re.NoteheadHalf,re.NoteheadWhole)],[75,new Ee("claves",20,75,re.NoteheadBlack,re.NoteheadHalf,re.NoteheadWhole)],[70,new Ee("maraca",-12,70,re.NoteheadBlack,re.NoteheadHalf,re.NoteheadWhole)],[118,new Ee("maraca",-13,70,re.NoteheadBlack,re.NoteheadHalf,re.NoteheadWhole,re.StringsUpBow,oe.Bottom)],[119,new Ee("maraca",-14,70,re.NoteheadBlack,re.NoteheadHalf,re.NoteheadWhole)],[120,new Ee("maraca",-15,70,re.NoteheadBlack,re.NoteheadHalf,re.NoteheadWhole,re.StringsUpBow,oe.Bottom)],[82,new Ee("shaker",-23,54,re.NoteheadBlack,re.NoteheadHalf,re.NoteheadWhole)],[122,new Ee("shaker",-24,54,re.NoteheadBlack,re.NoteheadHalf,re.NoteheadWhole,re.StringsUpBow,oe.Bottom)],[84,new Ee("bellTree",-18,53,re.NoteheadBlack,re.NoteheadHalf,re.NoteheadWhole)],[123,new Ee("bellTree",-19,53,re.NoteheadBlack,re.NoteheadHalf,re.NoteheadWhole,re.StringsUpBow,oe.Bottom)],[83,new Ee("jingleBell",-20,53,re.NoteheadBlack,re.NoteheadHalf,re.NoteheadWhole)],[124,new Ee("unpitched",-21,62,re.NoteheadNull,re.NoteheadNull,re.NoteheadNull,re.GuitarGolpe,oe.Top)],[125,new Ee("unpitched",-22,62,re.NoteheadNull,re.NoteheadNull,re.NoteheadNull,re.GuitarGolpe,oe.Bottom)],[39,new Ee("handClap",3,39,re.NoteheadBlack,re.NoteheadHalf,re.NoteheadWhole)],[40,new Ee("snare",3,40,re.NoteheadBlack,re.NoteheadHalf,re.NoteheadWhole)],[31,new Ee("snare",3,40,re.NoteheadSlashedBlack2,re.NoteheadSlashedBlack2,re.NoteheadSlashedBlack2)],[41,new Ee("tom",5,41,re.NoteheadBlack,re.NoteheadHalf,re.NoteheadWhole)],[59,new Ee("ride",2,59,re.NoteheadXBlack,re.NoteheadXBlack,re.NoteheadXBlack,re.PictEdgeOfCymbal,oe.Bottom)],[126,new Ee("ride",2,59,re.NoteheadXBlack,re.NoteheadXBlack,re.NoteheadXBlack)],[127,new Ee("ride",2,59,re.NoteheadDiamondWhite,re.NoteheadDiamondWhite,re.NoteheadDiamondWhite)],[29,new Ee("ride",2,59,re.NoteheadXBlack,re.NoteheadXBlack,re.NoteheadXBlack,re.ArticStaccatoAbove,oe.Top)],[30,new Ee("crash",-3,49,re.NoteheadXBlack,re.NoteheadXBlack,re.NoteheadXBlack)],[33,new Ee("snare",3,37,re.NoteheadXBlack,re.NoteheadXBlack,re.NoteheadXBlack)],[34,new Ee("snare",3,38,re.NoteheadBlack,re.NoteheadBlack,re.NoteheadBlack)]]),Le.instrumentArticulationNames=new Map([["Ride (choke)",29],["Cymbal (hit)",30],["Snare (side stick)",31],["Snare (side stick) 2",33],["Snare (hit)",34],["Kick (hit)",35],["Kick (hit) 2",36],["Snare (side stick) 3",37],["Snare (hit) 2",38],["Hand Clap (hit)",39],["Snare (hit) 3",40],["Low Floor Tom (hit)",41],["Hi-Hat (closed)",42],["Very Low Tom (hit)",43],["Pedal Hi-Hat (hit)",44],["Low Tom (hit)",45],["Hi-Hat (open)",46],["Mid Tom (hit)",47],["High Tom (hit)",48],["Crash high (hit)",49],["High Floor Tom (hit)",50],["Ride (middle)",51],["China (hit)",52],["Ride (bell)",53],["Tambourine (hit)",54],["Splash (hit)",55],["Cowbell medium (hit)",56],["Crash medium (hit)",57],["Vibraslap (hit)",58],["Ride (edge)",59],["Hand (hit)",60],["Hand (hit)",61],["Conga high (mute)",62],["Conga high (hit)",63],["Conga low (hit)",64],["Timbale high (hit)",65],["Timbale low (hit)",66],["Agogo high (hit)",67],["Agogo tow (hit)",68],["Cabasa (hit)",69],["Left Maraca (hit)",70],["Whistle high (hit)",71],["Whistle low (hit)",72],["Guiro (hit)",73],["Guiro (scrap-return)",74],["Claves (hit)",75],["Woodblock high (hit)",76],["Woodblock low (hit)",77],["Cuica (mute)",78],["Cuica (open)",79],["Triangle (rnute)",80],["Triangle (hit)",81],["Shaker (hit)",82],["Tinkle Bell (hat)",83],["Jingle Bell (hit)",83],["Bell Tree (hit)",84],["Castanets (hit)",85],["Surdo (hit)",86],["Surdo (mute)",87],["Snare (rim shot)",91],["Hi-Hat (half)",92],["Ride (edge) 2",93],["Ride (choke) 2",94],["Splash (choke)",95],["China (choke)",96],["Crash high (choke)",97],["Crash medium (choke)",98],["Cowbell low (hit)",99],["Cowbell low (tip)",100],["Cowbell medium (tip)",101],["Cowbell high (hit)",102],["Cowbell high (tip)",103],["Hand (mute)",104],["Hand (slap)",105],["Hand (mute) 2",106],["Hand (slap) 2",107],["Conga low (slap)",108],["Conga low (mute)",109],["Conga high (slap)",110],["Tambourine (return)",111],["Tambourine (roll)",112],["Tambourine (hand)",113],["Grancassa (hit)",114],["Piatti (hat)",115],["Piatti (hand)",116],["Cabasa (return)",117],["Left Maraca (return)",118],["Right Maraca (hit)",119],["Right Maraca (return)",120],["Shaker (return)",122],["Bell Tee (return)",123],["Golpe (thumb)",124],["Golpe (finger)",125],["Ride (middle) 2",126],["Ride (bell) 2",127]]),function(e){e[e.None=0]="None",e[e.InvertedTurn=1]="InvertedTurn",e[e.Turn=2]="Turn",e[e.UpperMordent=3]="UpperMordent",e[e.LowerMordent=4]="LowerMordent"}(he||(he={}));class Me{constructor(){this.tieDestinationNoteId=-1,this.tieOriginNoteId=-1,this.slurDestinationNoteId=-1,this.slurOriginNoteId=-1,this.hammerPullDestinationNoteId=-1,this.hammerPullOriginNoteId=-1,this.slideTargetNoteId=-1,this.slideOriginNoteId=-1}}!function(e){e[e.Effects=0]="Effects",e[e.StandardNotationNoteHead=1]="StandardNotationNoteHead",e[e.StandardNotationAccidentals=2]="StandardNotationAccidentals",e[e.StandardNotationEffects=3]="StandardNotationEffects",e[e.GuitarTabFretNumber=4]="GuitarTabFretNumber",e[e.GuitarTabEffects=5]="GuitarTabEffects",e[e.SlashNoteHead=6]="SlashNoteHead",e[e.SlashEffects=7]="SlashEffects",e[e.NumberedNumber=8]="NumberedNumber",e[e.NumberedAccidentals=9]="NumberedAccidentals",e[e.NumberedEffects=10]="NumberedEffects"}(le||(le={}));class Ie extends H{}class Ae{constructor(){this.id=Ae.GlobalNoteId++,this.index=0,this.accentuated=B.None,this.bendType=y.None,this.bendStyle=f.Default,this.bendOrigin=null,this.isContinuedBend=!1,this.bendPoints=null,this.maxBendPoint=null,this.fret=-1,this.string=-1,this.showStringNumber=!1,this.octave=-1,this.tone=-1,this.percussionArticulation=-1,this.isVisible=!0,this.isLeftHandTapped=!1,this.isHammerPullOrigin=!1,this.hammerPullOrigin=null,this.hammerPullDestination=null,this.isSlurDestination=!1,this.slurOrigin=null,this.slurDestination=null,this.harmonicType=T.None,this.harmonicValue=0,this.isGhost=!1,this.isLetRing=!1,this.letRingDestination=null,this.isPalmMute=!1,this.palmMuteDestination=null,this.isDead=!1,this.isStaccato=!1,this.slideInType=x.None,this.slideOutType=v.None,this.slideTarget=null,this.slideOrigin=null,this.vibrato=P.None,this.tieOrigin=null,this.tieDestination=null,this.isTieDestination=!1,this.leftHandFinger=k.Unknown,this.rightHandFinger=k.Unknown,this.trillValue=-1,this.trillSpeed=_.ThirtySecond,this.durationPercent=1,this.accidentalMode=N.Default,this.dynamics=g.F,this.isEffectSlurOrigin=!1,this.hasEffectSlur=!1,this.effectSlurOrigin=null,this.effectSlurDestination=null,this.ornament=he.None,this._noteIdBag=null}static resetIds(){Ae.GlobalNoteId=0}get hasBend(){return null!==this.bendPoints&&this.bendType!==y.None}get isStringed(){return this.string>=0}get isPiano(){return!this.isStringed&&this.octave>=0&&this.tone>=0}get isPercussion(){return!this.isStringed&&this.percussionArticulation>=0}get element(){return this.isPercussion?Le.getElementAndVariation(this)[0]:-1}get variation(){return this.isPercussion?Le.getElementAndVariation(this)[1]:-1}get isHammerPullDestination(){return!!this.hammerPullOrigin}get isSlurOrigin(){return!!this.slurDestination}get isHarmonic(){return this.harmonicType!==T.None}get isTieOrigin(){return null!==this.tieDestination}get isFingering(){return this.leftHandFinger!==k.Unknown||this.rightHandFinger!==k.Unknown}get trillFret(){return this.trillValue-this.stringTuning}get isTrill(){return this.trillValue>=0}get isEffectSlurDestination(){return!!this.effectSlurOrigin}get stringTuning(){return this.beat.voice.bar.staff.capo+Ae.getStringTuning(this.beat.voice.bar.staff,this.string)}static getStringTuning(e,t){return e.tuning.length>0?e.tuning[e.tuning.length-(t-1)-1]:0}get realValue(){return this.calculateRealValue(!0,!0)}get realValueWithoutHarmonic(){return this.calculateRealValue(!0,!1)}calculateRealValue(e,t){const s=e?this.beat.voice.bar.staff.transpositionPitch:0;if(t){let t=this.calculateRealValue(e,!1);return this.isStringed&&(this.harmonicType===T.Natural?t=this.harmonicPitch+this.stringTuning-s:t+=this.harmonicPitch),t}return this.isPercussion?this.percussionArticulation:this.isStringed?this.fret+this.stringTuning-s:this.isPiano?12*this.octave+this.tone-s:0}get harmonicPitch(){if(this.harmonicType===T.None||!this.isStringed)return 0;const e=this.harmonicValue;return ie.isAlmostEqualTo(e,2.4)?36:ie.isAlmostEqualTo(e,2.7)?34:e<3?0:e<=3.5?31:e<=4?28:e<=5?24:e<=6?34:e<=7?19:e<=8.5?36:e<=9?28:e<=10?34:e<=11?0:e<=12?12:e<14?0:e<=15?34:e<=16?28:e<=17?36:e<=18?0:e<=19?19:e<=21?0:e<=22?36:e<=24?24:0}get initialBendValue(){return this.hasBend?Math.floor(this.bendPoints[0].value/2):this.bendOrigin?Math.floor(this.bendOrigin.bendPoints[this.bendOrigin.bendPoints.length-1].value/2):this.isTieDestination&&this.tieOrigin.bendOrigin?Math.floor(this.tieOrigin.bendOrigin.bendPoints[this.tieOrigin.bendOrigin.bendPoints.length-1].value/2):this.beat.hasWhammyBar?Math.floor(this.beat.whammyBarPoints[0].value/2):this.beat.isContinuedWhammy?Math.floor(this.beat.previousBeat.whammyBarPoints[this.beat.previousBeat.whammyBarPoints.length-1].value/2):0}get displayValue(){return this.displayValueWithoutBend+this.initialBendValue}get displayValueWithoutBend(){let e=this.realValue;switch(this.harmonicType!==T.Natural&&this.harmonicType!==T.None&&(e-=this.harmonicPitch),this.beat.ottava){case o._15ma:e-=24;break;case o._8va:e-=12;break;case o.Regular:break;case o._8vb:e+=12;break;case o._15mb:e+=24}switch(this.beat.voice.bar.clefOttava){case o._15ma:e-=24;break;case o._8va:e-=12;break;case o.Regular:break;case o._8vb:e+=12;break;case o._15mb:e+=24}return e-this.beat.voice.bar.staff.displayTranspositionPitch}get hasQuarterToneOffset(){return this.hasBend?this.bendPoints[0].value%2!=0:this.bendOrigin?this.bendOrigin.bendPoints[this.bendOrigin.bendPoints.length-1].value%2!=0:this.beat.hasWhammyBar?this.beat.whammyBarPoints[0].value%2!=0:!!this.beat.isContinuedWhammy&&this.beat.previousBeat.whammyBarPoints[this.beat.previousBeat.whammyBarPoints.length-1].value%2!=0}addBendPoint(e){let t=this.bendPoints;null===t&&(t=[],this.bendPoints=t),t.push(e),(!this.maxBendPoint||e.value>this.maxBendPoint.value)&&(this.maxBendPoint=e),this.bendType===y.None&&(this.bendType=y.Custom)}finish(e,t=null){const s=new Y((()=>Ae.nextNoteOnSameLine(this))),i=e&&e.notation.notationMode===D.SongBook;if(this.isTieDestination&&(this.chain(t),i&&this.tieOrigin&&this.tieOrigin.isLetRing&&(this.isLetRing=!0)),this.isLetRing&&(s.value&&s.value.isLetRing?this.letRingDestination=s.value:this.letRingDestination=this,i&&this.isTieDestination&&!this.tieOrigin.hasBend&&(this.isVisible=!1)),this.isPalmMute&&(s.value&&s.value.isPalmMute?this.palmMuteDestination=s.value:this.palmMuteDestination=this),this.isHammerPullOrigin){const e=Ae.findHammerPullDestination(this);e?(this.hammerPullDestination=e,e.hammerPullOrigin=this):this.isHammerPullOrigin=!1}switch(this.slideOutType){case v.Shift:case v.Legato:this.slideTarget||(this.slideTarget=s.value),this.slideTarget?this.slideTarget.slideOrigin=this:this.slideOutType=v.None}let a=null;this.isHammerPullOrigin&&this.hammerPullDestination?a=this.hammerPullDestination:this.slideOutType===v.Legato&&this.slideTarget&&(a=this.slideTarget),a&&(this.hasEffectSlur=!0,this.effectSlurOrigin&&this.beat.pickStroke===ae.None?(this.effectSlurOrigin.effectSlurDestination=a,this.effectSlurOrigin.effectSlurDestination.effectSlurOrigin=this.effectSlurOrigin,this.effectSlurOrigin=null):(this.isEffectSlurOrigin=!0,this.effectSlurDestination=a,this.effectSlurDestination.effectSlurOrigin=this));const r=this.bendPoints,n=null!=r&&r.length>0;if(n){const e=this.isTieDestination&&this.tieOrigin.hasBend;this.isContinuedBend=e}else this.bendType=y.None;if(n&&this.bendType===y.Custom)if(4===r.length){const e=r[0],t=r[1],s=r[2],i=r[3];t.value===s.value?i.value>e.value?t.value>i.value?this.bendType=y.BendRelease:!this.isContinuedBend&&e.value>0?(this.bendType=y.PrebendBend,r.splice(2,1),r.splice(1,1)):(this.bendType=y.Bend,r.splice(2,1),r.splice(1,1)):i.value<e.value?this.isContinuedBend?(this.bendType=y.Release,r.splice(2,1),r.splice(1,1)):(this.bendType=y.PrebendRelease,r.splice(2,1),r.splice(1,1)):t.value>e.value?this.bendType=y.BendRelease:e.value>0&&!this.isContinuedBend?(this.bendType=y.Prebend,r.splice(2,1),r.splice(1,1)):(this.bendType=y.Hold,r.splice(2,1),r.splice(1,1)):q.warning("Model","Unsupported bend type detected, fallback to custom",null)}else if(2===r.length){const e=r[0],t=r[1];t.value>e.value?!this.isContinuedBend&&e.value>0?this.bendType=y.PrebendBend:this.bendType=y.Bend:t.value<e.value?this.isContinuedBend?this.bendType=y.Release:this.bendType=y.PrebendRelease:e.value>0&&!this.isContinuedBend?this.bendType=y.Prebend:this.bendType=y.Hold}this.initialBendValue>0&&(this.accidentalMode=N.Default)}static nextNoteOnSameLine(e){let t=e.beat.nextBeat;for(;t&&t.voice.bar.index<=e.beat.voice.bar.index+Ae.MaxOffsetForSameLineSearch;){const s=t.getNoteOnString(e.string);if(s)return s;t=t.nextBeat}return null}static findHammerPullDestination(e){let t=e.beat.nextBeat;for(;t&&t.voice.bar.index<=e.beat.voice.bar.index+Ae.MaxOffsetForSameLineSearch;){let s=t.getNoteOnString(e.string);if(s)return s;for(let i=e.string;i>0;i--)if(s=t.getNoteOnString(i),s){if(s.isLeftHandTapped)return s;break}for(let i=e.string;i<=e.beat.voice.bar.staff.tuning.length;i++)if(s=t.getNoteOnString(i),s){if(s.isLeftHandTapped)return s;break}t=t.nextBeat}return null}static findTieOrigin(e){let t=e.beat.previousBeat;for(;t&&t.voice.bar.index>=e.beat.voice.bar.index-Ae.MaxOffsetForSameLineSearch;){if(e.isStringed){const s=t.getNoteOnString(e.string);if(s)return s}else if(-1===e.octave&&-1===e.tone){if(e.index<t.notes.length)return t.notes[e.index]}else{const s=t.getNoteWithRealValue(e.realValue);if(s)return s}t=t.previousBeat}return null}chain(e=null){if(null!==e)if(null!==this._noteIdBag){let t;e.has(Ae.NoteIdLookupKey)?t=e.get(Ae.NoteIdLookupKey):(t=new Map,e.set(Ae.NoteIdLookupKey,t)),-1===this._noteIdBag.hammerPullDestinationNoteId&&-1===this._noteIdBag.tieDestinationNoteId&&-1===this._noteIdBag.slurDestinationNoteId&&-1===this._noteIdBag.slideTargetNoteId||t.set(this.id,this),-1!==this._noteIdBag.hammerPullOriginNoteId&&(this.hammerPullOrigin=t.get(this._noteIdBag.hammerPullOriginNoteId),this.hammerPullOrigin.hammerPullDestination=this),-1!==this._noteIdBag.tieOriginNoteId&&(this.tieOrigin=t.get(this._noteIdBag.tieOriginNoteId),this.tieOrigin.tieDestination=this),-1!==this._noteIdBag.slurOriginNoteId&&(this.slurOrigin=t.get(this._noteIdBag.slurOriginNoteId),this.slurOrigin.slurDestination=this),-1!==this._noteIdBag.slideOriginNoteId&&(this.slideOrigin=t.get(this._noteIdBag.slideOriginNoteId),this.slideOrigin.slideTarget=this),this._noteIdBag=null}else{if(!this.isTieDestination&&null===this.tieOrigin)return;const e=this.tieOrigin??Ae.findTieOrigin(this);e?(e.tieDestination=this,this.tieOrigin=e,this.fret=e.fret,this.octave=e.octave,this.tone=e.tone,e.hasBend&&(this.bendOrigin=this.tieOrigin)):this.isTieDestination=!1}}toJson(e){null!==this.tieDestination&&e.set("tiedestinationnoteid",this.tieDestination.id),null!==this.tieOrigin&&e.set("tieoriginnoteid",this.tieOrigin.id),null!==this.slurDestination&&e.set("slurdestinationnoteid",this.slurDestination.id),null!==this.slurOrigin&&e.set("sluroriginnoteid",this.slurOrigin.id),null!==this.hammerPullOrigin&&e.set("hammerpulloriginnoteid",this.hammerPullOrigin.id),null!==this.hammerPullDestination&&e.set("hammerpulldestinationnoteid",this.hammerPullDestination.id),null!==this.slideTarget&&e.set("slidetargetnoteid",this.slideTarget.id),null!==this.slideOrigin&&e.set("slideoriginnoteid",this.slideOrigin.id)}setProperty(e,t){switch(e){case"tiedestinationnoteid":return null==this._noteIdBag&&(this._noteIdBag=new Me),this._noteIdBag.tieDestinationNoteId=t,!0;case"tieoriginnoteid":return null==this._noteIdBag&&(this._noteIdBag=new Me),this._noteIdBag.tieOriginNoteId=t,!0;case"slurdestinationnoteid":return null==this._noteIdBag&&(this._noteIdBag=new Me),this._noteIdBag.slurDestinationNoteId=t,!0;case"sluroriginnoteid":return null==this._noteIdBag&&(this._noteIdBag=new Me),this._noteIdBag.slurOriginNoteId=t,!0;case"hammerpulloriginnoteid":return null==this._noteIdBag&&(this._noteIdBag=new Me),this._noteIdBag.hammerPullOriginNoteId=t,!0;case"hammerpulldestinationnoteid":return null==this._noteIdBag&&(this._noteIdBag=new Me),this._noteIdBag.hammerPullDestinationNoteId=t,!0;case"slidetargetnoteid":return null==this._noteIdBag&&(this._noteIdBag=new Me),this._noteIdBag.slideTargetNoteId=t,!0;case"slideoriginnoteid":return null==this._noteIdBag&&(this._noteIdBag=new Me),this._noteIdBag.slideOriginNoteId=t,!0}return!1}}Ae.GlobalNoteId=0,Ae.MaxOffsetForSameLineSearch=3,Ae.NoteIdLookupKey="NoteIdLookup";class Re{constructor(e){this._isEqualLengthTuplet=!0,this.totalDuration=0,this.beats=[],this.isFull=!1,this.voice=e}check(e){if(0===this.beats.length)return this.beats.push(e),this.totalDuration+=e.playbackDuration,!0;if(e.graceType!==w.None)return!0;if(e.voice!==this.voice||this.isFull||e.tupletNumerator!==this.beats[0].tupletNumerator||e.tupletDenominator!==this.beats[0].tupletDenominator)return!1;if(e.playbackDuration!==this.beats[0].playbackDuration&&(this._isEqualLengthTuplet=!1),this.beats.push(e),this.totalDuration+=e.playbackDuration,this._isEqualLengthTuplet)this.beats.length===this.beats[0].tupletNumerator&&(this.isFull=!0);else{const e=this.beats[0].tupletNumerator/this.beats[0].tupletDenominator|0;for(const t of Re.AllTicks)if(this.totalDuration===t*e){this.isFull=!0;break}}return!0}}Re.HalfTicks=1920,Re.QuarterTicks=960,Re.EighthTicks=480,Re.SixteenthTicks=240,Re.ThirtySecondTicks=120,Re.SixtyFourthTicks=60,Re.OneHundredTwentyEighthTicks=30,Re.TwoHundredFiftySixthTicks=15,Re.AllTicks=[Re.HalfTicks,Re.QuarterTicks,Re.EighthTicks,Re.SixteenthTicks,Re.ThirtySecondTicks,Re.SixtyFourthTicks,Re.OneHundredTwentyEighthTicks,Re.TwoHundredFiftySixthTicks],function(e){e[e.None=0]="None",e[e.Custom=1]="Custom",e[e.Dive=2]="Dive",e[e.Dip=3]="Dip",e[e.Hold=4]="Hold",e[e.Predive=5]="Predive",e[e.PrediveDive=6]="PrediveDive"}(ce||(ce={}));class Oe{static clone(e){const t=new X;return t.offset=e.offset,t.value=e.value,t}}class He{static clone(e){const t=new Ae;if(t.index=e.index,t.accentuated=e.accentuated,t.bendType=e.bendType,t.bendStyle=e.bendStyle,t.isContinuedBend=e.isContinuedBend,e.bendPoints){t.bendPoints=[];for(const s of e.bendPoints)t.addBendPoint(Oe.clone(s))}return t.fret=e.fret,t.string=e.string,t.showStringNumber=e.showStringNumber,t.octave=e.octave,t.tone=e.tone,t.percussionArticulation=e.percussionArticulation,t.isVisible=e.isVisible,t.isLeftHandTapped=e.isLeftHandTapped,t.isHammerPullOrigin=e.isHammerPullOrigin,t.isSlurDestination=e.isSlurDestination,t.harmonicType=e.harmonicType,t.harmonicValue=e.harmonicValue,t.isGhost=e.isGhost,t.isLetRing=e.isLetRing,t.isPalmMute=e.isPalmMute,t.isDead=e.isDead,t.isStaccato=e.isStaccato,t.slideInType=e.slideInType,t.slideOutType=e.slideOutType,t.vibrato=e.vibrato,t.isTieDestination=e.isTieDestination,t.leftHandFinger=e.leftHandFinger,t.rightHandFinger=e.rightHandFinger,t.trillValue=e.trillValue,t.trillSpeed=e.trillSpeed,t.durationPercent=e.durationPercent,t.accidentalMode=e.accidentalMode,t.dynamics=e.dynamics,t.ornament=e.ornament,t}}class We{static clone(e){const t=new U;return t.isLinear=e.isLinear,t.type=e.type,t.value=e.value,t.ratioPosition=e.ratioPosition,t.text=e.text,t}}class Ve{static clone(e){const t=new ze;t.index=e.index,t.notes=[];for(const s of e.notes)t.addNote(He.clone(s));t.isEmpty=e.isEmpty,t.whammyStyle=e.whammyStyle,t.ottava=e.ottava,t.isLegatoOrigin=e.isLegatoOrigin,t.duration=e.duration,t.isLetRing=e.isLetRing,t.isPalmMute=e.isPalmMute,t.automations=[];for(const s of e.automations)t.automations.push(We.clone(s));if(t.dots=e.dots,t.fade=e.fade,t.lyrics=e.lyrics?e.lyrics.slice():null,t.pop=e.pop,t.slap=e.slap,t.tap=e.tap,t.text=e.text,t.slashed=e.slashed,t.deadSlapped=e.deadSlapped,t.brushType=e.brushType,t.brushDuration=e.brushDuration,t.tupletDenominator=e.tupletDenominator,t.tupletNumerator=e.tupletNumerator,t.isContinuedWhammy=e.isContinuedWhammy,t.whammyBarType=e.whammyBarType,e.whammyBarPoints){t.whammyBarPoints=[];for(const s of e.whammyBarPoints)t.addWhammyBarPoint(Oe.clone(s))}return t.vibrato=e.vibrato,t.chordId=e.chordId,t.graceType=e.graceType,t.pickStroke=e.pickStroke,t.tremoloSpeed=e.tremoloSpeed,t.crescendo=e.crescendo,t.displayStart=e.displayStart,t.playbackStart=e.playbackStart,t.displayDuration=e.displayDuration,t.playbackDuration=e.playbackDuration,t.overrideDisplayDuration=e.overrideDisplayDuration,t.golpe=e.golpe,t.dynamics=e.dynamics,t.invertBeamDirection=e.invertBeamDirection,t.preferredBeamDirection=e.preferredBeamDirection,t.isEffectSlurOrigin=e.isEffectSlurOrigin,t.beamingMode=e.beamingMode,t.wahPedal=e.wahPedal,t.barreFret=e.barreFret,t.barreShape=e.barreShape,t.rasgueado=e.rasgueado,t.showTimer=e.showTimer,t.timer=e.timer,t}}!function(e){e[e.None=0]="None",e[e.Thumb=1]="Thumb",e[e.Finger=2]="Finger"}(de||(de={})),function(e){e[e.None=0]="None",e[e.FadeIn=1]="FadeIn",e[e.FadeOut=2]="FadeOut",e[e.VolumeSwell=3]="VolumeSwell"}(ue||(ue={})),function(e){e[e.None=0]="None",e[e.Open=1]="Open",e[e.Closed=2]="Closed"}(pe||(pe={})),function(e){e[e.None=0]="None",e[e.Full=1]="Full",e[e.Half=2]="Half"}(ge||(ge={})),function(e){e[e.None=0]="None",e[e.Ii=1]="Ii",e[e.Mi=2]="Mi",e[e.MiiTriplet=3]="MiiTriplet",e[e.MiiAnapaest=4]="MiiAnapaest",e[e.PmpTriplet=5]="PmpTriplet",e[e.PmpAnapaest=6]="PmpAnapaest",e[e.PeiTriplet=7]="PeiTriplet",e[e.PeiAnapaest=8]="PeiAnapaest",e[e.PaiTriplet=9]="PaiTriplet",e[e.PaiAnapaest=10]="PaiAnapaest",e[e.AmiTriplet=11]="AmiTriplet",e[e.AmiAnapaest=12]="AmiAnapaest",e[e.Ppp=13]="Ppp",e[e.Amii=14]="Amii",e[e.Amip=15]="Amip",e[e.Eami=16]="Eami",e[e.Eamii=17]="Eamii",e[e.Peami=18]="Peami"}(me||(me={})),function(e){e[e.Auto=0]="Auto",e[e.ForceSplitToNext=1]="ForceSplitToNext",e[e.ForceMergeWithNext=2]="ForceMergeWithNext",e[e.ForceSplitOnSecondaryToNext=3]="ForceSplitOnSecondaryToNext"}(fe||(fe={})),function(e){e[e.Effects=0]="Effects",e[e.StandardNotationStem=1]="StandardNotationStem",e[e.StandardNotationFlags=2]="StandardNotationFlags",e[e.StandardNotationBeams=3]="StandardNotationBeams",e[e.StandardNotationTuplet=4]="StandardNotationTuplet",e[e.StandardNotationEffects=5]="StandardNotationEffects",e[e.StandardNotationRests=6]="StandardNotationRests",e[e.GuitarTabStem=7]="GuitarTabStem",e[e.GuitarTabFlags=8]="GuitarTabFlags",e[e.GuitarTabBeams=9]="GuitarTabBeams",e[e.GuitarTabTuplet=10]="GuitarTabTuplet",e[e.GuitarTabEffects=11]="GuitarTabEffects",e[e.GuitarTabRests=12]="GuitarTabRests",e[e.SlashStem=13]="SlashStem",e[e.SlashFlags=14]="SlashFlags",e[e.SlashBeams=15]="SlashBeams",e[e.SlashTuplet=16]="SlashTuplet",e[e.SlashRests=17]="SlashRests",e[e.SlashEffects=18]="SlashEffects",e[e.NumberedDuration=19]="NumberedDuration",e[e.NumberedEffects=20]="NumberedEffects",e[e.NumberedRests=21]="NumberedRests",e[e.NumberedTuplet=22]="NumberedTuplet"}(ye||(ye={}));class Ge extends H{}class ze{constructor(){this.id=ze._globalBeatId++,this.index=0,this.previousBeat=null,this.nextBeat=null,this.notes=[],this.noteStringLookup=new Map,this.noteValueLookup=new Map,this.isEmpty=!1,this.whammyStyle=f.Default,this.ottava=o.Regular,this.fermata=null,this.isLegatoOrigin=!1,this.minNote=null,this.maxNote=null,this.maxStringNote=null,this.minStringNote=null,this.duration=_.Quarter,this.isLetRing=!1,this.isPalmMute=!1,this.automations=[],this.dots=0,this.fade=ue.None,this.lyrics=null,this.pop=!1,this.slap=!1,this.tap=!1,this.text=null,this.slashed=!1,this.deadSlapped=!1,this.brushType=b.None,this.brushDuration=0,this.tupletDenominator=-1,this.tupletNumerator=-1,this.tupletGroup=null,this.isContinuedWhammy=!1,this.whammyBarType=ce.None,this.whammyBarPoints=null,this.maxWhammyPoint=null,this.minWhammyPoint=null,this.vibrato=P.None,this.chordId=null,this.graceType=w.None,this.graceGroup=null,this.graceIndex=-1,this.pickStroke=ae.None,this.tremoloSpeed=null,this.crescendo=S.None,this.displayStart=0,this.playbackStart=0,this.displayDuration=0,this.playbackDuration=0,this.golpe=de.None,this.dynamics=g.F,this.invertBeamDirection=!1,this.preferredBeamDirection=null,this.isEffectSlurOrigin=!1,this.effectSlurOrigin=null,this.effectSlurDestination=null,this.beamingMode=fe.Auto,this.wahPedal=pe.None,this.barreFret=-1,this.barreShape=ge.None,this.rasgueado=me.None,this.showTimer=!1,this.timer=null}static resetIds(){ze._globalBeatId=0}get isLastOfVoice(){return this.index===this.voice.beats.length-1}get isLegatoDestination(){return!!this.previousBeat&&this.previousBeat.isLegatoOrigin}get isRest(){return this.isEmpty||!this.deadSlapped&&0===this.notes.length}get isFullBarRest(){return this.isRest&&1===this.voice.beats.length&&this.duration===_.Whole}get fadeIn(){return this.fade===ue.FadeIn}set fadeIn(e){this.fade=e?ue.FadeIn:ue.None}get hasRasgueado(){return this.rasgueado!==me.None}get hasTuplet(){return!(-1===this.tupletDenominator&&-1===this.tupletNumerator||1===this.tupletDenominator&&1===this.tupletNumerator)}get hasWhammyBar(){return null!==this.whammyBarPoints&&this.whammyBarType!==ce.None}get hasChord(){return!!this.chordId}get chord(){return this.chordId?this.voice.bar.staff.getChord(this.chordId):null}get isTremolo(){return!!this.tremoloSpeed}get displayEnd(){return this.displayStart+this.displayDuration}get absoluteDisplayStart(){return this.voice.bar.masterBar.start+this.displayStart}get absolutePlaybackStart(){return this.voice.bar.masterBar.start+this.playbackStart}get isEffectSlurDestination(){return!!this.effectSlurOrigin}get isBarre(){return this.barreShape!==ge.None&&this.barreFret>=0}addWhammyBarPoint(e){let t=this.whammyBarPoints;null===t&&(t=[],this.whammyBarPoints=t),t.push(e),(!this.maxWhammyPoint||e.value>this.maxWhammyPoint.value)&&(this.maxWhammyPoint=e),(!this.minWhammyPoint||e.value<this.minWhammyPoint.value)&&(this.minWhammyPoint=e),this.whammyBarType===ce.None&&(this.whammyBarType=ce.Custom)}removeWhammyBarPoint(e){const t=this.whammyBarPoints;if(null===t||e<0||e>=t.length)return;t.splice(e,1);const s=t[e];if(s===this.maxWhammyPoint){this.maxWhammyPoint=null;for(const e of t)(!this.maxWhammyPoint||e.value>this.maxWhammyPoint.value)&&(this.maxWhammyPoint=e)}if(s===this.minWhammyPoint){this.minWhammyPoint=null;for(const e of t)(!this.minWhammyPoint||e.value<this.minWhammyPoint.value)&&(this.minWhammyPoint=e)}}addNote(e){e.beat=this,e.index=this.notes.length,this.notes.push(e),e.isStringed&&this.noteStringLookup.set(e.string,e)}removeNote(e){const t=this.notes.indexOf(e);t>=0&&(this.notes.splice(t,1),e.isStringed&&this.noteStringLookup.delete(e.string))}getAutomation(e){for(let t=0,s=this.automations.length;t<s;t++){const s=this.automations[t];if(s.type===e)return s}return null}getNoteOnString(e){return this.noteStringLookup.has(e)?this.noteStringLookup.get(e):null}calculateDuration(){if(void 0!==this.overrideDisplayDuration)return this.overrideDisplayDuration;if(this.isFullBarRest)return this.voice.bar.masterBar.calculateDuration();let e=z.toTicks(this.duration);return 2===this.dots?e=z.applyDot(e,!0):1===this.dots&&(e=z.applyDot(e,!1)),this.tupletDenominator>0&&this.tupletNumerator>=0&&(e=z.applyTuplet(e,this.tupletNumerator,this.tupletDenominator)),e}updateDurations(){const e=this.calculateDuration();switch(this.playbackDuration=e,this.graceType){case w.BeforeBeat:case w.OnBeat:switch(this.duration){case _.Sixteenth:this.playbackDuration=z.toTicks(_.SixtyFourth);break;case _.ThirtySecond:this.playbackDuration=z.toTicks(_.OneHundredTwentyEighth);break;default:this.playbackDuration=z.toTicks(_.ThirtySecond)}this.displayDuration=0;break;case w.BendGrace:this.playbackDuration/=2,this.displayDuration=0;break;default:this.displayDuration=e;const t=this.previousBeat;t&&t.graceType===w.BendGrace&&(this.playbackDuration=t.playbackDuration)}}finishTuplet(){const e=this.previousBeat;let t=e?e.tupletGroup:null;if((this.hasTuplet||this.graceType!==w.None&&t)&&(e&&t&&t.check(this)||(t=new Re(this.voice),t.check(this)),this.tupletGroup=t),this.index>0){const e=this.voice.bar.masterBar.calculateDuration(),t=[];for(const s of this.automations)0===s.ratioPosition&&(s.ratioPosition=this.playbackStart/e),s.type!==m.Volume&&t.push(s);this.automations=t}}finish(e,t=null){switch(null===this.getAutomation(m.Instrument)&&0===this.index&&0===this.voice.index&&0===this.voice.bar.index&&0===this.voice.bar.staff.index&&this.automations.push(U.buildInstrumentAutomation(!1,0,this.voice.bar.staff.track.playbackInfo.program)),this.graceType){case w.OnBeat:case w.BeforeBeat:const e=this.graceGroup.beats.length;this.duration=1===e?_.Eighth:2===e?_.Sixteenth:_.ThirtySecond}const s=e?e.notation.notationMode:D.GuitarPro;let i="grad"===this.text||"grad."===this.text;i&&s===D.SongBook&&(this.text="");let a=!1;this.minNote=null,this.maxNote=null,this.minStringNote=null,this.maxStringNote=null;let r=0,n=!1;for(let o=0,h=this.notes.length;o<h;o++){const h=this.notes[o];if(h.dynamics=this.dynamics,h.finish(e,t),h.isLetRing&&(this.isLetRing=!0),h.isPalmMute&&(this.isPalmMute=!0),s===D.SongBook&&h.hasBend&&this.graceType!==w.BendGrace){if(!h.isTieOrigin)switch(h.bendType){case y.Bend:case y.PrebendRelease:case y.PrebendBend:a=!0}i||h.bendStyle===f.Gradual?(i=!0,h.bendStyle=f.Gradual,a=!1):h.bendStyle=f.Fast}h.isVisible&&(r++,(!this.minNote||h.realValue<this.minNote.realValue)&&(this.minNote=h),(!this.maxNote||h.realValue>this.maxNote.realValue)&&(this.maxNote=h),(!this.minStringNote||h.string<this.minStringNote.string)&&(this.minStringNote=h),(!this.maxStringNote||h.string>this.maxStringNote.string)&&(this.maxStringNote=h),h.hasEffectSlur&&(n=!0))}if(n&&(this.effectSlurOrigin?(this.effectSlurOrigin.effectSlurDestination=this.nextBeat,this.effectSlurOrigin.effectSlurDestination&&(this.effectSlurOrigin.effectSlurDestination.effectSlurOrigin=this.effectSlurOrigin),this.effectSlurOrigin=null):(this.isEffectSlurOrigin=!0,this.effectSlurDestination=this.nextBeat,this.effectSlurDestination&&(this.effectSlurDestination.effectSlurOrigin=this))),this.notes.length>0&&0===r&&(this.isEmpty=!0),this.isRest||this.isLetRing&&this.isPalmMute)this.isRest&&this.previousBeat&&e&&e.notation.notationMode===D.GuitarPro&&(this.previousBeat.isLetRing&&(this.isLetRing=!0),this.previousBeat.isPalmMute&&(this.isPalmMute=!0));else{let e=this.previousBeat;for(;e&&e.isRest;)this.isLetRing||(e.isLetRing=!1),this.isPalmMute||(e.isPalmMute=!1),e=e.previousBeat}const o=this.whammyBarPoints,h=null!==o&&o.length>0;if(h){const e=!!this.previousBeat&&this.previousBeat.hasWhammyBar;this.isContinuedWhammy=e}else this.whammyBarType=ce.None;if(h&&this.whammyBarType===ce.Custom&&(s===D.SongBook&&(this.whammyStyle=i?f.Gradual:f.Fast),4===o.length)){const e=o[0],t=o[1],i=o[2],a=o[3];t.value===i.value&&(e.value<t.value&&t.value<a.value||e.value>t.value&&t.value>a.value?(0===e.value||this.isContinuedWhammy?this.whammyBarType=ce.Dive:this.whammyBarType=ce.PrediveDive,o.splice(2,1),o.splice(1,1)):e.value>t.value&&t.value<a.value||e.value<t.value&&t.value>a.value?(this.whammyBarType=ce.Dip,t.offset!==i.offset&&s!==D.SongBook||o.splice(2,1)):e.value===t.value&&t.value===a.value&&(0===e.value||this.isContinuedWhammy?this.whammyBarType=ce.Hold:this.whammyBarType=ce.Predive,o.splice(2,1),o.splice(1,1)))}if(this.updateDurations(),a){const e=Ve.clone(this);e.id=ze._globalBeatId++,e.pickStroke=ae.None;for(let t=0,s=e.notes.length;t<s;t++){const s=e.notes[t],i=this.notes[t];if(s.bendType=y.None,s.maxBendPoint=null,s.bendPoints=null,s.bendStyle=f.Default,s.id=Ae.GlobalNoteId++,i.isTieOrigin&&(s.tieDestination=i.tieDestination,i.tieDestination.tieOrigin=s),i.isTieDestination&&(s.tieOrigin=i.tieOrigin?i.tieOrigin:null,i.tieOrigin.tieDestination=s),i.hasBend&&i.isTieOrigin){const e=Ae.findTieOrigin(i);if(e&&e.hasBend){s.bendType=y.Hold;const e=i.bendPoints[i.bendPoints.length-1];s.addBendPoint(new X(0,e.value)),s.addBendPoint(new X(X.MaxPosition,e.value))}}s.isTieDestination=!0}this.graceType=w.BendGrace,this.graceGroup=new Q,this.graceGroup.addBeat(this),this.graceGroup.isComplete=!0,this.graceGroup.finish(),this.updateDurations(),this.voice.insertBeat(this,e),e.graceGroup=new Q,e.graceGroup.addBeat(this),e.graceGroup.isComplete=!0,e.graceGroup.finish()}}isBefore(e){return this.voice.bar.index<e.voice.bar.index||e.voice.bar.index===this.voice.bar.index&&this.index<e.index}isAfter(e){return this.voice.bar.index>e.voice.bar.index||e.voice.bar.index===this.voice.bar.index&&this.index>e.index}hasNoteOnString(e){return this.noteStringLookup.has(e)}getNoteWithRealValue(e){return this.noteValueLookup.has(e)?this.noteValueLookup.get(e):null}chain(e=null){for(const t of this.notes)this.noteValueLookup.set(t.realValue,t),t.chain(e)}}ze._globalBeatId=0,function(e){e[e.Title=0]="Title",e[e.SubTitle=1]="SubTitle",e[e.Artist=2]="Artist",e[e.Album=3]="Album",e[e.Words=4]="Words",e[e.Music=5]="Music",e[e.WordsAndMusic=6]="WordsAndMusic",e[e.Transcriber=7]="Transcriber",e[e.Copyright=8]="Copyright",e[e.CopyrightSecondLine=9]="CopyrightSecondLine",e[e.ChordDiagramList=10]="ChordDiagramList"}(be||(be={}));class Ue{constructor(e="",t=void 0,s=ne.Left){this.template=e,this.isVisible=t,this.textAlign=s}buildText(e){let t=!1,s=!1;const i=this.template.replace(Ue.PlaceholderPattern,((i,a)=>{s=!0;let r="";switch(a){case"TITLE":r=e.title;break;case"SUBTITLE":r=e.subTitle;break;case"ARTIST":r=e.artist;break;case"ALBUM":r=e.album;break;case"WORDS":case"WORDSMUSIC":r=e.words;break;case"MUSIC":r=e.music;break;case"TABBER":r=e.tab;break;case"COPYRIGHT":r=e.copyright;break;default:r=""}return r&&(t=!0),r}));return s&&!t?"":i}}Ue.PlaceholderPattern=/%([^%]+)%/g;class Xe extends H{constructor(){super(...arguments),this.headerAndFooter=new Map}}Xe.defaultHeaderAndFooter=new Map([[be.Title,new Ue("%TITLE%",void 0,ne.Center)],[be.SubTitle,new Ue("%SUBTITLE%",void 0,ne.Center)],[be.Artist,new Ue("%ARTIST%",void 0,ne.Center)],[be.Album,new Ue("%ALBUM%",void 0,ne.Center)],[be.Words,new Ue("Words by %WORDS%",void 0,ne.Left)],[be.Music,new Ue("Music by %MUSIC%",void 0,ne.Right)],[be.WordsAndMusic,new Ue("Words & Music by %MUSIC%",void 0,ne.Right)],[be.Transcriber,new Ue("Tabbed by %TABBER%",!1,ne.Right)],[be.Copyright,new Ue("%COPYRIGHT%",void 0,ne.Center)],[be.CopyrightSecondLine,new Ue("All Rights Reserved - International Copyright Secured",!0,ne.Center)]]);class Je{constructor(){this._currentRepeatGroup=null,this._openedRepeatGroups=[],this._properlyOpenedRepeatGroups=0,this.album="",this.artist="",this.copyright="",this.instructions="",this.music="",this.notices="",this.subTitle="",this.title="",this.words="",this.tab="",this.tempo=120,this.tempoLabel="",this.masterBars=[],this.tracks=[],this.defaultSystemsLayout=3,this.systemsLayout=[],this.stylesheet=new R}static resetIds(){G.resetIds(),ze.resetIds(),ee.resetIds(),Ae.resetIds()}rebuildRepeatGroups(){this._currentRepeatGroup=null,this._openedRepeatGroups=[],this._properlyOpenedRepeatGroups=0;for(const e of this.masterBars)this.addMasterBarToRepeatGroups(e)}addMasterBar(e){e.score=this,e.index=this.masterBars.length,0!==this.masterBars.length&&(e.previousMasterBar=this.masterBars[this.masterBars.length-1],e.previousMasterBar.nextMasterBar=e,e.start=e.previousMasterBar.start+(e.previousMasterBar.isAnacrusis?0:e.previousMasterBar.calculateDuration())),this.addMasterBarToRepeatGroups(e),this.masterBars.push(e)}addMasterBarToRepeatGroups(e){e.isRepeatStart?(this._currentRepeatGroup?.isClosed&&(this._openedRepeatGroups.pop(),this._properlyOpenedRepeatGroups--),this._currentRepeatGroup=new O,this._openedRepeatGroups.push(this._currentRepeatGroup),this._properlyOpenedRepeatGroups++):this._currentRepeatGroup||(this._currentRepeatGroup=new O,this._openedRepeatGroups.push(this._currentRepeatGroup)),this._currentRepeatGroup.addMasterBar(e),e.isRepeatEnd&&this._properlyOpenedRepeatGroups>1&&(this._openedRepeatGroups.pop(),this._properlyOpenedRepeatGroups--,this._currentRepeatGroup=this._openedRepeatGroups.length>0?this._openedRepeatGroups[this._openedRepeatGroups.length-1]:null)}addTrack(e){e.score=this,e.index=this.tracks.length,this.tracks.push(e)}finish(e){const t=new Map;for(let s=0,i=this.tracks.length;s<i;s++)this.tracks[s].finish(e,t)}}class Ye{init(e,t){this.data=e,this.settings=t,Je.resetIds()}}!function(e){e[e.General=0]="General",e[e.Format=1]="Format",e[e.AlphaTex=2]="AlphaTex"}(Se||(Se={}));class $e extends Error{constructor(e,t="",s){super(t??"",{cause:s}),this.type=e,Object.setPrototypeOf(this,$e.prototype)}}class qe extends $e{constructor(e=null,t){super(Se.Format,e??"Unsupported format",t),Object.setPrototypeOf(this,qe.prototype)}}class je{constructor(){this.name="",this.firstFret=1,this.strings=[],this.barreFrets=[],this.showName=!0,this.showDiagram=!0,this.showFingering=!0}get uniqueId(){return[this.name,this.firstFret.toString(),this.strings.join(","),this.barreFrets.join(","),this.showDiagram.toString(),this.showFingering.toString(),this.showName.toString()].join("|")}}!function(e){e[e.IgnoreSpaces=0]="IgnoreSpaces",e[e.Begin=1]="Begin",e[e.Text=2]="Text",e[e.Comment=3]="Comment",e[e.Dash=4]="Dash"}(_e||(_e={}));class Ke{constructor(){this.startBar=0,this.text=""}finish(e=!1){this.chunks=[],this.parse(this.text,0,this.chunks,e)}parse(e,t,s,i){if(!e)return;let a=_e.Begin,r=_e.Begin,n=!1,o=0;for(;t<e.length;){const s=e.charCodeAt(t);switch(a){case _e.IgnoreSpaces:switch(s){case Ke.CharCodeLF:case Ke.CharCodeCR:case Ke.CharCodeTab:break;case Ke.CharCodeSpace:if(!n){a=r;continue}break;default:n=!1,a=r;continue}break;case _e.Begin:if(s!==Ke.CharCodeBrackedOpen){o=t,a=_e.Text;continue}a=_e.Comment;break;case _e.Comment:if(s===Ke.CharCodeBrackedClose)a=_e.Begin;break;case _e.Text:switch(s){case Ke.CharCodeDash:a=_e.Dash;break;case Ke.CharCodeCR:case Ke.CharCodeLF:case Ke.CharCodeSpace:const s=e.substr(o,t-o);this.addChunk(s,i),a=_e.IgnoreSpaces,r=_e.Begin}break;case _e.Dash:if(s!==Ke.CharCodeDash){const s=e.substr(o,t-o);this.addChunk(s,i),n=!0,a=_e.IgnoreSpaces,r=_e.Begin;continue}}t+=1}a===_e.Text&&t!==o&&this.addChunk(e.substr(o,t-o),i)}addChunk(e,t){e=this.prepareChunk(e),(!t||e.length>0&&"-"!==e)&&this.chunks.push(e)}prepareChunk(e){const t=e.split("+").join(" ");let s=t.length;for(;s>0&&"_"===t.charAt(s-1);)s--;return s!==t.length?t.substr(0,s):t}}Ke.CharCodeLF=10,Ke.CharCodeTab=9,Ke.CharCodeCR=13,Ke.CharCodeSpace=32,Ke.CharCodeBrackedClose=93,Ke.CharCodeBrackedOpen=91,Ke.CharCodeDash=45;class Qe{constructor(){this.marker="",this.text=""}}class Ze extends $e{constructor(e){super(Se.Format,e),Object.setPrototypeOf(this,Ze.prototype)}}class et{constructor(e,t,s,i=255){this.raw=0,this.raw=(255&i)<<24|(255&e)<<16|(255&t)<<8|255&s,this.updateRgba()}updateRgba(){255===this.a?this.rgba=`#${ie.toHexString(this.r,2)}${ie.toHexString(this.g,2)}${ie.toHexString(this.b,2)}`:this.rgba=`rgba(${this.r},${this.g},${this.b},${this.a/255})`}get a(){return this.raw>>24&255}get r(){return this.raw>>16&255}get g(){return this.raw>>8&255}get b(){return 255&this.raw}static random(e=100){return new et(255*Math.random()|0,255*Math.random()|0,255*Math.random()|0,e)}static fromJson(e){if(e instanceof et)return e;switch(typeof e){case"number":{const t=new et(0,0,0,0);return t.raw=e,t.updateRgba(),t}case"string":{const t=e;if(t.startsWith("#")){if(4===t.length)return new et(17*Number.parseInt(t[1],16),17*Number.parseInt(t[2],16),17*Number.parseInt(t[3],16));if(5===t.length)return new et(17*Number.parseInt(t[1],16),17*Number.parseInt(t[2],16),17*Number.parseInt(t[3],16),17*Number.parseInt(t[4],16));if(7===t.length)return new et(Number.parseInt(t.substring(1,3),16),Number.parseInt(t.substring(3,5),16),Number.parseInt(t.substring(5,7),16));if(9===t.length)return new et(Number.parseInt(t.substring(1,3),16),Number.parseInt(t.substring(3,5),16),Number.parseInt(t.substring(5,7),16),Number.parseInt(t.substring(7,9),16))}else if(t.startsWith("rgba")||t.startsWith("rgb")){const e=t.indexOf("("),s=t.lastIndexOf(")");if(-1===e||-1===s)throw new Ze("No values specified for rgb/rgba function");const i=t.substring(e+1,s).split(",");if(3===i.length)return new et(Number.parseInt(i[0]),Number.parseInt(i[1]),Number.parseInt(i[2]));if(4===i.length)return new et(Number.parseInt(i[0]),Number.parseInt(i[1]),Number.parseInt(i[2]),255*Number.parseFloat(i[3]))}return null}}throw new Ze("Unsupported format for color")}static toJson(e){return null===e?null:e.raw}}et.BlackRgb="#000000";class tt{constructor(){this.volume=15,this.balance=8,this.port=1,this.program=0,this.primaryChannel=0,this.secondaryChannel=0,this.isMute=!1,this.isSolo=!1}}class st{static getTextForTuning(e,t){const s=st.getTextPartsForTuning(e);return t?s.join(""):s[0]}static getTextPartsForTuning(e,t=-1){return[["C","Db","D","Eb","E","F","Gb","G","Ab","A","Bb","B"][e%12],((e/12|0)+t).toString()]}static getDefaultTuningFor(e){return st._defaultTunings.has(e)?st._defaultTunings.get(e):null}static getPresetsFor(e){switch(e){case 7:return st._sevenStrings;case 6:return st._sixStrings;case 5:return st._fiveStrings;case 4:return st._fourStrings}return[]}static initialize(){st._defaultTunings.set(7,new st("Guitar 7 strings",[64,59,55,50,45,40,35],!0)),st._sevenStrings.push(st._defaultTunings.get(7)),st._defaultTunings.set(6,new st("Guitar Standard Tuning",[64,59,55,50,45,40],!0)),st._sixStrings.push(st._defaultTunings.get(6)),st._sixStrings.push(new st("Guitar Tune down ½ step",[63,58,54,49,44,39],!1)),st._sixStrings.push(new st("Guitar Tune down 1 step",[62,57,53,48,43,38],!1)),st._sixStrings.push(new st("Guitar Tune down 2 step",[60,55,51,46,41,36],!1)),st._sixStrings.push(new st("Guitar Dropped D Tuning",[64,59,55,50,45,38],!1)),st._sixStrings.push(new st("Guitar Dropped D Tuning variant",[64,57,55,50,45,38],!1)),st._sixStrings.push(new st("Guitar Double Dropped D Tuning",[62,59,55,50,45,38],!1)),st._sixStrings.push(new st("Guitar Dropped E Tuning",[66,61,57,52,47,40],!1)),st._sixStrings.push(new st("Guitar Dropped C Tuning",[62,57,53,48,43,36],!1)),st._sixStrings.push(new st("Guitar Open C Tuning",[64,60,55,48,43,36],!1)),st._sixStrings.push(new st("Guitar Open Cm Tuning",[63,60,55,48,43,36],!1)),st._sixStrings.push(new st("Guitar Open C6 Tuning",[64,57,55,48,43,36],!1)),st._sixStrings.push(new st("Guitar Open Cmaj7 Tuning",[64,59,55,52,43,36],!1)),st._sixStrings.push(new st("Guitar Open D Tuning",[62,57,54,50,45,38],!1)),st._sixStrings.push(new st("Guitar Open Dm Tuning",[62,57,53,50,45,38],!1)),st._sixStrings.push(new st("Guitar Open D5 Tuning",[62,57,50,50,45,38],!1)),st._sixStrings.push(new st("Guitar Open D6 Tuning",[62,59,54,50,45,38],!1)),st._sixStrings.push(new st("Guitar Open Dsus4 Tuning",[62,57,55,50,45,38],!1)),st._sixStrings.push(new st("Guitar Open E Tuning",[64,59,56,52,47,40],!1)),st._sixStrings.push(new st("Guitar Open Em Tuning",[64,59,55,52,47,40],!1)),st._sixStrings.push(new st("Guitar Open Esus11 Tuning",[64,59,55,52,45,40],!1)),st._sixStrings.push(new st("Guitar Open F Tuning",[65,60,53,48,45,41],!1)),st._sixStrings.push(new st("Guitar Open G Tuning",[62,59,55,50,43,38],!1)),st._sixStrings.push(new st("Guitar Open Gm Tuning",[62,58,55,50,43,38],!1)),st._sixStrings.push(new st("Guitar Open G6 Tuning",[64,59,55,50,43,38],!1)),st._sixStrings.push(new st("Guitar Open Gsus4 Tuning",[62,60,55,50,43,38],!1)),st._sixStrings.push(new st("Guitar Open A Tuning",[64,61,57,52,45,40],!1)),st._sixStrings.push(new st("Guitar Open Am Tuning",[64,60,57,52,45,40],!1)),st._sixStrings.push(new st("Guitar Nashville Tuning",[64,59,67,62,57,52],!1)),st._sixStrings.push(new st("Bass 6 Strings Tuning",[48,43,38,33,28,23],!1)),st._sixStrings.push(new st("Lute or Vihuela Tuning",[64,59,54,50,45,40],!1)),st._defaultTunings.set(5,new st("Bass 5 Strings Tuning",[43,38,33,28,23],!0)),st._fiveStrings.push(st._defaultTunings.get(5)),st._fiveStrings.push(new st("Banjo Dropped C Tuning",[62,59,55,48,67],!1)),st._fiveStrings.push(new st("Banjo Open D Tuning",[62,57,54,50,69],!1)),st._fiveStrings.push(new st("Banjo Open G Tuning",[62,59,55,50,67],!1)),st._fiveStrings.push(new st("Banjo G Minor Tuning",[62,58,55,50,67],!1)),st._fiveStrings.push(new st("Banjo G Modal Tuning",[62,57,55,50,67],!1)),st._defaultTunings.set(4,new st("Bass Standard Tuning",[43,38,33,28],!0)),st._fourStrings.push(st._defaultTunings.get(4)),st._fourStrings.push(new st("Bass Tune down ½ step",[42,37,32,27],!1)),st._fourStrings.push(new st("Bass Tune down 1 step",[41,36,31,26],!1)),st._fourStrings.push(new st("Bass Tune down 2 step",[39,34,29,24],!1)),st._fourStrings.push(new st("Bass Dropped D Tuning",[43,38,33,26],!1)),st._fourStrings.push(new st("Ukulele C Tuning",[45,40,36,43],!1)),st._fourStrings.push(new st("Ukulele G Tuning",[52,47,43,38],!1)),st._fourStrings.push(new st("Mandolin Standard Tuning",[64,57,50,43],!1)),st._fourStrings.push(new st("Mandolin or Violin Tuning",[76,69,62,55],!1)),st._fourStrings.push(new st("Viola Tuning",[69,62,55,48],!1)),st._fourStrings.push(new st("Cello Tuning",[57,50,43,36],!1))}static findTuning(e){const t=st.getPresetsFor(e.length);for(let s=0,i=t.length;s<i;s++){const i=t[s];let a=!0;for(let t=0,s=e.length;t<s;t++)if(e[t]!==i.tunings[t]){a=!1;break}if(a)return i}return null}constructor(e="",t=null,s=!1){this.isStandard=s,this.name=e,this.tunings=t??[]}finish(){const e=st.findTuning(this.tunings);e&&(this.name=e.name,this.isStandard=e.isStandard),this.name=this.name.trim()}}st._sevenStrings=[],st._sixStrings=[],st._fiveStrings=[],st._fourStrings=[],st._defaultTunings=new Map,st.defaultAccidentals=["","#","","#","","","#","","#","","#",""],st.defaultSteps=["C","C","D","D","E","F","F","G","G","A","A","B"],st.initialize();class it{constructor(){this.index=0,this.bars=[],this.chords=null,this.capo=0,this.transpositionPitch=0,this.displayTranspositionPitch=0,this.stringTuning=new st("",[],!1),this.showSlash=!1,this.showNumbered=!1,this.showTablature=!0,this.showStandardNotation=!0,this.isPercussion=!1,this.standardNotationLineCount=it.DefaultStandardNotationLineCount}get tuning(){return this.stringTuning.tunings}get tuningName(){return this.stringTuning.name}get isStringed(){return this.stringTuning.tunings.length>0}finish(e,t=null){this.stringTuning.finish();for(let s=0,i=this.bars.length;s<i;s++)this.bars[s].finish(e,t)}addChord(e,t){t.staff=this;let s=this.chords;null===s&&(s=new Map,this.chords=s),s.set(e,t)}hasChord(e){return this.chords?.has(e)??!1}getChord(e){return this.chords?.get(e)??null}addBar(e){const t=this.bars;e.staff=this,e.index=t.length,t.length>0&&(e.previousBar=t[t.length-1],e.previousBar.nextBar=e),t.push(e)}}it.DefaultStandardNotationLineCount=5,function(e){e[e.TrackName=0]="TrackName",e[e.BracesAndBrackets=1]="BracesAndBrackets",e[e.SystemSeparator=2]="SystemSeparator",e[e.StringTuning=3]="StringTuning"}(we||(we={}));class at extends H{}class rt{constructor(){this.index=0,this.staves=[],this.playbackInfo=new tt,this.color=new et(200,0,0,255),this.name="",this.isVisibleOnMultiTrack=!0,this.shortName="",this.defaultSystemsLayout=3,this.systemsLayout=[],this.percussionArticulations=[]}addLineBreaks(e){this.lineBreaks||(this.lineBreaks=new Set),this.lineBreaks.add(e)}ensureStaveCount(e){for(;this.staves.length<e;)this.addStaff(new it)}addStaff(e){e.index=this.staves.length,e.track=this,this.staves.push(e)}finish(e,t=null){this.shortName||(this.shortName=this.name,this.shortName.length>rt.ShortNameMaxLength&&(this.shortName=this.shortName.substr(0,rt.ShortNameMaxLength)));for(let s=0,i=this.staves.length;s<i;s++)this.staves[s].finish(e,t)}applyLyrics(e){for(const t of e)t.finish();const t=this.staves[0];for(let s=0;s<e.length;s++){const i=e[s];if(i.startBar>=0&&i.startBar<t.bars.length){let a=t.bars[i.startBar].voices[0].beats[0];for(let t=0;t<i.chunks.length&&a;t++){for(;a&&(a.isEmpty||a.isRest);)a=a.nextBeat;a&&(a.lyrics||(a.lyrics=new Array(e.length),a.lyrics.fill("")),a.lyrics[s]=i.chunks[t],a=a.nextBeat)}}}}}rt.ShortNameMaxLength=10;class nt{static float64ToBytes(e){return nt._dataView.setFloat64(0,e,!0),nt._conversionByteArray}static bytesToInt64LE(e){nt._conversionByteArray.set(e,0);const t=nt._dataView.getBigInt64(0,!0);return t<=Number.MAX_SAFE_INTEGER&&t>=Number.MIN_SAFE_INTEGER?Number(t):Number.MAX_SAFE_INTEGER}static bytesToFloat64LE(e){return nt._conversionByteArray.set(e,0),nt._dataView.getFloat64(0,!0)}static bytesToFloat32LE(e){return nt._conversionByteArray.set(e,0),nt._dataView.getFloat32(0,!0)}static float32BEToBytes(e){return nt._dataView.setFloat32(0,e,!1),nt._conversionByteArray.slice(0,4)}static uint16ToInt16(e){return nt._dataView.setUint16(0,e,!0),nt._dataView.getInt16(0,!0)}static int16ToUint32(e){return nt._dataView.setInt16(0,e,!0),nt._dataView.getUint32(0,!0)}static int32ToUint16(e){return nt._dataView.setInt32(0,e,!0),nt._dataView.getUint16(0,!0)}static int32ToInt16(e){return nt._dataView.setInt32(0,e,!0),nt._dataView.getInt16(0,!0)}static int32ToUint32(e){return nt._dataView.setInt32(0,e,!0),nt._dataView.getUint32(0,!0)}static uint8ToInt8(e){return nt._dataView.setUint8(0,e),nt._dataView.getInt8(0)}}nt._conversionBuffer=new ArrayBuffer(8),nt._conversionByteArray=new Uint8Array(nt._conversionBuffer),nt._dataView=new DataView(nt._conversionBuffer);class ot{static readInt32BE(e){return e.readByte()<<24|e.readByte()<<16|e.readByte()<<8|e.readByte()}static readFloat32BE(e){const t=new Uint8Array(4);return e.read(t,0,t.length),t.reverse(),nt.bytesToFloat32LE(t)}static readFloat64BE(e){const t=new Uint8Array(8);return e.read(t,0,t.length),t.reverse(),nt.bytesToFloat64LE(t)}static readInt32LE(e){const t=e.readByte(),s=e.readByte(),i=e.readByte();return e.readByte()<<24|i<<16|s<<8|t}static readInt64LE(e){const t=new Uint8Array(8);return e.read(t,0,t.length),nt.bytesToInt64LE(t)}static readUInt32LE(e){const t=e.readByte(),s=e.readByte(),i=e.readByte();return e.readByte()<<24|i<<16|s<<8|t}static decodeUInt32LE(e,t){const s=e[t],i=e[t+1],a=e[t+2];return e[t+3]<<24|a<<16|i<<8|s}static readUInt16LE(e){const t=e.readByte(),s=e.readByte();return nt.int32ToUint16(s<<8|t)}static readInt16LE(e){const t=e.readByte(),s=e.readByte();return nt.int32ToInt16(s<<8|t)}static readUInt32BE(e){const t=e.readByte(),s=e.readByte(),i=e.readByte(),a=e.readByte();return nt.int32ToUint32(t<<24|s<<16|i<<8|a)}static readUInt16BE(e){const t=e.readByte(),s=e.readByte();return nt.int32ToInt16(t<<8|s)}static readInt16BE(e){const t=e.readByte(),s=e.readByte();return nt.int32ToInt16(t<<8|s)}static readByteArray(e,t){const s=new Uint8Array(t);return e.read(s,0,t),s}static read8BitChars(e,t){const s=new Uint8Array(t);return e.read(s,0,s.length),ot.toString(s,"utf-8")}static read8BitString(e){let t="",s=e.readByte();for(;0!==s;)t+=String.fromCharCode(s),s=e.readByte();return t}static read8BitStringLength(e,t){let s="",i=-1;for(let a=0;a<t;a++){const t=e.readByte();0===t&&-1===i&&(i=a),s+=String.fromCharCode(t)}const a=s;return i>=0?a.substr(0,i):a}static readSInt8(e){const t=e.readByte();return-256*((255&t)>>7)+(255&t)}static readInt24(e,t){let s=e[t]|e[t+1]<<8|e[t+2]<<16;return 8388608&~s||(s|=255<<24),s}static readInt16(e,t){return nt.int32ToInt16(e[t]|e[t+1]<<8)}static toString(e,t){const s=ot.detectEncoding(e);s&&(t=s),t||(t="utf-8");return new TextDecoder(t).decode(e.buffer)}static detectEncoding(e){return e.length>2&&254===e[0]&&255===e[1]?"utf-16be":e.length>2&&255===e[0]&&254===e[1]?"utf-16le":e.length>4&&0===e[0]&&0===e[1]&&254===e[2]&&255===e[3]?"utf-32be":e.length>4&&255===e[0]&&254===e[1]&&0===e[2]&&0===e[3]?"utf-32le":null}static stringToBytes(e){return(new TextEncoder).encode(e)}static writeInt32BE(e,t){e.writeByte(t>>24&255),e.writeByte(t>>16&255),e.writeByte(t>>8&255),e.writeByte(255&t)}static writeInt32LE(e,t){e.writeByte(255&t),e.writeByte(t>>8&255),e.writeByte(t>>16&255),e.writeByte(t>>24&255)}static writeUInt16LE(e,t){e.writeByte(255&t),e.writeByte(t>>8&255)}static writeInt16LE(e,t){e.writeByte(255&t),e.writeByte(t>>8&255)}static writeInt16BE(e,t){e.writeByte(t>>8&255),e.writeByte(255&t)}static writeFloat32BE(e,t){const s=nt.float32BEToBytes(t);e.write(s,0,s.length)}}class ht{constructor(){this.length=0,this.position=0}get bytesWritten(){return this.position}getBuffer(){return this._buffer}static empty(){return ht.withCapacity(0)}static withCapacity(e){const t=new ht;return t._buffer=new Uint8Array(e),t}static fromBuffer(e){const t=new ht;return t._buffer=e,t.length=e.length,t}static fromString(e){const t=ot.stringToBytes(e);return ht.fromBuffer(t)}reset(){this.position=0}skip(e){this.position+=e}readByte(){return this.length-this.position<=0?-1:this._buffer[this.position++]}read(e,t,s){let i=this.length-this.position;return i>s&&(i=s),i<=0?0:(e.set(this._buffer.subarray(this.position,this.position+i),t),this.position+=i,i)}writeByte(e){const t=this.position+1;this.ensureCapacity(t),this._buffer[this.position]=255&e,t>this.length&&(this.length=t),this.position=t}write(e,t,s){const i=this.position+s;this.ensureCapacity(i);const a=Math.min(s,e.length-t);this._buffer.set(e.subarray(t,t+a),this.position),i>this.length&&(this.length=i),this.position=i}ensureCapacity(e){if(e>this._buffer.length){let t=e;t<256&&(t=256),t<2*this._buffer.length&&(t=2*this._buffer.length);const s=new Uint8Array(t);this.length>0&&s.set(this._buffer.subarray(0,0+this.length),0),this._buffer=s}}readAll(){return this.toArray()}toArray(){const e=new Uint8Array(this.length);return e.set(this._buffer.subarray(0,0+this.length),0),e}copyTo(e){e.write(this._buffer,0,this.length)}}!function(e){e[e.TargetFine=0]="TargetFine",e[e.TargetSegno=1]="TargetSegno",e[e.TargetSegnoSegno=2]="TargetSegnoSegno",e[e.TargetCoda=3]="TargetCoda",e[e.TargetDoubleCoda=4]="TargetDoubleCoda",e[e.JumpDaCapo=5]="JumpDaCapo",e[e.JumpDaCapoAlCoda=6]="JumpDaCapoAlCoda",e[e.JumpDaCapoAlDoubleCoda=7]="JumpDaCapoAlDoubleCoda",e[e.JumpDaCapoAlFine=8]="JumpDaCapoAlFine",e[e.JumpDalSegno=9]="JumpDalSegno",e[e.JumpDalSegnoAlCoda=10]="JumpDalSegnoAlCoda",e[e.JumpDalSegnoAlDoubleCoda=11]="JumpDalSegnoAlDoubleCoda",e[e.JumpDalSegnoAlFine=12]="JumpDalSegnoAlFine",e[e.JumpDalSegnoSegno=13]="JumpDalSegnoSegno",e[e.JumpDalSegnoSegnoAlCoda=14]="JumpDalSegnoSegnoAlCoda",e[e.JumpDalSegnoSegnoAlDoubleCoda=15]="JumpDalSegnoSegnoAlDoubleCoda",e[e.JumpDalSegnoSegnoAlFine=16]="JumpDalSegnoSegnoAlFine",e[e.JumpDaCoda=17]="JumpDaCoda",e[e.JumpDaDoubleCoda=18]="JumpDaDoubleCoda"}(Be||(Be={})),function(e){e[e.Short=0]="Short",e[e.Medium=1]="Medium",e[e.Long=2]="Long"}(ke||(ke={}));class lt{constructor(){this.type=ke.Short,this.length=0}}!function(e){e[e.Up=0]="Up",e[e.Down=1]="Down"}(Te||(Te={})),function(e){e[e.No=0]="No",e[e.Eof=1]="Eof",e[e.Number=2]="Number",e[e.DoubleDot=3]="DoubleDot",e[e.Dot=4]="Dot",e[e.String=5]="String",e[e.Tuning=6]="Tuning",e[e.LParensis=7]="LParensis",e[e.RParensis=8]="RParensis",e[e.LBrace=9]="LBrace",e[e.RBrace=10]="RBrace",e[e.Pipe=11]="Pipe",e[e.MetaCommand=12]="MetaCommand",e[e.Multiply=13]="Multiply",e[e.LowerThan=14]="LowerThan"}(Ne||(Ne={})),function(e){e[e.KnownStaffMeta=0]="KnownStaffMeta",e[e.UnknownStaffMeta=1]="UnknownStaffMeta",e[e.EndOfMetaDetected=2]="EndOfMetaDetected"}(xe||(xe={}));class ct extends $e{constructor(e,t,s,i,a,r,n,o=null){super(Se.AlphaTex,e),this.position=t,this.line=s,this.col=i,this.nonTerm=a??"",this.expected=r??Ne.No,this.symbol=n??Ne.No,this.symbolData=o,Object.setPrototypeOf(this,ct.prototype)}static symbolError(e,t,s,i,a,r,n=null){let o=`MalFormed AlphaTex: @${e} (line ${t}, col ${s}): Error on block ${i}`;return a!==r?(o+=`, expected a ${Ne[a]} found a ${Ne[r]}`,null!==n&&(o+=`: '${n}'`)):o+=`, invalid value: '${n}'`,new ct(o,e,t,s,i,a,r,n)}static errorMessage(e,t,s,i){return new ct(e=`MalFormed AlphaTex: @${t} (line ${s}, col ${i}): ${e}`,t,s,i,null,null,null,null)}}!function(e){e[e.Auto=0]="Auto",e[e.Explicit=1]="Explicit"}(ve||(ve={}));class dt extends Ye{constructor(){super(...arguments),this._trackChannel=0,this._barIndex=0,this._voiceIndex=0,this._input="",this._ch=dt.Eof,this._curChPos=0,this._line=1,this._col=0,this._lastValidSpot=[0,1,0],this._sy=Ne.No,this._syData="",this._allowNegatives=!1,this._allowFloat=!1,this._allowTuning=!1,this._currentDuration=_.QuadrupleWhole,this._currentDynamics=g.PPP,this._currentTuplet=0,this._staffHasExplicitDisplayTransposition=!1,this._staffHasExplicitTuning=!1,this._staffTuningApplied=!1,this._percussionArticulationNames=new Map,this._sustainPedalToBeat=new Map,this._slurs=new Map,this._articulationValueToIndex=new Map,this._accidentalMode=ve.Explicit,this.logErrors=!1}get name(){return"AlphaTex"}initFromString(e,t){this.data=ht.empty(),this._input=e,this.settings=t,Je.resetIds()}readScore(){try{if(this.data.length>0&&(this._input=ot.toString(this.data.readAll(),this.settings.importer.encoding)),this._allowTuning=!0,this._lyrics=new Map,this._sustainPedalToBeat=new Map,this.createDefaultScore(),this._curChPos=0,this._line=1,this._col=0,this.saveValidSpot(),this._currentDuration=_.Quarter,this._currentDynamics=g.F,this._currentTuplet=1,this._ch=this.nextChar(),this._sy=this.newSy(),this._sy===Ne.LowerThan)throw new qe("Unknown start sign '<' (meant to import as XML?)");if(this._sy!==Ne.Eof){const e=this.metaData(),t=this.bars();if(!e&&!t)throw new qe("No alphaTex data found")}ie.consolidate(this._score),this._score.finish(this.settings),this._score.rebuildRepeatGroups();for(const[e,t]of this._lyrics)this._score.tracks[e].applyLyrics(t);for(const[e,t]of this._sustainPedalToBeat){const s=t.voice.bar.masterBar.calculateDuration();e.ratioPosition=t.playbackStart/s}return this._score}catch(e){if(e instanceof ct)throw new qe(e.message,e);throw e}}error(e,t,s=!0){let i,a=!1;s?(i=this._sy,i!==Ne.String&&i!==Ne.Number&&i!==Ne.MetaCommand||(a=!0)):i=t;const r=ct.symbolError(this._lastValidSpot[0],this._lastValidSpot[1],this._lastValidSpot[2],e,t,i,a?this._syData:null);throw this.logErrors&&q.error(this.name,r.message),r}errorMessage(e){const t=ct.errorMessage(e,this._lastValidSpot[0],this._lastValidSpot[1],this._lastValidSpot[2]);throw this.logErrors&&q.error(this.name,t.message),t}createDefaultScore(){this._score=new Je,this._score.tempo=120,this._score.tempoLabel="",this.newTrack()}newTrack(){this._currentTrack=new rt,this._currentTrack.ensureStaveCount(1),this._currentTrack.playbackInfo.program=25,this._currentTrack.playbackInfo.primaryChannel=this._trackChannel++,this._currentTrack.playbackInfo.secondaryChannel=this._trackChannel++;const e=this._currentTrack.staves[0];e.displayTranspositionPitch=0,e.stringTuning.tunings=st.getDefaultTuningFor(6).tunings,this._articulationValueToIndex.clear(),this.beginStaff(e),this._score.addTrack(this._currentTrack),this._lyrics.set(this._currentTrack.index,[]),this._currentDynamics=g.F}parseClefFromString(e){switch(e.toLowerCase()){case"g2":case"treble":default:return n.G2;case"f4":case"bass":return n.F4;case"c3":case"tenor":return n.C3;case"c4":case"alto":return n.C4;case"n":case"neutral":return n.Neutral}}parseClefFromInt(e){switch(e){case 43:default:return n.G2;case 65:return n.F4;case 48:return n.C3;case 60:return n.C4}}parseTripletFeelFromString(e){switch(e.toLowerCase()){case"no":case"none":default:return M.NoTripletFeel;case"t16":case"triplet-16th":return M.Triplet16th;case"t8":case"triplet-8th":return M.Triplet8th;case"d16":case"dotted-16th":return M.Dotted16th;case"d8":case"dotted-8th":return M.Dotted8th;case"s16":case"scottish-16th":return M.Scottish16th;case"s8":case"scottish-8th":return M.Scottish8th}}parseTripletFeelFromInt(e){switch(e){case 0:default:return M.NoTripletFeel;case 1:return M.Triplet16th;case 2:return M.Triplet8th;case 3:return M.Dotted16th;case 4:return M.Dotted8th;case 5:return M.Scottish16th;case 6:return M.Scottish8th}}parseKeySignature(e){switch(e.toLowerCase()){case"cb":case"cbmajor":case"abminor":return l.Cb;case"gb":case"gbmajor":case"ebminor":return l.Gb;case"db":case"dbmajor":case"bbminor":return l.Db;case"ab":case"abmajor":case"fminor":return l.Ab;case"eb":case"ebmajor":case"cminor":return l.Eb;case"bb":case"bbmajor":case"gminor":return l.Bb;case"f":case"fmajor":case"dminor":return l.F;case"c":case"cmajor":case"aminor":default:return l.C;case"g":case"gmajor":case"eminor":return l.G;case"d":case"dmajor":case"bminor":return l.D;case"a":case"amajor":case"f#minor":return l.A;case"e":case"emajor":case"c#minor":return l.E;case"b":case"bmajor":case"g#minor":return l.B;case"f#":case"f#major":case"d#minor":return l.FSharp;case"c#":case"c#major":case"a#minor":return l.CSharp}}parseKeySignatureType(e){return e.toLowerCase().endsWith("minor")?c.Minor:c.Major}nextChar(){return this._curChPos<this._input.length?(this._ch=this._input.charCodeAt(this._curChPos++),10===this._ch?(this._line++,this._col=0):this._col++):this._ch=dt.Eof,this._ch}saveValidSpot(){this._lastValidSpot=[this._curChPos,this._line,this._col]}newSy(){for(this.saveValidSpot(),this._sy=Ne.No;this._sy===Ne.No;)if(this._ch===dt.Eof)this._sy=Ne.Eof;else if(dt.isWhiteSpace(this._ch))this._ch=this.nextChar(),this.saveValidSpot();else if(47===this._ch){if(this._ch=this.nextChar(),47===this._ch)for(;13!==this._ch&&10!==this._ch&&this._ch!==dt.Eof;)this._ch=this.nextChar();else if(42===this._ch)for(;this._ch!==dt.Eof;)if(42===this._ch){if(this._ch=this.nextChar(),47===this._ch){this._ch=this.nextChar();break}}else this._ch=this.nextChar();else this.error("comment",Ne.String,!1);this.saveValidSpot()}else if(34===this._ch||39===this._ch){const e=this._ch;this._ch=this.nextChar();let t="";for(this._sy=Ne.String;this._ch!==e&&this._ch!==dt.Eof;)92===this._ch?(this._ch=this.nextChar(),92===this._ch?t+="\\":this._ch===e?t+=String.fromCharCode(this._ch):82===this._ch||114===this._ch?t+="\r":78===this._ch||110===this._ch?t+="\n":84===this._ch||116===this._ch?t+="\t":this.errorMessage("Unsupported escape sequence")):t+=String.fromCharCode(this._ch),this._ch=this.nextChar();this._ch===dt.Eof&&this.errorMessage("String opened but never closed"),this._syData=t,this._ch=this.nextChar()}else if(45===this._ch)this._allowNegatives?this.readNumberOrName():(this._sy=Ne.String,this._syData=this.readName());else if(46===this._ch)this._sy=Ne.Dot,this._ch=this.nextChar();else if(58===this._ch)this._sy=Ne.DoubleDot,this._ch=this.nextChar();else if(40===this._ch)this._sy=Ne.LParensis,this._ch=this.nextChar();else if(92===this._ch)this._ch=this.nextChar(),this._sy=Ne.MetaCommand,92===this._ch&&(this._ch=this.nextChar()),this._syData=this.readName();else if(41===this._ch)this._sy=Ne.RParensis,this._ch=this.nextChar();else if(123===this._ch)this._sy=Ne.LBrace,this._ch=this.nextChar();else if(125===this._ch)this._sy=Ne.RBrace,this._ch=this.nextChar();else if(124===this._ch)this._sy=Ne.Pipe,this._ch=this.nextChar();else if(42===this._ch)this._sy=Ne.Multiply,this._ch=this.nextChar();else if(60===this._ch)this._sy=Ne.LowerThan,this._ch=this.nextChar();else if(this.isDigit(this._ch))this.readNumberOrName();else if(dt.isNameLetter(this._ch)){const e=this.readName(),t=this._allowTuning?ie.parseTuning(e):null;t?(this._sy=Ne.Tuning,this._syData=t):(this._sy=Ne.String,this._syData=e)}else this.error("symbol",Ne.String,!1);return this._sy}readNumberOrName(){let e="",t=!0;do{e+=String.fromCharCode(this._ch),this.isDigit(this._ch)||(t=!1),this._ch=this.nextChar()}while(this.isDigit(this._ch)||dt.isNameLetter(this._ch));t?(this._sy=Ne.Number,this._syData=this._allowFloat?Number.parseFloat(e):Number.parseInt(e)):(this._sy=Ne.String,this._syData=e)}static isNameLetter(e){return!dt.isTerminal(e)&&(33<=e&&e<=47||58<=e&&e<=126||128<=e)}static isTerminal(e){return 46===e||123===e||125===e||91===e||93===e||40===e||41===e||124===e||39===e||34===e||42===e||92===e}static isWhiteSpace(e){return 9===e||10===e||11===e||13===e||32===e}isDigit(e){return e>=48&&e<=57||this._allowNegatives&&45===e||this._allowFloat&&46===e}readName(){let e="";do{e+=String.fromCharCode(this._ch),this._ch=this.nextChar()}while(dt.isNameLetter(this._ch)||this.isDigit(this._ch));return e}metaData(){let e=!1,t=!1,s=!0;for(;this._sy===Ne.MetaCommand&&s;){const i=this._syData.toLowerCase();switch(i){case"title":case"subtitle":case"artist":case"album":case"words":case"music":case"copyright":case"instructions":case"notices":case"tab":this._sy=this.newSy(),this._sy!==Ne.String&&this.error(i,Ne.String,!0);const a=this._syData;this._sy=this.newSy(),e=!0;let r=be.ChordDiagramList;switch(i){case"title":this._score.title=a,r=be.Title;break;case"subtitle":this._score.subTitle=a,r=be.SubTitle;break;case"artist":this._score.artist=a,r=be.Artist;break;case"album":this._score.album=a,r=be.Album;break;case"words":this._score.words=a,r=be.Words;break;case"music":this._score.music=a,r=be.Music;break;case"copyright":this._score.copyright=a,r=be.Copyright;break;case"instructions":this._score.instructions=a;break;case"notices":this._score.notices=a;break;case"tab":this._score.tab=a,r=be.Transcriber}r!==be.ChordDiagramList&&this.headerFooterStyle(r);break;case"copyright2":this._sy=this.newSy(),this._sy!==Ne.String&&this.error(i,Ne.String,!0),this.headerFooterStyle(be.CopyrightSecondLine),e=!0;break;case"wordsandmusic":this._sy=this.newSy(),this._sy!==Ne.String&&this.error(i,Ne.String,!0),this.headerFooterStyle(be.WordsAndMusic),e=!0;break;case"tempo":this._allowFloat=!0,this._sy=this.newSy(),this._allowFloat=!1,this._sy===Ne.Number?this._score.tempo=this._syData:this.error("tempo",Ne.Number,!0),this._sy=this.newSy(),this._sy===Ne.String&&(this._score.tempoLabel=this._syData,this._sy=this.newSy()),e=!0;break;case"defaultsystemslayout":this._sy=this.newSy(),this._sy===Ne.Number?(this._score.defaultSystemsLayout=this._syData,this._sy=this.newSy(),e=!0):this.error("default-systems-layout",Ne.Number,!0);break;case"systemslayout":for(this._sy=this.newSy(),e=!0;this._sy===Ne.Number;)this._score.systemsLayout.push(this._syData),this._sy=this.newSy();break;case"hidedynamics":this._score.stylesheet.hideDynamics=!0,this._sy=this.newSy(),e=!0;break;case"showdynamics":this._score.stylesheet.hideDynamics=!1,this._sy=this.newSy(),e=!0;break;case"bracketextendmode":this._sy=this.newSy(),this._sy!==Ne.String&&this.error("bracketExtendMode",Ne.String,!0),this._score.stylesheet.bracketExtendMode=this.parseBracketExtendMode(this._syData),this._sy=this.newSy(),e=!0;break;case"usesystemsignseparator":this._score.stylesheet.useSystemSignSeparator=!0,this._sy=this.newSy(),e=!0;break;case"multibarrest":this._score.stylesheet.multiTrackMultiBarRest=!0,this._sy=this.newSy(),e=!0;break;case"singletracktracknamepolicy":this._sy=this.newSy(),this._sy!==Ne.String&&this.error("singleTrackTrackNamePolicy",Ne.String,!0),this._score.stylesheet.singleTrackTrackNamePolicy=this.parseTrackNamePolicy(this._syData),this._sy=this.newSy(),e=!0;break;case"multitracktracknamepolicy":this._sy=this.newSy(),this._sy!==Ne.String&&this.error("multiTrackTrackNamePolicy",Ne.String,!0),this._score.stylesheet.multiTrackTrackNamePolicy=this.parseTrackNamePolicy(this._syData),this._sy=this.newSy(),e=!0;break;case"firstsystemtracknamemode":this._sy=this.newSy(),this._sy!==Ne.String&&this.error("firstSystemTrackNameMode",Ne.String,!0),this._score.stylesheet.firstSystemTrackNameMode=this.parseTrackNameMode(this._syData),this._sy=this.newSy(),e=!0;break;case"othersystemstracknamemode":this._sy=this.newSy(),this._sy!==Ne.String&&this.error("otherSystemsTrackNameMode",Ne.String,!0),this._score.stylesheet.otherSystemsTrackNameMode=this.parseTrackNameMode(this._syData),this._sy=this.newSy(),e=!0;break;case"firstsystemtracknameorientation":this._sy=this.newSy(),this._sy!==Ne.String&&this.error("firstSystemTrackNameOrientation",Ne.String,!0),this._score.stylesheet.firstSystemTrackNameOrientation=this.parseTrackNameOrientation(this._syData),this._sy=this.newSy(),e=!0;break;case"othersystemstracknameorientation":this._sy=this.newSy(),this._sy!==Ne.String&&this.error("otherSystemsTrackNameOrientation",Ne.String,!0),this._score.stylesheet.otherSystemsTrackNameOrientation=this.parseTrackNameOrientation(this._syData),this._sy=this.newSy(),e=!0;break;default:switch(this.handleStaffMeta()){case xe.KnownStaffMeta:t=!0;break;case xe.UnknownStaffMeta:e||t?this.error("metaDataTags",Ne.String,!1):s=!1;break;case xe.EndOfMetaDetected:s=!1}}}return e?(this._sy!==Ne.Dot&&this.error("song",Ne.Dot,!0),this._sy=this.newSy()):this._sy===Ne.Dot&&(this._sy=this.newSy(),e=!0),e||t}headerFooterStyle(e){const t=ie.getOrCreateHeaderFooterStyle(this._score,e);if(void 0===t.isVisible&&(t.isVisible=!0),this._sy===Ne.String){const e=this._syData;e?t.template=e:t.isVisible=!1,this._sy=this.newSy()}if(this._sy===Ne.String){switch(this._syData.toLowerCase()){case"left":t.textAlign=ne.Left;break;case"center":t.textAlign=ne.Center;break;case"right":t.textAlign=ne.Right}this._sy=this.newSy()}}parseTrackNamePolicy(e){switch(e.toLowerCase()){case"hidden":return i.Hidden;case"allsystems":return i.AllSystems;default:return i.FirstSystem}}parseTrackNameMode(e){return"fullname"===e.toLowerCase()?a.FullName:a.ShortName}parseTrackNameOrientation(e){return"horizontal"===e.toLowerCase()?r.Horizontal:r.Vertical}handleStaffMeta(){switch(this._syData.toLowerCase()){case"capo":return this._sy=this.newSy(),this._sy===Ne.Number?this._currentStaff.capo=this._syData:this.error("capo",Ne.Number,!0),this._sy=this.newSy(),xe.KnownStaffMeta;case"tuning":this._sy=this.newSy();const e=this._currentStaff.tuning.length;switch(this._staffHasExplicitTuning=!0,this._staffTuningApplied=!1,this._sy){case Ne.String:const e=this._syData.toLowerCase();"piano"===e||"none"===e||"voice"===e?this.makeCurrentStaffPitched():this.error("tuning",Ne.Tuning,!0),this._sy=this.newSy();break;case Ne.Tuning:const t=[];do{const e=this._syData;t.push(e.realValue),this._sy=this.newSy()}while(this._sy===Ne.Tuning);this._currentStaff.stringTuning.tunings=t;break;default:this.error("tuning",Ne.Tuning,!0)}return this._sy===Ne.String&&"hide"===this._syData.toLowerCase()&&(this._score.stylesheet.perTrackDisplayTuning||(this._score.stylesheet.perTrackDisplayTuning=new Map),this._score.stylesheet.perTrackDisplayTuning.set(this._currentTrack.index,!1),this._sy=this.newSy()),e!==this._currentStaff.tuning.length&&(this._currentStaff.chords?.size??0)>0&&this.errorMessage("Tuning must be defined before any chord"),xe.KnownStaffMeta;case"instrument":if(this._sy=this.newSy(),this._staffTuningApplied=!1,this._sy===Ne.Number){const e=this._syData;e>=0&&e<=127?this._currentTrack.playbackInfo.program=this._syData:this.error("instrument",Ne.Number,!1)}else if(this._sy===Ne.String){const e=this._syData.toLowerCase();if("percussion"===e){for(const e of this._currentTrack.staves)this.applyPercussionStaff(e);this._currentTrack.playbackInfo.primaryChannel=K.PercussionChannel,this._currentTrack.playbackInfo.secondaryChannel=K.PercussionChannel}else this._currentTrack.playbackInfo.program=A.getValue(e)}else this.error("instrument",Ne.Number,!0);return this._sy=this.newSy(),xe.KnownStaffMeta;case"lyrics":this._sy=this.newSy();const t=new Ke;return t.startBar=0,t.text="",this._sy===Ne.Number&&(t.startBar=this._syData,this._sy=this.newSy()),this._sy===Ne.String?(t.text=this._syData,this._sy=this.newSy()):this.error("lyrics",Ne.String,!0),this._lyrics.get(this._currentTrack.index).push(t),xe.KnownStaffMeta;case"chord":this._sy=this.newSy();const s=new je;this.chordProperties(s),this._sy===Ne.String?(s.name=this._syData,this._sy=this.newSy()):this.error("chord-name",Ne.String,!0);for(let e=0;e<this._currentStaff.tuning.length;e++)this._sy===Ne.Number?s.strings.push(this._syData):this._sy===Ne.String&&"x"===this._syData.toLowerCase()&&s.strings.push(-1),this._sy=this.newSy();return this._currentStaff.addChord(this.getChordId(this._currentStaff,s.name),s),xe.KnownStaffMeta;case"articulation":this._sy=this.newSy();let i="";if(this._sy===Ne.String?(i=this._syData,this._sy=this.newSy()):this.error("articulation-name",Ne.String,!0),"defaults"===i){for(const[e,t]of Le.instrumentArticulationNames)this._percussionArticulationNames.set(e.toLowerCase(),t),this._percussionArticulationNames.set(dt.toArticulationId(e),t);return xe.KnownStaffMeta}let a=0;return this._sy===Ne.Number?(a=this._syData,this._sy=this.newSy()):this.error("articulation-number",Ne.Number,!0),Le.instrumentArticulations.has(a)||this.errorMessage(`Unknown articulation ${a}. Refer to https://www.alphatab.net/docs/alphatex/percussion for available ids`),this._percussionArticulationNames.set(i.toLowerCase(),a),xe.KnownStaffMeta;case"accidentals":return this.handleAccidentalMode(),xe.KnownStaffMeta;case"displaytranspose":return this._allowNegatives=!0,this._sy=this.newSy(),this._sy===Ne.Number?(this._currentStaff.displayTranspositionPitch=-1*this._syData,this._staffHasExplicitDisplayTransposition=!0):this.error("displaytranspose",Ne.Number,!0),this._allowNegatives=!1,this._sy=this.newSy(),xe.KnownStaffMeta;case"transpose":return this._allowNegatives=!0,this._sy=this.newSy(),this._sy===Ne.Number?this._currentStaff.transpositionPitch=-1*this._syData:this.error("transpose",Ne.Number,!0),this._allowNegatives=!1,this._sy=this.newSy(),xe.KnownStaffMeta;case"track":case"staff":return xe.EndOfMetaDetected;case"voice":return this._sy=this.newSy(),this.handleNewVoice()?xe.EndOfMetaDetected:xe.KnownStaffMeta;default:return xe.UnknownStaffMeta}}handleAccidentalMode(){switch(this._sy=this.newSy(),this._sy!==Ne.String&&this.error("accidental-mode",Ne.String,!0),this._syData){case"auto":this._accidentalMode=ve.Auto;break;case"explicit":this._accidentalMode=ve.Explicit}this._sy=this.newSy()}makeCurrentStaffPitched(){this._currentStaff.stringTuning.tunings=[],this._staffHasExplicitDisplayTransposition||(this._currentStaff.displayTranspositionPitch=0)}static toArticulationId(e){return e.replace(/[^a-zA-Z0-9]/g,"").toLowerCase()}applyPercussionStaff(e){e.isPercussion=!0,e.showTablature=!1}chordProperties(e){if(this._sy===Ne.LBrace){for(this._sy=this.newSy();this._sy===Ne.String;)switch(this._syData.toLowerCase()){case"firstfret":if(this._sy=this.newSy(),this._sy===Ne.Number)e.firstFret=this._syData;else this.error("chord-firstfret",Ne.Number,!0);this._sy=this.newSy();break;case"showdiagram":switch(this._sy=this.newSy(),this._sy){case Ne.String:e.showDiagram="false"!==this._syData.toLowerCase();break;case Ne.Number:e.showDiagram=0!==this._syData;break;default:this.error("chord-showdiagram",Ne.String,!0)}this._sy=this.newSy();break;case"showfingering":switch(this._sy=this.newSy(),this._sy){case Ne.String:e.showDiagram="false"!==this._syData.toLowerCase();break;case Ne.Number:e.showFingering=0!==this._syData;break;default:this.error("chord-showfingering",Ne.String,!0)}this._sy=this.newSy();break;case"showname":switch(this._sy=this.newSy(),this._sy){case Ne.String:e.showName="false"!==this._syData.toLowerCase();break;case Ne.Number:e.showName=0!==this._syData;break;default:this.error("chord-showname",Ne.String,!0)}this._sy=this.newSy();break;case"barre":for(this._sy=this.newSy();this._sy===Ne.Number;)e.barreFrets.push(this._syData),this._sy=this.newSy();break;default:this.error("chord-properties",Ne.String,!1)}this._sy!==Ne.RBrace&&this.error("chord-properties",Ne.RBrace,!0),this._sy=this.newSy()}}bars(){const e=this.bar();for(;this._sy!==Ne.Eof;)if(this._sy===Ne.Pipe)this._sy=this.newSy(),this.bar();else{if(this._sy!==Ne.MetaCommand)break;this.bar()}return e}trackStaffMeta(){if(this._sy!==Ne.MetaCommand)return!1;if("track"===this._syData.toLowerCase()&&(this._staffHasExplicitDisplayTransposition=!1,this._staffHasExplicitTuning=!1,this._staffTuningApplied=!1,this._sy=this.newSy(),this._score.masterBars.length>0&&this.newTrack(),this._sy===Ne.String&&(this._currentTrack.name=this._syData,this._sy=this.newSy()),this._sy===Ne.String&&(this._currentTrack.shortName=this._syData,this._sy=this.newSy()),this.trackProperties()),this._sy===Ne.MetaCommand&&"staff"===this._syData.toLowerCase()){if(this._staffHasExplicitDisplayTransposition=!1,this._staffHasExplicitTuning=!1,this._staffTuningApplied=!1,this._sy=this.newSy(),this._currentTrack.staves[0].bars.length>0){const e=this._currentStaff.isPercussion;this._currentTrack.ensureStaveCount(this._currentTrack.staves.length+1),this.beginStaff(this._currentTrack.staves[this._currentTrack.staves.length-1]),e&&this.applyPercussionStaff(this._currentStaff),this._currentDynamics=g.F}this.staffProperties()}return this._sy===Ne.MetaCommand&&"voice"===this._syData.toLowerCase()&&(this._sy=this.newSy(),this.handleNewVoice()),!0}handleNewVoice(){if(0===this._voiceIndex&&(0===this._currentStaff.bars.length||1===this._currentStaff.bars.length&&this._currentStaff.bars[0].isEmpty))return!1;for(const e of this._currentStaff.bars){const t=new ee;e.addVoice(t)}return this._voiceIndex++,this._barIndex=0,!0}beginStaff(e){this._currentStaff=e,this._slurs.clear(),this._barIndex=0,this._voiceIndex=0}trackProperties(){if(this._sy===Ne.LBrace){for(this._sy=this.newSy();this._sy===Ne.String;)switch(this._syData.toLowerCase()){case"color":this._sy=this.newSy(),this._sy!==Ne.String&&this.error("track-color",Ne.String,!0),this._currentTrack.color=et.fromJson(this._syData),this._sy=this.newSy();break;case"defaultsystemslayout":this._sy=this.newSy(),this._sy===Ne.Number?(this._currentTrack.defaultSystemsLayout=this._syData,this._sy=this.newSy()):this.error("default-systems-layout",Ne.Number,!0);break;case"systemslayout":for(this._sy=this.newSy();this._sy===Ne.Number;)this._currentTrack.systemsLayout.push(this._syData),this._sy=this.newSy();break;case"volume":this._sy=this.newSy(),this._sy!==Ne.Number&&this.error("track-volume",Ne.Number,!0),this._currentTrack.playbackInfo.volume=ie.clamp(this._syData,0,16),this._sy=this.newSy();break;case"balance":this._sy=this.newSy(),this._sy!==Ne.Number&&this.error("track-balance",Ne.Number,!0),this._currentTrack.playbackInfo.balance=ie.clamp(this._syData,0,16),this._sy=this.newSy();break;case"mute":this._sy=this.newSy(),this._currentTrack.playbackInfo.isMute=!0;break;case"solo":this._sy=this.newSy(),this._currentTrack.playbackInfo.isSolo=!0;break;case"multibarrest":this._sy=this.newSy(),this._score.stylesheet.perTrackMultiBarRest||(this._score.stylesheet.perTrackMultiBarRest=new Set),this._score.stylesheet.perTrackMultiBarRest.add(this._currentTrack.index);break;default:this.error("track-properties",Ne.String,!1)}this._sy!==Ne.RBrace&&this.error("track-properties",Ne.RBrace,!0),this._sy=this.newSy()}}staffProperties(){if(this._sy!==Ne.LBrace)return;this._sy=this.newSy();let e=!1,t=!1,s=!1,i=!1;for(;this._sy===Ne.String;)switch(this._syData.toLowerCase()){case"score":e=!0,this._sy=this.newSy(),this._sy===Ne.Number&&(this._currentStaff.standardNotationLineCount=this._syData,this._sy=this.newSy());break;case"tabs":t=!0,this._sy=this.newSy();break;case"slash":s=!0,this._sy=this.newSy();break;case"numbered":i=!0,this._sy=this.newSy();break;default:this.error("staff-properties",Ne.String,!1)}(e||t||s||i)&&(this._currentStaff.showStandardNotation=e,this._currentStaff.showTablature=t,this._currentStaff.showSlash=s,this._currentStaff.showNumbered=i),this._sy!==Ne.RBrace&&this.error("staff-properties",Ne.RBrace,!0),this._sy=this.newSy()}bar(){const e=this.trackStaffMeta(),t=this.newBar(this._currentStaff);if(this._currentStaff.bars.length>this._score.masterBars.length){const e=new j;this._score.addMasterBar(e),e.index>0&&(e.timeSignatureDenominator=e.previousMasterBar.timeSignatureDenominator,e.timeSignatureNumerator=e.previousMasterBar.timeSignatureNumerator,e.tripletFeel=e.previousMasterBar.tripletFeel)}const s=this.barMeta(t),i=this._currentTrack.playbackInfo.program;this._staffTuningApplied||this._staffHasExplicitTuning||(this._currentStaff.stringTuning.tunings=[],15===i||i>=24&&i<=31?this._currentStaff.stringTuning.tunings=st.getDefaultTuningFor(6).tunings:i>=32&&i<=39?this._currentStaff.stringTuning.tunings=[43,38,33,28]:40===i||44===i||45===i||48===i||49===i||50===i||51===i?this._currentStaff.stringTuning.tunings=[52,57,50,43]:41===i?this._currentStaff.stringTuning.tunings=[57,50,43,36]:42===i?this._currentStaff.stringTuning.tunings=[45,38,31,24]:43===i?this._currentStaff.stringTuning.tunings=[43,38,33,28]:105===i?this._currentStaff.stringTuning.tunings=[50,47,43,38,55]:106===i?this._currentStaff.stringTuning.tunings=[57,52,45]:107===i?this._currentStaff.stringTuning.tunings=[52,45,38,31]:110===i&&(this._currentStaff.stringTuning.tunings=[64,57,50,43]),this._staffTuningApplied=!0),this._staffHasExplicitDisplayTransposition||(this._currentStaff.displayTranspositionPitch=i>=24&&i<=31||i>=32&&i<=39||43===i?-12:0);let a=!1;const r=t.voices[this._voiceIndex];if(!(this._sy===Ne.MetaCommand&&("track"===this._syData.toLowerCase()||"staff"===this._syData.toLowerCase())))for(;this._sy!==Ne.Pipe&&this._sy!==Ne.Eof&&this.beat(r);)a=!0;if(0===r.beats.length){const e=new ze;e.isEmpty=!0,r.addBeat(e)}return e||s||a}newBar(e){if(this._barIndex<e.bars.length){const t=e.bars[this._barIndex];return this._barIndex++,t}const t=0===e.bars.length?1:e.bars[0].voices.length,s=new G;e.addBar(s),s.previousBar&&(s.clef=s.previousBar.clef,s.clefOttava=s.previousBar.clefOttava,s.keySignature=s.previousBar.keySignature,s.keySignatureType=s.previousBar.keySignatureType),this._barIndex++;for(let e=0;e<t;e++){const e=new ee;s.addVoice(e)}return s}beat(e){this.beatDuration();const t=new ze;if(e.addBeat(t),this._allowTuning=!this._currentStaff.isPercussion,this._sy===Ne.LParensis){for(this._sy=this.newSy(),this.note(t);this._sy!==Ne.RParensis&&this._sy!==Ne.Eof&&(this._allowTuning=!this._currentStaff.isPercussion,this.note(t)););this._sy!==Ne.RParensis&&this.error("note-list",Ne.RParensis,!0),this._sy=this.newSy()}else if(this._sy===Ne.String&&"r"===this._syData.toLowerCase())this._sy=this.newSy();else if(!this.note(t))return e.beats.splice(e.beats.length-1,1),!1;this._sy===Ne.Dot&&(this._allowNegatives=!0,this._sy=this.newSy(),this._allowNegatives=!1,this._sy!==Ne.Number&&this.error("duration",Ne.Number,!0),this._currentDuration=this.parseDuration(this._syData),this._sy=this.newSy()),t.duration=this._currentDuration,t.dynamics=this._currentDynamics,1===this._currentTuplet||t.hasTuplet||dt.applyTuplet(t,this._currentTuplet);let s=1;this._sy===Ne.Multiply&&(this._sy=this.newSy(),this._sy!==Ne.Number?this.error("multiplier",Ne.Number,!0):s=this._syData,this._sy=this.newSy()),this.beatEffects(t);for(let i=0;i<s-1;i++)e.addBeat(Ve.clone(t));return!0}beatDuration(){if(this._sy===Ne.DoubleDot&&(this._allowNegatives=!0,this._sy=this.newSy(),this._allowNegatives=!1,this._sy!==Ne.Number&&this.error("duration",Ne.Number,!0),this._currentDuration=this.parseDuration(this._syData),this._currentTuplet=1,this._sy=this.newSy(),this._sy===Ne.LBrace)){for(this._sy=this.newSy();this._sy===Ne.String;){if("tu"===this._syData.toLowerCase())this._sy=this.newSy(),this._sy!==Ne.Number&&this.error("duration-tuplet",Ne.Number,!0),this._currentTuplet=this._syData,this._sy=this.newSy();else this.error("beat-duration",Ne.String,!1)}this._sy!==Ne.RBrace&&this.error("beat-duration",Ne.RBrace,!0),this._sy=this.newSy()}}beatEffects(e){if(this._sy===Ne.LBrace){for(this._sy=this.newSy();this._sy===Ne.String;)this.applyBeatEffect(e)||this.error("beat-effects",Ne.String,!1);this._sy!==Ne.RBrace&&this.error("beat-effects",Ne.RBrace,!0),this._sy=this.newSy()}}applyBeatEffect(e){const t=this._syData.toLowerCase();if("f"===t)e.fade=ue.FadeIn;else if("fo"===t)e.fade=ue.FadeOut;else if("vs"===t)e.fade=ue.VolumeSwell;else if("v"===t)e.vibrato=P.Slight;else if("vw"===t)e.vibrato=P.Wide;else if("s"===t)e.slap=!0;else if("p"===t)e.pop=!0;else if("tt"===t)e.tap=!0;else if("txt"===t){if(this._sy=this.newSy(),this._sy!==Ne.String)return this.error("beat-text",Ne.String,!0),!1;e.text=this._syData}else if("dd"===t)e.dots=2;else if("d"===t)e.dots=1;else if("su"===t)e.pickStroke=ae.Up;else if("sd"===t)e.pickStroke=ae.Down;else{if("tu"===t){if(this._sy=this.newSy(),this._sy!==Ne.Number)return this.error("tuplet",Ne.Number,!0),!1;const t=this._syData;if(this._sy=this.newSy(),this._sy===Ne.Number){const s=this._syData;this._sy=this.newSy(),e.tupletNumerator=t,e.tupletDenominator=s}else dt.applyTuplet(e,t);return!0}if("tb"===t||"tbe"===t){this._sy=this.newSy();const s="tbe"===t;for(this._sy===Ne.String&&(e.whammyBarType=this.parseWhammyType(this._syData),this._sy=this.newSy()),this._sy===Ne.String&&(e.whammyStyle=this.parseBendStyle(this._syData),this._sy=this.newSy()),this._sy!==Ne.LParensis&&this.error("tremolobar-effect",Ne.LParensis,!0),this._allowNegatives=!0,this._allowFloat=!0,this._sy=this.newSy();this._sy!==Ne.RParensis&&this._sy!==Ne.Eof;){let t=0,i=0;s?(this._sy!==Ne.Number&&this.error("tremolobar-effect",Ne.Number,!0),t=this._syData,this._sy=this.newSy(),this._sy!==Ne.Number&&this.error("tremolobar-effect",Ne.Number,!0),i=this._syData):(this._sy!==Ne.Number&&this.error("tremolobar-effect",Ne.Number,!0),t=0,i=this._syData),e.addWhammyBarPoint(new X(t,i)),this._sy=this.newSy()}if(null!=e.whammyBarPoints){for(;e.whammyBarPoints.length>60;)e.removeWhammyBarPoint(e.whammyBarPoints.length-1);if(s)e.whammyBarPoints.sort(((e,t)=>e.offset-t.offset));else{const t=e.whammyBarPoints.length,s=60/t|0;let i=0;for(;i<t;)e.whammyBarPoints[i].offset=Math.min(60,i*s),i++}}this._allowNegatives=!1,this._allowFloat=!1,this._sy!==Ne.RParensis&&this.error("tremolobar-effect",Ne.RParensis,!0)}else{if("bu"===t||"bd"===t||"au"===t||"ad"===t){switch(t){case"bu":e.brushType=b.BrushUp;break;case"bd":e.brushType=b.BrushDown;break;case"au":e.brushType=b.ArpeggioUp;break;case"ad":e.brushType=b.ArpeggioDown}return this._sy=this.newSy(),this._sy===Ne.Number?(e.brushDuration=this._syData,this._sy=this.newSy(),!0):(e.updateDurations(),"bu"===t||"bd"===t?e.brushDuration=e.playbackDuration/4/e.notes.length:"au"!==t&&"ad"!==t||(e.brushDuration=e.playbackDuration/e.notes.length),!0)}if("ch"===t){this._sy=this.newSy();const t=this._syData,s=this.getChordId(this._currentStaff,t);if(!this._currentStaff.hasChord(s)){const e=new je;e.showDiagram=!1,e.name=t,this._currentStaff.addChord(s,e)}e.chordId=s}else{if("gr"===t)return this._sy=this.newSy(),"ob"===this._syData.toLowerCase()?(e.graceType=w.OnBeat,this._sy=this.newSy()):"b"===this._syData.toLowerCase()?(e.graceType=w.BendGrace,this._sy=this.newSy()):e.graceType=w.BeforeBeat,!0;if("dy"===t){this._sy=this.newSy();const t=this._syData.toUpperCase();switch(t){case"PPP":case"PP":case"P":case"MP":case"MF":case"F":case"FF":case"FFF":case"PPPP":case"PPPPP":case"PPPPPP":case"FFFF":case"FFFFF":case"FFFFFF":case"SF":case"SFP":case"SFPP":case"FP":case"RF":case"RFZ":case"SFZ":case"SFFZ":case"FZ":case"N":case"PF":case"SFZP":e.dynamics=g[t]}this._currentDynamics=e.dynamics}else if("cre"===t)e.crescendo=S.Crescendo;else if("dec"===t)e.crescendo=S.Decrescendo;else{if("tempo"===t){const t=this.readTempoAutomation();return e.automations.push(t),e.voice.bar.masterBar.tempoAutomations.push(t),!0}if("tp"===t){if(this._sy=this.newSy(),e.tremoloSpeed=_.Eighth,this._sy===Ne.Number){switch(this._syData){case 8:default:e.tremoloSpeed=_.Eighth;break;case 16:e.tremoloSpeed=_.Sixteenth;break;case 32:e.tremoloSpeed=_.ThirtySecond}this._sy=this.newSy()}return!0}if("spd"===t){const t=new W;return t.pedalType=d.Down,t.ratioPosition=e.voice.bar.sustainPedals.length,this._sustainPedalToBeat.set(t,e),e.voice.bar.sustainPedals.push(t),this._sy=this.newSy(),!0}if("spu"===t){const t=new W;return t.pedalType=d.Up,t.ratioPosition=e.voice.bar.sustainPedals.length,this._sustainPedalToBeat.set(t,e),e.voice.bar.sustainPedals.push(t),this._sy=this.newSy(),!0}if("spe"===t){const t=new W;return t.pedalType=d.Up,t.ratioPosition=1,e.voice.bar.sustainPedals.push(t),this._sy=this.newSy(),!0}if("slashed"===t)return e.slashed=!0,this._sy=this.newSy(),!0;if("ds"===t)return e.deadSlapped=!0,this._sy=this.newSy(),!0;if("glpf"===t)return this._sy=this.newSy(),e.golpe=de.Finger,!0;if("glpt"===t)return this._sy=this.newSy(),e.golpe=de.Thumb,!0;if("waho"===t)return this._sy=this.newSy(),e.wahPedal=pe.Open,!0;if("wahc"===t)return this._sy=this.newSy(),e.wahPedal=pe.Closed,!0;if("barre"===t){if(this._sy=this.newSy(),this._sy!==Ne.Number&&this.error("beat-barre",Ne.Number,!0),e.barreFret=this._syData,e.barreShape=ge.Full,this._sy=this.newSy(),this._sy===Ne.String)switch(this._syData.toLowerCase()){case"full":e.barreShape=ge.Full,this._sy=this.newSy();break;case"half":e.barreShape=ge.Half,this._sy=this.newSy()}return!0}if("rasg"===t){switch(this._sy=this.newSy(),this._sy!==Ne.String&&this.error("rasgueado",Ne.String,!0),this._syData.toLowerCase()){case"ii":e.rasgueado=me.Ii;break;case"mi":e.rasgueado=me.Mi;break;case"miitriplet":e.rasgueado=me.MiiTriplet;break;case"miianapaest":e.rasgueado=me.MiiAnapaest;break;case"pmptriplet":e.rasgueado=me.PmpTriplet;break;case"pmpanapaest":e.rasgueado=me.PmpAnapaest;break;case"peitriplet":e.rasgueado=me.PeiTriplet;break;case"peianapaest":e.rasgueado=me.PeiAnapaest;break;case"paitriplet":e.rasgueado=me.PaiTriplet;break;case"paianapaest":e.rasgueado=me.PaiAnapaest;break;case"amitriplet":e.rasgueado=me.AmiTriplet;break;case"amianapaest":e.rasgueado=me.AmiAnapaest;break;case"ppp":e.rasgueado=me.Ppp;break;case"amii":e.rasgueado=me.Amii;break;case"amip":e.rasgueado=me.Amip;break;case"eami":e.rasgueado=me.Eami;break;case"eamii":e.rasgueado=me.Eamii;break;case"peami":e.rasgueado=me.Peami}return this._sy=this.newSy(),!0}if("ot"===t)this._sy=this.newSy(),this._sy!==Ne.String&&this.error("beat-ottava",Ne.String,!0),e.ottava=this.parseClefOttavaFromString(this._syData);else if("legatoorigin"===t)e.isLegatoOrigin=!0;else{if("instrument"!==t){if("fermata"===t){this._sy=this.newSy(),this._sy!==Ne.String&&this.error("fermata",Ne.Number,!0);const t=new lt;return t.type=this.parseFermataFromString(this._syData),this._allowFloat=!0,this._sy=this.newSy(),this._sy===Ne.Number&&(t.length=this._syData,this._sy=this.newSy()),this._allowFloat=!1,e.fermata=t,!0}if("beam"===t){switch(this._sy=this.newSy(),this._sy!==Ne.String&&this.error("beam",Ne.Number,!0),this._syData.toLowerCase()){case"invert":e.invertBeamDirection=!0;break;case"up":e.preferredBeamDirection=Te.Up;break;case"down":e.preferredBeamDirection=Te.Down;break;case"auto":e.beamingMode=fe.Auto;break;case"split":e.beamingMode=fe.ForceSplitToNext;break;case"merge":e.beamingMode=fe.ForceMergeWithNext;break;case"splitsecondary":e.beamingMode=fe.ForceSplitOnSecondaryToNext}return this._sy=this.newSy(),!0}return"timer"===t&&(e.showTimer=!0,this._sy=this.newSy(),!0)}{this._sy=this.newSy();let t=0;this._sy===Ne.Number?t=this._syData:this._sy===Ne.String?t=A.getValue(this._syData):this.error("instrument-change",Ne.Number,!0);const s=new U;s.isLinear=!1,s.type=m.Instrument,s.value=t,e.automations.push(s)}}}}}}return this._sy=this.newSy(),!0}parseBracketExtendMode(e){switch(e.toLowerCase()){case"nobrackets":return s.NoBrackets;case"groupstaves":default:return s.GroupStaves;case"groupsimilarinstruments":return s.GroupSimilarInstruments}}parseFermataFromString(e){switch(e.toLowerCase()){case"short":return ke.Short;case"medium":default:return ke.Medium;case"long":return ke.Long}}parseClefOttavaFromString(e){switch(e.toLowerCase()){case"15ma":return o._15ma;case"8va":return o._8va;case"regular":default:return o.Regular;case"8vb":return o._8vb;case"15mb":return o._15mb}}getChordId(e,t){return t.toLowerCase()+e.index+e.track.index}static applyTuplet(e,t){switch(t){case 3:e.tupletNumerator=3,e.tupletDenominator=2;break;case 5:e.tupletNumerator=5,e.tupletDenominator=4;break;case 6:e.tupletNumerator=6,e.tupletDenominator=4;break;case 7:e.tupletNumerator=7,e.tupletDenominator=4;break;case 9:e.tupletNumerator=9,e.tupletDenominator=8;break;case 10:e.tupletNumerator=10,e.tupletDenominator=8;break;case 11:e.tupletNumerator=11,e.tupletDenominator=8;break;case 12:e.tupletNumerator=12,e.tupletDenominator=8;break;default:e.tupletNumerator=1,e.tupletDenominator=1}}isNoteText(e){return"x"===e||"-"===e||"r"===e}note(e){let t=!1,s=!1,i=-1,a=-1,r=-1,n=N.Default;switch(this._sy){case Ne.Number:i=this._syData,this._currentStaff.isPercussion&&!Le.instrumentArticulations.has(i)&&this.errorMessage(`Unknown percussion articulation ${i}`);break;case Ne.String:if(this._currentStaff.isPercussion){const e=this._syData.toLowerCase();this._percussionArticulationNames.has(e)?i=this._percussionArticulationNames.get(e):this.errorMessage(`Unknown percussion articulation '${this._syData}'`)}else t="x"===this._syData,s="-"===this._syData,s||t?i=0:this.error("note-fret",Ne.Number,!0);break;case Ne.Tuning:0===e.index&&0===e.voice.index&&0===e.voice.bar.index&&this.makeCurrentStaffPitched();const o=this._syData;a=o.octave,r=o.tone.noteValue,this._accidentalMode===ve.Explicit&&(n=o.tone.accidentalMode);break;default:return!1}this._sy=this.newSy();const o=-1===a&&this._currentStaff.tuning.length>0&&!this._currentStaff.isPercussion;let h=-1;o&&(this._sy!==Ne.Dot&&this.error("note",Ne.Dot,!0),this._sy=this.newSy(),this._sy!==Ne.Number&&this.error("note-string",Ne.Number,!0),h=this._syData,(h<1||h>this._currentStaff.tuning.length)&&this.error("note-string",Ne.Number,!1),this._sy=this.newSy());const l=new Ae;if(o)l.string=this._currentStaff.tuning.length-(h-1),l.isDead=t,l.isTieDestination=s,s||(l.fret=i);else if(this._currentStaff.isPercussion){const e=i;let t=0;if(this._articulationValueToIndex.has(e))t=this._articulationValueToIndex.get(e);else{t=this._currentTrack.percussionArticulations.length;const s=Le.getArticulationByInputMidiNumber(e);null===s&&this.errorMessage(`Unknown articulation value ${e}`),this._currentTrack.percussionArticulations.push(s),this._articulationValueToIndex.set(e,t)}l.percussionArticulation=t}else l.octave=a,l.tone=r,l.accidentalMode=n,l.isTieDestination=s;return e.addNote(l),this.noteEffects(l),!0}noteEffects(e){if(this._sy===Ne.LBrace){for(this._sy=this.newSy();this._sy===Ne.String;){const t=this._syData.toLowerCase();if("b"===t||"be"===t){this._sy=this.newSy();const s="be"===t;for(this._sy===Ne.String&&(e.bendType=this.parseBendType(this._syData),this._sy=this.newSy()),this._sy===Ne.String&&(e.bendStyle=this.parseBendStyle(this._syData),this._sy=this.newSy()),this._sy!==Ne.LParensis&&this.error("bend-effect",Ne.LParensis,!0),this._sy=this.newSy();this._sy!==Ne.RParensis&&this._sy!==Ne.Eof;){let t=0,i=0;s?(this._sy!==Ne.Number&&this.error("bend-effect-value",Ne.Number,!0),t=this._syData,this._sy=this.newSy(),this._sy!==Ne.Number&&this.error("bend-effect-value",Ne.Number,!0),i=this._syData):(this._sy!==Ne.Number&&this.error("bend-effect-value",Ne.Number,!0),i=this._syData),e.addBendPoint(new X(t,i)),this._sy=this.newSy()}const i=e.bendPoints;if(null!=i){for(;i.length>60;)i.splice(i.length-1,1);if(s)i.sort(((e,t)=>e.offset-t.offset));else{const e=i.length,t=60/(e-1)|0;let s=0;for(;s<e;)i[s].offset=Math.min(60,s*t),s++}}this._sy!==Ne.RParensis&&this.error("bend-effect",Ne.RParensis,!0),this._sy=this.newSy()}else if("nh"===t)e.harmonicType=T.Natural,e.harmonicValue=ie.deltaFretToHarmonicValue(e.fret),this._sy=this.newSy();else if("ah"===t)e.harmonicType=T.Artificial,e.harmonicValue=this.harmonicValue(e.harmonicValue);else if("th"===t)e.harmonicType=T.Tap,e.harmonicValue=this.harmonicValue(e.harmonicValue);else if("ph"===t)e.harmonicType=T.Pinch,e.harmonicValue=this.harmonicValue(e.harmonicValue);else if("sh"===t)e.harmonicType=T.Semi,e.harmonicValue=this.harmonicValue(e.harmonicValue);else if("fh"===t)e.harmonicType=T.Feedback,e.harmonicValue=this.harmonicValue(e.harmonicValue);else if("tr"===t){this._sy=this.newSy(),this._sy!==Ne.Number&&this.error("trill-effect",Ne.Number,!0);const t=this._syData;this._sy=this.newSy();let s=_.Sixteenth;if(this._sy===Ne.Number){switch(this._syData){case 16:default:s=_.Sixteenth;break;case 32:s=_.ThirtySecond;break;case 64:s=_.SixtyFourth}this._sy=this.newSy()}e.trillValue=t+e.stringTuning,e.trillSpeed=s}else if("v"===t)this._sy=this.newSy(),e.vibrato=P.Slight;else if("sl"===t)this._sy=this.newSy(),e.slideOutType=v.Legato;else if("ss"===t)this._sy=this.newSy(),e.slideOutType=v.Shift;else if("sib"===t)this._sy=this.newSy(),e.slideInType=x.IntoFromBelow;else if("sia"===t)this._sy=this.newSy(),e.slideInType=x.IntoFromAbove;else if("sou"===t)this._sy=this.newSy(),e.slideOutType=v.OutUp;else if("sod"===t)this._sy=this.newSy(),e.slideOutType=v.OutDown;else if("psd"===t)this._sy=this.newSy(),e.slideOutType=v.PickSlideDown;else if("psu"===t)this._sy=this.newSy(),e.slideOutType=v.PickSlideUp;else if("h"===t)this._sy=this.newSy(),e.isHammerPullOrigin=!0;else if("lht"===t)this._sy=this.newSy(),e.isLeftHandTapped=!0;else if("g"===t)this._sy=this.newSy(),e.isGhost=!0;else if("ac"===t)this._sy=this.newSy(),e.accentuated=B.Normal;else if("hac"===t)this._sy=this.newSy(),e.accentuated=B.Heavy;else if("ten"===t)this._sy=this.newSy(),e.accentuated=B.Tenuto;else if("pm"===t)this._sy=this.newSy(),e.isPalmMute=!0;else if("st"===t)this._sy=this.newSy(),e.isStaccato=!0;else if("lr"===t)this._sy=this.newSy(),e.isLetRing=!0;else if("x"===t)this._sy=this.newSy(),e.fret=0,e.isDead=!0;else if("-"===t||"t"===t)this._sy=this.newSy(),e.isTieDestination=!0;else if("lf"===t){this._sy=this.newSy();let t=k.Thumb;this._sy===Ne.Number&&(t=this.toFinger(this._syData),this._sy=this.newSy()),e.leftHandFinger=t}else if("rf"===t){this._sy=this.newSy();let t=k.Thumb;this._sy===Ne.Number&&(t=this.toFinger(this._syData),this._sy=this.newSy()),e.rightHandFinger=t}else if("acc"===t)this._sy=this.newSy(),this._sy!==Ne.String&&this.error("note-accidental",Ne.String,!0),e.accidentalMode=ie.parseAccidentalMode(this._syData),this._sy=this.newSy();else if("turn"===t)this._sy=this.newSy(),e.ornament=he.Turn;else if("iturn"===t)this._sy=this.newSy(),e.ornament=he.InvertedTurn;else if("umordent"===t)this._sy=this.newSy(),e.ornament=he.UpperMordent;else if("lmordent"===t)this._sy=this.newSy(),e.ornament=he.LowerMordent;else if("string"===t)this._sy=this.newSy(),e.showStringNumber=!0;else if("hide"===t)this._sy=this.newSy(),e.isVisible=!1;else if("slur"===t){this._sy=this.newSy(),this._sy!==Ne.String&&this.error("slur",Ne.String,!0);const t=this._syData;if(this._slurs.has(t)){const s=this._slurs.get(t);s.slurDestination=e,e.slurOrigin=s,e.isSlurDestination=!0}else this._slurs.set(t,e);this._sy=this.newSy()}else this.applyBeatEffect(e.beat)||this.error(t,Ne.String,!1)}this._sy!==Ne.RBrace&&this.error("note-effect",Ne.RBrace,!1),this._sy=this.newSy()}}harmonicValue(e){return this._allowNegatives=!0,this._allowFloat=!0,this._sy=this.newSy(),this._sy===Ne.Number&&(e=this._syData,this._sy=this.newSy()),this._allowNegatives=!1,this._allowFloat=!1,e}toFinger(e){switch(e){case 1:return k.Thumb;case 2:return k.IndexFinger;case 3:return k.MiddleFinger;case 4:return k.AnnularFinger;case 5:return k.LittleFinger}return k.Thumb}parseDuration(e){switch(e){case-4:return _.QuadrupleWhole;case-2:return _.DoubleWhole;case 1:return _.Whole;case 2:return _.Half;case 4:return _.Quarter;case 8:return _.Eighth;case 16:return _.Sixteenth;case 32:return _.ThirtySecond;case 64:return _.SixtyFourth;case 128:return _.OneHundredTwentyEighth;case 256:return _.TwoHundredFiftySixth;default:return _.Quarter}}parseBendStyle(e){switch(e.toLowerCase()){case"gradual":return f.Gradual;case"fast":return f.Fast;default:return f.Default}}parseBendType(e){switch(e.toLowerCase()){case"none":return y.None;case"custom":default:return y.Custom;case"bend":return y.Bend;case"release":return y.Release;case"bendrelease":return y.BendRelease;case"hold":return y.Hold;case"prebend":return y.Prebend;case"prebendbend":return y.PrebendBend;case"prebendrelease":return y.PrebendRelease}}barMeta(e){let t=!1;const s=e.masterBar;let i=!1;for(;!i&&this._sy===Ne.MetaCommand;){t=!0;const a=this._syData.toLowerCase();if("ts"===a)this._sy=this.newSy(),this._sy===Ne.String?"common"===this._syData.toLowerCase()?(s.timeSignatureCommon=!0,s.timeSignatureNumerator=4,s.timeSignatureDenominator=4,this._sy=this.newSy()):this.error("timesignature-numerator",Ne.String,!0):(this._sy!==Ne.Number&&this.error("timesignature-numerator",Ne.Number,!0),s.timeSignatureNumerator=this._syData,this._sy=this.newSy(),this._sy!==Ne.Number&&this.error("timesignature-denominator",Ne.Number,!0),s.timeSignatureDenominator=this._syData,this._sy=this.newSy());else if("ft"===a)s.isFreeTime=!0,this._sy=this.newSy();else if("ro"===a)s.isRepeatStart=!0,this._sy=this.newSy();else if("rc"===a)this._sy=this.newSy(),this._sy!==Ne.Number&&this.error("repeatclose",Ne.Number,!0),this._syData>2048&&this.error("repeatclose",Ne.Number,!1),s.repeatCount=this._syData,this._sy=this.newSy();else if("ae"===a)if(this._sy=this.newSy(),this._sy===Ne.LParensis){for(this._sy=this.newSy(),this._sy!==Ne.Number&&this.error("alternateending",Ne.Number,!0),this.applyAlternateEnding(s);this._sy===Ne.Number;)this.applyAlternateEnding(s);this._sy!==Ne.RParensis&&this.error("alternateending-list",Ne.RParensis,!0),this._sy=this.newSy()}else this._sy!==Ne.Number&&this.error("alternateending",Ne.Number,!0),this.applyAlternateEnding(s);else if("ks"===a)this._sy=this.newSy(),this._sy!==Ne.String&&this.error("keysignature",Ne.String,!0),e.keySignature=this.parseKeySignature(this._syData),e.keySignatureType=this.parseKeySignatureType(this._syData),this._sy=this.newSy();else if("clef"===a){switch(this._sy=this.newSy(),this._sy){case Ne.String:e.clef=this.parseClefFromString(this._syData);break;case Ne.Number:e.clef=this.parseClefFromInt(this._syData);break;case Ne.Tuning:const t=this._syData;e.clef=this.parseClefFromInt(t.realValue);break;default:this.error("clef",Ne.String,!0)}this._sy=this.newSy()}else if("tempo"===a){const e=this.readTempoAutomation();s.tempoAutomations.push(e)}else if("section"===a){this._sy=this.newSy(),this._sy!==Ne.String&&this.error("section",Ne.String,!0);let e=this._syData;this._sy=this.newSy();let t="";this._sy!==Ne.String||this.isNoteText(this._syData.toLowerCase())||(t=e,e=this._syData,this._sy=this.newSy());const i=new Qe;i.marker=t,i.text=e,s.section=i}else if("tf"===a){switch(this._allowTuning=!1,this._sy=this.newSy(),this._allowTuning=!0,this._sy){case Ne.String:s.tripletFeel=this.parseTripletFeelFromString(this._syData);break;case Ne.Number:s.tripletFeel=this.parseTripletFeelFromInt(this._syData);break;default:this.error("triplet-feel",Ne.String,!0)}this._sy=this.newSy()}else if("ac"===a)s.isAnacrusis=!0,this._sy=this.newSy();else if("db"===a)s.isDoubleBar=!0,e.barLineRight=p.LightLight,this._sy=this.newSy();else if("barlineleft"===a)this._sy=this.newSy(),this._sy!==Ne.String&&this.error("barlineleft",Ne.String,!0),e.barLineLeft=this.parseBarLineStyle(this._syData),this._sy=this.newSy();else if("barlineright"===a)this._sy=this.newSy(),this._sy!==Ne.String&&this.error("barlineright",Ne.String,!0),e.barLineRight=this.parseBarLineStyle(this._syData),this._sy=this.newSy();else if("accidentals"===a)this.handleAccidentalMode();else if("jump"===a)this.handleDirections(s);else if("ottava"===a)this._sy=this.newSy(),this._sy!==Ne.String&&this.error("ottava",Ne.String,!0),e.clefOttava=this.parseClefOttavaFromString(this._syData),this._sy=this.newSy();else if("simile"===a)this._sy=this.newSy(),this._sy!==Ne.String&&this.error("simile",Ne.String,!0),e.simileMark=this.parseSimileMarkFromString(this._syData),this._sy=this.newSy();else if("scale"===a)this._allowFloat=!0,this._sy=this.newSy(),this._allowFloat=!1,this._sy!==Ne.Number&&this.error("scale",Ne.Number,!0),s.displayScale=this._syData,e.displayScale=this._syData,this._sy=this.newSy();else if("width"===a)this._sy=this.newSy(),this._sy!==Ne.Number&&this.error("width",Ne.Number,!0),s.displayWidth=this._syData,e.displayWidth=this._syData,this._sy=this.newSy();else if(0===e.index)switch(this.handleStaffMeta()){case xe.KnownStaffMeta:break;case xe.UnknownStaffMeta:this.error("measure-effects",Ne.String,!1);break;case xe.EndOfMetaDetected:i=!0}else if(this.handleStaffMeta()===xe.EndOfMetaDetected)i=!0;else this.error("measure-effects",Ne.String,!1)}if(0===s.index&&0===s.tempoAutomations.length){const e=new U;e.isLinear=!1,e.type=m.Tempo,e.value=this._score.tempo,e.text=this._score.tempoLabel,s.tempoAutomations.push(e)}return t}parseBarLineStyle(e){switch(e.toLowerCase()){case"automatic":return p.Automatic;case"dashed":return p.Dashed;case"dotted":return p.Dotted;case"heavy":return p.Heavy;case"heavyheavy":return p.HeavyHeavy;case"heavylight":return p.HeavyLight;case"lightheavy":return p.LightHeavy;case"lightlight":return p.LightLight;case"none":return p.None;case"regular":return p.Regular;case"short":return p.Short;case"tick":return p.Tick}return p.Automatic}parseSimileMarkFromString(e){switch(e.toLowerCase()){case"none":default:return h.None;case"simple":return h.Simple;case"firstofdouble":return h.FirstOfDouble;case"secondofdouble":return h.SecondOfDouble}}handleDirections(e){switch(this._sy=this.newSy(),this._sy!==Ne.String&&this.error("direction",Ne.String,!0),this._syData.toLowerCase()){case"fine":e.addDirection(Be.TargetFine);break;case"segno":e.addDirection(Be.TargetSegno);break;case"segnosegno":e.addDirection(Be.TargetSegnoSegno);break;case"coda":e.addDirection(Be.TargetCoda);break;case"doublecoda":e.addDirection(Be.TargetDoubleCoda);break;case"dacapo":e.addDirection(Be.JumpDaCapo);break;case"dacapoalcoda":e.addDirection(Be.JumpDaCapoAlCoda);break;case"dacapoaldoublecoda":e.addDirection(Be.JumpDaCapoAlDoubleCoda);break;case"dacapoalfine":e.addDirection(Be.JumpDaCapoAlFine);break;case"dalsegno":e.addDirection(Be.JumpDalSegno);break;case"dalsegnoalcoda":e.addDirection(Be.JumpDalSegnoAlCoda);break;case"dalsegnoaldoublecoda":e.addDirection(Be.JumpDalSegnoAlDoubleCoda);break;case"dalsegnoalfine":e.addDirection(Be.JumpDalSegnoAlFine);break;case"dalsegnosegno":e.addDirection(Be.JumpDalSegnoSegno);break;case"dalsegnosegnoalcoda":e.addDirection(Be.JumpDalSegnoSegnoAlCoda);break;case"dalsegnosegnoaldoublecoda":e.addDirection(Be.JumpDalSegnoSegnoAlDoubleCoda);break;case"dalsegnosegnoalfine":e.addDirection(Be.JumpDalSegnoSegnoAlFine);break;case"dacoda":e.addDirection(Be.JumpDaCoda);break;case"dadoublecoda":e.addDirection(Be.JumpDaDoubleCoda);break;default:return void this.errorMessage(`Unexpected direction value: '${this._syData}'`)}this._sy=this.newSy()}readTempoAutomation(){this._allowFloat=!0,this._sy=this.newSy(),this._allowFloat=!1,this._sy!==Ne.Number&&this.error("tempo",Ne.Number,!0);const e=new U;return e.isLinear=!1,e.type=m.Tempo,e.value=this._syData,this._sy=this.newSy(),this._sy===Ne.String&&(e.text=this._syData,this._sy=this.newSy()),e}applyAlternateEnding(e){const t=this._syData;t<1&&this.error("alternateending",Ne.Number,!0),e.alternateEndings|=1<<t-1,this._sy=this.newSy()}parseWhammyType(e){switch(e.toLowerCase()){case"none":return ce.None;case"custom":default:return ce.Custom;case"dive":return ce.Dive;case"dip":return ce.Dip;case"hold":return ce.Hold;case"predive":return ce.Predive;case"predivedive":return ce.PrediveDive}}}dt.Eof=0;class ut extends Ye{constructor(){super(...arguments),this._versionNumber=0,this._globalTripletFeel=M.NoTripletFeel,this._lyricsTrack=0,this._lyrics=[],this._barCount=0,this._trackCount=0,this._playbackInfos=[],this._doubleBars=new Set,this._keySignatures=new Map,this._beatTextChunksByTrack=new Map,this._directionLookup=new Map}get name(){return"Guitar Pro 3-5"}readScore(){if(this._directionLookup.clear(),this.readVersion(),this._score=new Je,this.readScoreInformation(),this._versionNumber<500&&(this._globalTripletFeel=pt.gpReadBool(this.data)?M.Triplet8th:M.NoTripletFeel),this._versionNumber>=400&&this.readLyrics(),this._versionNumber>=510&&this.data.skip(19),this._versionNumber>=500&&(this.readPageSetup(),this._score.tempoLabel=pt.gpReadStringIntByte(this.data,this.settings.importer.encoding)),this._score.tempo=ot.readInt32LE(this.data),this._versionNumber>=510&&pt.gpReadBool(this.data),ot.readInt32LE(this.data),this._versionNumber>=400&&this.data.readByte(),this.readPlaybackInfos(),this._versionNumber>=500&&(this.readDirection(Be.TargetCoda),this.readDirection(Be.TargetDoubleCoda),this.readDirection(Be.TargetSegno),this.readDirection(Be.TargetSegnoSegno),this.readDirection(Be.TargetFine),this.readDirection(Be.JumpDaCapo),this.readDirection(Be.JumpDaCapoAlCoda),this.readDirection(Be.JumpDaCapoAlDoubleCoda),this.readDirection(Be.JumpDaCapoAlFine),this.readDirection(Be.JumpDalSegno),this.readDirection(Be.JumpDalSegnoAlCoda),this.readDirection(Be.JumpDalSegnoAlDoubleCoda),this.readDirection(Be.JumpDalSegnoAlFine),this.readDirection(Be.JumpDalSegnoSegno),this.readDirection(Be.JumpDalSegnoSegnoAlCoda),this.readDirection(Be.JumpDalSegnoSegnoAlDoubleCoda),this.readDirection(Be.JumpDalSegnoSegnoAlFine),this.readDirection(Be.JumpDaCoda),this.readDirection(Be.JumpDaDoubleCoda),this.data.skip(4)),this._barCount=ot.readInt32LE(this.data),this._trackCount=ot.readInt32LE(this.data),this.readMasterBars(),this.readTracks(),this.readBars(),this._score.masterBars.length>0){const e=U.buildTempoAutomation(!1,0,this._score.tempo,2);e.text=this._score.tempoLabel,this._score.masterBars[0].tempoAutomations.push(e)}return ie.consolidate(this._score),this._score.finish(this.settings),this._lyrics&&this._lyricsTrack>=0&&this._score.tracks[this._lyricsTrack].applyLyrics(this._lyrics),this._score}readDirection(e){let t,s=ot.readInt16LE(this.data);-1!==s&&(s--,this._directionLookup.has(s)?t=this._directionLookup.get(s):(t=[],this._directionLookup.set(s,t)),t.push(e))}readVersion(){let e=pt.gpReadStringByteLength(this.data,30,this.settings.importer.encoding);if(!e.startsWith(ut.VersionString))throw new qe("Unsupported format");e=e.substr(ut.VersionString.length+1);const t=e.indexOf(String.fromCharCode(46));this._versionNumber=100*Number.parseInt(e.substr(0,t))+Number.parseInt(e.substr(t+1)),q.debug(this.name,`Guitar Pro version ${e} detected`)}readScoreInformation(){this._score.title=pt.gpReadStringIntUnused(this.data,this.settings.importer.encoding),this._score.subTitle=pt.gpReadStringIntUnused(this.data,this.settings.importer.encoding),this._score.artist=pt.gpReadStringIntUnused(this.data,this.settings.importer.encoding),this._score.album=pt.gpReadStringIntUnused(this.data,this.settings.importer.encoding),this._score.words=pt.gpReadStringIntUnused(this.data,this.settings.importer.encoding),this._score.music=this._versionNumber>=500?pt.gpReadStringIntUnused(this.data,this.settings.importer.encoding):this._score.words,this._score.copyright=pt.gpReadStringIntUnused(this.data,this.settings.importer.encoding),this._score.tab=pt.gpReadStringIntUnused(this.data,this.settings.importer.encoding),this._score.instructions=pt.gpReadStringIntUnused(this.data,this.settings.importer.encoding);const e=ot.readInt32LE(this.data);let t="";for(let s=0;s<e;s++)s>0&&(t+="\r\n"),t+=pt.gpReadStringIntUnused(this.data,this.settings.importer.encoding)?.toString();this._score.notices=t}readLyrics(){this._lyrics=[],this._lyricsTrack=ot.readInt32LE(this.data)-1;for(let e=0;e<5;e++){const e=new Ke;e.startBar=ot.readInt32LE(this.data)-1,e.text=pt.gpReadStringInt(this.data,this.settings.importer.encoding),this._lyrics.push(e)}}readPageSetup(){this.data.skip(28);const e=ot.readInt16LE(this.data);ie.getOrCreateHeaderFooterStyle(this._score,be.Title).isVisible=!!(1&e),ie.getOrCreateHeaderFooterStyle(this._score,be.Title).template=pt.gpReadStringIntByte(this.data,this.settings.importer.encoding),ie.getOrCreateHeaderFooterStyle(this._score,be.SubTitle).isVisible=!!(2&e),ie.getOrCreateHeaderFooterStyle(this._score,be.SubTitle).template=pt.gpReadStringIntByte(this.data,this.settings.importer.encoding),ie.getOrCreateHeaderFooterStyle(this._score,be.Artist).isVisible=!!(4&e),ie.getOrCreateHeaderFooterStyle(this._score,be.Artist).template=pt.gpReadStringIntByte(this.data,this.settings.importer.encoding),ie.getOrCreateHeaderFooterStyle(this._score,be.Album).isVisible=!!(8&e),ie.getOrCreateHeaderFooterStyle(this._score,be.Album).template=pt.gpReadStringIntByte(this.data,this.settings.importer.encoding),ie.getOrCreateHeaderFooterStyle(this._score,be.Words).isVisible=!!(16&e),ie.getOrCreateHeaderFooterStyle(this._score,be.Words).template=pt.gpReadStringIntByte(this.data,this.settings.importer.encoding),ie.getOrCreateHeaderFooterStyle(this._score,be.Music).isVisible=!!(32&e),ie.getOrCreateHeaderFooterStyle(this._score,be.Music).template=pt.gpReadStringIntByte(this.data,this.settings.importer.encoding),ie.getOrCreateHeaderFooterStyle(this._score,be.WordsAndMusic).isVisible=!!(64&e),ie.getOrCreateHeaderFooterStyle(this._score,be.WordsAndMusic).template=pt.gpReadStringIntByte(this.data,this.settings.importer.encoding),ie.getOrCreateHeaderFooterStyle(this._score,be.Copyright).isVisible=!!(128&e),ie.getOrCreateHeaderFooterStyle(this._score,be.Copyright).template=pt.gpReadStringIntByte(this.data,this.settings.importer.encoding),ie.getOrCreateHeaderFooterStyle(this._score,be.CopyrightSecondLine).isVisible=!!(128&e),ie.getOrCreateHeaderFooterStyle(this._score,be.CopyrightSecondLine).template=pt.gpReadStringIntByte(this.data,this.settings.importer.encoding),pt.gpReadStringIntByte(this.data,this.settings.importer.encoding)}readPlaybackInfos(){this._playbackInfos=[];let e=0;for(let t=0;t<64;t++){const t=new tt;t.primaryChannel=e++,t.secondaryChannel=e++,t.program=ot.readInt32LE(this.data),t.volume=this.data.readByte(),t.balance=this.data.readByte(),this.data.skip(6),this._playbackInfos.push(t)}}readMasterBars(){for(let e=0;e<this._barCount;e++)this.readMasterBar()}readMasterBar(){let e=null;this._score.masterBars.length>0&&(e=this._score.masterBars[this._score.masterBars.length-1]);const t=new j,s=this.data.readByte();if(1&s?t.timeSignatureNumerator=this.data.readByte():e&&(t.timeSignatureNumerator=e.timeSignatureNumerator),2&s?t.timeSignatureDenominator=this.data.readByte():e&&(t.timeSignatureDenominator=e.timeSignatureDenominator),t.isRepeatStart=!!(4&s),8&s&&(t.repeatCount=this.data.readByte()+(this._versionNumber>=500?0:1)),16&s&&this._versionNumber<500){let s=e,i=0;for(;s&&(!s.isRepeatEnd||s===e)&&!s.isRepeatStart;)i|=s.alternateEndings,s=s.previousMasterBar;let a=0;const r=this.data.readByte();for(let e=0;e<8;e++){const t=1<<e;r>e&&!(i&t)&&(a|=t)}t.alternateEndings=a}if(32&s){const e=new Qe;e.text=pt.gpReadStringIntByte(this.data,this.settings.importer.encoding),e.marker="",pt.gpReadColor(this.data,!1),t.section=e}if(64&s&&this._keySignatures.set(this._score.masterBars.length,[ot.readSInt8(this.data),this.data.readByte()]),this._versionNumber>=500&&3&s&&this.data.skip(4),this._versionNumber>=500&&(t.alternateEndings=this.data.readByte()),this._versionNumber>=500){switch(this.data.readByte()){case 1:t.tripletFeel=M.Triplet8th;break;case 2:t.tripletFeel=M.Triplet16th}this.data.readByte()}else t.tripletFeel=this._globalTripletFeel;const i=!!(128&s);t.isDoubleBar=i;const a=this._score.masterBars.length;if(this._directionLookup.has(a))for(const e of this._directionLookup.get(a))t.addDirection(e);this._score.addMasterBar(t),i&&this._doubleBars.add(t.index)}readTracks(){for(let e=0;e<this._trackCount;e++)this.readTrack()}readTrack(){const e=new rt;e.ensureStaveCount(1),this._score.addTrack(e);const t=e.staves[0],s=this.data.readByte();e.name=pt.gpReadStringByteLength(this.data,40,this.settings.importer.encoding),1&s&&(t.isPercussion=!0),this._versionNumber>=500&&(e.isVisibleOnMultiTrack=!!(8&s)),null===this._score.stylesheet.perTrackDisplayTuning&&(this._score.stylesheet.perTrackDisplayTuning=new Map),this._score.stylesheet.perTrackDisplayTuning.set(e.index,!!(128&s));const i=ot.readInt32LE(this.data),a=[];for(let e=0;e<7;e++){const t=ot.readInt32LE(this.data);i>e&&a.push(t)}t.stringTuning.tunings=a;const r=ot.readInt32LE(this.data),n=ot.readInt32LE(this.data)-1,o=ot.readInt32LE(this.data)-1;if(this.data.skip(4),n>=0&&n<this._playbackInfos.length){const i=this._playbackInfos[n];i.port=r,i.isSolo=!!(16&s),i.isMute=!!(32&s),i.secondaryChannel=o,A.isGuitar(i.program)&&(t.displayTranspositionPitch=-12),e.playbackInfo=i}if(t.capo=ot.readInt32LE(this.data),e.color=pt.gpReadColor(this.data,!1),this._versionNumber>=500){const s=this.data.readByte();t.showTablature=!!(1&s),t.showStandardNotation=!!(2&s);const i=!!(100&s);null===this._score.stylesheet.perTrackChordDiagramsOnTop&&(this._score.stylesheet.perTrackChordDiagramsOnTop=new Map),this._score.stylesheet.perTrackChordDiagramsOnTop.set(e.index,i),this.data.readByte(),this.data.skip(43)}this._versionNumber>=510&&(this.data.skip(4),pt.gpReadStringIntByte(this.data,this.settings.importer.encoding),pt.gpReadStringIntByte(this.data,this.settings.importer.encoding))}readBars(){for(let e=0;e<this._barCount;e++)for(let e=0;e<this._trackCount;e++)this.readBar(this._score.tracks[e])}readBar(e){const t=new G,s=e.staves[0];if(s.isPercussion&&(t.clef=n.Neutral),s.addBar(t),this._keySignatures.has(t.index)){const e=this._keySignatures.get(t.index);t.keySignature=e[0],t.keySignatureType=e[1]}else t.index>0&&(t.keySignature=t.previousBar.keySignature,t.keySignatureType=t.previousBar.keySignatureType);this._doubleBars.has(t.index)&&(t.barLineRight=p.LightLight);let i=1;this._versionNumber>=500&&(this.data.readByte(),i=2);for(let s=0;s<i;s++)this.readVoice(e,t)}readVoice(e,t){const s=ot.readInt32LE(this.data);if(0===s)return;const i=new ee;t.addVoice(i);for(let a=0;a<s;a++)this.readBeat(e,t,i)}readBeat(e,t,s){const i=new ze,a=this.data.readByte();if(1&a&&(i.dots=1),64&a){const e=this.data.readByte();i.isEmpty=!(2&e)}s.addBeat(i);switch(ot.readSInt8(this.data)){case-2:i.duration=_.Whole;break;case-1:i.duration=_.Half;break;case 0:i.duration=_.Quarter;break;case 1:i.duration=_.Eighth;break;case 2:i.duration=_.Sixteenth;break;case 3:i.duration=_.ThirtySecond;break;case 4:i.duration=_.SixtyFourth;break;default:i.duration=_.Quarter}if(32&a)switch(i.tupletNumerator=ot.readInt32LE(this.data),i.tupletNumerator){case 1:i.tupletDenominator=1;break;case 3:i.tupletDenominator=2;break;case 5:case 6:case 7:i.tupletDenominator=4;break;case 9:case 10:case 11:case 12:case 13:i.tupletDenominator=8;break;case 2:case 4:case 8:break;default:i.tupletNumerator=1,i.tupletDenominator=1}2&a&&this.readChord(i);const r=this.settings.importer.beatTextAsLyrics&&e.index!==this._lyricsTrack;if(4&a){const t=pt.gpReadStringIntUnused(this.data,this.settings.importer.encoding);if(r){const s=new Ke;s.text=t.trim(),s.finish(!0);const i=[];for(let e=s.chunks.length-1;e>=0;e--)i.push(s.chunks[e]);this._beatTextChunksByTrack.set(e.index,i)}else i.text=t}let n=T.None;8&a&&(n=this.readBeatEffects(i)),16&a&&this.readMixTableChange(i);const h=this.data.readByte();for(let a=6;a>=0;a--)if(h&1<<a&&6-a<t.staff.tuning.length){const r=this.readNote(e,t,s,i,6-a);n!==T.None&&(r.harmonicType=n,r.harmonicType===T.Natural&&(r.harmonicValue=ie.deltaFretToHarmonicValue(r.fret)))}if(this._versionNumber>=500){const e=ot.readInt16LE(this.data);if(1&e&&i.index>0&&(s.beats[i.index-1].beamingMode=fe.ForceSplitToNext),2&e&&(i.preferredBeamDirection=Te.Down),4&e&&i.index>0&&(s.beats[i.index-1].beamingMode=fe.ForceMergeWithNext),8&e&&(i.preferredBeamDirection=Te.Up),16&e&&(i.ottava=o._8va),32&e&&(i.ottava=o._8vb),64&e&&(i.ottava=o._15ma),256&e&&(i.ottava=o._15mb),2048&e){const e=0!==this.data.readByte();i.index>0&&e&&(s.beats[i.index-1].beamingMode=fe.ForceSplitOnSecondaryToNext)}}r&&!i.isRest&&this._beatTextChunksByTrack.has(e.index)&&this._beatTextChunksByTrack.get(e.index).length>0&&(i.lyrics=[this._beatTextChunksByTrack.get(e.index).pop()])}readChord(e){const t=new je,s=ie.newGuid();if(this._versionNumber>=500){this.data.skip(17),t.name=pt.gpReadStringByteLength(this.data,21,this.settings.importer.encoding),this.data.skip(4),t.firstFret=ot.readInt32LE(this.data);for(let s=0;s<7;s++){const i=ot.readInt32LE(this.data);s<e.voice.bar.staff.tuning.length&&t.strings.push(i)}const s=this.data.readByte(),i=new Uint8Array(5);this.data.read(i,0,i.length);for(let e=0;e<s;e++)t.barreFrets.push(i[e]);this.data.skip(26)}else if(0!==this.data.readByte())if(this._versionNumber>=400){this.data.skip(16),t.name=pt.gpReadStringByteLength(this.data,21,this.settings.importer.encoding),this.data.skip(4),t.firstFret=ot.readInt32LE(this.data);for(let s=0;s<7;s++){const i=ot.readInt32LE(this.data);s<e.voice.bar.staff.tuning.length&&t.strings.push(i)}const s=this.data.readByte(),i=new Uint8Array(5);this.data.read(i,0,i.length);for(let e=0;e<s;e++)t.barreFrets.push(i[e]);this.data.skip(26)}else{this.data.skip(25),t.name=pt.gpReadStringByteLength(this.data,34,this.settings.importer.encoding),t.firstFret=ot.readInt32LE(this.data);for(let s=0;s<6;s++){const i=ot.readInt32LE(this.data);s<e.voice.bar.staff.tuning.length&&t.strings.push(i)}this.data.skip(36)}else{const s=this._versionNumber>=406?7:6;if(t.name=pt.gpReadStringIntByte(this.data,this.settings.importer.encoding),t.firstFret=ot.readInt32LE(this.data),t.firstFret>0)for(let i=0;i<s;i++){const s=ot.readInt32LE(this.data);i<e.voice.bar.staff.tuning.length&&t.strings.push(s)}}t.name&&(e.chordId=s,e.voice.bar.staff.addChord(e.chordId,t))}readBeatEffects(e){const t=this.data.readByte();let s=0;if(this._versionNumber>=400&&(s=this.data.readByte()),16&t&&(e.fade=ue.FadeIn),(this._versionNumber<400&&1&t||2&t)&&(e.vibrato=P.Slight),1&s&&(e.rasgueado=me.Ii),32&t&&this._versionNumber>=400){switch(ot.readSInt8(this.data)){case 1:e.tap=!0;break;case 2:e.slap=!0;break;case 3:e.pop=!0}}else if(32&t){switch(ot.readSInt8(this.data)){case 1:e.tap=!0;break;case 2:e.slap=!0;break;case 3:e.pop=!0}this.data.skip(4)}if(4&s&&this.readTremoloBarEffect(e),64&t){let t=0,s=0;this._versionNumber<500?(s=this.data.readByte(),t=this.data.readByte()):(t=this.data.readByte(),s=this.data.readByte()),t>0?(e.brushType=b.BrushUp,e.brushDuration=ut.toStrokeValue(t)):s>0&&(e.brushType=b.BrushDown,e.brushDuration=ut.toStrokeValue(s))}if(2&s)switch(ot.readSInt8(this.data)){case 0:e.pickStroke=ae.None;break;case 1:e.pickStroke=ae.Up;break;case 2:e.pickStroke=ae.Down}if(this._versionNumber<400){if(4&t)return T.Natural;if(8&t)return T.Artificial}return T.None}readTremoloBarEffect(e){this.data.readByte(),ot.readInt32LE(this.data);const t=ot.readInt32LE(this.data);if(t>0)for(let s=0;s<t;s++){const t=new X(0,0);t.offset=ot.readInt32LE(this.data),t.value=ot.readInt32LE(this.data)/ut.BendStep|0,pt.gpReadBool(this.data),e.addWhammyBarPoint(t)}}static toStrokeValue(e){switch(e){case 1:case 2:return 30;case 3:return 60;case 4:return 120;case 5:return 240;case 6:return 480;default:return 0}}readMixTableChange(e){const t=new gt;t.instrument=ot.readSInt8(this.data),this._versionNumber>=500&&this.data.skip(16),t.volume=ot.readSInt8(this.data),t.balance=ot.readSInt8(this.data);const s=ot.readSInt8(this.data),i=ot.readSInt8(this.data),a=ot.readSInt8(this.data),r=ot.readSInt8(this.data);if(this._versionNumber>=500&&(t.tempoName=pt.gpReadStringIntByte(this.data,this.settings.importer.encoding)),t.tempo=ot.readInt32LE(this.data),t.volume>=0&&this.data.readByte(),t.balance>=0&&this.data.readByte(),s>=0&&this.data.readByte(),i>=0&&this.data.readByte(),a>=0&&this.data.readByte(),r>=0&&this.data.readByte(),t.tempo>=0&&(t.duration=ot.readSInt8(this.data),this._versionNumber>=510&&this.data.readByte()),this._versionNumber>=400&&this.data.readByte(),this._versionNumber>=500){const t=ot.readSInt8(this.data);t>=100?e.wahPedal=pe.Closed:t>=0&&(e.wahPedal=pe.Open)}if(this._versionNumber>=510&&(pt.gpReadStringIntByte(this.data,this.settings.importer.encoding),pt.gpReadStringIntByte(this.data,this.settings.importer.encoding)),t.volume>=0){const s=new U;s.isLinear=!0,s.type=m.Volume,s.value=t.volume,e.automations.push(s)}if(t.balance>=0){const s=new U;s.isLinear=!0,s.type=m.Balance,s.value=t.balance,e.automations.push(s)}if(t.instrument>=0){const s=new U;s.isLinear=!0,s.type=m.Instrument,s.value=t.instrument,e.automations.push(s)}if(t.tempo>=0){const s=new U;s.isLinear=!0,s.type=m.Tempo,s.value=t.tempo,e.automations.push(s),e.voice.bar.masterBar.tempoAutomations.push(s)}}readNote(e,t,s,i,a){const r=new Ae;r.string=t.staff.tuning.length-a;const n=this.data.readByte();if(2&n?r.accentuated=B.Heavy:64&n&&(r.accentuated=B.Normal),r.isGhost=!!(4&n),32&n){const e=this.data.readByte();3===e?r.isDead=!0:2===e&&(r.isTieDestination=!0)}if(1&n&&this._versionNumber<500&&(this.data.readByte(),this.data.readByte()),16&n){const e=ot.readSInt8(this.data);r.dynamics=this.toDynamicValue(e),i.dynamics=r.dynamics}32&n&&(r.fret=ot.readSInt8(this.data)),128&n&&(r.leftHandFinger=ot.readSInt8(this.data),r.rightHandFinger=ot.readSInt8(this.data));let o=!1;if(this._versionNumber>=500){1&n&&(r.durationPercent=ot.readFloat64BE(this.data));o=!!(2&this.data.readByte())}if(i.addNote(r),8&n&&this.readNoteEffects(e,s,i,r),t.staff.isPercussion&&(r.percussionArticulation=r.fret,r.string=-1,r.fret=-1),o){const e=st.defaultAccidentals[r.realValueWithoutHarmonic%12];"#"===e?r.accidentalMode=N.ForceFlat:"b"===e&&(r.accidentalMode=N.ForceSharp)}return r}toDynamicValue(e){switch(e){case 1:return g.PPP;case 2:return g.PP;case 3:return g.P;case 4:return g.MP;case 5:return g.MF;case 6:default:return g.F;case 7:return g.FF;case 8:return g.FFF}}readNoteEffects(e,t,s,i){const a=this.data.readByte();let r=0;this._versionNumber>=400&&(r=this.data.readByte()),1&a&&this.readBend(i),16&a&&this.readGrace(t,i),4&r&&this.readTremoloPicking(s),8&r?this.readSlide(i):this._versionNumber<400&&4&a&&(i.slideOutType=v.Shift),16&r&&this.readArtificialHarmonic(i),32&r&&this.readTrill(i),i.isLetRing=!!(8&a),i.isHammerPullOrigin=!!(2&a),64&r&&(i.vibrato=P.Slight),i.isPalmMute=!!(2&r),i.isStaccato=!!(1&r)}readBend(e){this.data.readByte(),ot.readInt32LE(this.data);const t=ot.readInt32LE(this.data);if(t>0)for(let s=0;s<t;s++){const t=new X(0,0);t.offset=ot.readInt32LE(this.data),t.value=ot.readInt32LE(this.data)/ut.BendStep|0,pt.gpReadBool(this.data),e.addBendPoint(t)}}readGrace(e,t){const s=new ze,i=new Ae;i.string=t.string,i.fret=ot.readSInt8(this.data),s.duration=_.ThirtySecond,s.dynamics=this.toDynamicValue(ot.readSInt8(this.data));switch(ot.readSInt8(this.data)){case 0:case 2:break;case 1:i.slideOutType=v.Legato,i.slideTarget=t;break;case 3:i.isHammerPullOrigin=!0}if(i.dynamics=s.dynamics,this.data.skip(1),this._versionNumber<500)s.graceType=w.BeforeBeat;else{const e=this.data.readByte();i.isDead=!!(1&e),s.graceType=2&e?w.OnBeat:w.BeforeBeat}e.addGraceBeat(s),s.addNote(i)}readTremoloPicking(e){switch(this.data.readByte()){case 1:e.tremoloSpeed=_.Eighth;break;case 2:e.tremoloSpeed=_.Sixteenth;break;case 3:e.tremoloSpeed=_.ThirtySecond}}readSlide(e){if(this._versionNumber>=500){const t=ot.readSInt8(this.data);1&t?e.slideOutType=v.Shift:2&t?e.slideOutType=v.Legato:4&t?e.slideOutType=v.OutDown:8&t&&(e.slideOutType=v.OutUp),16&t?e.slideInType=x.IntoFromBelow:32&t&&(e.slideInType=x.IntoFromAbove)}else{switch(ot.readSInt8(this.data)){case 1:e.slideOutType=v.Shift;break;case 2:e.slideOutType=v.Legato;break;case 3:e.slideOutType=v.OutDown;break;case 4:e.slideOutType=v.OutUp;break;case-1:e.slideInType=x.IntoFromBelow;break;case-2:e.slideInType=x.IntoFromAbove}}}readArtificialHarmonic(e){const t=this.data.readByte();if(this._versionNumber>=500)switch(t){case 1:e.harmonicType=T.Natural,e.harmonicValue=ie.deltaFretToHarmonicValue(e.fret);break;case 2:this.data.readByte(),this.data.readByte(),this.data.readByte(),e.harmonicType=T.Artificial;break;case 3:e.harmonicType=T.Tap,e.harmonicValue=ie.deltaFretToHarmonicValue(this.data.readByte());break;case 4:e.harmonicType=T.Pinch,e.harmonicValue=12;break;case 5:e.harmonicType=T.Semi,e.harmonicValue=12}else if(this._versionNumber>=400)switch(t){case 1:e.harmonicType=T.Natural;break;case 3:e.harmonicType=T.Tap;break;case 4:e.harmonicType=T.Pinch;break;case 5:e.harmonicType=T.Semi;break;case 15:case 17:case 22:e.harmonicType=T.Artificial}}readTrill(e){switch(e.trillValue=this.data.readByte()+e.stringTuning,this.data.readByte()){case 1:e.trillSpeed=_.Sixteenth;break;case 2:e.trillSpeed=_.ThirtySecond;break;case 3:e.trillSpeed=_.SixtyFourth}}}ut.VersionString="FICHIER GUITAR PRO ",ut.BendStep=25;class pt{static gpReadColor(e,t=!1){const s=e.readByte(),i=e.readByte(),a=e.readByte();let r=255;return t?r=e.readByte():e.skip(1),new et(s,i,a,r)}static gpReadBool(e){return 0!==e.readByte()}static gpReadStringIntUnused(e,t){return e.skip(4),pt.gpReadString(e,e.readByte(),t)}static gpReadStringInt(e,t){return pt.gpReadString(e,ot.readInt32LE(e),t)}static gpReadStringIntByte(e,t){const s=ot.readInt32LE(e)-1;return e.readByte(),pt.gpReadString(e,s,t)}static gpReadString(e,t,s){const i=new Uint8Array(t);return e.read(i,0,i.length),ot.toString(i,s)}static gpWriteString(e,t){const s=ot.stringToBytes(t);e.writeByte(t.length),e.write(s,0,s.length)}static gpReadStringByteLength(e,t,s){const i=e.readByte(),a=pt.gpReadString(e,i,s);return i<t&&e.skip(t-i),a}}class gt{constructor(){this.volume=-1,this.balance=-1,this.instrument=-1,this.tempoName="",this.tempo=-1,this.duration=-1}}class mt{constructor(){this.x=0,this.y=0,this.w=0,this.h=0}scaleWith(e){this.x*=e,this.y*=e,this.w*=e,this.h*=e}}!function(e){e[e.Boolean=0]="Boolean",e[e.Integer=1]="Integer",e[e.Float=2]="Float",e[e.String=3]="String",e[e.Point=4]="Point",e[e.Size=5]="Size",e[e.Rectangle=6]="Rectangle",e[e.Color=7]="Color"}(Pe||(Pe={}));class ft{constructor(e){this._types=new Map,this.raw=new Map,e&&this.read(e)}read(e){const t=ht.fromBuffer(e),s=ot.readInt32BE(t);for(let e=0;e<s;e++){const e=pt.gpReadString(t,t.readByte(),"utf-8"),s=t.readByte();switch(this._types.set(e,s),s){case Pe.Boolean:const s=1===t.readByte();this.addValue(e,s);break;case Pe.Integer:const i=ot.readInt32BE(t);this.addValue(e,i);break;case Pe.Float:const a=ot.readFloat32BE(t);this.addValue(e,a);break;case Pe.String:const r=pt.gpReadString(t,ot.readInt16BE(t),"utf-8");this.addValue(e,r);break;case Pe.Point:const n=ot.readInt32BE(t),o=ot.readInt32BE(t);this.addValue(e,new X(n,o));break;case Pe.Size:const h=ot.readInt32BE(t),l=ot.readInt32BE(t);this.addValue(e,new X(h,l));break;case Pe.Rectangle:const c=new mt;c.x=ot.readInt32BE(t),c.y=ot.readInt32BE(t),c.w=ot.readInt32BE(t),c.h=ot.readInt32BE(t),this.addValue(e,c);break;case Pe.Color:const d=pt.gpReadColor(t,!0);this.addValue(e,d)}}}apply(e){for(const[t,s]of this.raw)switch(t){case"StandardNotation/hideDynamics":e.stylesheet.hideDynamics=s;break;case"System/bracketExtendMode":e.stylesheet.bracketExtendMode=s;break;case"Global/useSystemSignSeparator":e.stylesheet.useSystemSignSeparator=s;break;case"Global/DisplayTuning":e.stylesheet.globalDisplayTuning=s;break;case"Global/DrawChords":e.stylesheet.globalDisplayChordDiagramsOnTop=s;break;case"System/showTrackNameSingle":s||(e.stylesheet.singleTrackTrackNamePolicy=i.Hidden);break;case"System/showTrackNameMulti":s||(e.stylesheet.multiTrackTrackNamePolicy=i.Hidden);break;case"System/trackNameModeSingle":if(e.stylesheet.singleTrackTrackNamePolicy!==i.Hidden)switch(s){case 0:case 1:e.stylesheet.singleTrackTrackNamePolicy=i.FirstSystem;break;case 2:e.stylesheet.singleTrackTrackNamePolicy=i.AllSystems}break;case"System/trackNameModeMulti":if(e.stylesheet.multiTrackTrackNamePolicy!==i.Hidden)switch(s){case 0:case 1:e.stylesheet.multiTrackTrackNamePolicy=i.FirstSystem;break;case 2:e.stylesheet.multiTrackTrackNamePolicy=i.AllSystems}break;case"System/shortTrackNameOnFirstSystem":e.stylesheet.firstSystemTrackNameMode=s?a.ShortName:a.FullName;break;case"System/shortTrackNameOnOtherSystems":e.stylesheet.otherSystemsTrackNameMode=s?a.ShortName:a.FullName;break;case"System/horizontalTrackNameOnFirstSystem":e.stylesheet.firstSystemTrackNameOrientation=s?r.Horizontal:r.Vertical;break;case"System/horizontalTrackNameOnOtherSystems":e.stylesheet.otherSystemsTrackNameOrientation=s?r.Horizontal:r.Vertical;break;case"Header/Title":ie.getOrCreateHeaderFooterStyle(e,be.Title).template=s;break;case"Header/TitleAlignment":ie.getOrCreateHeaderFooterStyle(e,be.Title).textAlign=this.toTextAlign(s);break;case"Header/drawTitle":ie.getOrCreateHeaderFooterStyle(e,be.Title).isVisible=s;break;case"Header/Subtitle":ie.getOrCreateHeaderFooterStyle(e,be.SubTitle).template=s;break;case"Header/SubtitleAlignment":ie.getOrCreateHeaderFooterStyle(e,be.SubTitle).textAlign=this.toTextAlign(s);break;case"Header/drawSubtitle":ie.getOrCreateHeaderFooterStyle(e,be.SubTitle).isVisible=s;break;case"Header/Artist":ie.getOrCreateHeaderFooterStyle(e,be.Artist).template=s;break;case"Header/ArtistAlignment":ie.getOrCreateHeaderFooterStyle(e,be.Artist).textAlign=this.toTextAlign(s);break;case"Header/drawArtist":ie.getOrCreateHeaderFooterStyle(e,be.Artist).isVisible=s;break;case"Header/Album":ie.getOrCreateHeaderFooterStyle(e,be.Album).template=s;break;case"Header/AlbumAlignment":ie.getOrCreateHeaderFooterStyle(e,be.Album).textAlign=this.toTextAlign(s);break;case"Header/drawAlbum":ie.getOrCreateHeaderFooterStyle(e,be.Album).isVisible=s;break;case"Header/Words":ie.getOrCreateHeaderFooterStyle(e,be.Words).template=s;break;case"Header/WordsAlignment":ie.getOrCreateHeaderFooterStyle(e,be.Words).textAlign=this.toTextAlign(s);break;case"Header/drawWords":ie.getOrCreateHeaderFooterStyle(e,be.Words).isVisible=s;break;case"Header/Music":ie.getOrCreateHeaderFooterStyle(e,be.Music).template=s;break;case"Header/MusicAlignment":ie.getOrCreateHeaderFooterStyle(e,be.Music).textAlign=this.toTextAlign(s);break;case"Header/drawMusic":ie.getOrCreateHeaderFooterStyle(e,be.Music).isVisible=s;break;case"Header/WordsAndMusic":ie.getOrCreateHeaderFooterStyle(e,be.WordsAndMusic).template=s;break;case"Header/WordsAndMusicAlignment":ie.getOrCreateHeaderFooterStyle(e,be.WordsAndMusic).textAlign=this.toTextAlign(s);break;case"Header/drawWordsAndMusic":ie.getOrCreateHeaderFooterStyle(e,be.WordsAndMusic).isVisible=s;break;case"Header/Tabber":ie.getOrCreateHeaderFooterStyle(e,be.Transcriber).template=s;break;case"Header/TabberAlignment":ie.getOrCreateHeaderFooterStyle(e,be.Transcriber).textAlign=this.toTextAlign(s);break;case"Header/drawTabber":ie.getOrCreateHeaderFooterStyle(e,be.Transcriber).isVisible=s;break;case"Footer/Copyright":ie.getOrCreateHeaderFooterStyle(e,be.Copyright).template=s;break;case"Footer/CopyrightAlignment":ie.getOrCreateHeaderFooterStyle(e,be.Copyright).textAlign=this.toTextAlign(s);break;case"Footer/drawCopyright":ie.getOrCreateHeaderFooterStyle(e,be.Copyright).isVisible=s;break;case"Footer/Copyright2":ie.getOrCreateHeaderFooterStyle(e,be.CopyrightSecondLine).template=s;break;case"Footer/Copyright2Alignment":ie.getOrCreateHeaderFooterStyle(e,be.CopyrightSecondLine).textAlign=this.toTextAlign(s);break;case"Footer/drawCopyright2":ie.getOrCreateHeaderFooterStyle(e,be.CopyrightSecondLine).isVisible=s}}toTextAlign(e){switch(e){case 0:return ne.Left;case 1:return ne.Center;case 2:return ne.Right}return ne.Left}addValue(e,t,s){this.raw.set(e,t),void 0!==s&&this._types.set(e,s)}writeTo(e){ot.writeInt32BE(e,this.raw.size);for(const[t,s]of this.raw){const i=this.getDataType(t,s);switch(pt.gpWriteString(e,t),e.writeByte(i),i){case Pe.Boolean:e.writeByte(s?1:0);break;case Pe.Integer:ot.writeInt32BE(e,s);break;case Pe.Float:ot.writeFloat32BE(e,s);break;case Pe.String:const t=ot.stringToBytes(s);ot.writeInt16BE(e,t.length),e.write(t,0,t.length);break;case Pe.Point:case Pe.Size:ot.writeInt32BE(e,s.offset),ot.writeInt32BE(e,s.value);break;case Pe.Rectangle:ot.writeInt32BE(e,s.x),ot.writeInt32BE(e,s.y),ot.writeInt32BE(e,s.w),ot.writeInt32BE(e,s.h);break;case Pe.Color:e.writeByte(s.r),e.writeByte(s.g),e.writeByte(s.b),e.writeByte(s.a)}}}getDataType(e,t){if(this._types.has(e))return this._types.get(e);const s=typeof t;switch(typeof t){case"string":return Pe.String;case"number":return t===(0|t)?Pe.Integer:Pe.Float;case"object":if(t instanceof X)return Pe.Point;if(t instanceof mt)return Pe.Rectangle;if(t instanceof et)return Pe.Color}throw new $e(Se.General,`Unknown value type in BinaryStylesheet: ${s}`)}static writeForScore(e){const t=new ft;switch(t.addValue("StandardNotation/hideDynamics",e.stylesheet.hideDynamics,Pe.Boolean),t.addValue("System/bracketExtendMode",e.stylesheet.bracketExtendMode,Pe.Integer),t.addValue("Global/useSystemSignSeparator",e.stylesheet.useSystemSignSeparator,Pe.Boolean),t.addValue("Global/DisplayTuning",e.stylesheet.globalDisplayTuning,Pe.Boolean),t.addValue("Global/DrawChords",e.stylesheet.globalDisplayChordDiagramsOnTop,Pe.Boolean),e.stylesheet.singleTrackTrackNamePolicy){case i.Hidden:t.addValue("System/showTrackNameSingle",!1,Pe.Boolean);break;case i.FirstSystem:t.addValue("System/trackNameModeSingle",0,Pe.Integer);break;case i.AllSystems:t.addValue("System/trackNameModeSingle",2,Pe.Integer)}switch(e.stylesheet.multiTrackTrackNamePolicy){case i.Hidden:t.addValue("System/trackNameModeMulti",!1,Pe.Boolean);break;case i.FirstSystem:t.addValue("System/trackNameModeMulti",0,Pe.Integer);break;case i.AllSystems:t.addValue("System/trackNameModeMulti",2,Pe.Integer)}switch(e.stylesheet.firstSystemTrackNameMode){case a.FullName:t.addValue("System/shortTrackNameOnFirstSystem",!1,Pe.Boolean);break;case a.ShortName:t.addValue("System/shortTrackNameOnFirstSystem",!0,Pe.Boolean)}switch(e.stylesheet.otherSystemsTrackNameMode){case a.FullName:t.addValue("System/shortTrackNameOnOtherSystems",!1,Pe.Boolean);break;case a.ShortName:t.addValue("System/shortTrackNameOnOtherSystems",!0,Pe.Boolean)}switch(e.stylesheet.firstSystemTrackNameOrientation){case r.Horizontal:t.addValue("System/horizontalTrackNameOnFirstSystem",!0,Pe.Boolean);break;case r.Vertical:t.addValue("System/horizontalTrackNameOnFirstSystem",!1,Pe.Boolean)}switch(e.stylesheet.otherSystemsTrackNameOrientation){case r.Horizontal:t.addValue("System/horizontalTrackNameOnOtherSystems",!0,Pe.Boolean);break;case r.Vertical:t.addValue("System/horizontalTrackNameOnOtherSystems",!1,Pe.Boolean)}const s=e.style;if(s)for(const[e,i]of s.headerAndFooter)switch(e){case be.Title:ft.addHeaderAndFooter(t,i,"Header/","Title");break;case be.SubTitle:ft.addHeaderAndFooter(t,i,"Header/","Subtitle");break;case be.Artist:ft.addHeaderAndFooter(t,i,"Header/","Artist");break;case be.Album:ft.addHeaderAndFooter(t,i,"Header/","Album");break;case be.Words:ft.addHeaderAndFooter(t,i,"Header/","Words");break;case be.Music:ft.addHeaderAndFooter(t,i,"Header/","Music");break;case be.WordsAndMusic:ft.addHeaderAndFooter(t,i,"Header/","WordsAndMusic");break;case be.Transcriber:ft.addHeaderAndFooter(t,i,"Header/","Tabber");break;case be.Copyright:ft.addHeaderAndFooter(t,i,"Footer/","Copyright");break;case be.CopyrightSecondLine:ft.addHeaderAndFooter(t,i,"Footer/","Copyright2")}const n=ht.withCapacity(128);return t.writeTo(n),n.toArray()}static addHeaderAndFooter(e,t,s,i){void 0!==t.template&&e.addValue(`${s}${i}`,t.template,Pe.String),e.addValue(`${s}${i}Alignment`,t.textAlign,Pe.Integer),void 0!==t.isVisible&&e.addValue(`${s}draw${i}`,t.isVisible,Pe.Boolean)}}!function(e){e[e.None=0]="None",e[e.Element=1]="Element",e[e.Text=2]="Text",e[e.CDATA=3]="CDATA",e[e.Document=4]="Document",e[e.DocumentType=5]="DocumentType"}(Fe||(Fe={}));class yt{constructor(){this.nodeType=Fe.None,this.localName=null,this.value=null,this.childNodes=[],this.attributes=new Map,this.firstChild=null,this.firstElement=null}*childElements(){for(const e of this.childNodes)e.nodeType===Fe.Element&&(yield e)}addChild(e){this.childNodes.push(e),this.firstChild=e,e.nodeType!==Fe.Element&&e.nodeType!==Fe.CDATA||(this.firstElement=e)}getAttribute(e,t=""){return this.attributes.has(e)?this.attributes.get(e):t}getElementsByTagName(e,t=!1){const s=[];return this.searchElementsByTagName(this.childNodes,s,e,t),s}searchElementsByTagName(e,t,s,i=!1){for(const a of e)a&&a.nodeType===Fe.Element&&a.localName===s&&t.push(a),i&&this.searchElementsByTagName(a.childNodes,t,s,!0)}findChildElement(e){for(const t of this.childNodes)if(t&&t.nodeType===Fe.Element&&t.localName===e)return t;return null}addElement(e){const t=new yt;return t.nodeType=Fe.Element,t.localName=e,this.addChild(t),t}get innerText(){if(this.nodeType===Fe.Element||this.nodeType===Fe.Document){if(this.firstElement&&this.firstElement.nodeType===Fe.CDATA)return this.firstElement.innerText;let e="";for(const t of this.childNodes)e+=t.innerText?.toString();return e.trim()}return this.value??""}set innerText(e){const t=new yt;t.nodeType=Fe.Text,t.value=e,this.childNodes=[t]}setCData(e){const t=new yt;t.nodeType=Fe.CDATA,t.value=e,this.childNodes=[t]}}class bt extends $e{constructor(e,t,s){super(Se.Format,e),this.pos=0,this.xml=t,this.pos=s,Object.setPrototypeOf(this,bt.prototype)}}!function(e){e[e.IgnoreSpaces=0]="IgnoreSpaces",e[e.Begin=1]="Begin",e[e.BeginNode=2]="BeginNode",e[e.TagName=3]="TagName",e[e.Body=4]="Body",e[e.AttribName=5]="AttribName",e[e.Equals=6]="Equals",e[e.AttvalBegin=7]="AttvalBegin",e[e.AttribVal=8]="AttribVal",e[e.Childs=9]="Childs",e[e.Close=10]="Close",e[e.WaitEnd=11]="WaitEnd",e[e.WaitEndRet=12]="WaitEndRet",e[e.Pcdata=13]="Pcdata",e[e.Header=14]="Header",e[e.Comment=15]="Comment",e[e.Doctype=16]="Doctype",e[e.Cdata=17]="Cdata",e[e.Escape=18]="Escape"}(Ce||(Ce={}));class St{static parse(e,t,s){let i=e.charCodeAt(t),a=Ce.Begin,r=Ce.Begin,n=0,o="",h=Ce.Begin,l=null,c=null,d=0,u=0;for(;t<e.length;){switch(i=e.charCodeAt(t),a){case Ce.IgnoreSpaces:switch(i){case St.CharCodeLF:case St.CharCodeCR:case St.CharCodeTab:case St.CharCodeSpace:break;default:a=r;continue}break;case Ce.Begin:if(i!==St.CharCodeLowerThan){n=t,a=Ce.Pcdata;continue}a=Ce.IgnoreSpaces,r=Ce.BeginNode;break;case Ce.Pcdata:if(i===St.CharCodeLowerThan){o+=e.substr(n,t-n);const i=new yt;i.nodeType=Fe.Text,i.value=o,o="",s.addChild(i),a=Ce.IgnoreSpaces,r=Ce.BeginNode}else i===St.CharCodeAmp&&(o+=e.substr(n,t-n),a=Ce.Escape,h=Ce.Pcdata,n=t+1);break;case Ce.Cdata:if(i===St.CharCodeBrackedClose&&e.charCodeAt(t+1)===St.CharCodeBrackedClose&&e.charCodeAt(t+2)===St.CharCodeGreaterThan){const i=new yt;i.nodeType=Fe.CDATA,i.value=e.substr(n,t-n),s.addChild(i),t+=2,a=Ce.Begin}break;case Ce.BeginNode:switch(i){case St.CharCodeExclamation:if(e.charCodeAt(t+1)===St.CharCodeBrackedOpen){if(t+=2,"CDATA["!==e.substr(t,6).toUpperCase())throw new bt("Expected <![CDATA[",e,t);t+=5,a=Ce.Cdata,n=t+1}else if(e.charCodeAt(t+1)===St.CharCodeUpperD||e.charCodeAt(t+1)===St.CharCodeLowerD){if("OCTYPE"!==e.substr(t+2,6).toUpperCase())throw new bt("Expected <!DOCTYPE",e,t);t+=8,a=Ce.Doctype,n=t+1}else{if(e.charCodeAt(t+1)!==St.CharCodeMinus||e.charCodeAt(t+2)!==St.CharCodeMinus)throw new bt("Expected \x3c!--",e,t);t+=2,a=Ce.Comment,n=t+1}break;case St.CharCodeQuestion:a=Ce.Header,n=t;break;case St.CharCodeSlash:if(!s)throw new bt("Expected node name",e,t);n=t+1,a=Ce.IgnoreSpaces,r=Ce.Close;break;default:a=Ce.TagName,n=t;continue}break;case Ce.TagName:if(!St.isValidChar(i)){if(t===n)throw new bt("Expected node name",e,t);l=new yt,l.nodeType=Fe.Element,l.localName=e.substr(n,t-n),s.addChild(l),a=Ce.IgnoreSpaces,r=Ce.Body;continue}break;case Ce.Body:switch(i){case St.CharCodeSlash:a=Ce.WaitEnd;break;case St.CharCodeGreaterThan:a=Ce.Childs;break;default:a=Ce.AttribName,n=t;continue}break;case Ce.AttribName:if(!St.isValidChar(i)){if(n===t)throw new bt("Expected attribute name",e,t);if(c=e.substr(n,t-n),l.attributes.has(c))throw new bt(`Duplicate attribute [${c}]`,e,t);a=Ce.IgnoreSpaces,r=Ce.Equals;continue}break;case Ce.Equals:if(i!==St.CharCodeEquals)throw new bt("Expected =",e,t);a=Ce.IgnoreSpaces,r=Ce.AttvalBegin;break;case Ce.AttvalBegin:switch(i){case St.CharCodeDoubleQuote:case St.CharCodeSingleQuote:o="",a=Ce.AttribVal,n=t+1,u=i}break;case Ce.AttribVal:if(i===St.CharCodeAmp)o+=e.substr(n,t-n),a=Ce.Escape,h=Ce.AttribVal,n=t+1;else if(i===u){o+=e.substr(n,t-n);const s=o;o="",l.attributes.set(c,s),a=Ce.IgnoreSpaces,r=Ce.Body}break;case Ce.Childs:n=t=St.parse(e,t,l),a=Ce.Begin;break;case Ce.WaitEnd:if(i!==St.CharCodeGreaterThan)throw new bt("Expected >",e,t);a=Ce.Begin;break;case Ce.WaitEndRet:if(i===St.CharCodeGreaterThan)return t;throw new bt("Expected >",e,t);case Ce.Close:if(!St.isValidChar(i)){if(n===t)throw new bt("Expected node name",e,t);if(e.substr(n,t-n)!==s.localName)throw new bt(`Expected </${s.localName}>`,e,t);a=Ce.IgnoreSpaces,r=Ce.WaitEndRet;continue}break;case Ce.Comment:i===St.CharCodeMinus&&e.charCodeAt(t+1)===St.CharCodeMinus&&e.charCodeAt(t+2)===St.CharCodeGreaterThan&&(t+=2,a=Ce.Begin);break;case Ce.Doctype:if(i===St.CharCodeBrackedOpen)d++;else if(i===St.CharCodeBrackedClose)d--;else if(i===St.CharCodeGreaterThan&&0===d){const i=new yt;i.nodeType=Fe.DocumentType,i.value=e.substr(n,t-n),s.addChild(i),a=Ce.Begin}break;case Ce.Header:i===St.CharCodeQuestion&&e.charCodeAt(t+1)===St.CharCodeGreaterThan&&(t++,a=Ce.Begin);break;case Ce.Escape:if(i===St.CharCodeSemi){const s=e.substr(n,t-n);if(s.charCodeAt(0)===St.CharCodeSharp){const e=s.charCodeAt(1)===St.CharCodeLowerX?Number.parseInt(`0${s.substr(1,s.length-1)}`):Number.parseInt(s.substr(1,s.length-1));o+=String.fromCharCode(e)}else St.Escapes.has(s)?o+=St.Escapes.get(s):o+=`&${s};`?.toString();n=t+1,a=h}else St.isValidChar(i)||i===St.CharCodeSharp||(o+="&",o+=e.substr(n,t-n),n=--t+1,a=h)}t++}if(a===Ce.Begin&&(n=t,a=Ce.Pcdata),a===Ce.Pcdata){if(t!==n){o+=e.substr(n,t-n);const i=new yt;i.nodeType=Fe.Text,i.value=o,s.addChild(i)}return t}if(a===Ce.Escape&&h===Ce.Pcdata){o+="&",o+=e.substr(n,t-n);const i=new yt;return i.nodeType=Fe.Text,i.value=o,s.addChild(i),t}throw new bt("Unexpected end",e,t)}static isValidChar(e){return e>=St.CharCodeLowerA&&e<=St.CharCodeLowerZ||e>=St.CharCodeUpperA&&e<=St.CharCodeUpperZ||e>=St.CharCode0&&e<=St.CharCode9||e===St.CharCodeColon||e===St.CharCodeDot||e===St.CharCodeUnderscore||e===St.CharCodeMinus}}St.CharCodeLF=10,St.CharCodeTab=9,St.CharCodeCR=13,St.CharCodeSpace=32,St.CharCodeLowerThan=60,St.CharCodeAmp=38,St.CharCodeBrackedClose=93,St.CharCodeBrackedOpen=91,St.CharCodeGreaterThan=62,St.CharCodeExclamation=33,St.CharCodeUpperD=68,St.CharCodeLowerD=100,St.CharCodeMinus=45,St.CharCodeQuestion=63,St.CharCodeSlash=47,St.CharCodeEquals=61,St.CharCodeDoubleQuote=34,St.CharCodeSingleQuote=39,St.CharCodeSharp=35,St.CharCodeLowerX=120,St.CharCodeLowerA=97,St.CharCodeLowerZ=122,St.CharCodeUpperA=65,St.CharCodeUpperZ=90,St.CharCode0=48,St.CharCode9=57,St.CharCodeColon=58,St.CharCodeDot=46,St.CharCodeUnderscore=95,St.CharCodeSemi=59,St.Escapes=new Map([["lt","<"],["gt",">"],["amp","&"],["quot",'"'],["apos","'"]]);class _t{static write(e,t,s){const i=new _t(t,s);return i.writeNode(e),i.toString()}constructor(e,t){this._result=[],this._indention=e,this._xmlHeader=t,this._currentIndention="",this._isStartOfLine=!0}writeNode(e){switch(e.nodeType){case Fe.None:break;case Fe.Element:this._result.length>0&&this.writeLine(),this.write(`<${e.localName}`);for(const[t,s]of e.attributes)this.write(` ${t}="`),this.writeAttributeValue(s),this.write('"');if(0===e.childNodes.length)this.write("/>");else{if(this.write(">"),1!==e.childNodes.length||e.firstElement){this.indent();for(const t of e.childNodes)t.nodeType===Fe.Element&&this.writeNode(t);this.unindend(),this.writeLine()}else this.writeNode(e.childNodes[0]);this.write(`</${e.localName}>`)}break;case Fe.Text:e.value&&this.write(e.value);break;case Fe.CDATA:null!==e.value&&this.write(`<![CDATA[${e.value}]]>`);break;case Fe.Document:this._xmlHeader&&this.write('<?xml version="1.0" encoding="utf-8"?>');for(const t of e.childNodes)this.writeNode(t);break;case Fe.DocumentType:this.write(`<!DOCTYPE ${e.value}>`)}}unindend(){this._currentIndention=this._currentIndention.substr(0,this._currentIndention.length-this._indention.length)}indent(){this._currentIndention+=this._indention}writeAttributeValue(e){for(let t=0;t<e.length;t++){const s=e.charAt(t);switch(s){case"<":this._result.push("&lt;");break;case">":this._result.push("&gt;");break;case"&":this._result.push("&amp;");break;case"'":this._result.push("&apos;");break;case'"':this._result.push("&quot;");break;default:this._result.push(s)}}}write(e){this._isStartOfLine&&this._result.push(this._currentIndention),this._result.push(e),this._isStartOfLine=!1}writeLine(e=null){e&&this.write(e),this._indention.length>0&&!this._isStartOfLine&&(this._result.push("\n"),this._isStartOfLine=!0)}toString(){return this._result.join("").trimRight()}}class wt extends yt{constructor(){super(),this.nodeType=Fe.Document}parse(e){St.parse(e,0,this)}toString(){return this.toFormattedString()}toFormattedString(e="",t=!1){return _t.write(this,e,t)}}class Bt{constructor(){this.id="",this.dots=0,this.tupletDenominator=-1,this.tupletNumerator=-1,this.value=_.Quarter}}class kt{constructor(){this.name="",this.path="",this.role="",this.program=0}get uniqueId(){return`${this.path};${this.name};${this.role}`}}class Tt{constructor(){this._hasAnacrusis=!1,this._skipApplyLyrics=!1,this._doubleBars=new Set,this._keySignatures=new Map}parseXml(e,t){this._masterTrackAutomations=new Map,this._automationsPerTrackIdAndBarIndex=new Map,this._sustainPedalsPerTrackIdAndBarIndex=new Map,this._tracksMapping=[],this._tracksById=new Map,this._masterBars=[],this._barsOfMasterBar=[],this._voicesOfBar=new Map,this._barsById=new Map,this._voiceById=new Map,this._beatsOfVoice=new Map,this._beatById=new Map,this._rhythmOfBeat=new Map,this._rhythmById=new Map,this._notesOfBeat=new Map,this._noteById=new Map,this._tappedNotes=new Map,this._lyricsByTrack=new Map,this._soundsByTrack=new Map,this._skipApplyLyrics=!1;const s=new wt;try{s.parse(e)}catch(e){throw new qe("Could not parse XML",e)}if(this.parseDom(s),this.buildModel(),ie.consolidate(this.score),this.score.finish(t),!this._skipApplyLyrics&&this._lyricsByTrack.size>0)for(const[e,t]of this._lyricsByTrack){this._tracksById.get(e).applyLyrics(t)}}parseDom(e){const t=e.firstElement;if(t){if("GPIF"!==t.localName)throw new qe("Root node of XML was not GPIF");this.score=new Je;for(const e of t.childElements())switch(e.localName){case"Score":this.parseScoreNode(e);break;case"MasterTrack":this.parseMasterTrackNode(e);break;case"Tracks":this.parseTracksNode(e);break;case"MasterBars":this.parseMasterBarsNode(e);break;case"Bars":this.parseBars(e);break;case"Voices":this.parseVoices(e);break;case"Beats":this.parseBeats(e);break;case"Notes":this.parseNotes(e);break;case"Rhythms":this.parseRhythms(e)}}}parseScoreNode(e){for(const t of e.childElements())switch(t.localName){case"Title":this.score.title=t.innerText;break;case"SubTitle":this.score.subTitle=t.innerText;break;case"Artist":this.score.artist=t.innerText;break;case"Album":this.score.album=t.innerText;break;case"Words":this.score.words=t.innerText;break;case"Music":this.score.music=t.innerText;break;case"WordsAndMusic":const e=t.innerText;""!==e&&(e&&!this.score.words&&(this.score.words=e),e&&!this.score.music&&(this.score.music=e));break;case"Copyright":this.score.copyright=t.innerText;break;case"Tabber":this.score.tab=t.innerText;break;case"Instructions":this.score.instructions=t.innerText;break;case"Notices":this.score.notices=t.innerText;break;case"ScoreSystemsDefaultLayout":this.score.defaultSystemsLayout=Tt.parseIntSafe(t.innerText,4);break;case"ScoreSystemsLayout":this.score.systemsLayout=Tt.splitSafe(t.innerText).map((e=>Tt.parseIntSafe(e,4)))}}static parseIntSafe(e,t){if(!e)return t;const s=Number.parseInt(e);return Number.isNaN(s)?t:s}static parseFloatSafe(e,t){if(!e)return t;const s=Number.parseFloat(e);return Number.isNaN(s)?t:s}static splitSafe(e,t=" "){return e?e.split(t).map((e=>e.trim())).filter((e=>e.length>0)):[]}parseMasterTrackNode(e){for(const t of e.childElements())switch(t.localName){case"Automations":this.parseAutomations(t,this._masterTrackAutomations,null,null);break;case"Tracks":this._tracksMapping=Tt.splitSafe(t.innerText);break;case"Anacrusis":this._hasAnacrusis=!0}}parseAutomations(e,t,s,i){for(const a of e.childElements())if("Automation"===a.localName)this.parseAutomation(a,t,s,i)}parseAutomation(e,t,s,i){let a=null,r=!1,n=-1,o=0,h=0,l=null,c=0,u=null;for(const t of e.childElements())switch(t.localName){case"Type":a=t.innerText;break;case"Linear":r="true"===t.innerText.toLowerCase();break;case"Bar":n=Tt.parseIntSafe(t.innerText,0);break;case"Position":o=Tt.parseFloatSafe(t.innerText,0);break;case"Value":if(t.firstElement&&t.firstElement.nodeType===Fe.CDATA)l=t.innerText;else{const e=Tt.splitSafe(t.innerText);1===e.length?(h=Tt.parseFloatSafe(e[0],0),c=1):(h=Tt.parseFloatSafe(e[0],0),c=Tt.parseIntSafe(e[1],0))}break;case"Text":u=t.innerText}if(!a)return;let p=null;switch(a){case"Tempo":p=U.buildTempoAutomation(r,o,h,c);break;case"Sound":l&&s&&s.has(l)&&(p=U.buildInstrumentAutomation(r,o,s.get(l).program));break;case"SustainPedal":if(i){let e;i.has(n)?e=i.get(n):(e=[],i.set(n,e));const t=new W;switch(t.ratioPosition=o,c){case 1:t.pedalType=d.Down;break;case 3:t.pedalType=d.Up}e.push(t)}}p&&(u&&(p.text=u),n>=0&&(t.has(n)||t.set(n,[]),t.get(n).push(p)))}parseTracksNode(e){for(const t of e.childElements())if("Track"===t.localName)this.parseTrack(t)}parseTrack(e){this._articulationByName=new Map;const t=new rt;t.ensureStaveCount(1);t.staves[0].showStandardNotation=!0;const s=e.getAttribute("id");for(const i of e.childElements())switch(i.localName){case"Name":t.name=i.innerText;break;case"Color":const e=Tt.splitSafe(i.innerText);if(e.length>=3){const s=Tt.parseIntSafe(e[0],0),i=Tt.parseIntSafe(e[1],0),a=Tt.parseIntSafe(e[2],0);t.color=new et(s,i,a,255)}break;case"Instrument":const a=i.getAttribute("ref");(a.endsWith("-gs")||a.endsWith("GrandStaff"))&&(t.ensureStaveCount(2),t.staves[1].showStandardNotation=!0);break;case"InstrumentSet":this.parseInstrumentSet(t,i);break;case"NotationPatch":this.parseNotationPatch(t,i);break;case"ShortName":t.shortName=i.innerText;break;case"SystemsDefautLayout":t.defaultSystemsLayout=Tt.parseIntSafe(i.innerText,4);break;case"SystemsLayout":t.systemsLayout=Tt.splitSafe(i.innerText).map((e=>Tt.parseIntSafe(e,4)));break;case"Lyrics":this.parseLyrics(s,i);break;case"Properties":this.parseTrackProperties(t,i);break;case"GeneralMidi":case"MidiConnection":case"MIDISettings":this.parseGeneralMidi(t,i);break;case"Sounds":this.parseSounds(s,t,i);break;case"PlaybackState":const r=i.innerText;t.playbackInfo.isSolo="Solo"===r,t.playbackInfo.isMute="Mute"===r;break;case"PartSounding":this.parsePartSounding(t,i);break;case"Staves":this.parseStaves(t,i);break;case"Transpose":this.parseTranspose(t,i);break;case"RSE":this.parseRSE(t,i);break;case"Automations":this.parseTrackAutomations(s,i)}this._tracksById.set(s,t)}parseTrackAutomations(e,t){const s=new Map;this._automationsPerTrackIdAndBarIndex.set(e,s);const i=new Map;this._sustainPedalsPerTrackIdAndBarIndex.set(e,i),this.parseAutomations(t,s,this._soundsByTrack.get(e),i)}parseNotationPatch(e,t){for(const s of t.childElements())switch(s.localName){case"LineCount":const t=Tt.parseIntSafe(s.innerText,5);for(const s of e.staves)s.standardNotationLineCount=t;break;case"Elements":this.parseElements(e,s)}}parseInstrumentSet(e,t){for(const s of t.childElements())switch(s.localName){case"Type":if("drumKit"===s.innerText)for(const t of e.staves)t.isPercussion=!0;break;case"Elements":this.parseElements(e,s);break;case"LineCount":const t=Tt.parseIntSafe(s.innerText,5);for(const s of e.staves)s.standardNotationLineCount=t}}parseElements(e,t){for(const s of t.childElements())if("Element"===s.localName)this.parseElement(e,s)}parseElement(e,t){const s=t.findChildElement("Type")?.innerText??"";for(const i of t.childElements())switch(i.localName){case"Name":case"Articulations":this.parseArticulations(e,i,s)}}parseArticulations(e,t,s){for(const i of t.childElements())if("Articulation"===i.localName)this.parseArticulation(e,i,s)}parseArticulation(e,t,s){const i=new Ee;i.outputMidiNumber=-1,i.elementType=s;let a="";for(const e of t.childElements()){const t=e.innerText;switch(e.localName){case"Name":a=e.innerText;break;case"OutputMidiNumber":i.outputMidiNumber=Tt.parseIntSafe(t,0);break;case"TechniqueSymbol":i.techniqueSymbol=this.parseTechniqueSymbol(t);break;case"TechniquePlacement":switch(t){case"outside":case"above":i.techniqueSymbolPlacement=oe.Bottom;break;case"inside":i.techniqueSymbolPlacement=oe.Middle;break;case"below":i.techniqueSymbolPlacement=oe.Top}break;case"Noteheads":const s=Tt.splitSafe(t);s.length>=1&&(i.noteHeadDefault=this.parseNoteHead(s[0])),s.length>=2&&(i.noteHeadHalf=this.parseNoteHead(s[1])),s.length>=3&&(i.noteHeadWhole=this.parseNoteHead(s[2])),i.noteHeadHalf===re.None&&(i.noteHeadHalf=i.noteHeadDefault),i.noteHeadWhole===re.None&&(i.noteHeadWhole=i.noteHeadDefault);break;case"StaffLine":i.staffLine=Tt.parseIntSafe(t,0)}}-1!==i.outputMidiNumber?(e.percussionArticulations.push(i),a.length>0&&this._articulationByName.set(a,i)):a.length>0&&this._articulationByName.has(a)&&(this._articulationByName.get(a).staffLine=i.staffLine)}parseTechniqueSymbol(e){switch(e){case"pictEdgeOfCymbal":return re.PictEdgeOfCymbal;case"articStaccatoAbove":return re.ArticStaccatoAbove;case"noteheadParenthesis":return re.NoteheadParenthesis;case"stringsUpBow":return re.StringsUpBow;case"stringsDownBow":return re.StringsDownBow;case"guitarGolpe":return re.GuitarGolpe;default:return re.None}}parseNoteHead(e){switch(e){case"noteheadDoubleWholeSquare":return re.NoteheadDoubleWholeSquare;case"noteheadDoubleWhole":return re.NoteheadDoubleWhole;case"noteheadWhole":return re.NoteheadWhole;case"noteheadHalf":return re.NoteheadHalf;case"noteheadBlack":return re.NoteheadBlack;case"noteheadNull":return re.NoteheadNull;case"noteheadXOrnate":return re.NoteheadXOrnate;case"noteheadTriangleUpWhole":return re.NoteheadTriangleUpWhole;case"noteheadTriangleUpHalf":return re.NoteheadTriangleUpHalf;case"noteheadTriangleUpBlack":return re.NoteheadTriangleUpBlack;case"noteheadDiamondBlackWide":return re.NoteheadDiamondBlackWide;case"noteheadDiamondWhite":return re.NoteheadDiamondWhite;case"noteheadDiamondWhiteWide":return re.NoteheadDiamondWhiteWide;case"noteheadCircleX":return re.NoteheadCircleX;case"noteheadXWhole":return re.NoteheadXWhole;case"noteheadXHalf":return re.NoteheadXHalf;case"noteheadXBlack":return re.NoteheadXBlack;case"noteheadParenthesis":return re.NoteheadParenthesis;case"noteheadSlashedBlack2":return re.NoteheadSlashedBlack2;case"noteheadCircleSlash":return re.NoteheadCircleSlash;case"noteheadHeavyX":return re.NoteheadHeavyX;case"noteheadHeavyXHat":return re.NoteheadHeavyXHat;default:return q.warning("GPIF","Unknown notehead symbol",e),re.None}}parseStaves(e,t){let s=0;for(const i of t.childElements())if("Staff"===i.localName){e.ensureStaveCount(s+1);const t=e.staves[s];this.parseStaff(t,i),s++}}parseStaff(e,t){for(const s of t.childElements())if("Properties"===s.localName)this.parseStaffProperties(e,s)}parseStaffProperties(e,t){for(const s of t.childElements())if("Property"===s.localName)this.parseStaffProperty(e,s)}parseStaffProperty(e,t){switch(t.getAttribute("name")){case"Tuning":for(const s of t.childElements())switch(s.localName){case"Pitches":const i=Tt.splitSafe(t.findChildElement("Pitches")?.innerText),a=new Array(i.length);for(let e=0;e<a.length;e++)a[a.length-1-e]=Tt.parseIntSafe(i[e],0);e.stringTuning.tunings=a;break;case"Label":e.stringTuning.name=s.innerText}e.isPercussion||(e.showTablature=!0);break;case"DiagramCollection":case"ChordCollection":this.parseDiagramCollectionForStaff(e,t);break;case"CapoFret":const s=Tt.parseIntSafe(t.findChildElement("Fret")?.innerText,0);e.capo=s}}parseLyrics(e,t){const s=[];for(const e of t.childElements())if("Line"===e.localName)s.push(this.parseLyricsLine(e));this._lyricsByTrack.set(e,s)}parseLyricsLine(e){const t=new Ke;for(const s of e.childElements())switch(s.localName){case"Offset":t.startBar=Tt.parseIntSafe(s.innerText,0);break;case"Text":t.text=s.innerText}return t}parseDiagramCollectionForTrack(e,t){const s=t.findChildElement("Items");if(s)for(const t of s.childElements())if("Item"===t.localName)this.parseDiagramItemForTrack(e,t)}parseDiagramCollectionForStaff(e,t){const s=t.findChildElement("Items");if(s)for(const t of s.childElements())if("Item"===t.localName)this.parseDiagramItemForStaff(e,t)}parseDiagramItemForTrack(e,t){const s=new je,i=t.getAttribute("id");for(const t of e.staves)t.addChord(i,s);this.parseDiagramItemForChord(s,t)}parseDiagramItemForStaff(e,t){const s=new je,i=t.getAttribute("id");e.addChord(i,s),this.parseDiagramItemForChord(s,t)}parseDiagramItemForChord(e,t){e.name=t.getAttribute("name");const s=t.findChildElement("Diagram");if(!s)return e.showDiagram=!1,void(e.showFingering=!1);const i=Tt.parseIntSafe(s.getAttribute("stringCount"),6),a=Tt.parseIntSafe(s.getAttribute("baseFret"),0);e.firstFret=a+1;for(let t=0;t<i;t++)e.strings.push(-1);for(const t of s.childElements())switch(t.localName){case"Fret":const s=Tt.parseIntSafe(t.getAttribute("string"),0);e.strings[i-s-1]=a+Tt.parseIntSafe(t.getAttribute("fret"),0);break;case"Fingering":const r=new Map;for(const s of t.childElements())if("Position"===s.localName){let t=k.Unknown;const i=a+Tt.parseIntSafe(s.getAttribute("fret"),0);switch(s.getAttribute("finger")){case"Index":t=k.IndexFinger;break;case"Middle":t=k.MiddleFinger;break;case"Rank":t=k.AnnularFinger;break;case"Pinky":t=k.LittleFinger;break;case"Thumb":t=k.Thumb}t!==k.Unknown&&(r.has(t)?e.barreFrets.push(i):r.set(t,!0))}break;case"Property":switch(t.getAttribute("name")){case"ShowName":e.showName="true"===t.getAttribute("value");break;case"ShowDiagram":e.showDiagram="true"===t.getAttribute("value");break;case"ShowFingering":e.showFingering="true"===t.getAttribute("value")}}}parseTrackProperties(e,t){for(const s of t.childElements())if("Property"===s.localName)this.parseTrackProperty(e,s)}parseTrackProperty(e,t){switch(t.getAttribute("name")){case"Tuning":const s=Tt.splitSafe(t.findChildElement("Pitches")?.innerText),i=new Array(s.length);for(let e=0;e<i.length;e++)i[i.length-1-e]=Tt.parseIntSafe(s[e],0);for(const t of e.staves)t.stringTuning.tunings=i,t.showStandardNotation=!0,t.showTablature=!0;break;case"DiagramCollection":case"ChordCollection":this.parseDiagramCollectionForTrack(e,t);break;case"CapoFret":const a=Tt.parseIntSafe(t.findChildElement("Fret")?.innerText,0);for(const t of e.staves)t.capo=a}}parseGeneralMidi(e,t){for(const s of t.childElements())switch(s.localName){case"Program":e.playbackInfo.program=Tt.parseIntSafe(s.innerText,0);break;case"Port":e.playbackInfo.port=Tt.parseIntSafe(s.innerText,0);break;case"PrimaryChannel":e.playbackInfo.primaryChannel=Tt.parseIntSafe(s.innerText,0);break;case"SecondaryChannel":e.playbackInfo.secondaryChannel=Tt.parseIntSafe(s.innerText,0)}if("Percussion"===t.getAttribute("table"))for(const t of e.staves)t.isPercussion=!0}parseSounds(e,t,s){for(const i of s.childElements())if("Sound"===i.localName)this.parseSound(e,t,i)}parseSound(e,t,s){const i=new kt;for(const e of s.childElements())switch(e.localName){case"Name":i.name=e.innerText;break;case"Path":i.path=e.innerText;break;case"Role":i.role=e.innerText;break;case"MIDI":this.parseSoundMidi(i,e)}"Factory"!==i.role&&0!==t.playbackInfo.program||(t.playbackInfo.program=i.program),this._soundsByTrack.has(e)||this._soundsByTrack.set(e,new Map),this._soundsByTrack.get(e).set(i.uniqueId,i)}parseSoundMidi(e,t){for(const s of t.childElements())if("Program"===s.localName)e.program=Tt.parseIntSafe(s.innerText,0)}parsePartSounding(e,t){for(const s of t.childElements())if("TranspositionPitch"===s.localName)for(const t of e.staves)t.displayTranspositionPitch=Tt.parseIntSafe(s.innerText,0)}parseTranspose(e,t){let s=0,i=0;for(const e of t.childElements())switch(e.localName){case"Chromatic":i=Tt.parseIntSafe(e.innerText,0);break;case"Octave":s=Tt.parseIntSafe(e.innerText,0)}for(const t of e.staves)t.displayTranspositionPitch=12*s+i}parseRSE(e,t){for(const s of t.childElements())if("ChannelStrip"===s.localName)this.parseChannelStrip(e,s)}parseChannelStrip(e,t){for(const s of t.childElements())if("Parameters"===s.localName)this.parseChannelStripParameters(e,s)}parseChannelStripParameters(e,t){if(t.firstChild&&t.firstChild.value){const s=Tt.splitSafe(t.firstChild.value);s.length>=12&&(e.playbackInfo.balance=Math.floor(16*Tt.parseFloatSafe(s[11],.5)),e.playbackInfo.volume=Math.floor(16*Tt.parseFloatSafe(s[12],.9)))}}parseMasterBarsNode(e){for(const t of e.childElements())if("MasterBar"===t.localName)this.parseMasterBar(t)}parseMasterBar(e){const t=new j;0===this._masterBars.length&&this._hasAnacrusis&&(t.isAnacrusis=!0);for(const s of e.childElements())switch(s.localName){case"Time":const e=s.innerText.split("/");t.timeSignatureNumerator=Tt.parseIntSafe(e[0],4),t.timeSignatureDenominator=Tt.parseIntSafe(e[1],4);break;case"FreeTime":t.isFreeTime=!0;break;case"DoubleBar":t.isDoubleBar=!0,this._doubleBars.add(t);break;case"Section":t.section=new Qe,t.section.marker=s.findChildElement("Letter")?.innerText??"",t.section.text=s.findChildElement("Text")?.innerText??"";break;case"Repeat":"true"===s.getAttribute("start").toLowerCase()&&(t.isRepeatStart=!0),"true"===s.getAttribute("end").toLowerCase()&&s.getAttribute("count")&&(t.repeatCount=Tt.parseIntSafe(s.getAttribute("count"),1));break;case"AlternateEndings":const i=Tt.splitSafe(s.innerText);let a=0;for(let e=0;e<i.length;e++)a|=1<<-1+Tt.parseIntSafe(i[e],0);t.alternateEndings=a;break;case"Bars":this._barsOfMasterBar.push(Tt.splitSafe(s.innerText));break;case"TripletFeel":switch(s.innerText){case"NoTripletFeel":t.tripletFeel=M.NoTripletFeel;break;case"Triplet8th":t.tripletFeel=M.Triplet8th;break;case"Triplet16th":t.tripletFeel=M.Triplet16th;break;case"Dotted8th":t.tripletFeel=M.Dotted8th;break;case"Dotted16th":t.tripletFeel=M.Dotted16th;break;case"Scottish8th":t.tripletFeel=M.Scottish8th;break;case"Scottish16th":t.tripletFeel=M.Scottish16th}break;case"Key":const r=Tt.parseIntSafe(s.findChildElement("AccidentalCount")?.innerText,0),n=s.findChildElement("Mode");let o=c.Major;if(n)switch(n.innerText.toLowerCase()){case"major":o=c.Major;break;case"minor":o=c.Minor}this._keySignatures.set(this._masterBars.length,[r,o]);break;case"Fermatas":this.parseFermatas(t,s);break;case"XProperties":this.parseMasterBarXProperties(t,s);break;case"Directions":this.parseDirections(t,s)}this._masterBars.push(t)}parseDirections(e,t){for(const s of t.childElements())switch(s.localName){case"Target":switch(s.innerText){case"Coda":e.addDirection(Be.TargetCoda);break;case"DoubleCoda":e.addDirection(Be.TargetDoubleCoda);break;case"Segno":e.addDirection(Be.TargetSegno);break;case"SegnoSegno":e.addDirection(Be.TargetSegnoSegno);break;case"Fine":e.addDirection(Be.TargetFine)}break;case"Jump":switch(s.innerText){case"DaCapo":e.addDirection(Be.JumpDaCapo);break;case"DaCapoAlCoda":e.addDirection(Be.JumpDaCapoAlCoda);break;case"DaCapoAlDoubleCoda":e.addDirection(Be.JumpDaCapoAlDoubleCoda);break;case"DaCapoAlFine":e.addDirection(Be.JumpDaCapoAlFine);break;case"DaSegno":e.addDirection(Be.JumpDalSegno);break;case"DaSegnoAlCoda":e.addDirection(Be.JumpDalSegnoAlCoda);break;case"DaSegnoAlDoubleCoda":e.addDirection(Be.JumpDalSegnoAlDoubleCoda);break;case"DaSegnoAlFine":e.addDirection(Be.JumpDalSegnoAlFine);break;case"DaSegnoSegno":e.addDirection(Be.JumpDalSegnoSegno);break;case"DaSegnoSegnoAlCoda":e.addDirection(Be.JumpDalSegnoSegnoAlCoda);break;case"DaSegnoSegnoAlDoubleCoda":e.addDirection(Be.JumpDalSegnoSegnoAlDoubleCoda);break;case"DaSegnoSegnoAlFine":e.addDirection(Be.JumpDalSegnoSegnoAlFine);break;case"DaCoda":e.addDirection(Be.JumpDaCoda);break;case"DaDoubleCoda":e.addDirection(Be.JumpDaDoubleCoda)}}}parseFermatas(e,t){for(const s of t.childElements())if("Fermata"===s.localName)this.parseFermata(e,s)}parseFermata(e,t){let s=0;const i=new lt;for(const e of t.childElements())switch(e.localName){case"Type":switch(e.innerText){case"Short":i.type=ke.Short;break;case"Medium":i.type=ke.Medium;break;case"Long":i.type=ke.Long}break;case"Length":i.length=Tt.parseFloatSafe(e.innerText,0);break;case"Offset":const t=e.innerText.split("/");if(2===t.length){s=Tt.parseIntSafe(t[0],4)/Tt.parseIntSafe(t[1],4)*z.QuarterTime|0}}e.addFermata(s,i)}parseBars(e){for(const t of e.childElements())if("Bar"===t.localName)this.parseBar(t)}parseBar(e){const t=new G,s=e.getAttribute("id");for(const i of e.childElements())switch(i.localName){case"Voices":this._voicesOfBar.set(s,Tt.splitSafe(i.innerText));break;case"Clef":switch(i.innerText){case"Neutral":t.clef=n.Neutral;break;case"G2":t.clef=n.G2;break;case"F4":t.clef=n.F4;break;case"C4":t.clef=n.C4;break;case"C3":t.clef=n.C3}break;case"Ottavia":switch(i.innerText){case"8va":t.clefOttava=o._8va;break;case"15ma":t.clefOttava=o._15ma;break;case"8vb":t.clefOttava=o._8vb;break;case"15mb":t.clefOttava=o._15mb}break;case"SimileMark":switch(i.innerText){case"Simple":t.simileMark=h.Simple;break;case"FirstOfDouble":t.simileMark=h.FirstOfDouble;break;case"SecondOfDouble":t.simileMark=h.SecondOfDouble}break;case"XProperties":this.parseBarXProperties(i,t)}this._barsById.set(s,t)}parseVoices(e){for(const t of e.childElements())if("Voice"===t.localName)this.parseVoice(t)}parseVoice(e){const t=new ee,s=e.getAttribute("id");for(const t of e.childElements())if("Beats"===t.localName)this._beatsOfVoice.set(s,Tt.splitSafe(t.innerText));this._voiceById.set(s,t)}parseBeats(e){for(const t of e.childElements())if("Beat"===t.localName)this.parseBeat(t)}parseBeat(e){const t=new ze,s=e.getAttribute("id");for(const i of e.childElements())switch(i.localName){case"Notes":this._notesOfBeat.set(s,Tt.splitSafe(i.innerText));break;case"Rhythm":this._rhythmOfBeat.set(s,i.getAttribute("ref"));break;case"Fadding":switch(i.innerText){case"FadeIn":t.fade=ue.FadeIn;break;case"FadeOut":t.fade=ue.FadeOut;break;case"VolumeSwell":t.fade=ue.VolumeSwell}break;case"Tremolo":switch(i.innerText){case"1/2":t.tremoloSpeed=_.Eighth;break;case"1/4":t.tremoloSpeed=_.Sixteenth;break;case"1/8":t.tremoloSpeed=_.ThirtySecond}break;case"Chord":t.chordId=i.innerText;break;case"Hairpin":switch(i.innerText){case"Crescendo":t.crescendo=S.Crescendo;break;case"Decrescendo":t.crescendo=S.Decrescendo}break;case"Arpeggio":"Up"===i.innerText?t.brushType=b.ArpeggioUp:t.brushType=b.ArpeggioDown;break;case"Properties":this.parseBeatProperties(i,t);break;case"XProperties":this.parseBeatXProperties(i,t);break;case"FreeText":t.text=i.innerText;break;case"TransposedPitchStemOrientation":switch(i.innerText){case"Upward":t.preferredBeamDirection=Te.Up;break;case"Downward":t.preferredBeamDirection=Te.Down}break;case"Dynamic":switch(i.innerText){case"PPP":t.dynamics=g.PPP;break;case"PP":t.dynamics=g.PP;break;case"P":t.dynamics=g.P;break;case"MP":t.dynamics=g.MP;break;case"MF":t.dynamics=g.MF;break;case"F":t.dynamics=g.F;break;case"FF":t.dynamics=g.FF;break;case"FFF":t.dynamics=g.FFF}break;case"GraceNotes":switch(i.innerText){case"OnBeat":t.graceType=w.OnBeat;break;case"BeforeBeat":t.graceType=w.BeforeBeat}break;case"Legato":"true"===i.getAttribute("origin")&&(t.isLegatoOrigin=!0);break;case"Whammy":const e=new X(0,0);e.value=this.toBendValue(Tt.parseFloatSafe(i.getAttribute("originValue"),0)),e.offset=this.toBendOffset(Tt.parseFloatSafe(i.getAttribute("originOffset"),0)),t.addWhammyBarPoint(e);const a=new X(0,0);a.value=this.toBendValue(Tt.parseFloatSafe(i.getAttribute("middleValue"),0)),a.offset=this.toBendOffset(Tt.parseFloatSafe(i.getAttribute("middleOffset1"),0)),t.addWhammyBarPoint(a);const r=new X(0,0);r.value=this.toBendValue(Tt.parseFloatSafe(i.getAttribute("middleValue"),0)),r.offset=this.toBendOffset(Tt.parseFloatSafe(i.getAttribute("middleOffset2"),0)),t.addWhammyBarPoint(r);const n=new X(0,0);n.value=this.toBendValue(Tt.parseFloatSafe(i.getAttribute("destinationValue"),0)),n.offset=this.toBendOffset(Tt.parseFloatSafe(i.getAttribute("destinationOffset"),0)),t.addWhammyBarPoint(n);break;case"Ottavia":switch(i.innerText){case"8va":t.ottava=o._8va;break;case"8vb":t.ottava=o._8vb;break;case"15ma":t.ottava=o._15ma;break;case"15mb":t.ottava=o._15mb}break;case"Lyrics":t.lyrics=this.parseBeatLyrics(i),this._skipApplyLyrics=!0;break;case"Slashed":t.slashed=!0;break;case"DeadSlapped":t.deadSlapped=!0;break;case"Golpe":switch(i.innerText){case"Finger":t.golpe=de.Finger;break;case"Thumb":t.golpe=de.Thumb}break;case"Wah":switch(i.innerText){case"Open":t.wahPedal=pe.Open;break;case"Closed":t.wahPedal=pe.Closed}break;case"UserTransposedPitchStemOrientation":switch(i.innerText){case"Downward":t.preferredBeamDirection=Te.Down;break;case"Upward":t.preferredBeamDirection=Te.Up}break;case"Timer":t.showTimer=!0,t.timer=Tt.parseIntSafe(i.innerText,-1),t.timer<0&&(t.timer=null)}this._beatById.set(s,t)}parseBeatLyrics(e){const t=[];for(const s of e.childElements())if("Line"===s.localName)t.push(s.innerText);return t}parseBeatXProperties(e,t){for(const s of e.childElements())if("XProperty"===s.localName){let e=0;switch(s.getAttribute("id")){case"1124204546":switch(e=Tt.parseIntSafe(s.findChildElement("Int")?.innerText,0),e){case 1:t.beamingMode=fe.ForceMergeWithNext;break;case 2:t.beamingMode=fe.ForceSplitToNext}break;case"1124204552":if(e=Tt.parseIntSafe(s.findChildElement("Int")?.innerText,0),1===e)t.beamingMode!==fe.ForceSplitToNext&&(t.beamingMode=fe.ForceSplitOnSecondaryToNext);break;case"1124204545":e=Tt.parseIntSafe(s.findChildElement("Int")?.innerText,0),t.invertBeamDirection=1===e;break;case"687935489":e=Tt.parseIntSafe(s.findChildElement("Int")?.innerText,0),t.brushDuration=e}}}parseBarXProperties(e,t){for(const s of e.childElements())if("XProperty"===s.localName){if("1124139520"===s.getAttribute("id")){const e=s.findChildElement("Double")??s.findChildElement("Float");t.displayScale=Tt.parseFloatSafe(e?.innerText,1)}}}parseMasterBarXProperties(e,t){for(const s of t.childElements())if("XProperty"===s.localName){if("1124073984"===s.getAttribute("id"))e.displayScale=Tt.parseFloatSafe(s.findChildElement("Double")?.innerText,1)}}parseBeatProperties(e,t){let s=!1,i=null,a=null,r=null,n=null,o=null;for(const h of e.childElements())if("Property"===h.localName){switch(h.getAttribute("name")){case"Brush":"Up"===h.findChildElement("Direction")?.innerText?t.brushType=b.BrushUp:t.brushType=b.BrushDown;break;case"PickStroke":"Up"===h.findChildElement("Direction")?.innerText?t.pickStroke=ae.Up:t.pickStroke=ae.Down;break;case"Slapped":h.findChildElement("Enable")&&(t.slap=!0);break;case"Popped":h.findChildElement("Enable")&&(t.pop=!0);break;case"VibratoWTremBar":switch(h.findChildElement("Strength")?.innerText){case"Wide":t.vibrato=P.Wide;break;case"Slight":t.vibrato=P.Slight}break;case"WhammyBar":s=!0;break;case"WhammyBarExtend":break;case"WhammyBarOriginValue":i||(i=new X(0,0)),i.value=this.toBendValue(Tt.parseFloatSafe(h.findChildElement("Float")?.innerText,0));break;case"WhammyBarOriginOffset":i||(i=new X(0,0)),i.offset=this.toBendOffset(Tt.parseFloatSafe(h.findChildElement("Float")?.innerText,0));break;case"WhammyBarMiddleValue":a=this.toBendValue(Tt.parseFloatSafe(h.findChildElement("Float")?.innerText,0));break;case"WhammyBarMiddleOffset1":r=this.toBendOffset(Tt.parseFloatSafe(h.findChildElement("Float")?.innerText,0));break;case"WhammyBarMiddleOffset2":n=this.toBendOffset(Tt.parseFloatSafe(h.findChildElement("Float")?.innerText,0));break;case"WhammyBarDestinationValue":o||(o=new X(X.MaxPosition,0)),o.value=this.toBendValue(Tt.parseFloatSafe(h.findChildElement("Float")?.innerText,0));break;case"WhammyBarDestinationOffset":o||(o=new X(0,0)),o.offset=this.toBendOffset(Tt.parseFloatSafe(h.findChildElement("Float")?.innerText,0));break;case"BarreFret":t.barreFret=Tt.parseIntSafe(h.findChildElement("Fret")?.innerText,0);break;case"BarreString":switch(h.findChildElement("String")?.innerText){case"0":t.barreShape=ge.Full;break;case"1":t.barreShape=ge.Half}break;case"Rasgueado":switch(h.findChildElement("Rasgueado")?.innerText){case"ii_1":t.rasgueado=me.Ii;break;case"mi_1":t.rasgueado=me.Mi;break;case"mii_1":t.rasgueado=me.MiiTriplet;break;case"mii_2":t.rasgueado=me.MiiAnapaest;break;case"pmp_1":t.rasgueado=me.PmpTriplet;break;case"pmp_2":t.rasgueado=me.PmpAnapaest;break;case"pei_1":t.rasgueado=me.PeiTriplet;break;case"pei_2":t.rasgueado=me.PeiAnapaest;break;case"pai_1":t.rasgueado=me.PaiTriplet;break;case"pai_2":t.rasgueado=me.PaiAnapaest;break;case"ami_1":t.rasgueado=me.AmiTriplet;break;case"ami_2":t.rasgueado=me.AmiAnapaest;break;case"ppp_1":t.rasgueado=me.Ppp;break;case"amii_1":t.rasgueado=me.Amii;break;case"amip_1":t.rasgueado=me.Amip;break;case"eami_1":t.rasgueado=me.Eami;break;case"eamii_1":t.rasgueado=me.Eamii;break;case"peami_1":t.rasgueado=me.Peami}}}s&&(i||(i=new X(0,0)),o||(o=new X(X.MaxPosition,0)),t.addWhammyBarPoint(i),r&&a&&t.addWhammyBarPoint(new X(r,a)),n&&a&&t.addWhammyBarPoint(new X(n,a)),r||n||!a||t.addWhammyBarPoint(new X(X.MaxPosition/2|0,a)),t.addWhammyBarPoint(o))}parseNotes(e){for(const t of e.childElements())if("Note"===t.localName)this.parseNote(t)}parseNote(e){const t=new Ae,s=e.getAttribute("id");for(const i of e.childElements())switch(i.localName){case"Properties":this.parseNoteProperties(i,t,s);break;case"AntiAccent":"normal"===i.innerText.toLowerCase()&&(t.isGhost=!0);break;case"LetRing":t.isLetRing=!0;break;case"Trill":t.trillValue=Tt.parseIntSafe(i.innerText,-1),t.trillSpeed=_.Sixteenth;break;case"Accent":const e=Tt.parseIntSafe(i.innerText,0);1&e&&(t.isStaccato=!0),4&e&&(t.accentuated=B.Heavy),8&e&&(t.accentuated=B.Normal),16&e&&(t.accentuated=B.Tenuto);break;case"Tie":"true"===i.getAttribute("destination").toLowerCase()&&(t.isTieDestination=!0);break;case"Vibrato":switch(i.innerText){case"Slight":t.vibrato=P.Slight;break;case"Wide":t.vibrato=P.Wide}break;case"LeftFingering":switch(i.innerText){case"P":t.leftHandFinger=k.Thumb;break;case"I":t.leftHandFinger=k.IndexFinger;break;case"M":t.leftHandFinger=k.MiddleFinger;break;case"A":t.leftHandFinger=k.AnnularFinger;break;case"C":t.leftHandFinger=k.LittleFinger}break;case"RightFingering":switch(i.innerText){case"P":t.rightHandFinger=k.Thumb;break;case"I":t.rightHandFinger=k.IndexFinger;break;case"M":t.rightHandFinger=k.MiddleFinger;break;case"A":t.rightHandFinger=k.AnnularFinger;break;case"C":t.rightHandFinger=k.LittleFinger}break;case"InstrumentArticulation":t.percussionArticulation=Tt.parseIntSafe(i.innerText,0);break;case"Ornament":switch(i.innerText){case"Turn":t.ornament=he.Turn;break;case"InvertedTurn":t.ornament=he.InvertedTurn;break;case"UpperMordent":t.ornament=he.UpperMordent;break;case"LowerMordent":t.ornament=he.LowerMordent}}this._noteById.set(s,t)}parseNoteProperties(e,t,s){let i=!1,a=null,r=null,n=null,o=null,h=null,l=-1,c=-1;for(const d of e.childElements())if("Property"===d.localName){switch(d.getAttribute("name")){case"ShowStringNumber":d.findChildElement("Enable")&&(t.showStringNumber=!0);break;case"String":t.string=Tt.parseIntSafe(d.findChildElement("String")?.innerText,0)+1;break;case"Fret":t.fret=Tt.parseIntSafe(d.findChildElement("Fret")?.innerText,0);break;case"Element":l=Tt.parseIntSafe(d.findChildElement("Element")?.innerText,0);break;case"Variation":c=Tt.parseIntSafe(d.findChildElement("Variation")?.innerText,0);break;case"Tapped":this._tappedNotes.set(s,!0);break;case"HarmonicType":const e=d.findChildElement("HType");if(e)switch(e.innerText){case"NoHarmonic":t.harmonicType=T.None;break;case"Natural":t.harmonicType=T.Natural;break;case"Artificial":t.harmonicType=T.Artificial;break;case"Pinch":t.harmonicType=T.Pinch;break;case"Tap":t.harmonicType=T.Tap;break;case"Semi":t.harmonicType=T.Semi;break;case"Feedback":t.harmonicType=T.Feedback}break;case"HarmonicFret":const u=d.findChildElement("HFret");u&&(t.harmonicValue=Tt.parseFloatSafe(u.innerText,0));break;case"Muted":d.findChildElement("Enable")&&(t.isDead=!0);break;case"PalmMuted":d.findChildElement("Enable")&&(t.isPalmMute=!0);break;case"Octave":t.octave=Tt.parseIntSafe(d.findChildElement("Number")?.innerText,0),-1===t.tone&&(t.tone=0);break;case"Tone":t.tone=Tt.parseIntSafe(d.findChildElement("Step")?.innerText,0);break;case"ConcertPitch":this.parseConcertPitch(d,t);break;case"Bended":i=!0;break;case"BendOriginValue":a||(a=new X(0,0)),a.value=this.toBendValue(Tt.parseFloatSafe(d.findChildElement("Float")?.innerText,0));break;case"BendOriginOffset":a||(a=new X(0,0)),a.offset=this.toBendOffset(Tt.parseFloatSafe(d.findChildElement("Float")?.innerText,0));break;case"BendMiddleValue":r=this.toBendValue(Tt.parseFloatSafe(d.findChildElement("Float")?.innerText,0));break;case"BendMiddleOffset1":n=this.toBendOffset(Tt.parseFloatSafe(d.findChildElement("Float")?.innerText,0));break;case"BendMiddleOffset2":o=this.toBendOffset(Tt.parseFloatSafe(d.findChildElement("Float")?.innerText,0));break;case"BendDestinationValue":h||(h=new X(X.MaxPosition,0)),h.value=this.toBendValue(Tt.parseFloatSafe(d.findChildElement("Float")?.innerText,0));break;case"BendDestinationOffset":h||(h=new X(0,0)),h.offset=this.toBendOffset(Tt.parseFloatSafe(d.findChildElement("Float")?.innerText,0));break;case"HopoOrigin":d.findChildElement("Enable")&&(t.isHammerPullOrigin=!0);break;case"HopoDestination":break;case"LeftHandTapped":t.isLeftHandTapped=!0;break;case"Slide":const p=Tt.parseIntSafe(d.findChildElement("Flags")?.innerText,0);1&p?t.slideOutType=v.Shift:2&p?t.slideOutType=v.Legato:4&p?t.slideOutType=v.OutDown:8&p&&(t.slideOutType=v.OutUp),16&p?t.slideInType=x.IntoFromBelow:32&p&&(t.slideInType=x.IntoFromAbove),64&p?t.slideOutType=v.PickSlideDown:128&p&&(t.slideOutType=v.PickSlideUp)}}i&&(a||(a=new X(0,0)),h||(h=new X(X.MaxPosition,0)),t.addBendPoint(a),n&&r&&t.addBendPoint(new X(n,r)),o&&r&&t.addBendPoint(new X(o,r)),n||o||!r||t.addBendPoint(new X(X.MaxPosition/2|0,r)),t.addBendPoint(h)),-1!==l&&-1!==c&&(t.percussionArticulation=Le.articulationFromElementVariation(l,c))}parseConcertPitch(e,t){const s=e.findChildElement("Pitch");if(s)for(const e of s.childElements())if("Accidental"===e.localName)switch(e.innerText){case"x":t.accidentalMode=N.ForceDoubleSharp;break;case"#":t.accidentalMode=N.ForceSharp;break;case"b":t.accidentalMode=N.ForceFlat;break;case"bb":t.accidentalMode=N.ForceDoubleFlat}}toBendValue(e){return e*Tt.BendPointValueFactor|0}toBendOffset(e){return e*Tt.BendPointPositionFactor}parseRhythms(e){for(const t of e.childElements())if("Rhythm"===t.localName)this.parseRhythm(t)}parseRhythm(e){const t=new Bt,s=e.getAttribute("id");t.id=s;for(const s of e.childElements())switch(s.localName){case"NoteValue":switch(s.innerText){case"Long":t.value=_.QuadrupleWhole;break;case"DoubleWhole":t.value=_.DoubleWhole;break;case"Whole":t.value=_.Whole;break;case"Half":t.value=_.Half;break;case"Quarter":t.value=_.Quarter;break;case"Eighth":t.value=_.Eighth;break;case"16th":t.value=_.Sixteenth;break;case"32nd":t.value=_.ThirtySecond;break;case"64th":t.value=_.SixtyFourth;break;case"128th":t.value=_.OneHundredTwentyEighth;break;case"256th":t.value=_.TwoHundredFiftySixth}break;case"PrimaryTuplet":t.tupletNumerator=Tt.parseIntSafe(s.getAttribute("num"),-1),t.tupletDenominator=Tt.parseIntSafe(s.getAttribute("den"),-1);break;case"AugmentationDot":t.dots=Tt.parseIntSafe(s.getAttribute("count"),0)}this._rhythmById.set(s,t)}buildModel(){for(let e=0,t=this._masterBars.length;e<t;e++){const t=this._masterBars[e];this.score.addMasterBar(t)}const e=this._masterBars[this._masterBars.length-1];this._doubleBars.has(e)&&(this._doubleBars.delete(e),e.isDoubleBar=!1);for(const e of this._tracksMapping){if(!e)continue;const t=this._tracksById.get(e);this.score.addTrack(t)}let t;for(const e of this._barsOfMasterBar){let s=0;t=[l.C,c.Major];for(let i=0,a=0;i<e.length&&a<this.score.tracks.length;i++){const r=e[i];if(r!==Tt.InvalidId){const e=this._barsById.get(r),i=this.score.tracks[a],n=i.staves[s];n.addBar(e);const o=n.bars.length-1;if(this._keySignatures.has(o)&&(t=this._keySignatures.get(o)),e.keySignature=t[0],e.keySignatureType=t[1],this._doubleBars.has(e.masterBar)&&(e.barLineRight=p.LightLight),this._voicesOfBar.has(r))for(const t of this._voicesOfBar.get(r))if(t!==Tt.InvalidId){const s=this._voiceById.get(t);if(e.addVoice(s),this._beatsOfVoice.has(t))for(const e of this._beatsOfVoice.get(t))if(e!==Tt.InvalidId){const t=Ve.clone(this._beatById.get(e));s.addBeat(t);const i=this._rhythmOfBeat.get(e),a=this._rhythmById.get(i);if(t.duration=a.value,t.dots=a.dots,t.tupletNumerator=a.tupletNumerator,t.tupletDenominator=a.tupletDenominator,this._notesOfBeat.has(e))for(const s of this._notesOfBeat.get(e))if(s!==Tt.InvalidId){const e=He.clone(this._noteById.get(s));n.isPercussion?(e.fret=-1,e.string=-1):e.percussionArticulation=-1,t.addNote(e),this._tappedNotes.has(s)&&(t.tap=!0)}}}else{const t=new ee;e.addVoice(t);const s=new ze;s.isEmpty=!0,s.duration=_.Quarter,t.addBeat(s)}s===i.staves.length-1?(a++,s=0,t=[l.C,c.Major]):(s++,t=[l.C,c.Major])}else a++}}for(const e of this._tracksMapping){if(!e)continue;const t=this._tracksById.get(e);let s=!1;for(const e of t.staves)if(e.isPercussion){s=!0;break}if(s||(t.percussionArticulations=[]),this._automationsPerTrackIdAndBarIndex.has(e)){const s=this._automationsPerTrackIdAndBarIndex.get(e);for(const[e,i]of s)if(t.staves.length>0&&e<t.staves[0].bars.length){const s=t.staves[0].bars[e];if(s.voices.length>0&&s.voices[0].beats.length>0){const e=s.voices[0].beats[0];for(const t of i)e.automations.push(t)}}}if(this._sustainPedalsPerTrackIdAndBarIndex.has(e)){const s=this._sustainPedalsPerTrackIdAndBarIndex.get(e);for(const[e,i]of s)if(t.staves.length>0&&e<t.staves[0].bars.length){t.staves[0].bars[e].sustainPedals=i}}}for(const[e,t]of this._masterTrackAutomations){const s=this.score.masterBars[e];for(let i=0,a=t.length;i<a;i++){const a=t[i];a.type===m.Tempo&&(0===e&&(this.score.tempo=0|a.value,a.text&&(this.score.tempoLabel=a.text)),s.tempoAutomations.push(a))}}}}Tt.InvalidId="-1",Tt.BendPointPositionFactor=X.MaxPosition/100,Tt.BendPointValueFactor=.04;class Nt{constructor(){this.isMultiRest=!1,this.trackViewGroups=[]}}class xt{constructor(){this.showNumbered=!1,this.showSlash=!1,this.showStandardNotation=!1,this.showTablature=!1}}class vt{apply(e){if(this.scoreViews.length>0){let t=0;e.stylesheet.multiTrackMultiBarRest=this.scoreViews[0].isMultiRest;for(const s of this.scoreViews[0].trackViewGroups){if(t<e.tracks.length){const i=e.tracks[t];for(const e of i.staves)e.showTablature=s.showTablature,e.showStandardNotation=s.showStandardNotation,e.showSlash=s.showSlash,e.showNumbered=s.showNumbered}t++}for(let s=1;s<this.scoreViews.length;s++)this.scoreViews[s].isMultiRest&&(e.stylesheet.perTrackMultiBarRest||(e.stylesheet.perTrackMultiBarRest=new Set),t=s-1,e.stylesheet.perTrackMultiBarRest.add(t))}}constructor(e){this.scoreViews=[];const t=ht.fromBuffer(e),s=ot.readInt32BE(t);for(let e=0;e<s;e++){const e=new Nt;this.scoreViews.push(e),e.isMultiRest=pt.gpReadBool(t);const s=ot.readInt32BE(t);for(let i=0;i<s;i++){let s=t.readByte();0===s&&(s=1);const i=new xt;i.showStandardNotation=!!(1&s),i.showTablature=!!(2&s),i.showSlash=!!(4&s),i.showNumbered=!!(8&s),e.trackViewGroups.push(i)}}}static writeForScore(e){const t=ht.withCapacity(128),s=[new Nt];s[0].isMultiRest=e.stylesheet.multiTrackMultiBarRest;for(const t of e.tracks){const i=new xt;i.showStandardNotation=t.staves[0].showStandardNotation,i.showTablature=t.staves[0].showTablature,i.showSlash=t.staves[0].showSlash,i.showNumbered=t.staves[0].showNumbered,s[0].trackViewGroups.push(i);const a=new Nt;a.isMultiRest=!0===e.stylesheet.perTrackMultiBarRest?.has(t.index),a.trackViewGroups.push(i),s.push(a)}ot.writeInt32BE(t,s.length);for(const e of s){t.writeByte(e.isMultiRest?1:0),ot.writeInt32BE(t,e.trackViewGroups.length);for(const s of e.trackViewGroups){let e=0;s.showStandardNotation&&(e|=1),s.showTablature&&(e|=2),s.showSlash&&(e|=4),s.showNumbered&&(e|=8),t.writeByte(e)}}return ot.writeInt32BE(t,1),t.toArray()}}let Pt=class{};class Ft extends Pt{constructor(e){super(),this.n=e}}class Ct extends Pt{constructor(e,t){super(),this.left=e,this.right=t}}class Dt extends Pt{constructor(e,t){super(),this.n=e,this.table=t}}class Et{static make(e,t,s,i){const a=[],r=[];if(i>32)throw new Ze("Invalid huffman");for(let e=0;e<i;e++)a.push(0),r.push(0);for(let r=0;r<s;r++){const s=e[r+t];if(s>=i)throw new Ze("Invalid huffman");a[s]++}let n=0;for(let e=1;e<i-1;e++)n=n+a[e]<<1,r[e]=n;const o=new Map;for(let i=0;i<s;i++){const s=e[i+t];if(0!==s){const e=r[s-1];r[s-1]=e+1,o.set(e<<5|s,i)}}return Et.treeCompress(new Ct(Et.treeMake(o,i,0,1),Et.treeMake(o,i,1,1)))}static treeMake(e,t,s,i){if(i>t)throw new Ze("Invalid huffman");const a=s<<5|i;return e.has(a)?new Ft(e.get(a)):(s<<=1,i+=1,new Ct(Et.treeMake(e,t,s,i),Et.treeMake(e,t,1|s,i)))}static treeCompress(e){const t=Et.treeDepth(e);if(0===t)return e;if(1===t){if(e instanceof Ct)return new Ct(Et.treeCompress(e.left),Et.treeCompress(e.right));throw new Ze("assert")}const s=1<<t,i=[];for(let e=0;e<s;e++)i.push(new Ft(-1));return Et.treeWalk(i,0,0,t,e),new Dt(t,i)}static treeWalk(e,t,s,i,a){a instanceof Ct&&i>0?(Et.treeWalk(e,t,s+1,i-1,a.left),Et.treeWalk(e,t|1<<s,s+1,i-1,a.right)):e[t]=Et.treeCompress(a)}static treeDepth(e){if(e instanceof Ft)return 0;if(e instanceof Dt)throw new Ze("assert");if(e instanceof Ct){const t=Et.treeDepth(e.left),s=Et.treeDepth(e.right);return 1+(t<s?t:s)}return 0}}var Lt,Mt,It,At,Rt,Ot,Ht,Wt,Vt,Gt,zt,Ut,Xt,Jt,Yt,$t,qt,jt,Kt,Qt,Zt,es,ts,ss,is,as,rs,ns,os;!function(e){e[e.Head=0]="Head",e[e.Block=1]="Block",e[e.CData=2]="CData",e[e.Flat=3]="Flat",e[e.Crc=4]="Crc",e[e.Dist=5]="Dist",e[e.DistOne=6]="DistOne",e[e.Done=7]="Done"}(Lt||(Lt={}));class hs{constructor(){this.buffer=new Uint8Array(hs.BufferSize),this.pos=0}slide(){const e=new Uint8Array(hs.BufferSize);this.pos-=hs.Size,e.set(this.buffer.subarray(hs.Size,hs.Size+this.pos),0),this.buffer=e}addBytes(e,t,s){this.pos+s>hs.BufferSize&&this.slide(),this.buffer.set(e.subarray(t,t+s),this.pos),this.pos+=s}addByte(e){this.pos===hs.BufferSize&&this.slide(),this.buffer[this.pos]=e,this.pos++}getLastChar(){return this.buffer[this.pos-1]}available(){return this.pos}}hs.Size=32768,hs.BufferSize=65536;class ls{static buildFixedHuffman(){const e=[];for(let t=0;t<288;t++)e.push(t<=143?8:t<=255?9:t<=279?7:8);return Et.make(e,0,288,10)}constructor(e){this._nbits=0,this._bits=0,this._state=Lt.Block,this._isFinal=!1,this._huffman=ls._fixedHuffman,this._huffdist=null,this._len=0,this._dist=0,this._needed=0,this._output=null,this._outpos=0,this._lengths=[],this._window=new hs,this._input=e;for(let e=0;e<19;e++)this._lengths.push(-1)}readBytes(e,t,s){if(this._needed=s,this._outpos=t,this._output=e,s>0)for(;this.inflateLoop(););return s-this._needed}inflateLoop(){switch(this._state){case Lt.Head:const e=this._input.readByte();if(8!==(15&e))throw new Ze("Invalid data");const t=this._input.readByte(),s=!!(32&t);if(((e<<8)+t)%31!=0)throw new Ze("Invalid data");if(s)throw new Ze("Unsupported dictionary");return this._state=Lt.Block,!0;case Lt.Crc:return this._state=Lt.Done,!0;case Lt.Done:return!1;case Lt.Block:switch(this._isFinal=this.getBit(),this.getBits(2)){case 0:this._len=ot.readUInt16LE(this._input);if(ot.readUInt16LE(this._input)!==65535-this._len)throw new Ze("Invalid data");this._state=Lt.Flat;const e=this.inflateLoop();return this.resetBits(),e;case 1:return this._huffman=ls._fixedHuffman,this._huffdist=null,this._state=Lt.CData,!0;case 2:const t=this.getBits(5)+257,s=this.getBits(5)+1,i=this.getBits(4)+4;for(let e=0;e<i;e++)this._lengths[ls.CodeLengthsPos[e]]=this.getBits(3);for(let e=i;e<19;e++)this._lengths[ls.CodeLengthsPos[e]]=0;this._huffman=Et.make(this._lengths,0,19,8);const a=[];for(let e=0;e<t+s;e++)a.push(0);return this.inflateLengths(a,t+s),this._huffdist=Et.make(a,t,s,16),this._huffman=Et.make(a,0,t,16),this._state=Lt.CData,!0;default:throw new Ze("Invalid data")}case Lt.Flat:{const e=this._len<this._needed?this._len:this._needed,t=ot.readByteArray(this._input,e);return this._len-=e,this.addBytes(t,0,e),0===this._len&&(this._state=this._isFinal?Lt.Crc:Lt.Block),this._needed>0}case Lt.DistOne:{const e=this._len<this._needed?this._len:this._needed;return this.addDistOne(e),this._len-=e,0===this._len&&(this._state=Lt.CData),this._needed>0}case Lt.Dist:for(;this._len>0&&this._needed>0;){const e=this._len<this._dist?this._len:this._dist,t=this._needed<e?this._needed:e;this.addDist(this._dist,t),this._len-=t}return 0===this._len&&(this._state=Lt.CData),this._needed>0;case Lt.CData:let i=this.applyHuffman(this._huffman);if(i<256)return this.addByte(i),this._needed>0;if(256===i)return this._state=this._isFinal?Lt.Crc:Lt.Block,!0;i=i-257&255;let a=ls.LenExtraBitsTbl[i];if(-1===a)throw new Ze("Invalid data");this._len=ls.LenBaseValTbl[i]+this.getBits(a);const r=this._huffdist,n=r?this.applyHuffman(r):this.getRevBits(5);if(a=ls.DistExtraBitsTbl[n],-1===a)throw new Ze("Invalid data");if(this._dist=ls.DistBaseValTbl[n]+this.getBits(a),this._dist>this._window.available())throw new Ze("Invalid data");return this._state=1===this._dist?Lt.DistOne:Lt.Dist,!0}return!1}addDistOne(e){const t=this._window.getLastChar();for(let s=0;s<e;s++)this.addByte(t)}addByte(e){this._window.addByte(e),this._output[this._outpos]=e,this._needed--,this._outpos++}addDist(e,t){this.addBytes(this._window.buffer,this._window.pos-e,t)}getBit(){0===this._nbits&&(this._nbits=8,this._bits=this._input.readByte());const e=!(1&~this._bits);return this._nbits--,this._bits=this._bits>>1,e}getBits(e){for(;this._nbits<e;)this._bits=this._bits|this._input.readByte()<<this._nbits,this._nbits+=8;const t=this._bits&(1<<e)-1;return this._nbits-=e,this._bits=this._bits>>e,t}getRevBits(e){return 0===e?0:this.getBit()?1<<e-1|this.getRevBits(e-1):this.getRevBits(e-1)}resetBits(){this._bits=0,this._nbits=0}addBytes(e,t,s){this._window.addBytes(e,t,s),this._output.set(e.subarray(t,t+s),this._outpos),this._needed-=s,this._outpos+=s}inflateLengths(e,t){let s=0,i=0;for(;s<t;){const a=this.applyHuffman(this._huffman);switch(a){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:case 8:case 9:case 10:case 11:case 12:case 13:case 14:case 15:i=a,e[s]=a,s++;break;case 16:const r=s+3+this.getBits(2);if(r>t)throw new Ze("Invalid data");for(;s<r;)e[s]=i,s++;break;case 17:if(s+=3+this.getBits(3),s>t)throw new Ze("Invalid data");break;case 18:if(s+=11+this.getBits(7),s>t)throw new Ze("Invalid data");break;default:throw new Ze("Invalid data")}}}applyHuffman(e){if(e instanceof Ft)return e.n;if(e instanceof Ct)return this.applyHuffman(this.getBit()?e.right:e.left);if(e instanceof Dt)return this.applyHuffman(e.table[this.getBits(e.n)]);throw new Ze("Invalid data")}}ls.LenExtraBitsTbl=[0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,-1,-1],ls.LenBaseValTbl=[3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258],ls.DistExtraBitsTbl=[0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,-1,-1],ls.DistBaseValTbl=[1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577],ls.CodeLengthsPos=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15],ls._fixedHuffman=ls.buildFixedHuffman();class cs{constructor(e,t){this.fullName=e;const s=e.lastIndexOf("/");this.fileName=-1===s||s===e.length-1?this.fullName:e.substr(s+1),this.data=t}}cs.OptionalDataDescriptorSignature=134695760,cs.CompressionMethodDeflate=8,cs.LocalFileHeaderSignature=67324752,cs.CentralFileHeaderSignature=33639248,cs.EndOfCentralDirSignature=101010256;class ds{constructor(e){this._readable=e}read(){const e=[];for(;;){const t=this.readEntry();if(!t)break;e.push(t)}return e}readEntry(){const e=this._readable;if(ot.readInt32LE(e)!==cs.LocalFileHeaderSignature)return null;ot.readUInt16LE(e);const t=ot.readUInt16LE(e),s=ot.readUInt16LE(e),i=0!==s;if(i&&s!==cs.CompressionMethodDeflate)return null;ot.readInt16LE(this._readable),ot.readInt16LE(this._readable),ot.readInt32LE(e),ot.readInt32LE(e);const a=ot.readInt32LE(e),r=ot.readInt16LE(e),n=ot.readInt16LE(e),o=ot.toString(ot.readByteArray(e,r),"utf-8");let h;if(e.skip(n),i){const e=ht.empty(),t=new ls(this._readable),s=new Uint8Array(65536);for(;;){const i=t.readBytes(s,0,s.length);if(e.write(s,0,i),i<s.length)break}h=e.toArray()}else h=ot.readByteArray(this._readable,a);if(8&t){ot.readInt32LE(this._readable)===cs.OptionalDataDescriptorSignature&&ot.readInt32LE(this._readable),ot.readInt32LE(this._readable),ot.readInt32LE(this._readable)}return new cs(o,h)}}class us{constructor(){this.trackViewGroups=[]}}class ps{constructor(){this.isVisible=!1}}!function(e){e[e.PageVertical=0]="PageVertical",e[e.PageGrid=1]="PageGrid",e[e.PageParchment=2]="PageParchment",e[e.ScreenVertical=3]="ScreenVertical",e[e.ScreenHorizontal=4]="ScreenHorizontal",e[e.PageHorizontal=5]="PageHorizontal"}(Mt||(Mt={}));class gs{constructor(e,t){this.zoomLevel=4,this.view=Mt.PageVertical,this.muiltiVoiceCursor=!1,this.scoreViews=[];const s=ht.fromBuffer(t);this.zoomLevel=ot.readInt32BE(s),this.view=s.readByte(),this.muiltiVoiceCursor=0!==s.readByte();const i=e.scoreViews.length;for(let t=0;t<i;t++){const i=new us;this.scoreViews.push(i);const a=e.scoreViews[t];for(let e=0;e<a.trackViewGroups.length;e++){const e=new ps;e.isVisible=0!==s.readByte(),i.trackViewGroups.push(e)}}}apply(e){if(this.scoreViews.length>0){let t=0;for(const s of this.scoreViews[0].trackViewGroups){if(t<e.tracks.length){e.tracks[t].isVisibleOnMultiTrack=s.isVisible}t++}}}static writeForScore(e){const t=ht.withCapacity(128);ot.writeInt32BE(t,4),t.writeByte(0);const s=e.tracks.length>0&&e.tracks[0].staves[0].bars[0].isMultiVoice;t.writeByte(s?255:0);for(const s of e.tracks)t.writeByte(s.isVisibleOnMultiTrack?255:0);for(const s of e.tracks)t.writeByte(255);return t.toArray()}}class ms extends Ye{get name(){return"Guitar Pro 7-8"}readScore(){q.debug(this.name,"Loading ZIP entries");const e=new ds(this.data);let t;try{t=e.read()}catch(e){throw new qe("No Zip archive",e)}q.debug(this.name,"Zip entries loaded");let s=null,i=null,a=null,r=null;for(const e of t)switch(e.fileName){case"score.gpif":s=ot.toString(e.data,this.settings.importer.encoding);break;case"BinaryStylesheet":i=e.data;break;case"PartConfiguration":a=e.data;break;case"LayoutConfiguration":r=e.data}if(!s)throw new qe("No score.gpif found in zip archive");q.debug(this.name,"Start Parsing score.gpif");const n=new Tt;n.parseXml(s,this.settings),q.debug(this.name,"score.gpif parsed");const o=n.score;if(i){q.debug(this.name,"Start Parsing BinaryStylesheet");new ft(i).apply(o),q.debug(this.name,"BinaryStylesheet parsed")}let h=null;if(a&&(q.debug(this.name,"Start Parsing Part Configuration"),h=new vt(a),h.apply(o),q.debug(this.name,"Part Configuration parsed")),r&&null!=h){q.debug(this.name,"Start Parsing Layout Configuration");new gs(h,r).apply(o),q.debug(this.name,"Layout Configuration parsed")}return o}}class fs extends $e{constructor(){super(Se.Format,"Unexpected end of data within reader"),Object.setPrototypeOf(this,fs.prototype)}}class ys{constructor(e){this._currentByte=0,this._position=ys.ByteSize,this._source=e}readByte(){return this.readBits(8)}readBytes(e){const t=new Uint8Array(e);for(let s=0;s<e;s++)t[s]=255&this.readByte();return t}readBits(e){let t=0,s=e-1;for(;s>=0;)t|=this.readBit()<<s,s--;return t}readBitsReversed(e){let t=0;for(let s=0;s<e;s++)t|=this.readBit()<<s;return t}readBit(){if(this._position>=8){if(this._currentByte=this._source.readByte(),-1===this._currentByte)throw new fs;this._position=0}const e=this._currentByte>>ys.ByteSize-this._position-1&1;return this._position++,e}readAll(){const e=ht.empty();try{for(;;)e.writeByte(255&this.readByte())}catch(e){if(!(e instanceof fs))throw e}return e.toArray()}}ys.ByteSize=8;class bs{constructor(){this.fileName="",this.fileSize=0,this.data=null}}class Ss{constructor(){this.files=[],this.files=[],this.fileFilter=e=>!0}load(e){const t=new ys(e);this.readBlock(t)}readHeader(e){return this.getString(e.readBytes(4),0,4)}decompress(e,t=!1){const s=ht.empty();let i;const a=this.getInteger(e.readBytes(4),0);try{for(;s.length<a;){if(1===e.readBits(1)){const t=e.readBits(4),a=e.readBitsReversed(t),r=e.readBitsReversed(t),n=s.length-a,o=Math.min(a,r);i=s.getBuffer(),s.write(i,n,o)}else{const t=e.readBitsReversed(2);for(let i=0;i<t;i++)s.writeByte(e.readByte())}}}catch(e){if(!(e instanceof fs))throw e}i=s.getBuffer();const r=t?4:0,n=s.length-r,o=new Uint8Array(n),h=n;return o.set(i.subarray(r,r+h),0),o}readBlock(e){const t=this.readHeader(e);if("BCFZ"===t)this.readUncompressedBlock(this.decompress(e,!0));else{if("BCFS"!==t)throw new qe("Unsupported format");this.readUncompressedBlock(e.readAll())}}readUncompressedBlock(e){const t=4096;let s=t;for(;s+3<e.length;){if(2===this.getInteger(e,s)){const i=new bs;i.fileName=this.getString(e,s+4,127),i.fileSize=this.getInteger(e,s+140);const a=!this.fileFilter||this.fileFilter(i.fileName);a&&this.files.push(i);const r=s+148;let n=0,o=0;const h=a?ht.withCapacity(i.fileSize):null;for(;n=this.getInteger(e,r+4*o++),0!==n;)s=n*t,a&&h.write(e,s,t);if(a){i.data=new Uint8Array(Math.min(i.fileSize,h.length));const e=h.toArray();i.data.set(e.subarray(0,0+i.data.length),0)}}s+=t}}getString(e,t,s){let i="";for(let a=0;a<s;a++){const s=255&e[t+a];if(0===s)break;i+=String.fromCharCode(s)}return i}getInteger(e,t){return e[t+3]<<24|e[t+2]<<16|e[t+1]<<8|e[t]}}Ss.HeaderBcFs="BCFS",Ss.HeaderBcFz="BCFZ";class _s extends Ye{get name(){return"Guitar Pro 6"}readScore(){q.debug(this.name,"Loading GPX filesystem");const e=new Ss;e.fileFilter=e=>e.endsWith("score.gpif")||e.endsWith("BinaryStylesheet")||e.endsWith("PartConfiguration")||e.endsWith("LayoutConfiguration"),e.load(this.data),q.debug(this.name,"GPX filesystem loaded");let t=null,s=null,i=null,a=null;for(const r of e.files)switch(r.fileName){case"score.gpif":t=ot.toString(r.data,this.settings.importer.encoding);break;case"BinaryStylesheet":s=r.data;break;case"PartConfiguration":i=r.data;break;case"LayoutConfiguration":a=r.data}if(!t)throw new qe("No score.gpif found in GPX");q.debug(this.name,"Start Parsing score.gpif");const r=new Tt;r.parseXml(t,this.settings),q.debug(this.name,"score.gpif parsed");const n=r.score;if(s){q.debug(this.name,"Start Parsing BinaryStylesheet");new ft(s).apply(n),q.debug(this.name,"BinaryStylesheet parsed")}let o=null;if(i&&(q.debug(this.name,"Start Parsing Part Configuration"),o=new vt(i),o.apply(n),q.debug(this.name,"Part Configuration parsed")),a&&null!=o){q.debug(this.name,"Start Parsing Layout Configuration");new gs(o,a).apply(n),q.debug(this.name,"Layout Configuration parsed")}return n}}!function(e){e[e.None=0]="None",e[e.Natural=1]="Natural",e[e.Sharp=2]="Sharp",e[e.Flat=3]="Flat",e[e.NaturalQuarterNoteUp=4]="NaturalQuarterNoteUp",e[e.SharpQuarterNoteUp=5]="SharpQuarterNoteUp",e[e.FlatQuarterNoteUp=6]="FlatQuarterNoteUp",e[e.DoubleSharp=7]="DoubleSharp",e[e.DoubleFlat=8]="DoubleFlat"}(It||(It={}));class ws{constructor(){this.maxLine=-1e3,this.minLine=-1e3}}class Bs{constructor(e){this._registeredAccidentals=new Map,this._appliedScoreLines=new Map,this._appliedScoreLinesByValue=new Map,this._notesByValue=new Map,this._beatLines=new Map,this.maxLineBeat=null,this.minLineBeat=null,this.maxLine=-1e3,this.minLine=-1e3,this._barRenderer=e,this._bar=e.bar}static getPercussionLine(e,t){return t<e.staff.track.percussionArticulations.length?e.staff.track.percussionArticulations[t].staffLine:Le.getArticulationByInputMidiNumber(t)?.staffLine??0}static getNoteValue(e){if(e.isPercussion)return e.percussionArticulation;let t=e.displayValue;switch(e.accidentalMode){case N.ForceDoubleFlat:t+=2;break;case N.ForceDoubleSharp:t-=2;break;case N.ForceFlat:t+=1;break;case N.ForceSharp:t-=1}return t}applyAccidental(e){const t=Bs.getNoteValue(e),s=e.hasQuarterToneOffset;return this.getAccidental(t,s,e.beat,!1,e)}applyAccidentalForValue(e,t,s,i){return this.getAccidental(t,s,e,i,null)}static computeLineWithoutAccidentals(e,t){let s=0;const i=Bs.getNoteValue(t);return s=t.isPercussion?Bs.getPercussionLine(e,i):Bs.calculateNoteSteps(e.keySignature,e.clef,i),s}static computeAccidental(e,t,s,i,a=null){const r=e+7,n=s%12,o=r<7?It.Flat:It.Sharp,h=Bs.KeySignatureLookup[r][n],l=Bs.AccidentalNotes[n];let c=It.None;if(i)switch(c=l?o:It.Natural,c){case It.Natural:c=It.NaturalQuarterNoteUp;break;case It.Sharp:c=It.SharpQuarterNoteUp;break;case It.Flat:c=It.FlatQuarterNoteUp}else{switch(t){case N.ForceSharp:c=It.Sharp;break;case N.ForceDoubleSharp:c=It.DoubleSharp;break;case N.ForceFlat:c=It.Flat;break;case N.ForceDoubleFlat:c=It.DoubleFlat;break;default:l?c=o:h&&(c=It.Natural)}c!==It.None?null!=a?a===c&&(c=It.None):h&&c===o&&(c=It.None):null!==a&&(c=a===It.Natural?It.None:It.Natural)}return c}getAccidental(e,t,s,i,a=null){let r=0,n=It.None;if(null!=a?a.isPercussion:this._bar.staff.isPercussion)r=Bs.getPercussionLine(this._bar,e);else{const s=a?a.accidentalMode:N.Default;r=Bs.calculateNoteSteps(this._bar.keySignature,this._bar.clef,e);const i=this._registeredAccidentals.has(r)?this._registeredAccidentals.get(r):null;n=Bs.computeAccidental(this._bar.keySignature,s,e,t,i);let o=!1;switch(n){case It.NaturalQuarterNoteUp:case It.SharpQuarterNoteUp:case It.FlatQuarterNoteUp:break;default:if(a&&a.isTieDestination&&0===a.beat.index){const e=this._barRenderer.scoreRenderer.layout?.getRendererForBar(this._barRenderer.staff.staffId,a.tieOrigin.beat.voice.bar);if(e&&e.staff===this._barRenderer.staff){e.accidentalHelper.getNoteLine(a.tieOrigin)===r&&(o=!0)}}o?n=It.None:n!==It.None&&this._registeredAccidentals.set(r,n)}}return a?(this._appliedScoreLines.set(a.id,r),this._notesByValue.set(e,a)):this._appliedScoreLinesByValue.set(e,r),(-1e3===this.minLine||this.minLine<r)&&(this.minLine=r,this.minLineBeat=s),(-1e3===this.maxLine||this.maxLine>r)&&(this.maxLine=r,this.maxLineBeat=s),i||this.registerLine(s,r),n}registerLine(e,t){let s;this._beatLines.has(e.id)?s=this._beatLines.get(e.id):(s=new ws,this._beatLines.set(e.id,s)),(-1e3===s.minLine||t<s.minLine)&&(s.minLine=t),(-1e3===s.minLine||t>s.maxLine)&&(s.maxLine=t)}getMaxLine(e){return this._beatLines.has(e.id)?this._beatLines.get(e.id).maxLine:0}getMinLine(e){return this._beatLines.has(e.id)?this._beatLines.get(e.id).minLine:0}static calculateNoteSteps(e,t,s){const i=e,a=t,r=s%12,n=(s/12|0)-1;let o=Bs.OctaveSteps[a];o-=n*Bs.StepsPerOctave;return o-=(ie.keySignatureIsSharp(i)||ie.keySignatureIsNatural(i)?Bs.SharpNoteSteps:Bs.FlatNoteSteps)[r],o}getNoteLine(e){return this._appliedScoreLines.get(e.id)}getNoteLineForValue(e,t=!1){return this._appliedScoreLinesByValue.has(e)?this._appliedScoreLinesByValue.get(e):t&&this._notesByValue.has(e)?this.getNoteLine(this._notesByValue.get(e)):0}}Bs.KeySignatureLookup=[[!0,!0,!0,!0,!0,!0,!0,!0,!0,!0,!0,!0],[!0,!0,!0,!0,!0,!1,!0,!0,!0,!0,!0,!0],[!1,!0,!0,!0,!0,!1,!0,!0,!0,!0,!0,!0],[!1,!0,!0,!0,!0,!1,!1,!1,!0,!0,!0,!0],[!1,!1,!1,!0,!0,!1,!1,!1,!0,!0,!0,!0],[!1,!1,!1,!0,!0,!1,!1,!1,!1,!1,!0,!0],[!1,!1,!1,!1,!1,!1,!1,!1,!1,!1,!0,!0],[!1,!1,!1,!1,!1,!1,!1,!1,!1,!1,!1,!1],[!1,!1,!1,!1,!1,!0,!0,!1,!1,!1,!1,!1],[!0,!0,!1,!1,!1,!0,!0,!1,!1,!1,!1,!1],[!0,!0,!1,!1,!1,!0,!0,!0,!0,!1,!1,!1],[!0,!0,!0,!0,!1,!0,!0,!0,!0,!1,!1,!1],[!0,!0,!0,!0,!1,!0,!0,!0,!0,!0,!0,!1],[!0,!0,!0,!0,!0,!0,!0,!0,!0,!0,!0,!1],[!0,!0,!0,!0,!0,!0,!0,!0,!0,!0,!0,!0]],Bs.AccidentalNotes=[!1,!0,!1,!0,!1,!1,!0,!1,!0,!1,!0,!1],Bs.StepsPerOctave=7,Bs.OctaveSteps=[38,32,30,26,38],Bs.SharpNoteSteps=[0,0,1,1,2,3,3,4,4,5,5,6],Bs.FlatNoteSteps=[0,1,1,2,2,3,4,4,5,5,6,6];class ks{constructor(){this.currentDynamics=g.F,this.slideOrigins=new Map,this.transpose=0,this.isExplicitlyBeamed=!1,this.tieStarts=new Set,this.tieStartIds=new Map,this.slideOrigins=new Map,this.slurStarts=new Map}}class Ts extends Ee{constructor(){super(...arguments),this.outputMidiChannel=-1,this.outputMidiProgram=-1,this.outputVolume=-1,this.outputBalance=-1}}class Ns{constructor(e){this.instruments=new Map,this._instrumentIdToArticulationIndex=new Map,this._lyricsLine=0,this._lyricsLines=new Map,this.track=e}getLyricLine(e){if(this._lyricsLines.has(e))return this._lyricsLines.get(e);const t=this._lyricsLine;return this._lyricsLines.set(e,t),this._lyricsLine++,t}getOrCreateArticulation(e,t){const s=12*t.octave+t.tone,i=`${e}_${s}`;if(this._instrumentIdToArticulationIndex.has(i))return this._instrumentIdToArticulationIndex.get(i);let a;a=this.instruments.has(e)?this.instruments.get(e):Ns.defaultNoteArticulation;const r=this.track.percussionArticulations.length,n=t.beat.voice.bar;let o;o=0===s?4:Bs.calculateNoteSteps(n.keySignature,n.clef,s);const h=o-(9-(2*t.beat.voice.bar.staff.standardNotationLineCount-1)),l=new Ee(a.elementType,h,a.outputMidiNumber,a.noteHeadDefault,a.noteHeadHalf,a.noteHeadWhole,a.techniqueSymbol,a.techniqueSymbolPlacement);return this._instrumentIdToArticulationIndex.set(i,r),this.track.percussionArticulations.push(l),r}}Ns.defaultNoteArticulation=new Ee("Default",0,0,re.NoteheadBlack,re.NoteheadHalf,re.NoteheadWhole);class xs extends Ye{constructor(){super(...arguments),this._idToTrackInfo=new Map,this._indexToTrackInfo=new Map,this._staffToContext=new Map,this._divisionsPerQuarterNote=1,this._currentDynamics=g.F,this._musicalPosition=0,this._lastBeat=null,this._nextMasterBarRepeatEnding=0,this._nextBeatAutomations=null,this._nextBeatChord=null,this._nextBeatCrescendo=null,this._nextBeatLetRing=!1,this._nextBeatPalmMute=!1,this._nextBeatOttavia=null,this._nextBeatText=null,this._simileMarkAllStaves=null,this._simileMarkPerStaff=null,this._isBeatSlash=!1,this._keyAllStaves=null,this._currentTrillStep=-1}get name(){return"MusicXML"}readScore(){const e=this.extractMusicXml(),t=new wt;try{t.parse(e)}catch(e){throw new qe("Unsupported format",e)}return this._score=new Je,this._score.tempo=120,this._score.stylesheet.hideDynamics=!0,this.parseDom(t),ie.consolidate(this._score),this._score.finish(this.settings),this._score.rebuildRepeatGroups(),this._score}extractMusicXml(){const e=new ds(this.data);let t;try{t=e.read()}catch(e){t=[]}if(0===t.length)return this.data.reset(),ot.toString(this.data.readAll(),this.settings.importer.encoding);const s=t.find((e=>"META-INF/container.xml"===e.fullName));if(!s)throw new qe("No compressed MusicXML");const i=new wt;try{i.parse(ot.toString(s.data,this.settings.importer.encoding))}catch(e){throw new qe("Malformed container.xml, could not parse as XML",e)}const a=i.firstElement;if(!a||"container"!==a.localName)throw new qe("Malformed container.xml, root element not 'container'");const r=a.findChildElement("rootfiles");if(!r)throw new qe("Malformed container.xml, 'container/rootfiles' not found");let n="";for(const e of r.childElements())if("rootfile"===e.localName){n=e.getAttribute("full-path");break}if(!n)throw new qe("Unsupported compressed MusicXML, missing rootfile");const o=t.find((e=>e.fullName===n));if(!o)throw new qe(`Malformed container.xml, '${n}' not contained in zip`);return ot.toString(o.data,this.settings.importer.encoding)}parseDom(e){const t=e.firstElement;if(!t)throw new qe("Unsupported format");switch(t.localName){case"score-partwise":this.parsePartwise(t);break;case"score-timewise":this.parseTimewise(t);break;default:throw new qe("Unsupported format")}}parsePartwise(e){for(const t of e.childElements())switch(t.localName){case"credit":this.parseCredit(t);break;case"identification":this.parseIdentification(t);break;case"movement-title":this.parseMovementTitle(t);break;case"part":this.parsePartwisePart(t);break;case"part-list":this.parsePartList(t);break;case"work":this.parseWork(t)}}parseTimewise(e){let t=0;for(const s of e.childElements())switch(s.localName){case"credit":this.parseCredit(s);break;case"identification":this.parseIdentification(s);break;case"movement-title":this.parseMovementTitle(s);break;case"part-list":this.parsePartList(s);break;case"work":this.parseWork(s);break;case"measure":this.parseTimewiseMeasure(s,t),t++}}parseCredit(e){if("1"!==e.getAttribute("page","1"))return;const t=[];let s=null,i="";for(const a of e.childElements())switch(a.localName){case"credit-type":t.push(a.innerText);break;case"credit-words":null===s&&(s=a),i+=a.innerText}if(t.length>0)for(const e of t)switch(e){case"title":this._score.title=xs.sanitizeDisplay(i);break;case"subtitle":this._score.subTitle=xs.sanitizeDisplay(i);break;case"composer":case"arranger":this._score.artist=xs.sanitizeDisplay(i);break;case"lyricist":this._score.words=xs.sanitizeDisplay(i);break;case"rights":this._score.copyright=xs.sanitizeDisplay(i)}else if(s){const e=s.getAttribute("font-size","0"),t=s.getAttribute("font-size","top"),a=s.getAttribute("halign","left");if("top"===t){if(i.includes("copyright")||i.includes("Copyright")||i.includes("©")||i.includes("(c)")||i.includes("(C)"))return void(this._score.copyright=xs.sanitizeDisplay(i));if("center"===a||"center"===e){if(0===this._score.title.length)return void(this._score.title=xs.sanitizeDisplay(i));if(0===this._score.subTitle.length)return void(this._score.subTitle=xs.sanitizeDisplay(i));if(0===this._score.album.length)return void(this._score.album=xs.sanitizeDisplay(i))}else if(("right"===a||"right"===e)&&0===this._score.music.length)return void(this._score.music=xs.sanitizeDisplay(i));if(0===this._score.artist.length)return void(this._score.artist=xs.sanitizeDisplay(i));if(0===this._score.words.length)return void(this._score.words=xs.sanitizeDisplay(i))}}}static sanitizeDisplay(e){return e.replaceAll("\r","").replaceAll("\n"," ").replaceAll("\t","  ").replaceAll(" "," ")}parseIdentification(e){for(const t of e.childElements())switch(t.localName){case"creator":if(t.attributes.has("type"))switch(t.attributes.get("type")){case"composer":this._score.artist=xs.sanitizeDisplay(t.innerText);break;case"lyricist":this._score.words=xs.sanitizeDisplay(t.innerText);break;case"arranger":this._score.music=xs.sanitizeDisplay(t.innerText)}else this._score.artist=xs.sanitizeDisplay(t.innerText);break;case"rights":this._score.copyright.length>0&&(this._score.copyright+=", "),this._score.copyright+=t.innerText,t.attributes.has("type")&&(this._score.copyright+=` (${t.attributes.get("type")})`);break;case"encoding":this.parseEncoding(t)}}parseEncoding(e){for(const t of e.childElements())switch(t.localName){case"encoder":this._score.tab.length>0&&(this._score.tab+=", "),this._score.tab+=t.innerText,t.attributes.has("type")&&(this._score.tab+=` (${t.attributes.get("type")})`);break;case"encoding-description":this._score.notices+=xs.sanitizeDisplay(t.innerText)}}parseMovementTitle(e){0===this._score.title.length?this._score.title=xs.sanitizeDisplay(e.innerText):this._score.subTitle=xs.sanitizeDisplay(e.innerText)}parsePartList(e){for(const t of e.childElements())if("score-part"===t.localName)this.parseScorePart(t)}parseScorePart(e){const t=new rt;t.ensureStaveCount(1),this._score.addTrack(t);const s=e.attributes.get("id"),i=new Ns(t);this._idToTrackInfo.set(s,i),this._indexToTrackInfo.set(t.index,i);for(const s of e.childElements())switch(s.localName){case"part-name":t.name=xs.sanitizeDisplay(s.innerText);break;case"part-name-display":t.name=this.parsePartDisplayAsText(s);break;case"part-abbreviation":t.shortName=xs.sanitizeDisplay(s.innerText);break;case"part-abbreviation-display":t.shortName=this.parsePartDisplayAsText(s);break;case"score-instrument":this.parseScoreInstrument(s,i);break;case"midi-device":s.attributes.has("port")&&(t.playbackInfo.port=Number.parseInt(s.attributes.get("port"),10));break;case"midi-instrument":this.parseScorePartMidiInstrument(s,i)}i.firstArticulation&&(i.firstArticulation.outputMidiProgram>=0&&(t.playbackInfo.program=i.firstArticulation.outputMidiProgram),i.firstArticulation.outputBalance>=0&&(t.playbackInfo.balance=i.firstArticulation.outputBalance),i.firstArticulation.outputVolume>=0&&(t.playbackInfo.volume=i.firstArticulation.outputVolume),i.firstArticulation.outputMidiChannel>=0&&(t.playbackInfo.primaryChannel=i.firstArticulation.outputMidiChannel,t.playbackInfo.secondaryChannel=i.firstArticulation.outputMidiChannel))}parseScoreInstrument(e,t){const s=new Ts;t.firstArticulation||(t.firstArticulation=s),t.instruments.set(e.getAttribute("id",""),s)}parseScorePartMidiInstrument(e,t){const s=e.getAttribute("id","");if(!t.instruments.has(s))return;const i=t.instruments.get(s);for(const t of e.childElements())switch(t.localName){case"midi-channel":i.outputMidiChannel=Number.parseInt(t.innerText)-1;break;case"midi-program":i.outputMidiProgram=Number.parseInt(t.innerText)-1;break;case"midi-unpitched":i.outputMidiNumber=Number.parseInt(t.innerText)-1;break;case"volume":i.outputVolume=xs.interpolatePercent(Number.parseFloat(t.innerText));break;case"pan":i.outputBalance=xs.interpolatePan(Number.parseFloat(t.innerText))}}static interpolatePercent(e){return 0|xs.interpolate(0,100,0,16,e)}static interpolatePan(e){return 0|xs.interpolate(-90,90,0,16,e)}static interpolate(e,t,s,i,a){return s+(i-s)*((a-e)/(t-e))}parsePartDisplayAsText(e){let t="";for(const s of e.childElements())switch(s.localName){case"display-text":t+=s.innerText;break;case"accidental-text":switch(s.innerText){case"sharp":t+="♯";break;case"natural":t+="♮";break;case"flat":t+="♭";break;case"double-sharp":t+="𝄪";break;case"sharp-sharp":t+="♯♯";break;case"flat-flat":t+="𝄫";break;case"natural-sharp":t+="♮♯";break;case"natural-flat":t+="♮♭";break;case"sharp-down":t+="𝄱";break;case"sharp-up":t+="𝄰";break;case"natural-down":t+="𝄯";break;case"natural-up":t+="𝄮";break;case"flat-down":t+="𝄭";break;case"flat-up":t+="𝄬";break;case"arrow-down":t+="↓";break;case"arrow-up":t+="↑";break;case"triple-sharp":t+="♯𝄪";break;case"triple-flat":t+="𝄬𝄬𝄬";break;case"sharp-1":t+="♯¹";break;case"sharp-2":t+="♯²";break;case"sharp-3":t+="♯³";break;case"sharp-4":t+="♯⁴";break;case"sharp-5":t+="♯⁵";break;case"flat-1":t+="♭¹";break;case"flat-2":t+="♭²";break;case"flat-3":t+="♭³";break;case"flat-4":t+="♭⁴";break;case"flat-5":t+="♭⁵"}}return xs.sanitizeDisplay(t)}parseWork(e){for(const t of e.childElements())if("work-title"===t.localName)this._score.title=xs.sanitizeDisplay(t.innerText)}parsePartwisePart(e){const t=e.attributes.get("id");if(!t||!this._idToTrackInfo.has(t))return;const s=this._idToTrackInfo.get(t).track;let i=0;for(const t of e.childElements())if("measure"===t.localName)this.parsePartwiseMeasure(t,s,i),i++}parsePartwiseMeasure(e,t,s){const i=this.getOrCreateMasterBar(e,s);this.parsePartMeasure(e,i,t)}parseTimewiseMeasure(e,t){const s=this.getOrCreateMasterBar(e,t);for(const t of e.childElements())if("part"===t.localName)this.parseTimewisePart(t,s)}getOrCreateMasterBar(e,t){const s="yes"===e.attributes.get("implicit");for(;this._score.masterBars.length<=t;){const e=new j;s&&(e.isAnacrusis=!0),this._score.addMasterBar(e),e.index>0&&(e.timeSignatureDenominator=e.previousMasterBar.timeSignatureDenominator,e.timeSignatureNumerator=e.previousMasterBar.timeSignatureNumerator,e.tripletFeel=e.previousMasterBar.tripletFeel)}return this._score.masterBars[t]}parseTimewisePart(e,t){const s=e.attributes.get("id");if(!s||!this._idToTrackInfo.has(s))return;const i=this._idToTrackInfo.get(s).track;this.parsePartMeasure(e,t,i)}parsePartMeasure(e,t,s){this._musicalPosition=0,this._lastBeat=null,t.alternateEndings=this._nextMasterBarRepeatEnding;const i=[];for(const a of e.childElements())switch(a.localName){case"note":this.parseNote(a,t,s);break;case"backup":this.parseBackup(a);break;case"forward":this.parseForward(a);break;case"direction":this.parseDirection(a,t,s);break;case"attributes":this.parseAttributes(a,t,s);break;case"harmony":this.parseHarmony(a,s);break;case"print":this.parsePrint(a,t,s);break;case"sound":this.parseSound(a,t,s);break;case"barline":i.push(a)}for(const e of i)this.parseBarLine(e,t,s);this.applySimileMarks(t,s);const a=this.getOrCreateStaff(s,0);this.getOrCreateBar(a,t),this._keyAllStaves=null}parsePrint(e,t,s){("yes"===e.getAttribute("new-system","no")||"yes"===e.getAttribute("new-page","no"))&&s.addLineBreaks(t.index)}applySimileMarks(e,t){if(null!==this._simileMarkAllStaves){for(const s of t.staves){const t=this.getOrCreateBar(s,e);t.simileMark=this._simileMarkAllStaves,t.simileMark!==h.None&&this.clearBar(t)}this._simileMarkAllStaves===h.FirstOfDouble?this._simileMarkAllStaves=h.SecondOfDouble:this._simileMarkAllStaves=null}if(null!==this._simileMarkPerStaff){const s=Array.from(this._simileMarkPerStaff.keys());for(const i of s){const s=this.getOrCreateStaff(t,i),a=this.getOrCreateBar(s,e);a.simileMark=this._simileMarkPerStaff.get(i),a.simileMark!==h.None&&this.clearBar(a),a.simileMark===h.FirstOfDouble?this._simileMarkPerStaff.set(i,h.SecondOfDouble):this._simileMarkPerStaff.delete(i)}0===this._simileMarkPerStaff.size&&(this._simileMarkPerStaff=null)}}clearBar(e){for(const t of e.voices){const e=new ze;e.isEmpty=!0,t.addBeat(e)}}parseBarLine(e,t,s){for(const i of e.childElements())switch(i.localName){case"bar-style":this.parseBarStyle(i,t,s,e.getAttribute("location","right"));break;case"ending":this.parseEnding(i,t);break;case"repeat":this.parseRepeat(i,t)}}parseRepeat(e,t){const s=e.getAttribute("direction");let i=Number.parseInt(e.getAttribute("times"));(i<0||Number.isNaN(i))&&(i=2),"backward"===s?t.repeatCount=i:"forward"===s&&(t.isRepeatStart=!0)}parseEnding(e,t){const s=e.getAttribute("number").split(",").map((e=>Number.parseInt(e)));let i=0;for(const e of s)i|=1<<e-1&255;switch(t.alternateEndings=i,e.getAttribute("type","")){case"start":this._nextMasterBarRepeatEnding=this._nextMasterBarRepeatEnding|i;break;case"stop":case"discontinue":this._nextMasterBarRepeatEnding=this._nextMasterBarRepeatEnding&~i}}parseBarStyle(e,t,s,i){let a=p.Automatic;switch(e.innerText){case"dashed":a=p.Dashed;break;case"dotted":a=p.Dotted;break;case"heavy":a=p.Heavy;break;case"heavy-heavy":a=p.HeavyHeavy;break;case"heavy-light":a=p.HeavyLight;break;case"light-heavy":a=p.LightHeavy;break;case"light-light":a=p.LightLight;break;case"none":a=p.None;break;case"regular":a=p.Regular;break;case"short":a=p.Short;break;case"tick":a=p.Tick}for(const e of s.staves){const s=this.getOrCreateBar(e,t);switch(i){case"left":s.barLineLeft=a;break;case"right":s.barLineRight=a}}}parseSound(e,t,s){for(const s of e.childElements())switch(s.localName){case"midi-instrument":this.parseSoundMidiInstrument(s,t);break;case"swing":this.parseSwing(s,t)}if(e.attributes.has("coda")&&t.addDirection(Be.TargetCoda),e.attributes.has("tocoda")&&t.addDirection(Be.JumpDaCoda),e.attributes.has("dacapo")&&t.addDirection(Be.JumpDaCapo),e.attributes.has("dalsegno")&&t.addDirection(Be.JumpDalSegno),e.attributes.has("fine")&&t.addDirection(Be.TargetFine),e.attributes.has("segno")&&t.addDirection(Be.TargetSegno),e.attributes.has("pan")){this._nextBeatAutomations||(this._nextBeatAutomations=[]);const t=new U;t.type=m.Balance,t.value=xs.interpolatePan(Number.parseFloat(e.attributes.get("pan"))),this._nextBeatAutomations.push(t)}if(e.attributes.has("tempo")){this._nextBeatAutomations||(this._nextBeatAutomations=[]);const t=new U;t.type=m.Tempo,t.value=xs.interpolatePercent(Number.parseFloat(e.attributes.get("tempo"))),this._nextBeatAutomations.push(t)}}parseSwing(e,t){let s=0,i=0,a=null;for(const r of e.childElements())switch(r.localName){case"straight":return void(t.tripletFeel=M.NoTripletFeel);case"first":s=Number.parseInt(r.innerText);break;case"second":i=Number.parseInt(r.innerText);break;case"swing-type":a=this.parseBeatDuration(r)}a||(a=_.Eighth),a===_.Eighth?2===s&&1===i?t.tripletFeel=M.Triplet8th:3===s&&1===i?t.tripletFeel=M.Dotted8th:1===s&&3===i&&(t.tripletFeel=M.Scottish8th):a===_.Sixteenth&&(2===s&&1===i?t.tripletFeel=M.Triplet16th:3===s&&1===i?t.tripletFeel=M.Dotted16th:1===s&&3===i&&(t.tripletFeel=M.Scottish16th))}parseSoundMidiInstrument(e,t){let s;for(const t of e.childElements())switch(t.localName){case"midi-program":this._nextBeatAutomations||(this._nextBeatAutomations=[]),s=new U,s.type=m.Instrument,s.value=Number.parseInt(t.innerText)-1,this._nextBeatAutomations.push(s);break;case"volume":this._nextBeatAutomations||(this._nextBeatAutomations=[]),s=new U,s.type=m.Volume,s.value=xs.interpolatePercent(Number.parseFloat(t.innerText)),this._nextBeatAutomations.push(s);break;case"pan":this._nextBeatAutomations||(this._nextBeatAutomations=[]),s=new U,s.type=m.Balance,s.value=xs.interpolatePan(Number.parseFloat(t.innerText)),this._nextBeatAutomations.push(s)}}parseHarmony(e,t){const s=new je;let i=!1,a="";for(const t of e.childElements())switch(t.localName){case"root":s.name=this.parseHarmonyRoot(t);break;case"kind":s.name=s.name+this.parseHarmonyKind(t),"yes"===t.getAttribute("parentheses-degrees","no")&&(i=!0);break;case"frame":this.parseHarmonyFrame(t,s);break;case"degree":a+=this.parseDegree(t)}a&&(s.name+=i?`(${a})`:a),null===this._nextBeatChord&&(this._nextBeatChord=s)}parseDegree(e){let t="",s="",i="";for(const a of e.childElements())switch(a.localName){case"degree-value":t=a.innerText;break;case"degree-alter":switch(a.innerText){case"-1":s="♭";break;case"1":s="♯"}break;case"degree-type":i+=a.getAttribute("text","")}return`${i}${s}${t}`}parseHarmonyRoot(e){let t="",s="";for(const i of e.childElements())switch(i.localName){case"root-step":t=i.innerText;break;case"root-alter":switch(Number.parseFloat(i.innerText)){case-2:s="bb";break;case-1:s="b";break;case 0:s="";break;case 1:s="#";break;case 2:s="##"}}return t+s}parseHarmonyKind(e){const t=e.getAttribute("text");let s="";if(t)s=t;else{const t=e.innerText;switch(t){case"major":s="";break;case"minor":s="m";break;case"augmented":s="+";break;case"diminished":s="○";break;case"dominant":s="7";break;case"major-seventh":s="7M";break;case"minor-seventh":s="m7";break;case"diminished-seventh":s="○7";break;case"augmented-seventh":s="+7";break;case"half-diminished":s="⍉";break;case"major-minor":s="mMaj";break;case"major-sixth":s="maj6";break;case"minor-sixth":s="m6";break;case"dominant-ninth":s="9";break;case"major-ninth":s="maj9";break;case"minor-ninth":s="m9";break;case"dominant-11th":s="11";break;case"major-11th":s="maj11";break;case"minor-11th":s="m11";break;case"dominant-13th":s="13";break;case"major-13th":s="maj13";break;case"minor-13th":s="m13";break;case"suspended-second":s="sus2";break;case"suspended-fourth":s="sus4";break;case"Neapolitan":s="♭II";break;case"Italian":s="It⁺⁶";break;case"French":case"German":s="Fr⁺⁶";break;default:s=t}}return s}parseHarmonyFrame(e,t){for(const s of e.childElements())switch(s.localName){case"frame-strings":const e=Number.parseInt(s.innerText);t.strings=new Array(e);for(let s=0;s<e;s++)t.strings[s]=-1;break;case"first-fret":t.firstFret=Number.parseInt(s.innerText);break;case"frame-note":let i=null,a=null;for(const e of s.childElements())switch(e.localName){case"string":i=Number.parseInt(e.innerText);break;case"fret":a=Number.parseInt(e.innerText),i&&a>=0&&(t.strings[i-1]=a);break;case"barre":i&&a&&"start"===e.getAttribute("type")&&t.barreFrets.push(a)}}}parseAttributes(e,t,s){let i,a,r;if(null==this._lastBeat)for(const n of e.childElements())switch(n.localName){case"divisions":this._divisionsPerQuarterNote=Number.parseFloat(n.innerText);break;case"key":this.parseKey(n,t,s);break;case"time":this.parseTime(n,t);break;case"staves":s.ensureStaveCount(Number.parseInt(n.innerText));break;case"clef":i=Number.parseInt(n.getAttribute("number","1"))-1,a=this.getOrCreateStaff(s,i),r=this.getOrCreateBar(a,t),this.parseClef(n,r);break;case"staff-details":i=Number.parseInt(n.getAttribute("number","1"))-1,a=this.getOrCreateStaff(s,i),this.parseStaffDetails(n,a);break;case"transpose":this.parseTranspose(n,s);break;case"measure-style":this.parseMeasureStyle(n,s,!1)}else for(const t of e.childElements())switch(t.localName){case"divisions":this._divisionsPerQuarterNote=Number.parseFloat(t.innerText);break;case"measure-style":this.parseMeasureStyle(t,s,!0)}}parseMeasureStyle(e,t,s){for(const t of e.childElements())switch(t.localName){case"measure-repeat":if(!s){let s=null;switch(t.getAttribute("type")){case"start":switch(Number.parseInt(t.getAttribute("slashes","1"))){case 1:s=h.Simple;break;case 2:s=h.FirstOfDouble}break;case"stop":s=null}if(e.attributes.has("number")){this._simileMarkPerStaff=this._simileMarkPerStaff??new Map;const t=Number.parseInt(e.attributes.get("number"))-1;null==s?this._simileMarkPerStaff.delete(t):this._simileMarkPerStaff.set(t,s)}else this._simileMarkAllStaves=s}break;case"slash":switch(t.getAttribute("type")){case"start":this._isBeatSlash=!0;break;case"stop":this._isBeatSlash=!1}}}parseTranspose(e,t){let s=0;for(const t of e.childElements())switch(t.localName){case"chromatic":s+=Number.parseFloat(t.innerText);break;case"octave-change":s+=12*Number.parseFloat(t.innerText)}if(e.attributes.has("number")){const i=this.getOrCreateStaff(t,Number.parseInt(e.attributes.get("number"))-1);this.getStaffContext(i).transpose=s,i.displayTranspositionPitch=s}else for(const e of t.staves)this.getStaffContext(e).transpose=s,e.displayTranspositionPitch=s}parseStaffDetails(e,t){for(const s of e.childElements())switch(s.localName){case"staff-lines":t.standardNotationLineCount=Number.parseInt(s.innerText);break;case"staff-tuning":this.parseStaffTuning(s,t);break;case"capo":t.capo=Number.parseInt(s.innerText)}}parseStaffTuning(e,t){0===t.stringTuning.tunings.length&&(t.showTablature=!0,t.showStandardNotation=!1,t.stringTuning.tunings=new Array(t.standardNotationLineCount).fill(0));const s=Number.parseInt(e.getAttribute("line"));let i="C",a="",r=0;for(const t of e.childElements())switch(t.localName){case"tuning-step":i=t.innerText;break;case"tuning-alter":r=Number.parseFloat(t.innerText);break;case"tuning-octave":a=t.innerText}const n=ie.getTuningForText(i+a)+r;t.tuning[t.tuning.length-s]=n}parseClef(e,t){let s="s",i=0;for(const a of e.childElements())switch(a.localName){case"sign":s=a.innerText.toLowerCase();break;case"line":i=Number.parseInt(a.innerText);break;case"clef-octave-change":switch(Number.parseInt(a.innerText)){case-2:t.clefOttava=o._15mb;break;case-1:t.clefOttava=o._8vb;break;case 1:t.clefOttava=o._8va;break;case 2:t.clefOttava=o._15mb}}switch(s){case"g":default:t.clef=n.G2;break;case"f":t.clef=n.F4;break;case"c":t.clef=3===i?n.C3:n.C4;break;case"percussion":t.clef=n.Neutral,t.staff.isPercussion=!0;break;case"tab":t.clef=n.G2,t.staff.showTablature=!0}}parseTime(e,t){let s=!1,i=!1;for(const a of e.childElements()){const e=a.innerText;switch(a.localName){case"beats":s||(-1===e.indexOf("+")?t.timeSignatureNumerator=Number.parseInt(e):t.timeSignatureNumerator=e.split("+").map((e=>Number.parseInt(e))).reduce(((e,t)=>t+e),0),s=!0);break;case"beat-type":i||(-1===e.indexOf("+")?t.timeSignatureDenominator=Number.parseInt(e):t.timeSignatureDenominator=e.split("+").map((e=>Number.parseInt(e))).reduce(((e,t)=>t+e),0),i=!0)}}switch(e.getAttribute("symbol","")){case"common":case"cut":t.timeSignatureCommon=!0}}parseKey(e,t,s){let i,a,r=-l.C,n="";for(const t of e.childElements())switch(t.localName){case"fifths":r=Number.parseInt(t.innerText);break;case"mode":n=t.innerText}if(i=-7<=r&&r<=7?r:l.C,a="minor"===n?c.Minor:c.Major,e.attributes.has("number")){const r=this.getOrCreateStaff(s,Number.parseInt(e.attributes.get("number"))-1),n=this.getOrCreateBar(r,t);n.keySignature=i,n.keySignatureType=a}else{this._keyAllStaves=[i,a];for(const e of s.staves)e.bars.length>t.index&&(e.bars[t.index].keySignature=i,e.bars[t.index].keySignatureType=a)}}parseDirection(e,t,s){const i=[];let a=null,r=-1,n=-1;for(const t of e.childElements())switch(t.localName){case"direction-type":i.push(t.firstElement);break;case"offset":a=Number.parseFloat(t.innerText);break;case"voice":break;case"staff":r=Number.parseInt(t.innerText)-1;break;case"sound":t.attributes.has("tempo")&&(n=Number.parseFloat(t.attributes.get("tempo")))}let o=null;o=r>=0?this.getOrCreateStaff(s,r):null!==this._lastBeat?this._lastBeat.voice.bar.staff:this.getOrCreateStaff(s,0);const h=o?this.getOrCreateBar(o,t):null,l=()=>{let e=this._musicalPosition;null!==a&&(e+=a);return e/t.calculateDuration(!1)};if(n>0){const e=new U;e.type=m.Tempo,e.value=n,e.ratioPosition=l(),this.hasSameTempo(t,e)||(t.tempoAutomations.push(e),0===t.index&&(t.score.tempo=e.value))}let c="";for(const e of i)switch(e.localName){case"rehearsal":t.section=new Qe,t.section.marker=e.innerText;break;case"segno":t.addDirection(Be.TargetSegno);break;case"coda":t.addDirection(Be.TargetCoda);break;case"words":c=e.innerText;break;case"wedge":switch(e.getAttribute("type")){case"crescendo":this._nextBeatCrescendo=S.Crescendo;break;case"diminuendo":this._nextBeatCrescendo=S.Decrescendo;break;case"stop":this._nextBeatCrescendo=null}break;case"dynamics":const s=this.parseDynamics(e);null!==s&&(this._currentDynamics=s,this._score.stylesheet.hideDynamics=!1);break;case"dashes":const i=e.getAttribute("type","start");switch(c){case"LetRing":this._nextBeatLetRing="start"===i||"continue"===i;break;case"P.M.":this._nextBeatPalmMute="start"===i||"continue"===i}c="";break;case"pedal":const a=this.parsePedal(e);if(a&&h){a.ratioPosition=l();const e=h.sustainPedals.length>0&&h.sustainPedals[h.sustainPedals.length-1].pedalType!==d.Up;(a.pedalType!==d.Up||e)&&h.sustainPedals.push(a)}break;case"metronome":this.parseMetronome(e,t,l());break;case"octave-shift":this._nextBeatOttavia=this.parseOctaveShift(e)}c&&(this._nextBeatText=c)}parseOctaveShift(e){const t=e.getAttribute("type");switch(Number.parseInt(e.getAttribute("size","8"))){case 15:switch(t){case"up":return o._15mb;case"down":return o._15ma;case"stop":return o.Regular;case"continue":return this._nextBeatOttavia}break;case 8:switch(t){case"up":return o._8vb;case"down":return o._8va;case"stop":return o.Regular;case"continue":return this._nextBeatOttavia}}return null}parseMetronome(e,t,s){let i=null,a=-1;for(const t of e.childElements())switch(t.localName){case"beat-unit":i=this.parseBeatDuration(t);break;case"per-minute":a=Number.parseFloat(t.innerText)}if(null!==i&&a>0){const e=new U;e.type=m.Tempo,e.value=a*(i/4)|0,e.ratioPosition=s,this.hasSameTempo(t,e)||(t.tempoAutomations.push(e),0===t.index&&(t.score.tempo=e.value))}}hasSameTempo(e,t){for(const s of e.tempoAutomations)if(t.ratioPosition===s.ratioPosition&&t.value===s.value)return!0;return!1}parsePedal(e){const t=new W;switch(e.getAttribute("type")){case"start":t.pedalType=d.Down;break;case"stop":t.pedalType=d.Up;break;case"continue":t.pedalType=d.Hold;break;default:return null}return t}parseDynamics(e){for(const t of e.childElements()){const e=t.localName.toUpperCase();switch(e){case"PPP":case"PP":case"P":case"MP":case"MF":case"F":case"FF":case"FFF":case"PPPP":case"PPPPP":case"PPPPPP":case"FFFF":case"FFFFF":case"FFFFFF":case"SF":case"SFP":case"SFPP":case"FP":case"RF":case"RFZ":case"SFZ":case"SFFZ":case"FZ":case"N":case"PF":case"SFZP":return g[e]}}return null}parseForward(e){for(const t of e.childElements())if("duration"===t.localName)this._musicalPosition+=this.musicXmlDivisionsToAlphaTabTicks(Number.parseFloat(t.innerText))}parseBackup(e){for(const t of e.childElements())if("duration"===t.localName){if(this._lastBeat){let e=this._musicalPosition;e-=this.musicXmlDivisionsToAlphaTabTicks(Number.parseFloat(t.innerText)),e<0&&(e=0),this._musicalPosition=e}}}getOrCreateStaff(e,t){for(;e.staves.length<=t;){const t=new it;e.addStaff(t),this._score.masterBars.length>0&&this.getOrCreateBar(t,this._score.masterBars[this._score.masterBars.length-1])}return e.staves[t]}getOrCreateBar(e,t){const s=0===e.bars.length?1:e.bars[0].voices.length;for(;e.bars.length<=t.index;){const t=new G;e.addBar(t),t.previousBar&&(t.clef=t.previousBar.clef,t.clefOttava=t.previousBar.clefOttava,t.keySignature=t.previousBar.keySignature,t.keySignatureType=t.previousBar.keySignatureType),null!=this._keyAllStaves&&(t.keySignature=this._keyAllStaves[0],t.keySignatureType=this._keyAllStaves[1]);for(let e=0;e<s;e++){const e=new ee;t.addVoice(e)}}return e.bars[t.index]}getOrCreateVoice(e,t){let s=!1;for(;e.voices.length<=t;)e.addVoice(new ee),s=!0;if(s)for(const s of e.staff.bars)for(;s.voices.length<=t;)s.addVoice(new ee);return e.voices[t]}parseNote(e,t,s){let i=null,a=w.None,r=0,n=null,o=!1,h=0,l=0,c=-1,d=null,u=0,p=-1,g=-1,m=null,f=null,y=!1,b=null;const S="no"!==e.getAttribute("print-object","yes"),B=()=>{if(null!==i)return;o&&!this._lastBeat&&(q.warning("MusicXML","Malformed MusicXML, <chord /> cannot be set on the first note of a measure"),o=!1),o&&!f&&(q.warning("MusicXML","Cannot mix <chord /> and <rest />"),o=!1);const e=this.getOrCreateStaff(s,h);if(o)return i=this._lastBeat,void i.addNote(f);const B=this.getOrCreateBar(e,t),k=this.getOrCreateVoice(B,l),T=0===k.beats.length?0:k.beats[k.beats.length-1].displayEnd;let N=this._musicalPosition-T;if(N>0){if(this._lastBeat&&this._lastBeat.beamingMode===fe.ForceMergeWithNext&&this._lastBeat.voice.bar.staff.index!==h&&k.beats.length>0&&k.beats[k.beats.length-1].beamingMode===fe.ForceMergeWithNext){const e=k.beats[k.beats.length-1].duration;for(;N>0;){const t=this.createRestForGap(N,e);if(null===t)break;this.insertBeatToVoice(t,k),N-=t.playbackDuration}}if(N>0){const e=new ze;e.dynamics=this._currentDynamics,e.isEmpty=!0,e.duration=_.TwoHundredFiftySixth,e.overrideDisplayDuration=N,e.updateDurations(),this.insertBeatToVoice(e,k)}}else N<0&&q.error("MusicXML","Unsupported forward/backup detected. Cannot fill new beats into already filled area of voice");c<0&&null!==d&&(c=z.toTicks(d),u>0&&(c=z.applyDot(c,2===u)));const x=new ze;i=x,null===n?x.beamingMode=this.getStaffContext(e).isExplicitlyBeamed?fe.ForceSplitToNext:fe.Auto:(x.beamingMode=n,this.getStaffContext(e).isExplicitlyBeamed=!0),x.isEmpty=!1,x.dynamics=this._currentDynamics,this._isBeatSlash&&(x.slashed=!0);const v=this._nextBeatAutomations;if(this._nextBeatAutomations=null,null!==v)for(const e of v)x.automations.push(e);const P=this._nextBeatChord;this._nextBeatChord=null,null!==P&&(x.chordId=P.uniqueId,k.bar.staff.hasChord(P.uniqueId)||k.bar.staff.addChord(x.chordId,P));const F=this._nextBeatCrescendo;null!==F&&(x.crescendo=F);const C=this._nextBeatOttavia;if(null!==C&&(x.ottava=C),x.isLetRing=this._nextBeatLetRing,x.isPalmMute=this._nextBeatPalmMute,this._nextBeatText&&(x.text=this._nextBeatText,this._nextBeatText=null),null!==f&&x.addNote(f),this.insertBeatToVoice(x,k),null!==f){f.isVisible=S;const e=this._indexToTrackInfo.get(s.index);null!==b?f.percussionArticulation=e.getOrCreateArticulation(b,f):y||(f.percussionArticulation=e.getOrCreateArticulation("",f))}a!==w.None?(x.graceType=a,this.applyBeatDurationFromTicks(x,r,null,!1)):(x.tupletNumerator=p,x.tupletDenominator=g,x.dots=u,x.preferredBeamDirection=m,this.applyBeatDurationFromTicks(x,c,d,!0)),this._musicalPosition=x.displayEnd,this._lastBeat=x};for(const t of e.childElements())switch(t.localName){case"grace":const e=Number.parseFloat(t.getAttribute("make-time","-1"));e>=0?(r=this.musicXmlDivisionsToAlphaTabTicks(e),a=w.BeforeBeat):a=w.OnBeat,"yes"===t.getAttribute("slash")&&(a=w.BeforeBeat);break;case"chord":o=!0;break;case"cue":return;case"pitch":f=this.parsePitch(t),y=!0;break;case"unpitched":f=this.parseUnpitched(t,s);break;case"rest":f=null,null===d&&(d=_.Whole);break;case"duration":c=this.parseDuration(t);break;case"instrument":b=t.getAttribute("id","");break;case"voice":l=Number.parseInt(t.innerText),Number.isNaN(l)?(q.warning("MusicXML","Voices need to be specified as numbers"),l=0):l-=1;break;case"type":d=this.parseBeatDuration(t);break;case"dot":u++;break;case"accidental":null===f?q.warning("MusicXML","Malformed MusicXML, missing pitch or unpitched for note"):this.parseAccidental(t,f);break;case"time-modification":for(const e of t.childElements())switch(e.localName){case"actual-notes":p=Number.parseInt(e.innerText);break;case"normal-notes":g=Number.parseInt(e.innerText)}break;case"stem":m=this.parseStem(t);break;case"notehead":null===f?q.warning("MusicXML","Malformed MusicXML, missing pitch or unpitched for note"):this.parseNoteHead(t,f,d??_.Quarter,m??this.estimateBeamDirection(f));break;case"staff":h=Number.parseInt(t.innerText)-1;break;case"beam":if("1"===t.getAttribute("number","1"))switch(t.innerText){case"begin":case"continue":n=fe.ForceMergeWithNext;break;case"end":n=fe.ForceSplitToNext}break;case"notations":B(),this.parseNotations(t,f,i);break;case"lyric":B(),this.parseLyric(t,i,s);break;case"play":this.parsePlay(t,f)}if(y){const e=this.getOrCreateStaff(s,h),t=this.getStaffContext(e).transpose;if(0!==t){const e=12*f.octave+f.tone+t;f.octave=e/12|0,f.tone=e-12*f.octave}}B()}parsePlay(e,t){for(const s of e.childElements())if("mute"===s.localName)t&&"palm"===s.innerText&&(t.isPalmMute=!0)}estimateBeamDirection(e){return e.calculateRealValue(!1,!1)<xs.B4Value?Te.Down:Te.Up}parseNoteHead(e,t,s,i){"yes"===e.getAttribute("parentheses","no")&&(t.isGhost=!0);const a=e.getAttribute("filled","");let r;switch("yes"===a?r=!0:"no"===a&&(r=!1),t.style=new Ie,e.innerText){case"arrow down":t.style.noteHeadCenterOnStem=!0,this.applyNoteHead(t,s,r,re.NoteheadTriangleDownDoubleWhole,re.NoteheadTriangleDownWhole,re.NoteheadTriangleDownHalf,re.NoteheadTriangleDownBlack);break;case"arrow up":t.style.noteHeadCenterOnStem=!0,this.applyNoteHead(t,s,r,re.NoteheadTriangleUpDoubleWhole,re.NoteheadTriangleUpWhole,re.NoteheadTriangleUpHalf,re.NoteheadTriangleUpBlack);break;case"back slashed":this.applyNoteHead(t,s,r,re.NoteheadSlashedDoubleWhole2,re.NoteheadSlashedWhole2,re.NoteheadSlashedHalf2,re.NoteheadSlashedBlack2);break;case"circle dot":t.style.noteHead=re.NoteheadRoundWhiteWithDot;break;case"circle-x":this.applyNoteHead(t,s,r,re.NoteheadCircleXDoubleWhole,re.NoteheadCircleXWhole,re.NoteheadCircleXHalf,re.NoteheadCircleX);break;case"circled":this.applyNoteHead(t,s,r,re.NoteheadCircledDoubleWhole,re.NoteheadCircledWhole,re.NoteheadCircledHalf,re.NoteheadCircledBlack);break;case"cluster":this.applyNoteHead(t,s,r,re.NoteheadClusterDoubleWhole3rd,re.NoteheadClusterWhole3rd,re.NoteheadClusterHalf3rd,re.NoteheadClusterQuarter3rd);break;case"cross":this.applyNoteHead(t,s,r,re.NoteheadPlusDoubleWhole,re.NoteheadPlusWhole,re.NoteheadPlusHalf,re.NoteheadPlusBlack);break;case"diamond":this.applyNoteHead(t,s,r,re.NoteheadDiamondDoubleWhole,re.NoteheadDiamondWhole,re.NoteheadDiamondHalf,re.NoteheadDiamondBlack);break;case"do":this.applyNoteHead(t,s,r,re.NoteShapeTriangleUpWhite,re.NoteShapeTriangleUpWhite,re.NoteShapeTriangleUpWhite,re.NoteShapeTriangleUpBlack);break;case"fa":i===Te.Up?this.applyNoteHead(t,s,r,re.NoteShapeTriangleRightWhite,re.NoteShapeTriangleRightWhite,re.NoteShapeTriangleRightWhite,re.NoteShapeTriangleRightBlack):this.applyNoteHead(t,s,r,re.NoteShapeTriangleLeftWhite,re.NoteShapeTriangleLeftWhite,re.NoteShapeTriangleLeftWhite,re.NoteShapeTriangleLeftBlack);break;case"fa up":this.applyNoteHead(t,s,r,re.NoteShapeTriangleLeftWhite,re.NoteShapeTriangleLeftWhite,re.NoteShapeTriangleLeftWhite,re.NoteShapeTriangleLeftBlack);break;case"inverted triangle":this.applyNoteHead(t,s,r,re.NoteheadTriangleDownDoubleWhole,re.NoteheadTriangleDownWhole,re.NoteheadTriangleDownHalf,re.NoteheadTriangleDownBlack);break;case"la":case"square":this.applyNoteHead(t,s,r,re.NoteShapeSquareWhite,re.NoteShapeSquareWhite,re.NoteShapeSquareWhite,re.NoteShapeSquareBlack);break;case"left triangle":this.applyNoteHead(t,s,r,re.NoteheadTriangleRightWhite,re.NoteheadTriangleRightWhite,re.NoteheadTriangleRightWhite,re.NoteheadTriangleRightBlack);break;case"mi":this.applyNoteHead(t,s,r,re.NoteShapeDiamondWhite,re.NoteShapeDiamondWhite,re.NoteShapeDiamondWhite,re.NoteShapeDiamondBlack);break;case"none":t.style.noteHead=re.NoteheadNull;break;case"normal":this.applyNoteHead(t,s,r,re.NoteheadDoubleWhole,re.NoteheadWhole,re.NoteheadHalf,re.NoteheadBlack);break;case"re":this.applyNoteHead(t,s,r,re.NoteShapeMoonWhite,re.NoteShapeMoonWhite,re.NoteShapeMoonWhite,re.NoteShapeMoonBlack);break;case"rectangle":this.applyNoteHead(t,s,r,re.NoteheadSquareWhite,re.NoteheadSquareWhite,re.NoteheadSquareWhite,re.NoteheadSquareBlack);break;case"slash":this.applyNoteHead(t,s,r,re.NoteheadSlashWhiteWhole,re.NoteheadSlashWhiteWhole,re.NoteheadSlashWhiteHalf,re.NoteheadSlashVerticalEnds);break;case"slashed":this.applyNoteHead(t,s,r,re.NoteheadSlashedDoubleWhole1,re.NoteheadSlashedWhole1,re.NoteheadSlashedHalf1,re.NoteheadSlashedBlack1);break;case"so":this.applyNoteHead(t,s,r,re.NoteShapeRoundWhite,re.NoteShapeRoundWhite,re.NoteShapeRoundWhite,re.NoteShapeRoundBlack);break;case"ti":this.applyNoteHead(t,s,r,re.NoteShapeTriangleRoundWhite,re.NoteShapeTriangleRoundWhite,re.NoteShapeTriangleRoundWhite,re.NoteShapeTriangleRoundBlack);break;case"triangle":this.applyNoteHead(t,s,r,re.NoteheadTriangleUpDoubleWhole,re.NoteheadTriangleUpWhole,re.NoteheadTriangleUpHalf,re.NoteheadTriangleUpBlack);break;case"x":this.applyNoteHead(t,s,r,re.NoteheadXDoubleWhole,re.NoteheadXWhole,re.NoteheadXHalf,re.NoteheadXBlack)}}createRestForGap(e,t){let s=z.toTicks(t);for(;s>e;){if(t===_.TwoHundredFiftySixth)return null;t*=2,s=z.toTicks(t)}const i=new ze;return i.dynamics=this._currentDynamics,i.isEmpty=!1,i.duration=t,i.overrideDisplayDuration=s,i.updateDurations(),i}insertBeatToVoice(e,t){if(t.beats.length>0){const s=t.beats[t.beats.length-1];s.nextBeat=e,e.previousBeat=s;let i=s;for(;null!==i&&i.graceType!==w.None;)i=i.index>0?i.previousBeat:null;null!==i&&(e.displayStart=i.displayEnd)}t.addBeat(e)}musicXmlDivisionsToAlphaTabTicks(e){return e*z.QuarterTime/this._divisionsPerQuarterNote}parseBeatDuration(e){switch(e.innerText){case"1024th":case"512th":case"256th":return _.TwoHundredFiftySixth;case"128th":return _.OneHundredTwentyEighth;case"64th":return _.SixtyFourth;case"32nd":return _.ThirtySecond;case"16th":return _.Sixteenth;case"eighth":return _.Eighth;case"quarter":return _.Quarter;case"half":return _.Half;case"whole":return _.Whole;case"breve":return _.DoubleWhole;case"long":return _.QuadrupleWhole}return null}applyBeatDurationFromTicks(e,t,s,i){if(!s)for(let e=0;e<xs.allDurations.length;e++){if(!(t>=xs.allDurationTicks[e]))break;s=xs.allDurations[e]}e.duration=s??_.Sixteenth,i&&(e.overrideDisplayDuration=t),e.updateDurations()}parseLyric(e,t,s){const i=this._indexToTrackInfo.get(s.index).getLyricLine(e.getAttribute("number",""));for(null===t.lyrics&&(t.lyrics=[]);t.lyrics.length<=i;)t.lyrics.push("");for(const s of e.childElements())switch(s.localName){case"text":t.lyrics[i]?t.lyrics[i]+=` ${s.innerText}`:t.lyrics[i]=s.innerText;break;case"elision":t.lyrics[i]+=s.innerText}}parseNotations(e,t,s){for(const i of e.childElements())switch(i.localName){case"tied":t&&this.parseTied(i,t,s.voice.bar.staff);break;case"slur":t&&this.parseSlur(i,t);break;case"glissando":t&&this.parseGlissando(i,t);break;case"slide":t&&this.parseSlide(i,t);break;case"ornaments":t&&this.parseOrnaments(i,t);break;case"technical":this.parseTechnical(i,t,s);break;case"articulations":t&&this.parseArticulations(i,t);break;case"dynamics":const e=this.parseDynamics(i);null!==e&&(s.dynamics=e,this._currentDynamics=e);break;case"fermata":this.parseFermata(i,s);break;case"arpeggiate":this.parseArpeggiate(i,s)}}getStaffContext(e){if(!this._staffToContext.has(e)){const t=new ks;return this._staffToContext.set(e,t),t}return this._staffToContext.get(e)}parseGlissando(e,t){const s=e.getAttribute("type"),i=e.getAttribute("number","1"),a=this.getStaffContext(t.beat.voice.bar.staff);switch(s){case"start":a.slideOrigins.set(i,t);break;case"stop":if(a.slideOrigins.has(i)){const e=a.slideOrigins.get(i);e.slideTarget=t,t.slideOrigin=e,e.slideOutType=v.Shift}}}parseSlur(e,t){const s=e.getAttribute("number","1"),i=this.getStaffContext(t.beat.voice.bar.staff);switch(e.getAttribute("type")){case"start":i.slurStarts.set(s,t);break;case"stop":if(i.slurStarts.has(s)){t.isSlurDestination=!0;const e=i.slurStarts.get(s);e.slurDestination=t,t.slurOrigin=e,i.slurStarts.delete(s)}}}parseArpeggiate(e,t){switch(e.getAttribute("direction","down")){case"down":t.brushType=b.ArpeggioDown;break;case"up":t.brushType=b.ArpeggioUp}}parseFermata(e,t){let s;switch(e.innerText){case"normal":default:s=ke.Medium;break;case"angled":s=ke.Short;break;case"square":s=ke.Long}t.fermata=new lt,t.fermata.type=s}parseArticulations(e,t){for(const s of e.childElements())switch(s.localName){case"accent":t.accentuated=B.Normal;break;case"strong-accent":t.accentuated=B.Heavy;break;case"staccato":t.isStaccato=!0;break;case"tenuto":t.accentuated=B.Tenuto}}parseTechnical(e,t,s){const i=[];for(const a of e.childElements())switch(a.localName){case"up-bow":s.pickStroke=ae.Up;break;case"down-bow":s.pickStroke=ae.Down;break;case"harmonic":break;case"fingering":t&&(t.leftHandFinger=this.parseFingering(a));break;case"pluck":t&&(t.rightHandFinger=this.parseFingering(a));break;case"fret":t&&(t.fret=Number.parseInt(a.innerText));break;case"string":t&&(t.string=s.voice.bar.staff.tuning.length-Number.parseInt(a.innerText)+1);break;case"hammer-on":case"pull-off":t&&(t.isHammerPullOrigin=!0);break;case"bend":i.push(a);break;case"tap":s.tap=!0;break;case"smear":t&&(t.vibrato=P.Slight);break;case"golpe":switch(a.getAttribute("placement","above")){case"above":s.golpe=de.Finger;break;case"below":s.golpe=de.Thumb}}t&&i.length>0&&this.parseBends(i,t)}parseBends(e,t){const s=X.MaxPosition/e.length;let i=0,a=0,r=!0;for(const n of e){const e=n.findChildElement("bend-alter");if(e){const o=Math.round(2*Math.abs(Number.parseFloat(e.innerText)));n.findChildElement("pre-bend")?r?(i+=o,t.addBendPoint(new X(a,i)),a+=s,t.addBendPoint(new X(a,i)),r=!1):a+=s:n.findChildElement("release")?(r&&(i+=o),t.addBendPoint(new X(a,i)),a+=s,i-=o,t.addBendPoint(new X(a,i)),r=!1):(t.addBendPoint(new X(a,i)),i+=o,a+=s,t.addBendPoint(new X(a,i)),r=!1)}}}parseFingering(e){switch(e.innerText){case"0":return k.NoOrDead;case"1":case"p":case"t":return k.Thumb;case"2":case"i":return k.IndexFinger;case"3":case"m":return k.MiddleFinger;case"4":case"a":return k.AnnularFinger;case"5":case"c":return k.LittleFinger}return k.Unknown}parseOrnaments(e,t){let s=-1;for(const i of e.childElements())switch(i.localName){case"trill-mark":s=Number.parseInt(i.getAttribute("trill-step","2")),t.isStringed?t.trillValue=t.stringTuning+s:t.isPercussion||(t.trillValue=t.calculateRealValue(!1,!1)+s);break;case"turn":t.ornament=he.Turn;break;case"inverted-turn":t.ornament=he.InvertedTurn;break;case"wavy-line":s>0?"start"===i.getAttribute("type")&&(this._currentTrillStep=s):this._currentTrillStep>0?"stop"===i.getAttribute("type")?this._currentTrillStep=-1:t.isStringed?t.trillValue=t.stringTuning+this._currentTrillStep:t.isPercussion||(t.trillValue=t.calculateRealValue(!1,!1)+this._currentTrillStep):t.vibrato=P.Slight;break;case"mordent":t.ornament=he.LowerMordent;break;case"inverted-mordent":t.ornament=he.UpperMordent;break;case"tremolo":switch(i.innerText){case"1":t.beat.tremoloSpeed=_.Eighth;break;case"2":t.beat.tremoloSpeed=_.Sixteenth;break;case"3":t.beat.tremoloSpeed=_.ThirtySecond}}}parseSlide(e,t){const s=e.getAttribute("type"),i=e.getAttribute("number","1"),a=this.getStaffContext(t.beat.voice.bar.staff);switch(s){case"start":a.slideOrigins.set(i,t);break;case"stop":if(a.slideOrigins.has(i)){const e=a.slideOrigins.get(i);e.slideTarget=t,t.slideOrigin=e,e.slideOutType=v.Shift}}}parseTied(e,t,s){const i=e.getAttribute("type"),a=e.getAttribute("number",""),r=this.getStaffContext(s);if("start"===i){if(a){if(r.tieStartIds.has(a)){const e=r.tieStartIds.get(a);r.tieStarts.delete(e)}r.tieStartIds.set(a,t)}r.tieStarts.add(t)}else if("stop"===i&&!t.isTieDestination){let e=null;if(a){if(!r.tieStartIds.has(a))return;e=r.tieStartIds.get(a),r.tieStartIds.delete(a),r.tieStarts.delete(t)}else{const s=this.calculatePitchedNoteValue(t);for(const t of r.tieStarts)if(this.calculatePitchedNoteValue(t)===s){e=t,r.tieStarts.delete(e);break}}if(!e)return;t.isTieDestination=!0,t.tieOrigin=e}}parseStem(e){switch(e.innerText){case"down":return Te.Down;case"up":return Te.Up;default:return null}}parseAccidental(e,t){switch(e.innerText){case"sharp":t.accidentalMode=N.ForceSharp;break;case"natural":t.accidentalMode=N.ForceNatural;break;case"flat":t.accidentalMode=N.ForceFlat;break;case"double-sharp":t.accidentalMode=N.ForceDoubleSharp;break;case"flat-flat":t.accidentalMode=N.ForceDoubleFlat}}calculatePitchedNoteValue(e){return 12*e.octave+e.tone}parseDuration(e){return this.musicXmlDivisionsToAlphaTabTicks(Number.parseFloat(e.innerText))}parseUnpitched(e,t){let s="",i=0;for(const t of e.childElements())switch(t.localName){case"display-step":s=t.innerText;break;case"display-octave":i=Number.parseInt(t.innerText)+1}const a=new Ae;if(""===s)a.octave=0,a.tone=0;else{const e=12*i+ie.getToneForText(s).noteValue;a.octave=e/12|0,a.tone=e-12*a.octave}return a}parsePitch(e){let t="",s=0,i=0;for(const a of e.childElements())switch(a.localName){case"step":t=a.innerText;break;case"alter":s=Number.parseFloat(a.innerText),Number.isNaN(s)&&(s=0);break;case"octave":i=Number.parseInt(a.innerText)+1}s|=0;const a=12*i+ie.getToneForText(t).noteValue+s,r=new Ae;return r.octave=a/12|0,r.tone=a-12*r.octave,r}applyNoteHead(e,t,s,i,a,r,n){if(void 0===s)switch(t){case _.QuadrupleWhole:case _.DoubleWhole:e.style.noteHead=i;break;case _.Whole:e.style.noteHead=a;break;case _.Half:e.style.noteHead=r;break;default:e.style.noteHead=n}else if(!0===s)e.style.noteHead=n;else switch(t){case _.QuadrupleWhole:case _.DoubleWhole:e.style.noteHead=i;break;case _.Whole:e.style.noteHead=a;break;case _.Half:default:e.style.noteHead=r}}}xs.B4Value=71,xs.allDurations=[_.TwoHundredFiftySixth,_.OneHundredTwentyEighth,_.SixtyFourth,_.ThirtySecond,_.Sixteenth,_.Eighth,_.Quarter,_.Half,_.Whole,_.DoubleWhole,_.QuadrupleWhole],xs.allDurationTicks=xs.allDurations.map((e=>z.toTicks(e))),function(e){e[e.SingleTrackMultiChannel=0]="SingleTrackMultiChannel",e[e.MultiTrack=1]="MultiTrack"}(At||(At={}));class vs{constructor(){this.events=[]}addEvent(e){if(0===this.events.length||e.tick>=this.events[this.events.length-1].tick)this.events.push(e);else{let t=this.events.length;for(;t>0;){if(!(this.events[t-1].tick>e.tick))break;t--}this.events.splice(t,0,e)}}writeTo(e){const t=ht.empty();let s=0;for(const e of this.events){const i=e.tick-s;Ps.writeVariableInt(t,i),e.writeTo(t),s=e.tick}const i=new Uint8Array([77,84,114,107]);e.write(i,0,i.length);const a=t.toArray();ot.writeInt32BE(e,a.length),e.write(a,0,a.length)}}class Ps{constructor(){this.format=At.SingleTrackMultiChannel,this.division=z.QuarterTime,this.tracks=[]}get events(){if(1===this.tracks.length)return this.tracks[0].events;const e=[];for(const e of this.tracks)this.events.push(...e.events);return e.sort(((e,t)=>e.tick-t.tick)),e}ensureTracks(e){for(;this.tracks.length<e;)this.tracks.push(new vs)}addEvent(e){this.format===At.SingleTrackMultiChannel?(this.ensureTracks(1),this.tracks[0].addEvent(e)):(this.ensureTracks(e.track+1),this.tracks[e.track].addEvent(e))}toBinary(){const e=ht.empty();return this.writeTo(e),e.toArray()}writeTo(e){const t=new Uint8Array([77,84,104,100]);e.write(t,0,t.length),ot.writeInt32BE(e,6),ot.writeInt16BE(e,this.format),ot.writeInt16BE(e,this.tracks.length),ot.writeInt16BE(e,this.division);for(const t of this.tracks)t.writeTo(e)}static writeVariableInt(e,t){const s=new Uint8Array(4);let i=0;do{s[i++]=127&t,t>>=7}while(t>0);for(;i>0;)i--,i>0?e.writeByte(128|s[i]):e.writeByte(s[i])}}!function(e){e[e.TimeSignature=88]="TimeSignature",e[e.NoteOn=128]="NoteOn",e[e.NoteOff=144]="NoteOff",e[e.ControlChange=176]="ControlChange",e[e.ProgramChange=192]="ProgramChange",e[e.TempoChange=81]="TempoChange",e[e.PitchBend=224]="PitchBend",e[e.PerNotePitchBend=96]="PerNotePitchBend",e[e.EndOfTrack=47]="EndOfTrack",e[e.AlphaTabRest=241]="AlphaTabRest",e[e.AlphaTabMetronome=242]="AlphaTabMetronome",e[e.SystemExclusive=240]="SystemExclusive",e[e.SystemExclusive2=247]="SystemExclusive2",e[e.Meta=255]="Meta"}(Rt||(Rt={}));class Fs{constructor(e,t,s){this.track=e,this.tick=t,this.type=s}get command(){return this.type}get message(){return 0}get data1(){return 0}get data2(){return 0}}class Cs extends Fs{constructor(e,t,s,i,a,r){super(e,t,Rt.TimeSignature),this.track=e,this.tick=t,this.numerator=s,this.denominatorIndex=i,this.midiClocksPerMetronomeClick=a,this.thirtySecondNodesInQuarter=r}writeTo(e){e.writeByte(255),e.writeByte(88),Ps.writeVariableInt(e,4),e.writeByte(255&this.numerator),e.writeByte(255&this.denominatorIndex),e.writeByte(255&this.midiClocksPerMetronomeClick),e.writeByte(255&this.thirtySecondNodesInQuarter)}}class Ds extends Fs{writeTo(e){e.writeByte(240);const t=ht.withCapacity(16);t.writeByte(Ds.AlphaTabManufacturerId),this.writeEventData(t),t.writeByte(247),Ps.writeVariableInt(e,t.length),t.copyTo(e)}}Ds.AlphaTabManufacturerId=125,Ds.MetronomeEventId=0,Ds.RestEventId=1;class Es extends Ds{constructor(e,t,s,i,a){super(e,t,Rt.AlphaTabMetronome),this.isMetronome=!0,this.metronomeNumerator=s,this.metronomeDurationInMilliseconds=a,this.metronomeDurationInTicks=i}writeEventData(e){e.writeByte(Ds.MetronomeEventId),e.writeByte(this.metronomeNumerator),ot.writeInt32LE(e,this.metronomeDurationInTicks),ot.writeInt32LE(e,this.metronomeDurationInMilliseconds)}}class Ls extends Ds{constructor(e,t,s){super(e,t,Rt.AlphaTabRest),this.channel=s}writeEventData(e){e.writeByte(Ds.RestEventId),e.writeByte(this.channel)}}class Ms extends Fs{constructor(e,t,s,i,a,r){super(e,t,s),this.channel=i,this.noteKey=a,this.noteVelocity=r}get data1(){return this.noteKey}get data2(){return this.noteVelocity}}class Is extends Ms{constructor(e,t,s,i,a){super(e,t,Rt.NoteOn,s,i,a)}writeTo(e){e.writeByte(15&this.channel|144),e.writeByte(255&this.noteKey),e.writeByte(255&this.noteVelocity)}}class As extends Ms{constructor(e,t,s,i,a){super(e,t,Rt.NoteOff,s,i,a)}writeTo(e){e.writeByte(15&this.channel|128),e.writeByte(255&this.noteKey),e.writeByte(255&this.noteVelocity)}}class Rs extends Fs{constructor(e,t,s,i,a){super(e,t,Rt.ControlChange),this.channel=s,this.controller=i,this.value=a}writeTo(e){e.writeByte(15&this.channel|176),e.writeByte(255&this.controller),e.writeByte(255&this.value)}get data1(){return this.controller}get data2(){return this.value}}class Os extends Fs{constructor(e,t,s,i){super(e,t,Rt.ProgramChange),this.channel=s,this.program=i}writeTo(e){e.writeByte(15&this.channel|192),e.writeByte(255&this.program)}get data1(){return this.program}}class Hs extends Fs{constructor(e,t){super(0,e,Rt.TempoChange),this.microSecondsPerQuarterNote=t}writeTo(e){e.writeByte(255),e.writeByte(81),e.writeByte(3),e.writeByte(this.microSecondsPerQuarterNote>>16&255),e.writeByte(this.microSecondsPerQuarterNote>>8&255),e.writeByte(255&this.microSecondsPerQuarterNote)}}class Ws extends Fs{constructor(e,t,s,i){super(e,t,Rt.PitchBend),this.channel=s,this.value=i}writeTo(e){e.writeByte(15&this.channel|224),e.writeByte(127&this.value),e.writeByte(this.value>>7&127)}get data1(){return 127&this.value}get data2(){return this.value>>7&127}}class Vs extends Fs{constructor(e,t,s,i,a){super(e,t,Rt.PerNotePitchBend),this.channel=s,this.noteKey=i,this.value=a}writeTo(e){throw new $e(Se.General,"Note Bend (Midi2.0) events cannot be exported to SMF1.0")}}class Gs extends Fs{constructor(e,t){super(e,t,Rt.EndOfTrack)}writeTo(e){e.writeByte(255),e.writeByte(47),e.writeByte(0)}}class zs{constructor(e,t){this.time=0,this.eventIndex=e,this.event=t,this.isMetronome=this.event.type===Rt.AlphaTabMetronome}static newMetronomeEvent(e,t,s,i,a){const r=new Es(0,t,s,i,a);return new zs(e,r)}}class Us{constructor(e,t,s){this.bpm=e,this.ticks=t,this.time=s}}class Xs{constructor(){this.tempoChanges=[],this.firstProgramEventPerChannel=new Map,this.firstTimeSignatureNumerator=0,this.firstTimeSignatureDenominator=0,this.synthData=[],this.division=z.QuarterTime,this.eventIndex=0,this.currentTime=0,this.playbackRange=null,this.playbackRangeStartTime=0,this.playbackRangeEndTime=0,this.endTick=0,this.endTime=0}}class Js{get isPlayingMain(){return this._currentState===this._mainState}get isPlayingOneTimeMidi(){return this._currentState===this._oneTimeState}get isPlayingCountIn(){return this._currentState===this._countInState}constructor(e){this._oneTimeState=null,this._countInState=null,this.isLooping=!1,this.playbackSpeed=1,this.instrumentPrograms=new Set,this.percussionKeys=new Set,this._synthesizer=e,this._mainState=new Xs,this._currentState=this._mainState}get mainPlaybackRange(){return this._mainState.playbackRange}set mainPlaybackRange(e){this._mainState.playbackRange=e,e&&(this._mainState.playbackRangeStartTime=this.tickPositionToTimePositionWithSpeed(this._mainState,e.startTick,1),this._mainState.playbackRangeEndTime=this.tickPositionToTimePositionWithSpeed(this._mainState,e.endTick,1))}get currentTime(){return this._currentState.currentTime/this.playbackSpeed}get currentEndTick(){return this._currentState.endTick}get currentEndTime(){return this._currentState.endTime/this.playbackSpeed}mainSeek(e){if(e*=this.playbackSpeed,this.mainPlaybackRange&&(e<this._mainState.playbackRangeStartTime?e=this._mainState.playbackRangeStartTime:e>this._mainState.playbackRangeEndTime&&(e=this._mainState.playbackRangeEndTime)),e>this._mainState.currentTime)this.mainSilentProcess(e-this._mainState.currentTime);else if(e<this._mainState.currentTime){if(this._mainState.currentTime=0,this._mainState.eventIndex=0,this.isPlayingMain){const e=this._synthesizer.metronomeVolume;this._synthesizer.noteOffAll(!0),this._synthesizer.resetSoft(),this._synthesizer.setupMetronomeChannel(e)}this.mainSilentProcess(e)}}mainSilentProcess(e){if(e<=0)return;const t=Date.now(),s=this._mainState.currentTime+e;if(this.isPlayingMain)for(;this._mainState.currentTime<s;)this.fillMidiEventQueueLimited(s-this._mainState.currentTime)&&this._synthesizer.synthesizeSilent(K.MicroBufferSize);this._mainState.currentTime=s;const i=Date.now()-t;q.debug("Sequencer",`Silent seek finished in ${i}ms (main)`)}loadOneTimeMidi(e){this._oneTimeState=this.createStateFromFile(e),this._currentState=this._oneTimeState}loadMidi(e){this.instrumentPrograms.clear(),this.percussionKeys.clear(),this._mainState=this.createStateFromFile(e),this._currentState=this._mainState}createStateFromFile(e){const t=new Xs;this.percussionKeys.add(K.MetronomeKey),t.tempoChanges=[],t.division=e.division,t.eventIndex=0,t.currentTime=0,t.synthData=[];let s=120,i=0,a=0,r=0,n=0,o=0,h=0,l=0,c=0;for(const d of e.events){const u=new zs(t.synthData.length,d);t.synthData.push(u);const p=d.tick-c;if(i+=p,a+=p*(6e4/(s*e.division)),u.time=a,c=d.tick,n>0)for(;h<i;){const e=zs.newMetronomeEvent(t.synthData.length,h,Math.floor(h/n)%r,n,o);t.synthData.push(e),e.time=l,h+=n,l+=o}if(d.type===Rt.TempoChange){s=6e7/d.microSecondsPerQuarterNote,t.tempoChanges.push(new Us(s,i,a)),o=n*(6e4/(s*e.division))}else if(d.type===Rt.TimeSignature){const i=d,a=Math.pow(2,i.denominatorIndex);r=i.numerator,n=t.division*(4/a)|0,o=n*(6e4/(s*e.division)),0===t.firstTimeSignatureDenominator&&(t.firstTimeSignatureNumerator=i.numerator,t.firstTimeSignatureDenominator=a)}else if(d.type===Rt.ProgramChange){const e=d,s=e.channel;t.firstProgramEventPerChannel.has(s)||t.firstProgramEventPerChannel.set(s,u);s===K.PercussionChannel||this.instrumentPrograms.add(e.program)}else if(d.type===Rt.NoteOn){const e=d;e.channel===K.PercussionChannel&&this.percussionKeys.add(e.noteKey)}}return t.synthData.sort(((e,t)=>e.time>t.time?1:e.time<t.time?-1:e.eventIndex-t.eventIndex)),t.endTime=a,t.endTick=i,t}fillMidiEventQueue(){return this.fillMidiEventQueueLimited(-1)}fillMidiEventQueueLimited(e){let t=K.MicroBufferSize/this._synthesizer.outSampleRate*1e3*this.playbackSpeed,s=this.internalEndTime;e>0&&(e<t&&(t=e),s=Math.min(this.internalEndTime,this._currentState.currentTime+e));let i=!1;for(this._currentState.currentTime+=t;this._currentState.eventIndex<this._currentState.synthData.length&&this._currentState.synthData[this._currentState.eventIndex].time<this._currentState.currentTime&&this._currentState.currentTime<s;)this._synthesizer.dispatchEvent(this._currentState.synthData[this._currentState.eventIndex]),this._currentState.eventIndex++,i=!0;return i}mainTickPositionToTimePosition(e){return this.tickPositionToTimePositionWithSpeed(this._mainState,e,this.playbackSpeed)}mainTimePositionToTickPosition(e){return this.timePositionToTickPositionWithSpeed(this._mainState,e,this.playbackSpeed)}currentTimePositionToTickPosition(e){return this.timePositionToTickPositionWithSpeed(this._currentState,e,this.playbackSpeed)}tickPositionToTimePositionWithSpeed(e,t,s){let i=0,a=120,r=0;for(const s of e.tempoChanges){if(t<s.ticks)break;i=s.time,a=s.bpm,r=s.ticks}return i+=(t-=r)*(6e4/(a*e.division)),i/s}timePositionToTickPositionWithSpeed(e,t,s){t*=s;let i=0,a=120,r=0;for(const s of e.tempoChanges){if(t<s.time)break;i=s.ticks,a=s.bpm,r=s.time}return i+=(t-=r)/(6e4/(a*e.division))|0,i+1}get internalEndTime(){return this.isPlayingMain&&this.mainPlaybackRange?this._currentState.playbackRangeEndTime:this._currentState.endTime}get isFinished(){return this._currentState.currentTime>=this.internalEndTime}stop(){this.isPlayingMain&&this.mainPlaybackRange?this._currentState.currentTime=this.mainPlaybackRange.startTick:this._currentState.currentTime=0,this._currentState.eventIndex=0}resetOneTimeMidi(){this._oneTimeState=null,this._currentState=this._mainState}resetCountIn(){this._countInState=null,this._currentState=this._mainState}startCountIn(){this.generateCountInMidi(),this._currentState=this._countInState,this.stop(),this._synthesizer.noteOffAll(!0)}generateCountInMidi(){const e=new Xs;e.division=this._mainState.division;let t=120,s=4,i=4;0===this._mainState.eventIndex?(t=this._mainState.tempoChanges[0].bpm,s=this._mainState.firstTimeSignatureNumerator,i=this._mainState.firstTimeSignatureDenominator):(t=this._synthesizer.currentTempo,s=this._synthesizer.timeSignatureNumerator,i=this._synthesizer.timeSignatureDenominator),e.tempoChanges.push(new Us(t,0,0));const a=e.division*(4/i)|0,r=a*(6e4/(t*this._mainState.division));let n=0,o=0;for(let t=0;t<s;t++){const s=zs.newMetronomeEvent(e.synthData.length,n,t,a,r);e.synthData.push(s),s.time=o,n+=a,o+=r}e.synthData.sort(((e,t)=>e.time>t.time?1:e.time<t.time?-1:e.eventIndex-t.eventIndex)),e.endTime=o,e.endTick=n,this._countInState=e}}!function(e){e[e.Paused=0]="Paused",e[e.Playing=1]="Playing"}(Ot||(Ot={}));class Ys{constructor(e,t){this.state=e,this.stopped=t}}class $s{constructor(e,t,s,i,a){this.currentTime=e,this.endTime=t,this.currentTick=s,this.endTick=i,this.isSeek=a}}class qs{constructor(){this.id="",this.size=0}static load(e,t,s){if(e&&qs.HeaderSize>e.size)return!1;if(s.position+qs.HeaderSize>=s.length)return!1;if(t.id=ot.read8BitStringLength(s,4),t.id.charCodeAt(0)<=32||t.id.charCodeAt(0)>=122)return!1;if(t.size=ot.readUInt32LE(s),e&&qs.HeaderSize+t.size>e.size)return!1;e&&(e.size-=qs.HeaderSize+t.size);const i="RIFF"===t.id,a="LIST"===t.id;return(!i||!e)&&(!i&&!a||(t.id=ot.read8BitStringLength(s,4),!(t.id.charCodeAt(0)<=32||t.id.charCodeAt(0)>=122)&&(t.size-=4,!0)))}}qs.HeaderSize=8;class js{constructor(e,t,s,i){this.packetData=e,this.isBeginningOfStream=t,this.isEndOfStream=s,this.granulePosition=s?i:null}addData(e){const t=this.packetData,s=new Uint8Array(t.length+e.length);s.set(t,0),s.set(e,t.length)}}!function(e){e[e.ContinuesPacket=1]="ContinuesPacket",e[e.BeginningOfStream=2]="BeginningOfStream",e[e.EndOfStream=4]="EndOfStream"}(Ht||(Ht={}));class Ks{constructor(e){this._readable=e}read(){const e=[];for(;this.findAndReadPage(e););return e}findAndReadPage(e){return!!this.seekPageHeader()&&this.readPage(e)}seekPageHeader(){for(let e=0;e<65536;e++){if(1399285583===ot.readInt32LE(this._readable))return!0;this._readable.position-=3}return!1}readPage(e){const t=this._readable.readByte();if(-1===t||0!==t)return!1;const s=this._readable.readByte(),i=ot.readInt64LE(this._readable);this._readable.skip(4),this._readable.skip(4),this._readable.skip(4);const a=this._readable.readByte();if(-1===a)return!1;const r=[];let n=0;for(let e=0;e<a;e++){const e=this._readable.readByte();n===r.length&&r.push(0),r[n]+=e,e<255&&n++}for(let t=0;t<r.length;t++){const a=new Uint8Array(r[t]);if(this._readable.read(a,0,a.length)!==a.length)return!1;if(s&Ht.ContinuesPacket){if(0===e.length)throw new $e(Se.Format,"OGG: Continuation page without any previous packets");e[e.length-1].addData(a)}else{const n=new js(a,!!(s&Ht.BeginningOfStream)&&0===t,!!(s&Ht.EndOfStream)&&t===r.length-1,i);e.push(n)}}return!0}}class Qs{constructor(){this.audioChannels=0,this.audioSampleRate=0,this.samples=new Float32Array(0),this.bitrateMaximum=0,this.bitrateNominal=0,this.bitrateMinimum=0,this.blocksize0=0,this.blocksize1=0}}class Zs{constructor(){this.value=0,this.bitsRead=0}}class ei{constructor(e){this._bitBucket=0n,this._bitCount=0n,this._overflowBits=0n,this._source=e}readByte(){return this.readBits(ei.ByteSize)}readBit(){return 1===this.readBits(1)}readBytes(e){const t=new Uint8Array(e);for(let s=0;s<e;s++)t[s]=255&this.readByte();return t}readBits(e){if(0===e)return 0;const t=this.tryPeekBits(e);return this.skipBits(e),t.value}tryPeekBits(e){if(e<0||e>32)throw new $e(Se.General,"IO: Cannot read more than 32 bits in one go");if(0===e)return new Zs;const t=new Zs;for(;this._bitCount<e;){const e=BigInt(this._source.readByte());if(-1n===e)return t.bitsRead=Number(this._bitCount),t.value=Number(this._bitBucket),this._bitBucket=0n,this._bitCount=0n,t;this._bitBucket=(0xffn&e)<<this._bitCount|this._bitBucket,this._bitCount+=8n,this._bitCount>32&&(this._overflowBits=e>>40n-this._bitCount&0xffn)}let s=this._bitBucket;return e<64&&(s&=(1n<<BigInt(e))-1n),t.value=Number(s),t.bitsRead=e,t}skipBits(e){let t=BigInt(e);if(0===e);else if(this._bitCount>t){if(this._bitBucket=e>31?0n:this._bitBucket>>t,this._bitCount>32){const s=this._bitCount-32n;this._bitBucket=this._bitBucket|this._overflowBits<<this._bitCount-t-s,s>e&&(this._overflowBits=this._overflowBits>>t&0xffn)}this._bitCount-=t}else if(this._bitCount===t)this._bitBucket=0n,this._bitCount=0n;else{for(t-=this._bitCount,this._bitCount=0n,this._bitBucket=0n;t>8;){if(-1===this._source.readByte()){t=0n;break}t-=8n}if(t>0){const e=BigInt(this._source.readByte());-1n===e||(this._bitBucket=e>>t,this._bitCount=8n-t)}}}}ei.ByteSize=8;class ti{constructor(){this.codebooks=[],this.timeDomainTransforms=[],this.floors=[],this.residues=[],this.mappings=[],this.modes=[]}}class si{static ilog(e){let t=0;for(;e>0;)++t,e>>=1;return t}static bitReverse(e,t=32){let s=BigInt(e);s=(s&BigInt(2863311530))>>1n|(s&BigInt(1431655765))<<1n,s=(s&BigInt(3435973836))>>2n|(s&BigInt(858993459))<<2n,s=(s&BigInt(4042322160))>>4n|(s&BigInt(252645135))<<4n,s=(s&BigInt(4278255360))>>8n|(s&BigInt(16711935))<<8n,s=(s>>16n|s<<16n)>>32n-BigInt(t);return Number(BigInt.asUintN(32,s))}static convertFromVorbisFloat32(e){const t=BigInt(e);let s=t&BigInt(2097151);const i=t&BigInt(2147483648),a=(t&BigInt(2145386496))>>21n;return 0n!==i&&(s=-s),Number(s)*Math.pow(2,Number(a)-788)}}class ii{constructor(e){this._data=e}get(e){return this._data[e]}}class ai{get(e){return e}}ai.instance=new ai;class ri{constructor(e,t){this._maxBits=0,this._overflowList=null,this._prefixList=null,this._prefixBitLength=0,this.dimensions=0,this.entries=0,this.mapType=0;if(5653314!==e.readBits(24))throw new $e(Se.Format,"Vorbis: Book header had invalid signature!");this.dimensions=e.readBits(16),this.entries=e.readBits(24),this._lengths=new Int32Array(this.entries),this.initTree(e,t),this.initLookupTable(e)}get(e,t){return this._lookupTable[e*this.dimensions+t]}decodeScalar(e){let t=e.tryPeekBits(this._prefixBitLength);if(0===t.bitsRead)return-1;let s=this._prefixList[t.value];if(null!=s)return e.skipBits(s.length),s.value;if(t=e.tryPeekBits(this._maxBits),null!==this._overflowList)for(let i=0;i<this._overflowList.length;i++){s=this._overflowList[i];const a=t.value&s.mask;if(s.bits===a)return e.skipBits(s.length),s.value}return-1}initTree(e,t){let s,i,a=0;if(e.readBit()){let t=e.readBits(5)+1;for(let s=0;s<this.entries;){let i=e.readBits(si.ilog(this.entries-s));for(;--i>=0;)this._lengths[s++]=t;++t}a=0,s=!1,i=t}else{i=-1,s=e.readBit();for(let t=0;t<this.entries;t++)!s||e.readBit()?(this._lengths[t]=e.readBits(5)+1,++a):this._lengths[t]=-1,this._lengths[t]>i&&(i=this._lengths[t])}if(this._maxBits=i,i>-1){let e,i=null;s&&a>=this.entries>>2&&(i=new Int32Array(this.entries),i.set(this._lengths.subarray(0,this.entries),0),s=!1),e=s?a:0;let r=null,n=null;if(s?0!==e&&(i=new Int32Array(e),n=new Int32Array(e),r=new Int32Array(e)):n=new Int32Array(this.entries),!this.computeCodewords(s,n,i,this._lengths,this.entries,r))throw new $e(Se.Format,"Vorbis: Failed to compute codewords");const o=null==r?ai.instance:new ii(r);t.generateTable(o,i??this._lengths,n),this._prefixList=t.prefixTree,this._prefixBitLength=t.tableBits,this._overflowList=t.overflowList}}computeCodewords(e,t,s,i,a,r){const n=new Uint32Array(32);let o=0,h=0;for(o=0;o<a&&!(i[o]>0);++o);if(o===a)return!0;this.addEntry(e,t,s,0,o,h++,i[o],r);for(let e=1;e<=i[o];++e)n[e]=1<<32-e;for(let l=o+1;l<a;++l){let a=i[l];if(a<=0)continue;for(;a>0&&0===n[a];)--a;if(0===a)return!1;const o=n[a];if(n[a]=0,this.addEntry(e,t,s,si.bitReverse(o),l,h++,i[l],r),a!==i[l])for(let e=i[l];e>a;--e)n[e]=o+(1<<32-e)}return!0}addEntry(e,t,s,i,a,r,n,o){e?(t[r]=i,s[r]=n,o[r]=a):t[a]=i}initLookupTable(e){if(this.mapType=e.readBits(4),0===this.mapType)return;const t=si.convertFromVorbisFloat32(e.readBits(32)),s=si.convertFromVorbisFloat32(e.readBits(32)),i=e.readBits(4)+1,a=e.readBit();let r=this.entries*this.dimensions;const n=new Float32Array(r);1===this.mapType&&(r=this.lookup1Values());const o=new Uint32Array(r);for(let t=0;t<r;t++)o[t]=e.readBits(i);if(1===this.mapType)for(let e=0;e<this.entries;e++){let i=0,h=1;for(let l=0;l<this.dimensions;l++){const c=o[e/h%r|0]*s+t+i;n[e*this.dimensions+l]=c,a&&(i=c),h*=r}}else for(let e=0;e<this.entries;e++){let i=0,r=e*this.dimensions;for(let h=0;h<this.dimensions;h++){const l=o[r]*s+t+i;n[e*this.dimensions+h]=l,a&&(i=l),++r}}this._lookupTable=n}lookup1Values(){let e=Math.floor(Math.exp(Math.log(this.entries)/this.dimensions));return Math.floor(Math.pow(e+1,this.dimensions))<=this.entries&&++e,e}}class ni{constructor(){this.value=0,this.length=0,this.bits=0,this.mask=0}}class oi{constructor(){this.tableBits=0,this.prefixTree=[],this.overflowList=null}generateTable(e,t,s){const i=new Array(t.length);let a=0;for(let r=0;r<i.length;r++){const n=new ni;n.value=e.get(r),n.length=t[r]<=0?99999:t[r],n.bits=s[r],n.mask=(1<<t[r])-1,i[r]=n,t[r]>0&&a<t[r]&&(a=t[r])}i.sort(((e,t)=>{const s=e.length-t.length;return 0===s?e.bits-t.bits:s}));const r=a>oi.MAX_TABLE_BITS?oi.MAX_TABLE_BITS:a,n=[];let o=null;for(let e=0;e<i.length&&i[e].length<99999;e++){const t=i[e].length;if(t>r)for(o=[];e<i.length&&i[e].length<99999;e++)o.push(i[e]);else{const s=1<<r-t,a=i[e];for(let e=0;e<s;e++){const s=e<<t|a.bits;for(;n.length<=s;)n.push(null);n[s]=a}}}for(;n.length<1<<r;)n.push(null);this.tableBits=r,this.prefixTree=n,this.overflowList=o}}oi.MAX_TABLE_BITS=10;class hi{constructor(e){e.readBits(16)}}class li{get executeChannel(){return(this.forceEnergy||this.amp>0)&&!this.forceNoEnergy}constructor(e){this.amp=0,this.forceEnergy=!1,this.forceNoEnergy=!1,this.coeff=e}}class ci{constructor(e,t,s,i){if(this._order=e.readBits(8),this._rate=e.readBits(16),this._bark_map_size=e.readBits(16),this._ampBits=e.readBits(6),this._ampOfs=e.readBits(8),this._books=new Array(e.readBits(4)+1),this._order<1||this._rate<1||this._bark_map_size<1||0===this._books.length)throw new $e(Se.Format,"Vorbis: Invalid Floor0 Data");this._ampDiv=(1<<this._ampBits)-1;for(let t=0;t<this._books.length;t++){const s=e.readBits(8);if(s<0||s>=i.length)throw new $e(Se.Format,"Vorbis: Invalid Floor0 Data");const a=i[s];if(0===a.mapType||a.dimensions<1)throw new $e(Se.Format,"Vorbis: Invalid Floor0 Data");this._books[t]=a}this._bookBits=si.ilog(this._books.length),this._barkMaps=new Map([[t,this.synthesizeBarkCurve(t/2)],[s,this.synthesizeBarkCurve(s/2)]]),this._wMap=new Map([[t,this.synthesizeWDelMap(t/2)],[s,this.synthesizeWDelMap(s/2)]])}synthesizeBarkCurve(e){const t=this._bark_map_size/ci.toBARK(this._rate/2),s=new Int32Array(e+1);for(let i=0;i<e-1;i++)s[i]=Math.min(this._bark_map_size-1,Math.floor(ci.toBARK(this._rate/2/e*i)*t));return s[e]=-1,s}static toBARK(e){return 13.1*Math.atan(74e-5*e)+2.24*Math.atan(1.85e-8*e*e)+1e-4*e}synthesizeWDelMap(e){const t=Math.PI/this._bark_map_size,s=new Float32Array(e);for(let i=0;i<e;i++)s[i]=2*Math.cos(t*i);return s}unpack(e,t,s){const i=new li(new Float32Array(this._order+1));if(i.amp=e.readBits(this._ampBits),i.amp>0){i.amp=i.amp/this._ampDiv*this._ampOfs;const t=e.readBits(this._bookBits);if(t>=this._books.length)return i.amp=0,i;const s=this._books[t];for(let t=0;t<this._order;){const a=s.decodeScalar(e);if(-1===a)return i.amp=0,i;for(let e=0;t<this._order&&e<s.dimensions;e++,t++)i.coeff[t]=s.get(a,e)}let a=0;for(let e=0;e<this._order;){for(let t=0;e<this._order&&t<s.dimensions;e++,t++)i.coeff[e]+=a;a=i.coeff[e-1]}}return i}apply(e,t,s){const i=e,a=t/2;if(i.amp>0){const e=this._barkMaps.get(t),r=this._wMap.get(t);let n=0;for(n=0;n<this._order;n++)i.coeff[n]=2*Math.cos(i.coeff[n]);for(n=0;n<a;){let t=0;const a=e[n];let o=.5,h=.5;const l=r[a];for(t=1;t<this._order;t+=2)h*=l-i.coeff[t-1],o*=l-i.coeff[t];for(t===this._order?(h*=l-i.coeff[t-1],o*=o*(4-l*l),h*=h):(o*=o*(2-l),h*=h*(2+l)),h=i.amp/Math.sqrt(o+h)-this._ampOfs,h=Math.exp(.11512925*h),s[n]*=h;e[++n]===a;)s[n]*=h}}else s.fill(0,0,a)}}class di{constructor(){this.posts=new Int32Array(64),this.postCount=0,this.forceEnergy=!1,this.forceNoEnergy=!1}get executeChannel(){return(this.forceEnergy||this.postCount>0)&&!this.forceNoEnergy}}class ui{constructor(e,t){let s=-1;this._partitionClass=new Int32Array(e.readBits(5));for(let t=0;t<this._partitionClass.length;t++)this._partitionClass[t]=e.readBits(4),this._partitionClass[t]>s&&(s=this._partitionClass[t]);++s,this._classDimensions=new Int32Array(s),this._classSubclasses=new Int32Array(s),this._classMasterbooks=new Array(s),this._classMasterBookIndex=new Int32Array(s),this._subclassBooks=new Array(s),this._subclassBookIndex=new Array(s);for(let i=0;i<s;i++){this._classDimensions[i]=e.readBits(3)+1,this._classSubclasses[i]=e.readBits(2),this._classSubclasses[i]>0&&(this._classMasterBookIndex[i]=e.readBits(8),this._classMasterbooks[i]=t[this._classMasterBookIndex[i]]),this._subclassBooks[i]=new Array(1<<this._classSubclasses[i]),this._subclassBookIndex[i]=new Int32Array(this._subclassBooks[i].length);for(let s=0;s<this._subclassBooks[i].length;s++){const a=e.readBits(8)-1;a>=0&&(this._subclassBooks[i][s]=t[a]),this._subclassBookIndex[i][s]=a}}this._multiplier=e.readBits(2),this._range=ui._rangeLookup[this._multiplier],this._yBits=ui._yBitsLookup[this._multiplier],++this._multiplier;const i=e.readBits(4),a=[];a.push(0),a.push(1<<i);for(let t=0;t<this._partitionClass.length;t++){const s=this._partitionClass[t];for(let t=0;t<this._classDimensions[s];t++)a.push(e.readBits(i))}this._xList=new Int32Array(a),this._lNeigh=new Int32Array(a.length),this._hNeigh=new Int32Array(a.length),this._sortIdx=new Int32Array(a.length),this._sortIdx[0]=0,this._sortIdx[1]=1;for(let e=2;e<this._lNeigh.length;e++){this._lNeigh[e]=0,this._hNeigh[e]=1,this._sortIdx[e]=e;for(let t=2;t<e;t++){const s=this._xList[t];s<this._xList[e]?s>this._xList[this._lNeigh[e]]&&(this._lNeigh[e]=t):s<this._xList[this._hNeigh[e]]&&(this._hNeigh[e]=t)}}for(let e=0;e<this._sortIdx.length-1;e++)for(let t=e+1;t<this._sortIdx.length;t++){if(this._xList[e]===this._xList[t])throw new $e(Se.Format,"Vorbis: Invalid Floor1 Data");if(this._xList[this._sortIdx[e]]>this._xList[this._sortIdx[t]]){const s=this._sortIdx[e];this._sortIdx[e]=this._sortIdx[t],this._sortIdx[t]=s}}}unpack(e,t,s){const i=new di;if(e.readBit()){let t=2;i.posts[0]=e.readBits(this._yBits),i.posts[1]=e.readBits(this._yBits);for(let s=0;s<this._partitionClass.length;s++){const a=this._partitionClass[s],r=this._classDimensions[a],n=this._classSubclasses[a],o=(1<<n)-1;let h=0;if(n>0&&(h=this._classMasterbooks[a].decodeScalar(e),-1===h)){t=0;break}for(let l=0;l<r;l++){const r=this._subclassBooks[a][h&o];if(h>>=n,null!=r&&(i.posts[t]=r.decodeScalar(e),-1===i.posts[t])){t=0,s=this._partitionClass.length;break}++t}}i.postCount=t}return i}apply(e,t,s){const i=e,a=t/2;if(i.postCount>0){const e=this.unwrapPosts(i);let t=0,r=i.posts[0]*this._multiplier;for(let n=1;n<i.postCount;n++){const o=this._sortIdx[n];if(e[o]){const e=this._xList[o],n=i.posts[o]*this._multiplier;t<a&&this.renderLineMulti(t,r,Math.min(e,a),n,s),t=e,r=n}if(t>=a)break}t<a&&this.renderLineMulti(t,r,a,r,s)}else s.fill(0,0,a)}unwrapPosts(e){const t=new Array(64);t.fill(!1),t[0]=!0,t[1]=!0;const s=new Int32Array(64);s[0]=e.posts[0],s[1]=e.posts[1];for(let i=2;i<e.postCount;i++){const a=this._lNeigh[i],r=this._hNeigh[i],n=this.renderPoint(this._xList[a],s[a],this._xList[r],s[r],this._xList[i]),o=e.posts[i],h=this._range-n,l=n;let c;c=h<l?2*h:2*l,0!==o?(t[a]=!0,t[r]=!0,t[i]=!0,s[i]=o>=c?h>l?o-l+n:n-o+h-1:o%2==1?n-(o+1)/2:n+o/2):(t[i]=!1,s[i]=n)}for(let t=0;t<e.postCount;t++)e.posts[t]=s[t];return t}renderPoint(e,t,s,i,a){const r=i-t,n=s-e,o=Math.abs(r)*(a-e)/n|0;return r<0?t-o:t+o}renderLineMulti(e,t,s,i,a){const r=i-t,n=s-e;let o=Math.abs(r);const h=1-2*(r>>31&1),l=r/n|0;let c=e,d=t,u=-n;for(a[e]*=ui.inverse_dB_table[t],o-=Math.abs(l)*n;++c<s;)d+=l,u+=o,u>=0&&(u-=n,d+=h),a[c]*=ui.inverse_dB_table[d]}}ui._rangeLookup=[256,128,86,64],ui._yBitsLookup=[8,7,7,6],ui.inverse_dB_table=new Float32Array([1.0649863e-7,1.1341951e-7,1.2079015e-7,1.2863978e-7,1.3699951e-7,1.4590251e-7,1.5538408e-7,1.6548181e-7,1.7623575e-7,1.8768855e-7,1.9988561e-7,2.128753e-7,2.2670913e-7,2.4144197e-7,2.5713223e-7,2.7384213e-7,2.9163793e-7,3.1059021e-7,3.3077411e-7,3.5226968e-7,3.7516214e-7,3.9954229e-7,4.255068e-7,4.5315863e-7,4.8260743e-7,5.1396998e-7,5.4737065e-7,5.8294187e-7,6.2082472e-7,6.6116941e-7,7.0413592e-7,7.4989464e-7,7.9862701e-7,8.505263e-7,9.0579828e-7,9.6466216e-7,10273513e-13,10941144e-13,11652161e-13,12409384e-13,13215816e-13,14074654e-13,14989305e-13,15963394e-13,17000785e-13,18105592e-13,19282195e-13,20535261e-13,21869758e-13,23290978e-13,24804557e-13,26416497e-13,2813319e-12,29961443e-13,31908506e-13,33982101e-13,36190449e-13,38542308e-13,41047004e-13,4371447e-12,46555282e-13,49580707e-13,5280274e-12,5623416e-12,59888572e-13,63780469e-13,67925283e-13,72339451e-13,77040476e-13,82047e-10,87378876e-13,93057248e-13,99104632e-13,10554501e-12,11240392e-12,11970856e-12,12748789e-12,13577278e-12,14459606e-12,15399272e-12,16400004e-12,17465768e-12,18600792e-12,19809576e-12,21096914e-12,22467911e-12,23928002e-12,25482978e-12,27139006e-12,28902651e-12,30780908e-12,32781225e-12,34911534e-12,37180282e-12,39596466e-12,42169667e-12,4491009e-11,47828601e-12,50936773e-12,54246931e-12,57772202e-12,61526565e-12,65524908e-12,69783085e-12,74317983e-12,79147585e-12,8429104e-11,89768747e-12,95602426e-12,.00010181521,.00010843174,.00011547824,.00012298267,.00013097477,.00013948625,.00014855085,.00015820453,.00016848555,.00017943469,.00019109536,.00020351382,.00021673929,.00023082423,.00024582449,.00026179955,.00027881276,.00029693158,.00031622787,.00033677814,.00035866388,.00038197188,.00040679456,.00043323036,.00046138411,.00049136745,.00052329927,.00055730621,.00059352311,.00063209358,.00067317058,716917e-9,.0007635063,.00081312324,.00086596457,.00092223983,.00098217216,.0010459992,.0011139742,.0011863665,.0012634633,.0013455702,.0014330129,.0015261382,.0016253153,.0017309374,.0018434235,.0019632195,.0020908006,.0022266726,.0023713743,.0025254795,.0026895994,.0028643847,.0030505286,.0032487691,.0034598925,.0036847358,.0039241906,.0041792066,.004450795,.0047400328,.0050480668,.0053761186,.0057254891,.0060975636,.0064938176,.0069158225,.0073652516,.0078438871,.0083536271,.0088964928,.009474637,.010090352,.01074608,.011444421,.012188144,.012980198,.013823725,.014722068,.015678791,.016697687,.017782797,.018938423,.020169149,.021479854,.022875735,.02436233,.025945531,.027631618,.029427276,.031339626,.033376252,.035545228,.037855157,.040315199,.042935108,.045725273,.048696758,.051861348,.055231591,.05882085,.062643361,.066714279,.071049749,.075666962,.080584227,.085821044,.091398179,.097337747,.1036633,.11039993,.11757434,.12521498,.13335215,.14201813,.15124727,.16107617,.1715438,.18269168,.19456402,.20720788,.22067342,.23501402,.25028656,.26655159,.28387361,.30232132,.32196786,.34289114,.36517414,.38890521,.41417847,.44109412,.4697589,.50028648,.53279791,.56742212,.6042964,.64356699,.68538959,.72993007,.77736504,.8278826,.88168307,.9389798,1]);class pi{constructor(e,t,s,i){const a=e.readBits(16);switch(a){case 0:this.floor=new ci(e,t,s,i);break;case 1:this.floor=new ui(e,i);break;default:throw new $e(Se.Format,`Vorbis: Invalid Floor type: ${a}`)}}apply(e,t,s){this.floor.apply(e,t,s)}unpack(e,t,s){return this.floor.unpack(e,t,s)}}class gi{constructor(e,t,s){this._begin=e.readBits(24),this._end=e.readBits(24),this._partitionSize=e.readBits(24)+1,this._classifications=e.readBits(6)+1,this._classBook=s[e.readBits(8)],this._cascade=new Int32Array(this._classifications);let i=0;for(let t=0;t<this._classifications;t++){const s=e.readBits(3);e.readBit()?this._cascade[t]=e.readBits(5)<<3|s:this._cascade[t]=s,i+=gi.icount(this._cascade[t])}const a=new Int32Array(i);for(let t=0;t<i;t++)if(a[t]=e.readBits(8),0===s[a[t]].mapType)throw new $e(Se.Format,"Vorbis: Invalid Residue 0");const r=this._classBook.entries;let n=this._classBook.dimensions,o=1;for(;n>0;){if(o*=this._classifications,o>r)throw new $e(Se.Format,"Vorbis: Invalid Residue 0");--n}this._books=new Array(this._classifications),i=0;let h,l=0;for(let e=0;e<this._classifications;e++)if(h=si.ilog(this._cascade[e]),this._books[e]=new Array(h),h>0){l=Math.max(l,h);for(let t=0;t<h;t++)(this._cascade[e]&1<<t)>0&&(this._books[e][t]=s[a[i++]])}this._maxStages=l,this._decodeMap=new Array(o);for(let e=0;e<o;e++){let t=e,s=o/this._classifications|0;this._decodeMap[e]=new Int32Array(this._classBook.dimensions);for(let i=0;i<this._classBook.dimensions;i++){const a=t/s|0;t-=a*s,s=s/this._classifications|0,this._decodeMap[e][i]=a}}this._channels=t}static icount(e){let t=0;for(;0!==e;)t+=1&e,e>>=1;return t}decode(e,t,s,i){const a=(this._end<s/2?this._end:s/2)-this._begin;if(a>0&&-1!==t.indexOf(!1)){const t=a/this._partitionSize,s=(t+this._classBook.dimensions-1)/this._classBook.dimensions|0,r=[];for(let e=0;e<this._channels;e++)r.push(new Array(s));for(let s=0;s<this._maxStages;s++)for(let a=0,n=0;a<t;n++){if(0===s)for(let i=0;i<this._channels;i++){const o=this._classBook.decodeScalar(e);if(!(o>=0&&o<this._decodeMap.length)){a=t,s=this._maxStages;break}r[i][n]=this._decodeMap[o]}for(let o=0;a<t&&o<this._classBook.dimensions;o++,a++){const h=this._begin+a*this._partitionSize;for(let l=0;l<this._channels;l++){const c=r[l][n][o];if(this._cascade[c]&1<<s){const r=this._books[c][s];if(r&&this.writeVectors(r,e,i,l,h,this._partitionSize)){a=t,s=this._maxStages;break}}}}}}}writeVectors(e,t,s,i,a,r){const n=s[i],o=r/e.dimensions,h=new Int32Array(o);for(let s=0;s<o;s++)if(h[s]=e.decodeScalar(t),-1===h[s])return!0;for(let t=0;t<e.dimensions;t++)for(let s=0;s<o;s++,a++)n[a]+=e.get(h[s],t);return!1}}class mi extends gi{writeVectors(e,t,s,i,a,r){const n=s[i];for(let s=0;s<r;){const i=e.decodeScalar(t);if(-1===i)return!0;for(let t=0;t<e.dimensions;s++,t++)n[a+s]+=e.get(i,t)}return!1}}class fi extends gi{constructor(e,t,s){super(e,1,s),this._realChannels=t}decode(e,t,s,i){super.decode(e,t,s*this._realChannels,i)}writeVectors(e,t,s,i,a,r){let n=0;a/=this._realChannels;for(let i=0;i<r;){const r=e.decodeScalar(t);if(-1===r)return!0;for(let t=0;t<e.dimensions;t++,i++)s[n][a]+=e.get(r,t),++n===this._realChannels&&(n=0,a++)}return!1}}class yi{constructor(e,t,s){const i=e.readBits(16);switch(i){case 0:this.residue=new gi(e,t,s);break;case 1:this.residue=new mi(e,t,s);break;case 2:this.residue=new fi(e,t,s);break;default:throw new $e(Se.Format,`Vorbis: Invalid Residue type: ${i}`)}}decode(e,t,s,i){this.residue.decode(e,t,s,i)}}class bi{constructor(e,t,s,i,a){if(0!==e.readBits(16))throw new $e(Se.Format,"Vorbis: Invalid mapping type!");let r=1;e.readBit()&&(r+=e.readBits(4));let n=0;e.readBit()&&(n=e.readBits(8)+1);const o=si.ilog(t-1);this._couplingAngle=new Int32Array(n),this._couplingMangitude=new Int32Array(n);for(let s=0;s<n;s++){const i=e.readBits(o),a=e.readBits(o);if(i===a||i>t-1||a>t-1)throw new $e(Se.Format,"Vorbis: Invalid magnitude or angle in mapping header!");this._couplingAngle[s]=a,this._couplingMangitude[s]=i}if(0!==e.readBits(2))throw new $e(Se.Format,"Vorbis: Reserved bits not 0 in mapping header.");const h=new Int32Array(t);if(r>1)for(let s=0;s<t;s++)if(h[s]=e.readBits(4),h[s]>r)throw new $e(Se.Format,"Vorbis: Invalid channel mux submap index in mapping header!");this._submapFloor=new Array(r),this._submapResidue=new Array(r);for(let t=0;t<r;t++){e.skipBits(8);const a=e.readBits(8);if(a>=s.length)throw new $e(Se.Format,"Vorbis: Invalid floor number in mapping header!");const r=e.readBits(8);if(r>=i.length)throw new $e(Se.Format,"Vorbis: Invalid residue number in mapping header!");this._submapFloor[t]=s[a],this._submapResidue[t]=i[r]}this._channelFloor=new Array(t),this._channelResidue=new Array(t);for(let e=0;e<t;e++)this._channelFloor[e]=this._submapFloor[h[e]],this._channelResidue[e]=this._submapResidue[h[e]];this._mdct=a}decodePacket(e,t,s){const i=t>>1,a=new Array(this._channelFloor.length),r=new Array(this._channelFloor.length);r.fill(!1);for(let n=0;n<this._channelFloor.length;n++)a[n]=this._channelFloor[n].unpack(e,t,n),r[n]=!a[n].executeChannel,s[n].fill(0,0,i);for(let e=0;e<this._couplingAngle.length;e++)(a[this._couplingAngle[e]].executeChannel||a[this._couplingMangitude[e]].executeChannel)&&(a[this._couplingAngle[e]].forceEnergy=!0,a[this._couplingMangitude[e]].forceEnergy=!0);for(let i=0;i<this._submapFloor.length;i++){for(let e=0;e<this._channelFloor.length;e++)this._submapFloor[i]===this._channelFloor[e]&&this._submapResidue[i]===this._channelResidue[e]||(a[e].forceNoEnergy=!0);this._submapResidue[i].decode(e,r,t,s)}for(let e=this._couplingAngle.length-1;e>=0;e--)if(a[this._couplingAngle[e]].executeChannel||a[this._couplingMangitude[e]].executeChannel){const t=s[this._couplingMangitude[e]],a=s[this._couplingAngle[e]];for(let e=0;e<i;e++){let s,i;const r=t[e],n=a[e];r>0?n>0?(s=r,i=r-n):(i=r,s=r+n):n>0?(s=r,i=r+n):(i=r,s=r-n),t[e]=s,a[e]=i}}for(let e=0;e<this._channelFloor.length;e++)a[e].executeChannel?(this._channelFloor[e].apply(a[e],t,s[e]),this._mdct.reverse(s[e],t)):s[e].fill(0,i,2*i)}}class Si{constructor(){this.packetStartIndex=0,this.packetTotalLength=0,this.packetValidLength=0}}class _i{constructor(){this.overlapInfo=new Si,this.windowIndex=0}}class wi{constructor(e=null){this.samplePosition=null,this.samplePosition=e}}class Bi{constructor(e,t,s,i,a){if(this._overlapInfo=null,this._channels=t,this._blockFlag=e.readBit(),0!==e.readBits(32))throw new $e(Se.Format,"Vorbis: Mode header had invalid window or transform type!");const r=e.readBits(8);if(r>=a.length)throw new $e(Se.Format,"Vorbis: Mode header had invalid mapping index!");this._mapping=a[r],this._blockFlag?(this._blockSize=i,this._windows=[Bi.calcWindow(s,i,s),Bi.calcWindow(i,i,s),Bi.calcWindow(s,i,i),Bi.calcWindow(i,i,i)],this._overlapInfo=[Bi.calcOverlap(s,i,s),Bi.calcOverlap(i,i,s),Bi.calcOverlap(s,i,i),Bi.calcOverlap(i,i,i)]):(this._blockSize=s,this._windows=[Bi.calcWindow(s,s,s)])}decode(e,t){const s=this.getPacketInfo(e);this._mapping.decodePacket(e,this._blockSize,t);const i=this._windows[s.windowIndex];for(let e=0;e<this._blockSize;e++)for(let s=0;s<this._channels;s++)t[s][e]*=i[e];return s.overlapInfo}getPacketInfo(e){const t=new _i;if(this._blockFlag){const s=e.readBit(),i=e.readBit();t.windowIndex=(s?1:0)+(i?2:0);const a=this._overlapInfo[t.windowIndex];t.overlapInfo.packetStartIndex=a.packetStartIndex,t.overlapInfo.packetValidLength=a.packetValidLength,t.overlapInfo.packetTotalLength=a.packetTotalLength}else t.windowIndex=0,t.overlapInfo.packetStartIndex=0,t.overlapInfo.packetValidLength=this._blockSize/2,t.overlapInfo.packetTotalLength=this._blockSize;return t}static calcWindow(e,t,s){const i=new Float32Array(t),a=e/2,r=s/2,n=t/4-a/2,o=t-t/4-r/2;for(let e=0;e<a;e++){let t=Math.sin((e+.5)/a*Bi.M_PI2);t*=t,i[n+e]=Math.sin(t*Bi.M_PI2)}for(let e=n+a;e<o;e++)i[e]=1;for(let e=0;e<r;e++){let t=Math.sin((r-e-.5)/r*Bi.M_PI2);t*=t,i[o+e]=Math.sin(t*Bi.M_PI2)}return i}static calcOverlap(e,t,s){const i=s/4,a=t/4-e/4,r=t/4*3+i,n=r-2*i,o=new Si;return o.packetStartIndex=a,o.packetValidLength=n,o.packetTotalLength=r,o}}Bi.M_PI2=1.57079632695;class ki{constructor(e){this._n=e,this._n2=e>>1,this._n4=this._n2>>1,this._n8=this._n4>>1,this._ld=si.ilog(e)-1,this._a=new Float32Array(this._n2),this._b=new Float32Array(this._n2),this._c=new Float32Array(this._n4);let t=0,s=0;for(;t<this._n4;++t,s+=2)this._a[s]=Math.cos(4*t*ki.M_PI/e),this._a[s+1]=-Math.sin(4*t*ki.M_PI/e),this._b[s]=.5*Math.cos((s+1)*ki.M_PI/e/2),this._b[s+1]=.5*Math.sin((s+1)*ki.M_PI/e/2);for(t=0,s=0;t<this._n8;++t,s+=2)this._c[s]=Math.cos(2*(s+1)*ki.M_PI/e),this._c[s+1]=-Math.sin(2*(s+1)*ki.M_PI/e);this._bitrev=new Uint16Array(this._n8);for(let e=0;e<this._n8;++e)this._bitrev[e]=nt.int32ToUint16(si.bitReverse(e,this._ld-3)<<2)}calcReverse(e){let t,s;const i=new Float32Array(this._n2);{let t=this._n2-2,s=0,a=0;const r=this._n2;for(;a!==r;)i[t+1]=e[a]*this._a[s]-e[a+2]*this._a[s+1],i[t]=e[a]*this._a[s+1]+e[a+2]*this._a[s],t-=2,s+=2,a+=4;for(a=this._n2-3;t>=0;)i[t+1]=-e[a+2]*this._a[s]- -e[a]*this._a[s+1],i[t]=-e[a+2]*this._a[s+1]+-e[a]*this._a[s],t-=2,s+=2,a-=4}t=e,s=i;{let e=this._n2-8,i=this._n4,a=0,r=this._n4,n=0;for(;e>=0;){let o,h;h=s[i+1]-s[a+1],o=s[i]-s[a],t[r+1]=s[i+1]+s[a+1],t[r]=s[i]+s[a],t[n+1]=h*this._a[e+4]-o*this._a[e+5],t[n]=o*this._a[e+4]+h*this._a[e+5],h=s[i+3]-s[a+3],o=s[i+2]-s[a+2],t[r+3]=s[i+3]+s[a+3],t[r+2]=s[i+2]+s[a+2],t[n+3]=h*this._a[e]-o*this._a[e+1],t[n+2]=o*this._a[e]+h*this._a[e+1],e-=8,r+=4,n+=4,i+=4,a+=4}}this.step3_iter0_loop(this._n>>4,t,this._n2-1-0*this._n4,-this._n8),this.step3_iter0_loop(this._n>>4,t,this._n2-1-1*this._n4,-this._n8),this.step3_inner_r_loop(this._n>>5,t,this._n2-1-0*this._n8,-(this._n>>4),16),this.step3_inner_r_loop(this._n>>5,t,this._n2-1-1*this._n8,-(this._n>>4),16),this.step3_inner_r_loop(this._n>>5,t,this._n2-1-2*this._n8,-(this._n>>4),16),this.step3_inner_r_loop(this._n>>5,t,this._n2-1-3*this._n8,-(this._n>>4),16);let a=2;for(;a<this._ld-3>>1;++a){const e=this._n>>a+2,s=e>>1,i=1<<a+1;for(let r=0;r<i;++r)this.step3_inner_r_loop(this._n>>a+4,t,this._n2-1-e*r,-s,1<<a+3)}for(;a<this._ld-6;++a){const e=this._n>>a+2,s=1<<a+3,i=e>>1,r=this._n>>a+6,n=1<<a+1;let o=this._n2-1,h=0;for(let a=r;a>0;--a)this.step3_inner_s_loop(n,t,o,-i,h,s,e),h+=4*s,o-=8}this.step3_inner_s_loop_ld654(this._n>>5,t,this._n2-1,this._n);{let e=0,i=this._n4-4,a=this._n2-4;for(;i>=0;){let r;r=this._bitrev[e],s[a+3]=t[r],s[a+2]=t[r+1],s[i+3]=t[r+2],s[i+2]=t[r+3],r=this._bitrev[e+1],s[a+1]=t[r],s[a]=t[r+1],s[i+1]=t[r+2],s[i]=t[r+3],i-=4,a-=4,e+=2}}{let e=0,t=0,i=this._n2-4;for(;t<i;){let a,r,n,o,h,l;a=s[t]-s[i+2],r=s[t+1]+s[i+3],n=this._c[e+1]*a+this._c[e]*r,o=this._c[e+1]*r-this._c[e]*a,h=s[t]+s[i+2],l=s[t+1]-s[i+3],s[t]=h+n,s[t+1]=l+o,s[i+2]=h-n,s[i+3]=o-l,a=s[t+2]-s[i],r=s[t+3]+s[i+1],n=this._c[e+3]*a+this._c[e+2]*r,o=this._c[e+3]*r-this._c[e+2]*a,h=s[t+2]+s[i],l=s[t+3]-s[i+1],s[t+2]=h+n,s[t+3]=l+o,s[i]=h-n,s[i+1]=o-l,e+=4,t+=4,i-=4}}{let t=this._n2-8,s=this._n2-8,a=0,r=this._n2-4,n=this._n2,o=this._n-4;for(;s>=0;){let h,l,c,d;d=i[s+6]*this._b[t+7]-i[s+7]*this._b[t+6],c=-i[s+6]*this._b[t+6]-i[s+7]*this._b[t+7],e[a]=d,e[r+3]=-d,e[n]=c,e[o+3]=c,l=i[s+4]*this._b[t+5]-i[s+5]*this._b[t+4],h=-i[s+4]*this._b[t+4]-i[s+5]*this._b[t+5],e[a+1]=l,e[r+2]=-l,e[n+1]=h,e[o+2]=h,d=i[s+2]*this._b[t+3]-i[s+3]*this._b[t+2],c=-i[s+2]*this._b[t+2]-i[s+3]*this._b[t+3],e[a+2]=d,e[r+1]=-d,e[n+2]=c,e[o+1]=c,l=i[s]*this._b[t+1]-i[s+1]*this._b[t],h=-i[s]*this._b[t]-i[s+1]*this._b[t+1],e[a+3]=l,e[r]=-l,e[n+3]=h,e[o]=h,t-=8,s-=8,a+=4,n+=4,r-=4,o-=4}}}step3_inner_r_loop(e,t,s,i,a){let r,n,o=s,h=o+i,l=0;for(let s=e>>2;s>0;--s)r=t[o]-t[h],n=t[o-1]-t[h-1],t[o]+=t[h],t[o-1]+=t[h-1],t[h]=r*this._a[l]-n*this._a[l+1],t[h-1]=n*this._a[l]+r*this._a[l+1],l+=a,r=t[o-2]-t[h-2],n=t[o-3]-t[h-3],t[o-2]+=t[h-2],t[o-3]+=t[h-3],t[h-2]=r*this._a[l]-n*this._a[l+1],t[h-3]=n*this._a[l]+r*this._a[l+1],l+=a,r=t[o-4]-t[h-4],n=t[o-5]-t[h-5],t[o-4]+=t[h-4],t[o-5]+=t[h-5],t[h-4]=r*this._a[l]-n*this._a[l+1],t[h-5]=n*this._a[l]+r*this._a[l+1],l+=a,r=t[o-6]-t[h-6],n=t[o-7]-t[h-7],t[o-6]+=t[h-6],t[o-7]+=t[h-7],t[h-6]=r*this._a[l]-n*this._a[l+1],t[h-7]=n*this._a[l]+r*this._a[l+1],l+=a,o-=8,h-=8}step3_iter0_loop(e,t,s,i){let a=s,r=a+i,n=0;for(let s=e>>2;s>0;--s){let e,s;e=t[a]-t[r],s=t[a-1]-t[r-1],t[a]+=t[r],t[a-1]+=t[r-1],t[r]=e*this._a[n]-s*this._a[n+1],t[r-1]=s*this._a[n]+e*this._a[n+1],n+=8,e=t[a-2]-t[r-2],s=t[a-3]-t[r-3],t[a-2]+=t[r-2],t[a-3]+=t[r-3],t[r-2]=e*this._a[n]-s*this._a[n+1],t[r-3]=s*this._a[n]+e*this._a[n+1],n+=8,e=t[a-4]-t[r-4],s=t[a-5]-t[r-5],t[a-4]+=t[r-4],t[a-5]+=t[r-5],t[r-4]=e*this._a[n]-s*this._a[n+1],t[r-5]=s*this._a[n]+e*this._a[n+1],n+=8,e=t[a-6]-t[r-6],s=t[a-7]-t[r-7],t[a-6]+=t[r-6],t[a-7]+=t[r-7],t[r-6]=e*this._a[n]-s*this._a[n+1],t[r-7]=s*this._a[n]+e*this._a[n+1],n+=8,a-=8,r-=8}}step3_inner_s_loop(e,t,s,i,a,r,n){const o=this._a[a],h=this._a[a+1],l=this._a[a+r],c=this._a[a+r+1],d=this._a[a+2*r],u=this._a[a+2*r+1],p=this._a[a+3*r],g=this._a[a+3*r+1];let m,f,y=s,b=y+i;for(let s=e;s>0;--s)m=t[y]-t[b],f=t[y-1]-t[b-1],t[y]+=t[b],t[y-1]+=t[b-1],t[b]=m*o-f*h,t[b-1]=f*o+m*h,m=t[y-2]-t[b-2],f=t[y-3]-t[b-3],t[y-2]+=t[b-2],t[y-3]+=t[b-3],t[b-2]=m*l-f*c,t[b-3]=f*l+m*c,m=t[y-4]-t[b-4],f=t[y-5]-t[b-5],t[y-4]+=t[b-4],t[y-5]+=t[b-5],t[b-4]=m*d-f*u,t[b-5]=f*d+m*u,m=t[y-6]-t[b-6],f=t[y-7]-t[b-7],t[y-6]+=t[b-6],t[y-7]+=t[b-7],t[b-6]=m*p-f*g,t[b-7]=f*p+m*g,y-=n,b-=n}step3_inner_s_loop_ld654(e,t,s,i){const a=i>>3,r=this._a[a];let n=s;const o=n-16*e;for(;n>o;){let e,s;e=t[n]-t[n-8],s=t[n-1]-t[n-9],t[n]+=t[n-8],t[n-1]+=t[n-9],t[n-8]=e,t[n-9]=s,e=t[n-2]-t[n-10],s=t[n-3]-t[n-11],t[n-2]+=t[n-10],t[n-3]+=t[n-11],t[n-10]=(e+s)*r,t[n-11]=(s-e)*r,e=t[n-12]-t[n-4],s=t[n-5]-t[n-13],t[n-4]+=t[n-12],t[n-5]+=t[n-13],t[n-12]=s,t[n-13]=e,e=t[n-14]-t[n-6],s=t[n-7]-t[n-15],t[n-6]+=t[n-14],t[n-7]+=t[n-15],t[n-14]=(e+s)*r,t[n-15]=(e-s)*r,this.iter_54(t,n),this.iter_54(t,n-8),n-=16}}iter_54(e,t){const s=e[t]-e[t-4],i=e[t]+e[t-4],a=e[t-2]+e[t-6],r=e[t-2]-e[t-6];e[t]=i+a,e[t-2]=i-a;const n=e[t-3]-e[t-7];e[t-4]=s+n,e[t-6]=s-n;const o=e[t-1]-e[t-5],h=e[t-1]+e[t-5],l=e[t-3]+e[t-7];e[t-1]=h+l,e[t-3]=h-l,e[t-5]=o-r,e[t-7]=o+r}}ki.M_PI=3.141592653589793;class Ti{constructor(){this._setupCache=new Map}reverse(e,t){let s;this._setupCache.has(t)?s=this._setupCache.get(t):(s=new ki(t),this._setupCache.set(t,s)),s.calcReverse(e)}}class Ni{constructor(e,t,s){this._packetIndex=0,this._stream=e,this._setup=t,this._packets=s,this._currentPosition=0,this._prevPacketBuf=null,this._prevPacketStart=0,this._prevPacketEnd=0,this._prevPacketStop=0,this._nextPacketBuf=null,this._eosFound=!1,this._hasPosition=!1,this._modeFieldBits=si.ilog(t.modes.length-1)}decode(){let e=new Float32Array(this._packets[this._packets.length-1].granulePosition*this._stream.audioChannels);const t=new Float32Array(.2*this._stream.audioSampleRate*this._stream.audioChannels);let s=0,i=0;for(;s=this.read(t,0,t.length),0!==s;){if(i+s>=e.length){const s=new Float32Array(e.length+t.length);s.set(e,0),e=s}e.set(t.subarray(0,s),i),i+=s}return e.subarray(0,i)}read(e,t,s){if(0===s)return 0;let i=t;const a=t+s;for(;i<a;){if(this._prevPacketStart===this._prevPacketEnd){if(this._eosFound){this._nextPacketBuf=null,this._prevPacketBuf=null;break}const e=this.readNextPacket((i-t)/this._stream.audioChannels);null===e&&(this._prevPacketEnd=this._prevPacketStop),null===e||null===e.samplePosition||this._hasPosition||(this._hasPosition=!0,this._currentPosition=e.samplePosition-(this._prevPacketEnd-this._prevPacketStart)-(i-t)/this._stream.audioChannels)}const s=Math.min((a-i)/this._stream.audioChannels,this._prevPacketEnd-this._prevPacketStart);s>0&&(i+=this.copyBuffer(e,i,s))}return s=i-t,this._currentPosition+=s/this._stream.audioChannels,s}copyBuffer(e,t,s){let i=t;for(;s>0;this._prevPacketStart++,s--)for(let t=0;t<this._stream.audioChannels;t++)e[i++]=this._prevPacketBuf[t][this._prevPacketStart];return i-t}readNextPacket(e){const t=this.decodeNextPacket();if(this._eosFound=this._eosFound||t.isEndOfStream,null==t.curPacket)return null;if(null!==t.samplePosition&&t.isEndOfStream){const s=this._currentPosition+e+t.validLen-t.startIndex,i=t.samplePosition-s;i<0&&(t.validLen+=i,t.validLen<0&&(t.validLen=0))}return this._prevPacketEnd>0?(Ni.overlapBuffers(this._prevPacketBuf,t.curPacket,this._prevPacketStart,this._prevPacketStop,t.startIndex,this._stream.audioChannels),this._prevPacketStart=t.startIndex):null==this._prevPacketBuf&&(this._prevPacketStart=t.validLen),this._nextPacketBuf=this._prevPacketBuf,this._prevPacketEnd=t.validLen,this._prevPacketStop=t.totalLen,this._prevPacketBuf=t.curPacket,new wi(t.samplePosition)}static overlapBuffers(e,t,s,i,a,r){for(;s<i;s++,a++)for(let i=0;i<r;i++)t[i][a]+=e[i][s]}decodeNextPacket(){const e=new xi;let t=null;if(this._packetIndex>=this._packets.length)e.isEndOfStream=!0;else{t=this._packets[this._packetIndex++];const s=new ei(ht.fromBuffer(t.packetData));if(e.isEndOfStream=t.isEndOfStream,!s.readBit()){const i=this._setup.modes[s.readBits(this._modeFieldBits)];if(null==this._nextPacketBuf){this._nextPacketBuf=new Array(this._stream.audioChannels);for(let e=0;e<this._stream.audioChannels;e++)this._nextPacketBuf[e]=new Float32Array(this._stream.blocksize1)}const a=i.decode(s,this._nextPacketBuf);return e.startIndex=a.packetStartIndex,e.validLen=a.packetValidLength,e.totalLen=a.packetTotalLength,e.samplePosition=t.granulePosition,e.curPacket=this._nextPacketBuf,e}}return e}}class xi{constructor(){this.curPacket=null,this.startIndex=0,this.validLen=0,this.totalLen=0,this.isEndOfStream=!1,this.samplePosition=null}}!function(e){e[e.IdentificationHeader=1]="IdentificationHeader",e[e.Comment=3]="Comment",e[e.SetupHeader=5]="SetupHeader"}(Wt||(Wt={}));class vi{constructor(e){this._packetIndex=-1,this._packets=e}read(){let e;for(;;){if(e=this.nextPacket(),null==e)return null;if(e.isBeginningOfStream){const t=this.readStream(e);if(null!=t)return t}}}nextPacket(){return this._packetIndex++,this._packetIndex<this._packets.length?this._packets[this._packetIndex]:null}readStream(e){const t=new Qs;if(!this.readIdentificationHeader(t,e))return null;if(!this.readComments(this.nextPacket()))return null;const s=new ti;if(!this.readSetupHeader(t,s,this.nextPacket()))return null;const i=[];let a;for(;a=this.nextPacket(),null!=a&&(i.push(a),!a.isEndOfStream););const r=new Ni(t,s,i);return t.samples=r.decode(),t}comonHeaderDecode(e,t){const s=new Uint8Array(7);if(t.read(s,0,s.length),s[0]!==e)return!1;for(let e=0;e<vi.VorbisHeaderMarker.length;e++)if(s[1+e]!==vi.VorbisHeaderMarker[e])return!1;return!0}comonHeaderDecodeBit(e,t){const s=t.readBytes(7);if(s[0]!==e)return!1;for(let e=0;e<vi.VorbisHeaderMarker.length;e++)if(s[1+e]!==vi.VorbisHeaderMarker[e])return!1;return!0}readIdentificationHeader(e,t){const s=ht.fromBuffer(t.packetData);if(!this.comonHeaderDecode(Wt.IdentificationHeader,s))return!1;if(0!==ot.readUInt32LE(s))return!1;if(e.audioChannels=s.readByte(),e.audioSampleRate=ot.readUInt32LE(s),e.audioChannels<=0||e.audioSampleRate<=0)return!1;e.bitrateMaximum=ot.readInt32LE(s),e.bitrateNominal=ot.readInt32LE(s),e.bitrateMinimum=ot.readInt32LE(s);const i=s.readByte();if(e.blocksize0=1<<(15&i),e.blocksize1=1<<(i>>4),e.blocksize0>e.blocksize1||!vi.isAllowedBlockSize(e.blocksize0)||!vi.isAllowedBlockSize(e.blocksize0))return!1;return 0!==s.readByte()}static isAllowedBlockSize(e){switch(e){case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:return!0;default:return!1}}readComments(e){if(null==e)return!1;const t=ht.fromBuffer(e.packetData);if(!this.comonHeaderDecode(Wt.Comment,t))return!1;const s=ot.readUInt32LE(t);t.skip(s);const i=ot.readUInt32LE(t);for(let e=0;e<i;e++){const e=ot.readUInt32LE(t);t.skip(e)}return 0!==t.readByte()}readSetupHeader(e,t,s){if(null==s)return!1;const i=new ei(ht.fromBuffer(s.packetData)),a=new Ti,r=new oi;if(!this.comonHeaderDecodeBit(Wt.SetupHeader,i))return!1;let n=i.readByte()+1;for(let e=0;e<n;e++)t.codebooks.push(new ri(i,r));n=i.readBits(6)+1;for(let e=0;e<n;e++)t.timeDomainTransforms.push(new hi(i));n=i.readBits(6)+1;for(let s=0;s<n;s++)t.floors.push(new pi(i,e.blocksize0,e.blocksize1,t.codebooks));n=i.readBits(6)+1;for(let s=0;s<n;s++)t.residues.push(new yi(i,e.audioChannels,t.codebooks));n=i.readBits(6)+1;for(let s=0;s<n;s++)t.mappings.push(new bi(i,e.audioChannels,t.floors,t.residues,a));n=i.readBits(6)+1;for(let s=0;s<n;s++)t.modes.push(new Bi(i,e.audioChannels,e.blocksize0,e.blocksize1,t.mappings));return!!i.readBit()}}vi.VorbisHeaderMarker=new Uint8Array(["v".charCodeAt(0),"o".charCodeAt(0),"r".charCodeAt(0),"b".charCodeAt(0),"i".charCodeAt(0),"s".charCodeAt(0)]);class Pi{constructor(e){this.streams=[];const t=new Ks(e).read(),s=new vi(t);for(;;){const e=s.read();if(null==e)break;this.streams.push(e)}}}class Fi{constructor(){this.phdrs=[],this.pbags=[],this.pmods=[],this.pgens=[],this.insts=[],this.ibags=[],this.imods=[],this.igens=[],this.sHdrs=[],this.sampleData=new Uint8Array(0),this._sampleCache=new Map}decodeSamples(e,t,s){const i=`${e}_${t}_${s}`;if(!this._sampleCache.has(i)){let a;const r=this.sampleData.slice(e,t);if(s){a=new Pi(ht.fromBuffer(r)).streams[0].samples}else{const e=new DataView(r.buffer,r.byteOffset,r.length);a=new Float32Array(r.length/2);for(let t=0;t<a.length;t++)a[t]=e.getInt16(2*t,!0)/32767}return this._sampleCache.set(i,a),a}return this._sampleCache.get(i)}load(e){const t=new qs,s=new qs;if(!qs.load(null,t,e)||"sfbk"!==t.id)throw new Ze("Soundfont is not a valid Soundfont2 file");for(;qs.load(t,s,e);){const t=new qs;if("pdta"===s.id)for(;qs.load(s,t,e);)switch(t.id){case"phdr":for(let s=0,i=t.size/Ai.SizeInFile|0;s<i;s++)this.phdrs.push(new Ai(e));break;case"pbag":for(let s=0,i=t.size/Mi.SizeInFile|0;s<i;s++)this.pbags.push(new Mi(e));break;case"pmod":for(let s=0,i=t.size/Ri.SizeInFile|0;s<i;s++)this.pmods.push(new Ri(e));break;case"pgen":for(let s=0,i=t.size/Ii.SizeInFile|0;s<i;s++)this.pgens.push(new Ii(e));break;case"inst":for(let s=0,i=t.size/Li.SizeInFile|0;s<i;s++)this.insts.push(new Li(e));break;case"ibag":for(let s=0,i=t.size/Ci.SizeInFile|0;s<i;s++)this.ibags.push(new Ci(e));break;case"imod":for(let s=0,i=t.size/Di.SizeInFile|0;s<i;s++)this.imods.push(new Di(e));break;case"igen":for(let s=0,i=t.size/Ei.SizeInFile|0;s<i;s++)this.igens.push(new Ei(e));break;case"shdr":for(let s=0,i=t.size/Oi.SizeInFile|0;s<i;s++)this.sHdrs.push(new Oi(e));break;default:e.position+=t.size}else if("sdta"===s.id)for(;qs.load(s,t,e);)if("smpl"===t.id)this.sampleData=new Uint8Array(t.size),e.read(this.sampleData,0,t.size);else e.position+=t.size;else e.position+=s.size}}}class Ci{constructor(e){this.instGenNdx=ot.readUInt16LE(e),this.instModNdx=ot.readUInt16LE(e)}}Ci.SizeInFile=4;class Di{constructor(e){this.modSrcOper=ot.readUInt16LE(e),this.modDestOper=ot.readUInt16LE(e),this.modAmount=ot.readInt16LE(e),this.modAmtSrcOper=ot.readUInt16LE(e),this.modTransOper=ot.readUInt16LE(e)}}Di.SizeInFile=10;class Ei{constructor(e){this.genOper=ot.readUInt16LE(e),this.genAmount=new Hi(e)}}Ei.SizeInFile=4;class Li{constructor(e){this.instName=ot.read8BitStringLength(e,20),this.instBagNdx=ot.readUInt16LE(e)}}Li.SizeInFile=22;class Mi{constructor(e){this.genNdx=ot.readUInt16LE(e),this.modNdx=ot.readUInt16LE(e)}}Mi.SizeInFile=4;class Ii{constructor(e){this.genOper=ot.readUInt16LE(e),this.genAmount=new Hi(e)}}Ii.SizeInFile=4,Ii.GenInstrument=41,Ii.GenKeyRange=43,Ii.GenVelRange=44,Ii.GenSampleId=53;class Ai{constructor(e){this.presetName=ot.read8BitStringLength(e,20),this.preset=ot.readUInt16LE(e),this.bank=ot.readUInt16LE(e),this.presetBagNdx=ot.readUInt16LE(e),this.library=ot.readUInt32LE(e),this.genre=ot.readUInt32LE(e),this.morphology=ot.readUInt32LE(e)}}Ai.SizeInFile=38;class Ri{constructor(e){this.modSrcOper=ot.readUInt16LE(e),this.modDestOper=ot.readUInt16LE(e),this.modAmount=ot.readUInt16LE(e),this.modAmtSrcOper=ot.readUInt16LE(e),this.modTransOper=ot.readUInt16LE(e)}}Ri.SizeInFile=10;class Oi{constructor(e){this.sampleName=ot.read8BitStringLength(e,20),this.start=ot.readUInt32LE(e),this.end=ot.readUInt32LE(e),this.startLoop=ot.readUInt32LE(e),this.endLoop=ot.readUInt32LE(e),this.sampleRate=ot.readUInt32LE(e),this.originalPitch=e.readByte(),this.pitchCorrection=ot.readSInt8(e),this.sampleLink=ot.readUInt16LE(e),this.sampleType=ot.readUInt16LE(e)}}Oi.SizeInFile=46;class Hi{get shortAmount(){return nt.uint16ToInt16(this.wordAmount)}get lowByteAmount(){return 255&this.wordAmount}get highByteAmount(){return(65280&this.wordAmount)>>8&255}constructor(e){this.wordAmount=ot.readUInt16LE(e)}}class Wi{constructor(){this.presetIndex=0,this.bank=0,this.pitchWheel=0,this.perNotePitchWheel=new Map,this.midiPan=0,this.midiVolume=0,this.midiExpression=0,this.midiRpn=0,this.midiData=0,this.panOffset=0,this.gainDb=0,this.pitchRange=0,this.tuning=0,this.mixVolume=0,this.mute=!1,this.solo=!1}}class Vi{constructor(){this.activeChannel=0,this.channelList=[]}setupVoice(e,t){const s=this.channelList[this.activeChannel],i=t.region.pan+s.panOffset;t.playingChannel=this.activeChannel,t.mixVolume=s.mixVolume,t.noteGainDb+=s.gainDb,t.updatePitchRatio(s,e.outSampleRate),i<=-.5?(t.panFactorLeft=1,t.panFactorRight=0):i>=.5?(t.panFactorLeft=0,t.panFactorRight=1):(t.panFactorLeft=Math.sqrt(.5-i),t.panFactorRight=Math.sqrt(.5+i))}}!function(e){e[e.None=0]="None",e[e.Continuous=1]="Continuous",e[e.Sustain=2]="Sustain"}(Vt||(Vt={})),function(e){e[e.StereoInterleaved=0]="StereoInterleaved",e[e.StereoUnweaved=1]="StereoUnweaved",e[e.Mono=2]="Mono"}(Gt||(Gt={}));class Gi{constructor(){this.name="",this.presetNumber=0,this.bank=0,this.regions=null}}class zi{static timecents2Secs(e){return Math.pow(2,e/1200)}static decibelsToGain(e){return e>-100?Math.pow(10,.05*e):0}static gainToDecibels(e){return e<=1e-5?-100:20*Math.log10(e)}static cents2Hertz(e){return 8.176*Math.pow(2,e/1200)}}class Ui{constructor(e){this.delay=0,this.attack=0,this.hold=0,this.decay=0,this.sustain=0,this.release=0,this.keynumToHold=0,this.keynumToDecay=0,e&&(this.delay=e.delay,this.attack=e.attack,this.hold=e.hold,this.decay=e.decay,this.sustain=e.sustain,this.release=e.release,this.keynumToHold=e.keynumToHold,this.keynumToDecay=e.keynumToDecay)}clear(){this.delay=0,this.attack=0,this.hold=0,this.decay=0,this.sustain=0,this.release=0,this.keynumToHold=0,this.keynumToDecay=0}envToSecs(e){this.delay=this.delay<-11950?0:zi.timecents2Secs(this.delay),this.attack=this.attack<-11950?0:zi.timecents2Secs(this.attack),this.release=this.release<-11950?0:zi.timecents2Secs(this.release),0===this.keynumToHold&&(this.hold=this.hold<-11950?0:zi.timecents2Secs(this.hold)),0===this.keynumToDecay&&(this.decay=this.decay<-11950?0:zi.timecents2Secs(this.decay)),this.sustain<0?this.sustain=0:this.sustain=e?zi.decibelsToGain(-this.sustain/10):1-this.sustain/1e3}}!function(e){e[e.StartAddrsOffset=0]="StartAddrsOffset",e[e.EndAddrsOffset=1]="EndAddrsOffset",e[e.StartloopAddrsOffset=2]="StartloopAddrsOffset",e[e.EndloopAddrsOffset=3]="EndloopAddrsOffset",e[e.StartAddrsCoarseOffset=4]="StartAddrsCoarseOffset",e[e.ModLfoToPitch=5]="ModLfoToPitch",e[e.VibLfoToPitch=6]="VibLfoToPitch",e[e.ModEnvToPitch=7]="ModEnvToPitch",e[e.InitialFilterFc=8]="InitialFilterFc",e[e.InitialFilterQ=9]="InitialFilterQ",e[e.ModLfoToFilterFc=10]="ModLfoToFilterFc",e[e.ModEnvToFilterFc=11]="ModEnvToFilterFc",e[e.EndAddrsCoarseOffset=12]="EndAddrsCoarseOffset",e[e.ModLfoToVolume=13]="ModLfoToVolume",e[e.Unused1=14]="Unused1",e[e.ChorusEffectsSend=15]="ChorusEffectsSend",e[e.ReverbEffectsSend=16]="ReverbEffectsSend",e[e.Pan=17]="Pan",e[e.Unused2=18]="Unused2",e[e.Unused3=19]="Unused3",e[e.Unused4=20]="Unused4",e[e.DelayModLFO=21]="DelayModLFO",e[e.FreqModLFO=22]="FreqModLFO",e[e.DelayVibLFO=23]="DelayVibLFO",e[e.FreqVibLFO=24]="FreqVibLFO",e[e.DelayModEnv=25]="DelayModEnv",e[e.AttackModEnv=26]="AttackModEnv",e[e.HoldModEnv=27]="HoldModEnv",e[e.DecayModEnv=28]="DecayModEnv",e[e.SustainModEnv=29]="SustainModEnv",e[e.ReleaseModEnv=30]="ReleaseModEnv",e[e.KeynumToModEnvHold=31]="KeynumToModEnvHold",e[e.KeynumToModEnvDecay=32]="KeynumToModEnvDecay",e[e.DelayVolEnv=33]="DelayVolEnv",e[e.AttackVolEnv=34]="AttackVolEnv",e[e.HoldVolEnv=35]="HoldVolEnv",e[e.DecayVolEnv=36]="DecayVolEnv",e[e.SustainVolEnv=37]="SustainVolEnv",e[e.ReleaseVolEnv=38]="ReleaseVolEnv",e[e.KeynumToVolEnvHold=39]="KeynumToVolEnvHold",e[e.KeynumToVolEnvDecay=40]="KeynumToVolEnvDecay",e[e.Instrument=41]="Instrument",e[e.Reserved1=42]="Reserved1",e[e.KeyRange=43]="KeyRange",e[e.VelRange=44]="VelRange",e[e.StartloopAddrsCoarseOffset=45]="StartloopAddrsCoarseOffset",e[e.Keynum=46]="Keynum",e[e.Velocity=47]="Velocity",e[e.InitialAttenuation=48]="InitialAttenuation",e[e.Reserved2=49]="Reserved2",e[e.EndloopAddrsCoarseOffset=50]="EndloopAddrsCoarseOffset",e[e.CoarseTune=51]="CoarseTune",e[e.FineTune=52]="FineTune",e[e.SampleID=53]="SampleID",e[e.SampleModes=54]="SampleModes",e[e.Reserved3=55]="Reserved3",e[e.ScaleTuning=56]="ScaleTuning",e[e.ExclusiveClass=57]="ExclusiveClass",e[e.OverridingRootKey=58]="OverridingRootKey",e[e.Unused5=59]="Unused5",e[e.EndOper=60]="EndOper"}(zt||(zt={}));class Xi{constructor(e){this.loopMode=Vt.None,this.samples=Xi.NoSamples,this.sampleRate=0,this.loKey=0,this.hiKey=0,this.loVel=0,this.hiVel=0,this.group=0,this.offset=0,this.end=0,this.loopStart=0,this.loopEnd=0,this.transpose=0,this.tune=0,this.pitchKeyCenter=0,this.pitchKeyTrack=0,this.attenuation=0,this.pan=0,this.ampEnv=new Ui,this.modEnv=new Ui,this.initialFilterQ=0,this.initialFilterFc=0,this.modEnvToPitch=0,this.modEnvToFilterFc=0,this.modLfoToFilterFc=0,this.modLfoToVolume=0,this.delayModLFO=0,this.freqModLFO=0,this.modLfoToPitch=0,this.delayVibLFO=0,this.freqVibLFO=0,this.vibLfoToPitch=0,e&&(this.loopMode=e.loopMode,this.samples=e.samples,this.sampleRate=e.sampleRate,this.loKey=e.loKey,this.hiKey=e.hiKey,this.loVel=e.loVel,this.hiVel=e.hiVel,this.group=e.group,this.offset=e.offset,this.end=e.end,this.loopStart=e.loopStart,this.loopEnd=e.loopEnd,this.transpose=e.transpose,this.tune=e.tune,this.pitchKeyCenter=e.pitchKeyCenter,this.pitchKeyTrack=e.pitchKeyTrack,this.attenuation=e.attenuation,this.pan=e.pan,this.ampEnv=new Ui(e.ampEnv),this.modEnv=new Ui(e.modEnv),this.initialFilterQ=e.initialFilterQ,this.initialFilterFc=e.initialFilterFc,this.modEnvToPitch=e.modEnvToPitch,this.modEnvToFilterFc=e.modEnvToFilterFc,this.modLfoToFilterFc=e.modLfoToFilterFc,this.modLfoToVolume=e.modLfoToVolume,this.delayModLFO=e.delayModLFO,this.freqModLFO=e.freqModLFO,this.modLfoToPitch=e.modLfoToPitch,this.delayVibLFO=e.delayVibLFO,this.freqVibLFO=e.freqVibLFO,this.vibLfoToPitch=e.vibLfoToPitch)}clear(e){this.loopMode=Vt.None,this.samples=Xi.NoSamples,this.sampleRate=0,this.loKey=0,this.hiKey=0,this.loVel=0,this.hiVel=0,this.group=0,this.offset=0,this.end=0,this.loopStart=0,this.loopEnd=0,this.transpose=0,this.tune=0,this.pitchKeyCenter=0,this.pitchKeyTrack=0,this.attenuation=0,this.pan=0,this.ampEnv.clear(),this.modEnv.clear(),this.initialFilterQ=0,this.initialFilterFc=0,this.modEnvToPitch=0,this.modEnvToFilterFc=0,this.modLfoToFilterFc=0,this.modLfoToVolume=0,this.delayModLFO=0,this.freqModLFO=0,this.modLfoToPitch=0,this.delayVibLFO=0,this.freqVibLFO=0,this.vibLfoToPitch=0,this.hiKey=127,this.hiVel=127,this.pitchKeyCenter=60,e||(this.pitchKeyTrack=100,this.pitchKeyCenter=-1,this.ampEnv.delay=-12e3,this.ampEnv.attack=-12e3,this.ampEnv.hold=-12e3,this.ampEnv.decay=-12e3,this.ampEnv.release=-12e3,this.modEnv.delay=-12e3,this.modEnv.attack=-12e3,this.modEnv.hold=-12e3,this.modEnv.decay=-12e3,this.modEnv.release=-12e3,this.initialFilterFc=13500,this.delayModLFO=-12e3,this.delayVibLFO=-12e3)}operator(e,t){switch(e){case zt.StartAddrsOffset:this.offset+=nt.int16ToUint32(t.shortAmount);break;case zt.EndAddrsOffset:this.end+=nt.int16ToUint32(t.shortAmount);break;case zt.StartloopAddrsOffset:this.loopStart+=nt.int16ToUint32(t.shortAmount);break;case zt.EndloopAddrsOffset:this.loopEnd+=nt.int16ToUint32(t.shortAmount);break;case zt.StartAddrsCoarseOffset:this.offset+=32768*nt.int16ToUint32(t.shortAmount);break;case zt.ModLfoToPitch:this.modLfoToPitch=t.shortAmount;break;case zt.VibLfoToPitch:this.vibLfoToPitch=t.shortAmount;break;case zt.ModEnvToPitch:this.modEnvToPitch=t.shortAmount;break;case zt.InitialFilterFc:this.initialFilterFc=t.shortAmount;break;case zt.InitialFilterQ:this.initialFilterQ=t.shortAmount;break;case zt.ModLfoToFilterFc:this.modLfoToFilterFc=t.shortAmount;break;case zt.ModEnvToFilterFc:this.modEnvToFilterFc=t.shortAmount;break;case zt.EndAddrsCoarseOffset:this.end+=32768*nt.int16ToUint32(t.shortAmount);break;case zt.ModLfoToVolume:this.modLfoToVolume=t.shortAmount;break;case zt.Pan:this.pan=t.shortAmount/1e3;break;case zt.DelayModLFO:this.delayModLFO=t.shortAmount;break;case zt.FreqModLFO:this.freqModLFO=t.shortAmount;break;case zt.DelayVibLFO:this.delayVibLFO=t.shortAmount;break;case zt.FreqVibLFO:this.freqVibLFO=t.shortAmount;break;case zt.DelayModEnv:this.modEnv.delay=t.shortAmount;break;case zt.AttackModEnv:this.modEnv.attack=t.shortAmount;break;case zt.HoldModEnv:this.modEnv.hold=t.shortAmount;break;case zt.DecayModEnv:this.modEnv.decay=t.shortAmount;break;case zt.SustainModEnv:this.modEnv.sustain=t.shortAmount;break;case zt.ReleaseModEnv:this.modEnv.release=t.shortAmount;break;case zt.KeynumToModEnvHold:this.modEnv.keynumToHold=t.shortAmount;break;case zt.KeynumToModEnvDecay:this.modEnv.keynumToDecay=t.shortAmount;break;case zt.DelayVolEnv:this.ampEnv.delay=t.shortAmount;break;case zt.AttackVolEnv:this.ampEnv.attack=t.shortAmount;break;case zt.HoldVolEnv:this.ampEnv.hold=t.shortAmount;break;case zt.DecayVolEnv:this.ampEnv.decay=t.shortAmount;break;case zt.SustainVolEnv:this.ampEnv.sustain=t.shortAmount;break;case zt.ReleaseVolEnv:this.ampEnv.release=t.shortAmount;break;case zt.KeynumToVolEnvHold:this.ampEnv.keynumToHold=t.shortAmount;break;case zt.KeynumToVolEnvDecay:this.ampEnv.keynumToDecay=t.shortAmount;break;case zt.KeyRange:this.loKey=t.lowByteAmount,this.hiKey=t.highByteAmount;break;case zt.VelRange:this.loVel=t.lowByteAmount,this.hiVel=t.highByteAmount;break;case zt.StartloopAddrsCoarseOffset:this.loopStart+=32768*nt.int16ToUint32(t.shortAmount);break;case zt.InitialAttenuation:this.attenuation+=.1*t.shortAmount;break;case zt.EndloopAddrsCoarseOffset:this.loopEnd+=32768*nt.int16ToUint32(t.shortAmount);break;case zt.CoarseTune:this.transpose+=t.shortAmount;break;case zt.FineTune:this.tune+=t.shortAmount;break;case zt.SampleModes:this.loopMode=3&~t.wordAmount?1==(3&t.wordAmount)?Vt.Continuous:Vt.None:Vt.Sustain;break;case zt.ScaleTuning:this.pitchKeyTrack=t.shortAmount;break;case zt.ExclusiveClass:this.group=t.wordAmount;break;case zt.OverridingRootKey:this.pitchKeyCenter=t.shortAmount}}}Xi.NoSamples=new Float32Array(0),function(e){e[e.None=0]="None",e[e.Delay=1]="Delay",e[e.Attack=2]="Attack",e[e.Hold=3]="Hold",e[e.Decay=4]="Decay",e[e.Sustain=5]="Sustain",e[e.Release=6]="Release",e[e.Done=7]="Done"}(Ut||(Ut={}));class Ji{constructor(){this.level=0,this.slope=0,this.samplesUntilNextSegment=0,this.segment=Ut.None,this.midiVelocity=0,this.parameters=null,this.segmentIsExponential=!1,this.isAmpEnv=!1}nextSegment(e,t){if(this.parameters)for(;;)switch(e){case Ut.None:if(this.samplesUntilNextSegment=this.parameters.delay*t|0,this.samplesUntilNextSegment>0)return this.segment=Ut.Delay,this.segmentIsExponential=!1,this.level=0,void(this.slope=0);e=Ut.Delay;break;case Ut.Delay:if(this.samplesUntilNextSegment=this.parameters.attack*t|0,this.samplesUntilNextSegment>0)return this.isAmpEnv||(this.samplesUntilNextSegment=this.parameters.attack*((145-this.midiVelocity)/144)*t|0),this.segment=Ut.Attack,this.segmentIsExponential=!1,this.level=0,void(this.slope=1/this.samplesUntilNextSegment);e=Ut.Attack;break;case Ut.Attack:if(this.samplesUntilNextSegment=this.parameters.hold*t|0,this.samplesUntilNextSegment>0)return this.segment=Ut.Hold,this.segmentIsExponential=!1,this.level=1,void(this.slope=0);e=Ut.Hold;break;case Ut.Hold:if(this.samplesUntilNextSegment=this.parameters.decay*t|0,this.samplesUntilNextSegment>0){if(this.segment=Ut.Decay,this.level=1,this.isAmpEnv){const e=-9.226/this.samplesUntilNextSegment;this.slope=Math.exp(e),this.segmentIsExponential=!0,this.parameters.sustain>0&&(this.samplesUntilNextSegment=Math.log(this.parameters.sustain)/e|0)}else this.slope=-1/this.samplesUntilNextSegment,this.samplesUntilNextSegment=this.parameters.decay*(1-this.parameters.sustain)*t|0,this.segmentIsExponential=!1;return}e=Ut.Decay;break;case Ut.Decay:return this.segment=Ut.Sustain,this.level=this.parameters.sustain,this.slope=0,this.samplesUntilNextSegment=2147483647,void(this.segmentIsExponential=!1);case Ut.Sustain:if(this.segment=Ut.Release,this.samplesUntilNextSegment=(this.parameters.release<=0?Ji.FastReleaseTime:this.parameters.release)*t|0,this.isAmpEnv){const e=-9.226/this.samplesUntilNextSegment;this.slope=Math.exp(e),this.segmentIsExponential=!0}else this.slope=-this.level/this.samplesUntilNextSegment,this.segmentIsExponential=!1;return;default:return this.segment=Ut.Done,this.segmentIsExponential=!1,this.level=0,this.slope=0,void(this.samplesUntilNextSegment=134217727)}}setup(e,t,s,i,a){this.parameters=new Ui(e),this.parameters.keynumToHold>0&&(this.parameters.hold+=this.parameters.keynumToHold*(60-t),this.parameters.hold=this.parameters.hold<-1e4?0:zi.timecents2Secs(this.parameters.hold)),this.parameters.keynumToDecay>0&&(this.parameters.decay+=this.parameters.keynumToDecay*(60-t),this.parameters.decay=this.parameters.decay<-1e4?0:zi.timecents2Secs(this.parameters.decay)),this.midiVelocity=0|s,this.isAmpEnv=i,this.nextSegment(Ut.None,a)}process(e,t){this.slope>0&&(this.segmentIsExponential?this.level*=Math.pow(this.slope,e):this.level+=this.slope*e),this.samplesUntilNextSegment-=e,this.samplesUntilNextSegment<=0&&this.nextSegment(this.segment,t)}}Ji.FastReleaseTime=.01;class Yi{constructor(){this.samplesUntil=0,this.level=0,this.delta=0}setup(e,t,s){this.samplesUntil=e*s|0,this.delta=4*zi.cents2Hertz(t)/s,this.level=0}process(e){this.samplesUntil>e?this.samplesUntil-=e:(this.level+=this.delta*e,this.level>1?(this.delta=-this.delta,this.level=2-this.level):this.level<-1&&(this.delta=-this.delta,this.level=-2-this.level))}}class $i{constructor(e){this.qInv=0,this.a0=0,this.a1=0,this.b1=0,this.b2=0,this.z1=0,this.z2=0,this.active=!1,e&&(this.qInv=e.qInv,this.a0=e.a0,this.a1=e.a1,this.b1=e.b1,this.b2=e.b2,this.z1=e.z1,this.z2=e.z2,this.active=e.active)}setup(e){const t=Math.tan(Math.PI*e),s=t*t,i=1/(1+t*this.qInv+s);this.a0=s*i,this.a1=2*this.a0,this.b1=2*(s-1)*i,this.b2=(1-t*this.qInv+s)*i}process(e){const t=e*this.a0+this.z1;return this.z1=e*this.a1+this.z2-this.b1*t,this.z2=e*this.a0-this.b2*t,t}}class qi{constructor(){this.playingPreset=0,this.playingKey=0,this.playingChannel=0,this.region=null,this.pitchInputTimecents=0,this.pitchOutputFactor=0,this.sourceSamplePosition=0,this.noteGainDb=0,this.panFactorLeft=0,this.panFactorRight=0,this.playIndex=0,this.loopStart=0,this.loopEnd=0,this.ampEnv=new Ji,this.modEnv=new Ji,this.lowPass=new $i,this.modLfo=new Yi,this.vibLfo=new Yi,this.mixVolume=0,this.mute=!1}updatePitchRatio(e,t){let s=e.pitchWheel;e.perNotePitchWheel.has(this.playingKey)&&(s+=e.perNotePitchWheel.get(this.playingKey)-8192);const i=8192===s?e.tuning:s/16383*e.pitchRange*2-e.pitchRange+e.tuning;this.calcPitchRatio(i,t)}calcPitchRatio(e,t){if(!this.region)return;const s=this.playingKey+this.region.transpose+this.region.tune/100;let i=this.region.pitchKeyCenter+(s-this.region.pitchKeyCenter)*(this.region.pitchKeyTrack/100);0!==e&&(i+=e),this.pitchInputTimecents=100*i,this.pitchOutputFactor=this.region.sampleRate/(zi.timecents2Secs(100*this.region.pitchKeyCenter)*t)}end(e){this.region&&(this.ampEnv.nextSegment(Ut.Sustain,e),this.modEnv.nextSegment(Ut.Sustain,e),this.region.loopMode===Vt.Sustain&&(this.loopEnd=this.loopStart))}endQuick(e){this.ampEnv.parameters.release=0,this.ampEnv.nextSegment(Ut.Sustain,e),this.modEnv.parameters.release=0,this.modEnv.nextSegment(Ut.Sustain,e)}render(e,t,s,i,a){if(!this.region)return;const r=this.region,n=r.samples;let o=0,h=e.outputMode===Gt.StereoUnweaved?i:-1;const l=0!==r.modEnvToPitch||0!==r.modEnvToFilterFc,c=this.modLfo.delta>0&&(0!==r.modLfoToPitch||0!==r.modLfoToFilterFc||0!==r.modLfoToVolume),d=this.vibLfo.delta>0&&0!==r.vibLfoToPitch,u=this.loopStart<this.loopEnd,p=this.loopStart,g=this.loopEnd,m=r.end,f=g+1;let y=this.sourceSamplePosition;const b=new $i(this.lowPass),S=0!==r.modLfoToFilterFc||0!==r.modEnvToFilterFc;let _=0,w=0,B=0,k=0;const T=0!==r.modLfoToPitch||0!==r.modEnvToPitch||0!==r.vibLfoToPitch;let N=0,x=0,v=0,P=0;const F=0!==r.modLfoToVolume;let C=0,D=0;for(S?(_=e.outSampleRate,w=r.initialFilterFc,B=r.modLfoToFilterFc,k=r.modEnvToFilterFc):(_=0,w=0,B=0,k=0),T?(N=0,x=r.modLfoToPitch,v=r.vibLfoToPitch,P=r.modEnvToPitch):(N=zi.timecents2Secs(this.pitchInputTimecents)*this.pitchOutputFactor,x=0,v=0,P=0),F?D=.1*r.modLfoToVolume:(C=zi.decibelsToGain(this.noteGainDb),D=0);i>0;){let r,E,L=0,M=i>qi.RenderEffectSampleBlock?qi.RenderEffectSampleBlock:i;if(i-=M,S){const e=w+this.modLfo.level*B+this.modEnv.level*k;b.active=e<=13500,b.active&&b.setup(zi.cents2Hertz(e)/_)}switch(T&&(N=zi.timecents2Secs(this.pitchInputTimecents+(this.modLfo.level*x+this.vibLfo.level*v+this.modEnv.level*P))*this.pitchOutputFactor),F&&(C=zi.decibelsToGain(this.noteGainDb+this.modLfo.level*D)),r=C*this.ampEnv.level,a?r=0:r*=this.mixVolume,this.ampEnv.process(M,e.outSampleRate),l&&this.modEnv.process(M,e.outSampleRate),c&&this.modLfo.process(M),d&&this.vibLfo.process(M),e.outputMode){case Gt.StereoInterleaved:for(E=r*this.panFactorLeft,L=r*this.panFactorRight;M-- >0&&y<m;){const e=0|y,i=e>=g&&u?p:e+1,a=y-e;let r=n[e]*(1-a)+n[i]*a;b.active&&(r=b.process(r)),t[s+o]+=r*E,o++,t[s+o]+=r*L,o++,y+=N,y>=f&&u&&(y-=g-p+1)}break;case Gt.StereoUnweaved:for(E=r*this.panFactorLeft,L=r*this.panFactorRight;M-- >0&&y<m;){const e=0|y,i=e>=g&&u?p:e+1,a=y-e;let r=n[e]*(1-a)+n[i]*a;b.active&&(r=b.process(r)),t[s+o]+=r*E,o++,t[s+h]+=r*L,h++,y+=N,y>=f&&u&&(y-=g-p+1)}break;case Gt.Mono:for(;M-- >0&&y<m;){const e=0|y,i=e>=g&&u?p:e+1,a=y-e;let h=n[e]*(1-a)+n[i]*a;b.active&&(h=b.process(h)),t[s+o]=h*r,o++,y+=N,y>=f&&u&&(y-=g-p+1)}}if(y>=m||this.ampEnv.segment===Ut.Done)return void this.kill()}this.sourceSamplePosition=y,(b.active||S)&&(this.lowPass=b)}kill(){this.playingPreset=-1}}qi.RenderEffectSampleBlock=K.MicroBufferSize;class ji{constructor(){this._items=[],this._position=0,this.isEmpty=!0}clear(){this._items=[],this._position=0,this.isEmpty=!0}enqueue(e){this.isEmpty=!1,this._items.push(e)}peek(){return this._items[this._position]}dequeue(){const e=this._items[this._position];return this._position++,this._position>=this._items.length/2&&(this._items=this._items.slice(this._position),this._position=0),this.isEmpty=0===this._items.length,e}toArray(){const e=this._items.slice(this._position);return e.reverse(),e}}!function(e){e[e.BankSelectCoarse=0]="BankSelectCoarse",e[e.ModulationCoarse=1]="ModulationCoarse",e[e.DataEntryCoarse=6]="DataEntryCoarse",e[e.VolumeCoarse=7]="VolumeCoarse",e[e.PanCoarse=10]="PanCoarse",e[e.ExpressionControllerCoarse=11]="ExpressionControllerCoarse",e[e.BankSelectFine=32]="BankSelectFine",e[e.ModulationFine=33]="ModulationFine",e[e.DataEntryFine=38]="DataEntryFine",e[e.VolumeFine=39]="VolumeFine",e[e.PanFine=42]="PanFine",e[e.ExpressionControllerFine=43]="ExpressionControllerFine",e[e.HoldPedal=64]="HoldPedal",e[e.LegatoPedal=68]="LegatoPedal",e[e.NonRegisteredParameterFine=98]="NonRegisteredParameterFine",e[e.NonRegisteredParameterCourse=99]="NonRegisteredParameterCourse",e[e.RegisteredParameterFine=100]="RegisteredParameterFine",e[e.RegisteredParameterCourse=101]="RegisteredParameterCourse",e[e.AllSoundOff=120]="AllSoundOff",e[e.ResetControllers=121]="ResetControllers",e[e.AllNotesOff=123]="AllNotesOff"}(Xt||(Xt={}));class Ki{constructor(e){this._midiEventQueue=new ji,this._mutedChannels=new Map,this._soloChannels=new Map,this._isAnySolo=!1,this._transpositionPitches=new Map,this._liveTranspositionPitches=new Map,this.currentTempo=0,this.timeSignatureNumerator=0,this.timeSignatureDenominator=0,this.presets=null,this._voices=[],this._channels=null,this._voicePlayIndex=0,this.outputMode=Gt.StereoInterleaved,this.outSampleRate=0,this.globalGainDb=0,this.outSampleRate=e}synthesize(e,t,s){return this.fillWorkingBuffer(e,t,s)}synthesizeSilent(e){this.fillWorkingBuffer(null,0,e)}channelGetMixVolume(e){return this._channels&&e<this._channels.channelList.length?this._channels.channelList[e].mixVolume:1}channelSetMixVolume(e,t){const s=this.channelInit(e);for(const s of this._voices)s.playingChannel===e&&-1!==s.playingPreset&&(s.mixVolume=t);s.mixVolume=t}channelSetMute(e,t){t?this._mutedChannels.set(e,!0):this._mutedChannels.delete(e)}channelSetSolo(e,t){t?this._soloChannels.set(e,!0):this._soloChannels.delete(e),this._isAnySolo=this._soloChannels.size>0}resetChannelStates(){this._mutedChannels=new Map,this._soloChannels=new Map,this._liveTranspositionPitches=new Map,this.applyTranspositionPitches(new Map),this._isAnySolo=!1}setChannelTranspositionPitch(e,t){let s=0;this._liveTranspositionPitches.has(e)&&(s=this._liveTranspositionPitches.get(e)),0===t?this._liveTranspositionPitches.delete(e):this._liveTranspositionPitches.set(e,t);for(const i of this._voices)if(i.playingChannel===e&&9!==i.playingChannel){let e=0;e-=s,e+=t,i.playingKey+=e,this._channels&&i.updatePitchRatio(this._channels.channelList[i.playingChannel],this.outSampleRate)}}applyTranspositionPitches(e){const t=this._transpositionPitches;for(const s of this._voices)if(s.playingChannel>=0&&9!==s.playingChannel){let i=0;t.has(s.playingChannel)&&(i-=t.get(s.playingChannel)),e.has(s.playingChannel)&&(i+=e.get(s.playingChannel)),s.playingKey+=i,this._channels&&s.updatePitchRatio(this._channels.channelList[s.playingChannel],this.outSampleRate)}this._transpositionPitches=e}dispatchEvent(e){this._midiEventQueue.enqueue(e)}fillWorkingBuffer(e,t,s){const i=this._isAnySolo,a=[];for(;!this._midiEventQueue.isEmpty;){const e=this._midiEventQueue.dequeue();e.isMetronome&&this.metronomeVolume>0?(this.channelNoteOff(K.MetronomeChannel,K.MetronomeKey),this.channelNoteOn(K.MetronomeChannel,K.MetronomeKey,95/127)):e.event&&this.processMidiMessage(e.event),a.push(e)}for(const a of this._voices)if(-1!==a.playingPreset){const r=a.playingChannel,n=this._mutedChannels.has(r)||i&&r!==K.MetronomeChannel&&!this._soloChannels.has(r);e?a.render(this,e,t,s,n):a.kill()}return a}processMidiMessage(e){q.debug("Midi",`Processing Midi message ${Rt[e.type]}/${e.tick}`);switch(e.type){case Rt.TimeSignature:const t=e;this.timeSignatureNumerator=t.numerator,this.timeSignatureDenominator=Math.pow(2,t.denominatorIndex);break;case Rt.NoteOn:const s=e;this.channelNoteOn(s.channel,s.noteKey,s.noteVelocity/127);break;case Rt.NoteOff:const i=e;this.channelNoteOff(i.channel,i.noteKey);break;case Rt.ControlChange:const a=e;this.channelMidiControl(a.channel,a.controller,a.value);break;case Rt.ProgramChange:const r=e;this.channelSetPresetNumber(r.channel,r.program,9===r.channel);break;case Rt.TempoChange:const n=e;this.currentTempo=6e7/n.microSecondsPerQuarterNote;break;case Rt.PitchBend:const o=e;this.channelSetPitchWheel(o.channel,o.value);break;case Rt.PerNotePitchBend:const h=e;let l=h.value;l=l*K.MaxPitchWheel/K.MaxPitchWheel20,this.channelSetPerNotePitchWheel(h.channel,h.noteKey,l)}}get metronomeVolume(){return this.channelGetMixVolume(K.MetronomeChannel)}set metronomeVolume(e){this.setupMetronomeChannel(e)}setupMetronomeChannel(e){this.channelSetMixVolume(K.MetronomeChannel,e),e>0&&(this.channelSetVolume(K.MetronomeChannel,1),this.channelSetPresetNumber(K.MetronomeChannel,0,!0))}get masterVolume(){return zi.decibelsToGain(this.globalGainDb)}set masterVolume(e){const t=zi.gainToDecibels(e),s=t-this.globalGainDb;if(0!==s){for(const e of this._voices)-1!==e.playingPreset&&(e.noteGainDb+=s);this.globalGainDb=t}}resetSoft(){for(const e of this._voices)-1!==e.playingPreset&&(e.ampEnv.segment<Ut.Release||0!==e.ampEnv.parameters.release)&&e.endQuick(this.outSampleRate);if(this._channels)for(const e of this._channels.channelList)e.presetIndex=0,e.bank=0,e.pitchWheel=8192,e.midiPan=8192,e.perNotePitchWheel.clear(),e.midiVolume=16383,e.midiExpression=16383,e.midiRpn=65535,e.midiData=0,e.panOffset=0,e.gainDb=0,e.pitchRange=2,e.tuning=0}get presetCount(){return this.presets?.length??0}reset(){for(const e of this._voices)-1!==e.playingPreset&&(e.ampEnv.segment<Ut.Release||0!==e.ampEnv.parameters.release)&&e.endQuick(this.outSampleRate);this._channels=null}setOutput(e,t,s){this.outputMode=e,this.outSampleRate=t>=1?t:44100,this.globalGainDb=s}noteOn(e,t,s){if(!this.presets)return;const i=127*s|0;if(e<0||e>=this.presets.length)return;if(s<=0)return void this.noteOff(e,t);const a=this._voicePlayIndex++;for(const r of this.presets[e].regions){if(t<r.loKey||t>r.hiKey||i<r.loVel||i>r.hiVel)continue;let n=null;if(0!==r.group)for(const t of this._voices)t.playingPreset===e&&t.region.group===r.group?t.endQuick(this.outSampleRate):-1!==t.playingPreset||n||(n=t);else for(const e of this._voices)-1===e.playingPreset&&(n=e);if(!n){for(let e=0;e<4;e++){const e=new qi;e.playingPreset=-1,this._voices.push(e)}n=this._voices[this._voices.length-4]}n.region=r,n.playingPreset=e,n.playingKey=t,n.playIndex=a,n.noteGainDb=this.globalGainDb-r.attenuation-zi.gainToDecibels(1/s),this._channels?this._channels.setupVoice(this,n):(n.calcPitchRatio(0,this.outSampleRate),n.panFactorLeft=Math.sqrt(.5-r.pan),n.panFactorRight=Math.sqrt(.5+r.pan)),n.sourceSamplePosition=r.offset;const o=r.loopMode!==Vt.None&&r.loopStart<r.loopEnd;n.loopStart=o?r.loopStart:0,n.loopEnd=o?r.loopEnd:0,n.ampEnv.setup(r.ampEnv,t,i,!0,this.outSampleRate),n.modEnv.setup(r.modEnv,t,i,!1,this.outSampleRate);const h=r.initialFilterQ/10;n.lowPass.qInv=1/Math.pow(10,h/20),n.lowPass.z1=0,n.lowPass.z2=0,n.lowPass.active=r.initialFilterFc<=13500,n.lowPass.active&&n.lowPass.setup(zi.cents2Hertz(r.initialFilterFc)/this.outSampleRate),n.modLfo.setup(r.delayModLFO,r.freqModLFO,this.outSampleRate),n.vibLfo.setup(r.delayVibLFO,r.freqVibLFO,this.outSampleRate)}}bankNoteOn(e,t,s,i){const a=this.getPresetIndex(e,t);return-1!==a&&(this.noteOn(a,s,i),!0)}noteOff(e,t){let s=null,i=null;const a=[];for(const r of this._voices)r.playingPreset!==e||r.playingKey!==t||r.ampEnv.segment>=Ut.Release||(!s||r.playIndex<s.playIndex?(s=r,i=r,a.push(r)):r.playIndex===s.playIndex&&(i=r,a.push(r)));if(s)for(const r of a)r!==s&&r!==i&&(r.playIndex!==s.playIndex||r.playingPreset!==e||r.playingKey!==t||r.ampEnv.segment>=Ut.Release)||r.end(this.outSampleRate)}bankNoteOff(e,t,s){const i=this.getPresetIndex(e,t);return-1!==i&&(this.noteOff(i,s),!0)}noteOffAll(e){for(const t of this._voices)-1!==t.playingPreset&&(e?t.endQuick(this.outSampleRate):t.ampEnv.segment<Ut.Release&&t.end(this.outSampleRate))}get activeVoiceCount(){let e=0;for(const t of this._voices)-1!==t.playingPreset&&e++;return e}channelInit(e){if(this._channels&&e<this._channels.channelList.length)return this._channels.channelList[e];this._channels||(this._channels=new Vi);for(let t=this._channels.channelList.length;t<=e;t++){const e=new Wi;e.presetIndex=0,e.bank=0,e.pitchWheel=8192,e.midiPan=8192,e.midiVolume=16383,e.midiExpression=16383,e.midiRpn=65535,e.midiData=0,e.panOffset=0,e.gainDb=0,e.pitchRange=2,e.tuning=0,e.mixVolume=1,this._channels.channelList.push(e)}return this._channels.channelList[e]}getPresetIndex(e,t){if(!this.presets)return-1;for(let s=this.presets.length-1;s>=0;s--){const i=this.presets[s];if(i.presetNumber===t&&i.bank===e)return s}return-1}getPresetName(e){return this.presets?e<0||e>=this.presets.length?null:this.presets[e].name:null}bankGetPresetName(e,t){return this.getPresetName(this.getPresetIndex(e,t))}channelNoteOn(e,t,s){!this._channels||e>this._channels.channelList.length||(this._transpositionPitches.has(e)&&(t+=this._transpositionPitches.get(e)),this._liveTranspositionPitches.has(e)&&(t+=this._liveTranspositionPitches.get(e)),this._channels.activeChannel=e,this.noteOn(this._channels.channelList[e].presetIndex,t,s))}channelNoteOff(e,t){this._transpositionPitches.has(e)&&(t+=this._transpositionPitches.get(e)),this._liveTranspositionPitches.has(e)&&(t+=this._liveTranspositionPitches.get(e));const s=[];let i=null,a=null;for(const r of this._voices)-1===r.playingPreset||r.playingChannel!==e||r.playingKey!==t||r.ampEnv.segment>=Ut.Release||(!i||r.playIndex<i.playIndex?(i=r,a=r,s.push(r)):r.playIndex===i.playIndex&&(a=r,s.push(r)));if(this.channelInit(e).perNotePitchWheel.delete(t),i)for(const r of s)r!==i&&r!==a&&(r.playIndex!==i.playIndex||-1===r.playingPreset||r.playingChannel!==e||r.playingKey!==t||r.ampEnv.segment>=Ut.Release)||r.end(this.outSampleRate)}channelNoteOffAll(e){this.channelInit(e).perNotePitchWheel.clear();for(const t of this._voices)-1!==t.playingPreset&&t.playingChannel===e&&t.ampEnv.segment<Ut.Release&&t.end(this.outSampleRate)}channelSoundsOffAll(e){this.channelInit(e).perNotePitchWheel.clear();for(const t of this._voices)-1!==t.playingPreset&&t.playingChannel===e&&(t.ampEnv.segment<Ut.Release||0===t.ampEnv.parameters.release)&&t.endQuick(this.outSampleRate)}channelSetPresetIndex(e,t){this.channelInit(e).presetIndex=nt.int32ToUint16(t)}channelSetPresetNumber(e,t,s=!1){const i=this.channelInit(e);let a=0;return s?(a=this.getPresetIndex(128|32767&i.bank,t),-1===a&&(a=this.getPresetIndex(128,t)),-1===a&&(a=this.getPresetIndex(128,0)),-1===a&&(a=this.getPresetIndex(2047&i.bank,t))):a=this.getPresetIndex(2047&i.bank,t),i.presetIndex=a,-1!==a}channelSetBank(e,t){this.channelInit(e).bank=nt.int32ToUint16(t)}channelSetBankPreset(e,t,s){const i=this.channelInit(e),a=this.getPresetIndex(t,s);return-1!==a&&(i.presetIndex=nt.int32ToUint16(a),i.bank=nt.int32ToUint16(t),!0)}channelSetPan(e,t){for(const s of this._voices)if(s.playingChannel===e&&-1!==s.playingPreset){const e=s.region.pan+t-.5;e<=-.5?(s.panFactorLeft=1,s.panFactorRight=0):e>=.5?(s.panFactorLeft=0,s.panFactorRight=1):(s.panFactorLeft=Math.sqrt(.5-e),s.panFactorRight=Math.sqrt(.5+e))}this.channelInit(e).panOffset=t-.5}channelSetVolume(e,t){const s=this.channelInit(e),i=zi.gainToDecibels(t),a=i-s.gainDb;if(0!==a){for(const t of this._voices)t.playingChannel===e&&-1!==t.playingPreset&&(t.noteGainDb+=a);s.gainDb=i}}channelSetPitchWheel(e,t){const s=this.channelInit(e);s.pitchWheel!==t&&(s.pitchWheel=nt.int32ToUint16(t),this.channelApplyPitch(e,s))}channelSetPerNotePitchWheel(e,t,s){this._transpositionPitches.has(e)&&(t+=this._transpositionPitches.get(e)),this._liveTranspositionPitches.has(e)&&(t+=this._liveTranspositionPitches.get(e));const i=this.channelInit(e);i.perNotePitchWheel.has(t)&&i.perNotePitchWheel.get(t)===s||(i.perNotePitchWheel.set(t,s),this.channelApplyPitch(e,i,t))}channelApplyPitch(e,t,s=-1){for(const i of this._voices)i.playingChannel!==e||-1===i.playingPreset||-1!==s&&i.playingKey!==s||i.updatePitchRatio(t,this.outSampleRate)}channelSetPitchRange(e,t){const s=this.channelInit(e);s.pitchRange!==t&&(s.pitchRange=t,8192!==s.pitchWheel&&this.channelApplyPitch(e,s))}channelSetTuning(e,t){const s=this.channelInit(e);s.tuning!==t&&(s.tuning=t,this.channelApplyPitch(e,s))}channelMidiControl(e,t,s){const i=this.channelInit(e);switch(t){case Xt.DataEntryFine:return i.midiData=nt.int32ToUint16(16256&i.midiData|s),void(0===i.midiRpn?this.channelSetPitchRange(e,(i.midiData>>7)+.01*(127&i.midiData)):1===i.midiRpn?this.channelSetTuning(e,(0|i.tuning)+(i.midiData-8192)/8192):2===i.midiRpn&&this.channelSetTuning(e,s-64+(i.tuning-(0|i.tuning))));case Xt.VolumeCoarse:return i.midiVolume=nt.int32ToUint16(127&i.midiVolume|s<<7),void this.channelSetVolume(e,Math.pow(i.midiVolume/16383*(i.midiExpression/16383),3));case Xt.VolumeFine:return i.midiVolume=nt.int32ToUint16(16256&i.midiVolume|s),void this.channelSetVolume(e,Math.pow(i.midiVolume/16383*(i.midiExpression/16383),3));case Xt.ExpressionControllerCoarse:return i.midiExpression=nt.int32ToUint16(127&i.midiExpression|s<<7),void this.channelSetVolume(e,Math.pow(i.midiVolume/16383*(i.midiExpression/16383),3));case Xt.ExpressionControllerFine:return i.midiExpression=nt.int32ToUint16(16256&i.midiExpression|s),void this.channelSetVolume(e,Math.pow(i.midiVolume/16383*(i.midiExpression/16383),3));case Xt.PanCoarse:return i.midiPan=nt.int32ToUint16(127&i.midiPan|s<<7),void this.channelSetPan(e,i.midiPan/16383);case Xt.PanFine:return i.midiPan=nt.int32ToUint16(16256&i.midiPan|s),void this.channelSetPan(e,i.midiPan/16383);case Xt.DataEntryCoarse:return i.midiData=nt.int32ToUint16(127&i.midiData|s<<7),void(0===i.midiRpn?this.channelSetPitchRange(e,(i.midiData>>7)+.01*(127&i.midiData)):1===i.midiRpn?this.channelSetTuning(e,(0|i.tuning)+(i.midiData-8192)/8192):2===i.midiRpn&&t===Xt.DataEntryCoarse&&this.channelSetTuning(e,s-64+(i.tuning-(0|i.tuning))));case Xt.BankSelectCoarse:return void(i.bank=nt.int32ToUint16(32768|s));case Xt.BankSelectFine:return void(i.bank=nt.int32ToUint16((32768&i.bank?(127&i.bank)<<7:0)|s));case Xt.RegisteredParameterCourse:return void(i.midiRpn=nt.int32ToUint16(127&(65535===i.midiRpn?0:i.midiRpn)|s<<7));case Xt.RegisteredParameterFine:return void(i.midiRpn=nt.int32ToUint16(16256&(65535===i.midiRpn?0:i.midiRpn)|s));case Xt.NonRegisteredParameterFine:case Xt.NonRegisteredParameterCourse:return void(i.midiRpn=65535);case Xt.AllSoundOff:return void this.channelSoundsOffAll(e);case Xt.AllNotesOff:return void this.channelNoteOffAll(e);case Xt.ResetControllers:return i.midiVolume=16383,i.midiExpression=16383,i.midiPan=8192,i.bank=0,this.channelSetVolume(e,1),this.channelSetPan(e,.5),void this.channelSetPitchRange(e,2)}}channelGetPresetIndex(e){return this._channels&&e<this._channels.channelList.length?this._channels.channelList[e].presetIndex:0}channelGetPresetBank(e){return this._channels&&e<this._channels.channelList.length?32767&this._channels.channelList[e].bank:0}channelGetPan(e){return this._channels&&e<this._channels.channelList.length?this._channels.channelList[e].panOffset-.5:.5}channelGetVolume(e){return this._channels&&e<this._channels.channelList.length?zi.decibelsToGain(this._channels.channelList[e].gainDb):1}channelGetPitchWheel(e){return this._channels&&e<this._channels.channelList.length?this._channels.channelList[e].pitchWheel:8192}channelGetPitchRange(e){return this._channels&&e<this._channels.channelList.length?this._channels.channelList[e].pitchRange:2}channelGetTuning(e){return this._channels&&e<this._channels.channelList.length?this._channels.channelList[e].tuning:0}resetPresets(){this.presets=[]}loadPresets(e,t,s,i){const a=[];for(let i=0;i<e.phdrs.length-1;i++){const r=e.phdrs[i];let n=0;const o=new Gi;a.push(o),o.name=r.presetName,o.bank=r.bank,o.presetNumber=r.preset;let h=0;for(let t=r.presetBagNdx;t<e.phdrs[i+1].presetBagNdx;t++){let s=0,i=127,a=0,r=127;for(let n=e.pbags[t].genNdx;n<e.pbags[t+1].genNdx;n++){const t=e.pgens[n];if(t.genOper===Ii.GenKeyRange){s=t.genAmount.lowByteAmount,i=t.genAmount.highByteAmount;continue}if(t.genOper===Ii.GenVelRange){a=t.genAmount.lowByteAmount,r=t.genAmount.highByteAmount;continue}if(t.genOper!==Ii.GenInstrument)continue;if(t.genAmount.wordAmount>=e.insts.length)continue;for(let n=e.insts[t.genAmount.wordAmount].instBagNdx;n<e.insts[t.genAmount.wordAmount+1].instBagNdx;n++){let t=0,o=127,l=0,c=127;for(let d=e.ibags[n].instGenNdx;d<e.ibags[n+1].instGenNdx;d++){const n=e.igens[d];n.genOper!==Ii.GenKeyRange?n.genOper!==Ii.GenVelRange?53===n.genOper&&o>=s&&t<=i&&c>=a&&l<=r&&h++:(l=n.genAmount.lowByteAmount,c=n.genAmount.highByteAmount):(t=n.genAmount.lowByteAmount,o=n.genAmount.highByteAmount)}}}}o.regions=new Array(h);let l=new Xi;l.clear(!0);for(let a=r.presetBagNdx;a<e.phdrs[i+1].presetBagNdx;a++){const i=e.pbags[a],h=new Xi(l);let c=!1;for(let l=i.genNdx;l<e.pbags[a+1].genNdx;l++){const i=e.pgens[l];if(i.genOper===Ii.GenInstrument){const a=i.genAmount.wordAmount;if(a>=e.insts.length)continue;let l=new Xi;l.clear(!1);const d=e.insts[a];for(let i=d.instBagNdx;i<e.insts[a+1].instBagNdx;i++){const a=e.ibags[i],c=new Xi(l);let u=!1;for(let l=a.instGenNdx;l<e.ibags[i+1].instGenNdx;l++){const i=e.igens[l];if(i.genOper===Ii.GenSampleId){if(c.hiKey<h.loKey||c.loKey>h.hiKey)continue;if(c.hiVel<h.loVel||c.loVel>h.hiVel)continue;h.loKey>c.loKey&&(c.loKey=h.loKey),h.hiKey<c.hiKey&&(c.hiKey=h.hiKey),h.loVel>c.loVel&&(c.loVel=h.loVel),h.hiVel<c.hiVel&&(c.hiVel=h.hiVel),c.offset+=h.offset,c.end+=h.end,c.loopStart+=h.loopStart,c.loopEnd+=h.loopEnd,c.transpose+=h.transpose,c.tune+=h.tune,c.pitchKeyTrack+=h.pitchKeyTrack,c.attenuation+=h.attenuation,c.pan+=h.pan,c.ampEnv.delay+=h.ampEnv.delay,c.ampEnv.attack+=h.ampEnv.attack,c.ampEnv.hold+=h.ampEnv.hold,c.ampEnv.decay+=h.ampEnv.decay,c.ampEnv.sustain+=h.ampEnv.sustain,c.ampEnv.release+=h.ampEnv.release,c.modEnv.delay+=h.modEnv.delay,c.modEnv.attack+=h.modEnv.attack,c.modEnv.hold+=h.modEnv.hold,c.modEnv.decay+=h.modEnv.decay,c.modEnv.sustain+=h.modEnv.sustain,c.modEnv.release+=h.modEnv.release,c.initialFilterQ+=h.initialFilterQ,c.initialFilterFc+=h.initialFilterFc,c.modEnvToPitch+=h.modEnvToPitch,c.modEnvToFilterFc+=h.modEnvToFilterFc,c.delayModLFO+=h.delayModLFO,c.freqModLFO+=h.freqModLFO,c.modLfoToPitch+=h.modLfoToPitch,c.modLfoToFilterFc+=h.modLfoToFilterFc,c.modLfoToVolume+=h.modLfoToVolume,c.delayVibLFO+=h.delayVibLFO,c.freqVibLFO+=h.freqVibLFO,c.vibLfoToPitch+=h.vibLfoToPitch,c.ampEnv.envToSecs(!0),c.modEnv.envToSecs(!1),c.delayModLFO=c.delayModLFO<-11950?0:zi.timecents2Secs(c.delayModLFO),c.delayVibLFO=c.delayVibLFO<-11950?0:zi.timecents2Secs(c.delayVibLFO),c.pan<-.5?c.pan=-.5:c.pan>.5&&(c.pan=.5),(c.initialFilterQ<1500||c.initialFilterQ>13500)&&(c.initialFilterQ=0);const a=e.sHdrs[i.genAmount.wordAmount];c.offset+=a.start,c.end+=a.end,c.loopStart+=a.startLoop,c.loopEnd+=a.endLoop,a.endLoop>0&&(c.loopEnd-=1),-1===c.pitchKeyCenter&&(c.pitchKeyCenter=a.originalPitch),c.tune+=a.pitchCorrection,c.sampleRate=a.sampleRate;const l=r.bank===K.PercussionBank;if(l&&Ki.setContainsRange(s,c.loKey,c.hiKey)||!l&&t.has(r.preset))if(1&a.sampleType){q.debug("AlphaSynth",`Loading of used sample ${a.sampleName} for preset ${r.presetName} (bank ${o.bank} program ${o.presetNumber})`);!!(16&a.sampleType)?c.samples=e.decodeSamples(a.start,a.end,!0):(c.samples=e.decodeSamples(2*c.offset,2*c.end,!1),c.loopStart>0&&(c.loopStart-=c.offset),c.loopEnd>0&&(c.loopEnd-=c.offset)),c.offset=0,c.end=c.samples.length-1}else q.warning("AlphaSynth",`Skipping load of unsupported sample ${a.sampleName} for preset ${r.presetName}, sample type ${a.sampleType} is not supported (bank ${o.bank} program ${o.presetNumber})`),c.samples=new Float32Array(0);else q.debug("AlphaSynth",`Skipping load of unused sample ${a.sampleName} for preset ${r.presetName} (bank ${o.bank} program ${o.presetNumber})`),c.samples=new Float32Array(0);o.regions[n]=new Xi(c),n++,u=!0}else c.operator(i.genOper,i.genAmount)}a!==e.ibags[d.instBagNdx]||u||(l=new Xi(c))}c=!0}else h.operator(i.genOper,i.genAmount)}i!==e.pbags[r.presetBagNdx]||c||(l=h)}}if(i&&this.presets)for(const e of a)this.presets.push(e);else this.presets=a}static setContainsRange(e,t,s){for(let i=t;i<=s;i++)if(e.has(i))return!0;return!1}hasSamplesForProgram(e){const t=this.presets;if(!t)return!1;for(const s of t)if(s.presetNumber===e)for(const e of s.regions)if(e.samples.length>0)return!0;return!1}hasSamplesForPercussion(e){const t=this.presets;if(!t)return!1;for(const s of t)if(s.bank===K.PercussionBank)for(const t of s.regions)if(t.loKey>=e&&t.hiKey<=e&&t.samples.length>0)return!0;return!1}}class Qi{constructor(){this._listeners=[]}on(e){this._listeners.push(e)}off(e){this._listeners=this._listeners.filter((t=>t!==e))}trigger(){for(const e of this._listeners)e()}}class Zi{constructor(){this._listeners=[]}on(e){this._listeners.push(e)}off(e){this._listeners=this._listeners.filter((t=>t!==e))}trigger(e){for(const t of this._listeners)t(e)}}class ea{constructor(e){this.events=e}}class ta{constructor(e){this.playbackRange=e}}class sa{get output(){return this._output}get isReadyForPlayback(){return this.isReady&&this._isSoundFontLoaded&&this._isMidiLoaded}get logLevel(){return q.logLevel}set logLevel(e){q.logLevel=e}get masterVolume(){return this._synthesizer.masterVolume}set masterVolume(e){e=Math.max(e,K.MinVolume),this._synthesizer.masterVolume=e}get metronomeVolume(){return this._metronomeVolume}set metronomeVolume(e){e=Math.max(e,K.MinVolume),this._metronomeVolume=e,this._synthesizer.metronomeVolume=e}get countInVolume(){return this._countInVolume}set countInVolume(e){e=Math.max(e,K.MinVolume),this._countInVolume=e}get midiEventsPlayedFilter(){return Array.from(this._midiEventsPlayedFilter)}set midiEventsPlayedFilter(e){this._midiEventsPlayedFilter=new Set(e)}get playbackSpeed(){return this._sequencer.playbackSpeed}set playbackSpeed(e){e=ie.clamp(e,K.MinPlaybackSpeed,K.MaxPlaybackSpeed);const t=this._sequencer.playbackSpeed;this._sequencer.playbackSpeed=e,this.timePosition=this.timePosition*(t/e)}get tickPosition(){return this._tickPosition}set tickPosition(e){this.timePosition=this._sequencer.mainTickPositionToTimePosition(e)}get timePosition(){return this._timePosition}set timePosition(e){q.debug("AlphaSynth",`Seeking to position ${e}ms (main)`),this._sequencer.mainSeek(e),this.updateTimePosition(e,!0),this._sequencer.isPlayingMain&&(this._notPlayedSamples=0,this.output.resetSamples())}get playbackRange(){return this._sequencer.mainPlaybackRange}set playbackRange(e){this._sequencer.mainPlaybackRange=e,e&&(this.tickPosition=e.startTick),this.playbackRangeChanged.trigger(new ta(e))}get isLooping(){return this._sequencer.isLooping}set isLooping(e){this._sequencer.isLooping=e}destroy(){q.debug("AlphaSynth","Destroying player"),this.stop(),this.output.destroy()}constructor(e,t){this._isSoundFontLoaded=!1,this._isMidiLoaded=!1,this._tickPosition=0,this._timePosition=0,this._metronomeVolume=0,this._countInVolume=0,this._playedEventsQueue=new ji,this._midiEventsPlayedFilter=new Set,this._notPlayedSamples=0,this._synthStopping=!1,this.isReady=!1,this.state=Ot.Paused,this._loadedSoundFonts=[],this.ready=new Qi,this.readyForPlayback=new Qi,this.finished=new Qi,this.soundFontLoaded=new Qi,this.soundFontLoadFailed=new Zi,this.midiLoaded=new Zi,this.midiLoadFailed=new Zi,this.stateChanged=new Zi,this.positionChanged=new Zi,this.midiEventsPlayed=new Zi,this.playbackRangeChanged=new Zi,q.debug("AlphaSynth","Initializing player"),this.state=Ot.Paused,q.debug("AlphaSynth","Creating output"),this._output=e,q.debug("AlphaSynth","Creating synthesizer"),this._synthesizer=new Ki(this.output.sampleRate),this._sequencer=new Js(this._synthesizer),q.debug("AlphaSynth","Opening output"),this.output.ready.on((()=>{this.isReady=!0,this.ready.trigger(),this.checkReadyForPlayback()})),this.output.sampleRequest.on((()=>{if(this.state===Ot.Playing&&(!this._sequencer.isFinished||this._synthesizer.activeVoiceCount>0)){let e=new Float32Array(K.MicroBufferSize*K.MicroBufferCount*K.AudioChannels),t=0;for(let s=0;s<K.MicroBufferCount;s++){this._sequencer.fillMidiEventQueue();const s=this._synthesizer.synthesize(e,t,K.MicroBufferSize);t+=K.MicroBufferSize*K.AudioChannels;for(const e of s)this._midiEventsPlayedFilter.has(e.event.type)&&this._playedEventsQueue.enqueue(e);if(this._sequencer.isFinished)break}t<e.length&&(e=e.subarray(0,t)),this._notPlayedSamples+=e.length,this.output.addSamples(e)}else{const e=new Float32Array(0);this.output.addSamples(e)}})),this.output.samplesPlayed.on(this.onSamplesPlayed.bind(this)),this.output.open(t)}play(){return!(this.state!==Ot.Paused||!this._isMidiLoaded)&&(this.output.activate(),this.playInternal(),this._countInVolume>0&&(q.debug("AlphaSynth","Starting countin"),this._sequencer.startCountIn(),this._synthesizer.setupMetronomeChannel(this._countInVolume),this.updateTimePosition(0,!0)),this.output.play(),!0)}playInternal(){this._sequencer.isPlayingOneTimeMidi&&(q.debug("AlphaSynth","Cancelling one time midi"),this.stopOneTimeMidi()),q.debug("AlphaSynth","Starting playback"),this._synthesizer.setupMetronomeChannel(this.metronomeVolume),this._synthStopping=!1,this.state=Ot.Playing,this.stateChanged.trigger(new Ys(this.state,!1))}pause(){this.state!==Ot.Paused&&this._isMidiLoaded&&(q.debug("AlphaSynth","Pausing playback"),this.state=Ot.Paused,this.stateChanged.trigger(new Ys(this.state,!1)),this.output.pause(),this._synthesizer.noteOffAll(!1))}playPause(){this.state===Ot.Paused&&this._isMidiLoaded?this.play():this.pause()}stop(){this._isMidiLoaded&&(q.debug("AlphaSynth","Stopping playback"),this.state=Ot.Paused,this.output.pause(),this._notPlayedSamples=0,this._sequencer.stop(),this._synthesizer.noteOffAll(!0),this.tickPosition=this._sequencer.mainPlaybackRange?this._sequencer.mainPlaybackRange.startTick:0,this.stateChanged.trigger(new Ys(this.state,!0)))}playOneTimeMidiFile(e){this._sequencer.isPlayingOneTimeMidi?this.stopOneTimeMidi():this.pause(),this._sequencer.loadOneTimeMidi(e),this._synthesizer.noteOffAll(!0),this.updateTimePosition(0,!0),this._notPlayedSamples=0,this.output.resetSamples(),this.output.play()}resetSoundFonts(){this.stop(),this._synthesizer.resetPresets(),this._loadedSoundFonts=[],this._isSoundFontLoaded=!1,this.soundFontLoaded.trigger()}loadSoundFont(e,t){this.pause();const s=ht.fromBuffer(e);try{q.debug("AlphaSynth","Loading soundfont from bytes");const e=new Fi;e.load(s),t||(this._loadedSoundFonts=[]),this._loadedSoundFonts.push(e),this._isSoundFontLoaded=!0,this.soundFontLoaded.trigger(),q.debug("AlphaSynth","soundFont successfully loaded"),this.checkReadyForPlayback()}catch(e){q.error("AlphaSynth",`Could not load soundfont from bytes ${e}`),this.soundFontLoadFailed.trigger(e)}}checkReadyForPlayback(){if(this.isReadyForPlayback){this._synthesizer.setupMetronomeChannel(this.metronomeVolume);const e=this._sequencer.instrumentPrograms,t=this._sequencer.percussionKeys;let s=!1;for(const i of this._loadedSoundFonts)this._synthesizer.loadPresets(i,e,t,s),s=!0;this.readyForPlayback.trigger()}}loadMidiFile(e){this.stop();try{q.debug("AlphaSynth","Loading midi from model"),this._sequencer.loadMidi(e),this._isMidiLoaded=!0,this.midiLoaded.trigger(new $s(0,this._sequencer.currentEndTime,0,this._sequencer.currentEndTick,!1)),q.debug("AlphaSynth","Midi successfully loaded"),this.checkReadyForPlayback(),this.tickPosition=0}catch(e){q.error("AlphaSynth",`Could not load midi from model ${e}`),this.midiLoadFailed.trigger(e)}}applyTranspositionPitches(e){this._synthesizer.applyTranspositionPitches(e)}setChannelTranspositionPitch(e,t){this._synthesizer.setChannelTranspositionPitch(e,t)}setChannelMute(e,t){this._synthesizer.channelSetMute(e,t)}resetChannelStates(){this._synthesizer.resetChannelStates()}setChannelSolo(e,t){this._synthesizer.channelSetSolo(e,t)}setChannelVolume(e,t){t=Math.max(t,K.MinVolume),this._synthesizer.channelSetMixVolume(e,t)}onSamplesPlayed(e){if(0===e)return;const t=e/this._synthesizer.outSampleRate*1e3;this._notPlayedSamples-=e*K.AudioChannels,this.updateTimePosition(this._timePosition+t,!1),this.checkForFinish()}checkForFinish(){let e=0,t=0;this.playbackRange&&this._sequencer.isPlayingMain?(e=this.playbackRange.startTick,t=this.playbackRange.endTick):t=this._sequencer.currentEndTick,this._tickPosition>=t&&this._notPlayedSamples<=0&&(this._notPlayedSamples=0,this._sequencer.isPlayingCountIn?(q.debug("AlphaSynth","Finished playback (count-in)"),this._sequencer.resetCountIn(),this.timePosition=this._sequencer.currentTime,this.playInternal(),this.output.resetSamples()):this._sequencer.isPlayingOneTimeMidi?(q.debug("AlphaSynth","Finished playback (one time)"),this.output.resetSamples(),this.state=Ot.Paused,this.stopOneTimeMidi()):this.isLooping?(q.debug("AlphaSynth","Finished playback (main looping)"),this.finished.trigger(),this.tickPosition=e,this._synthStopping=!1):this._synthesizer.activeVoiceCount>0?this._synthStopping||(this._synthesizer.noteOffAll(!0),this._synthStopping=!0):(this._synthStopping=!1,q.debug("AlphaSynth","Finished playback (main)"),this.finished.trigger(),this.stop()))}stopOneTimeMidi(){this.output.pause(),this._synthesizer.noteOffAll(!0),this._sequencer.resetOneTimeMidi(),this.timePosition=this._sequencer.currentTime}updateTimePosition(e,t){let s=e;this._timePosition=s;let i=this._sequencer.currentTimePositionToTickPosition(s);this._tickPosition=i;const a=this._sequencer.currentEndTime,r=this._sequencer.currentEndTick;s>a&&(s=a,i=r);const n=this._sequencer.isPlayingMain?"main":this._sequencer.isPlayingCountIn?"count-in":"one-time";if(q.debug("AlphaSynth",`Position changed: (time: ${s}/${a}, tick: ${i}/${r}, Active Voices: ${this._synthesizer.activeVoiceCount} (${n})`),this._sequencer.isPlayingMain&&this.positionChanged.trigger(new $s(s,a,i,r,t)),t)this._playedEventsQueue.clear();else{const e=new ji;for(;!this._playedEventsQueue.isEmpty&&this._playedEventsQueue.peek().time<s;){const t=this._playedEventsQueue.dequeue();e.enqueue(t.event)}e.isEmpty||this.midiEventsPlayed.trigger(new ea(e.toArray()))}}hasSamplesForProgram(e){return this._synthesizer.hasSamplesForProgram(e)}hasSamplesForPercussion(e){return this._synthesizer.hasSamplesForPercussion(e)}}class ia{static parseEnum(e,t){switch(typeof e){case"string":const s=Number.parseInt(e);return Number.isNaN(s)?t[Object.keys(t).find((t=>t.toLowerCase()===e.toLowerCase()))]:s;case"number":return e;case"undefined":case"object":return}throw new $e(Se.Format,`Could not parse enum value '${e}'`)}static forEach(e,t){if(e instanceof Map)e.forEach(t);else if("object"==typeof e)for(const s in e)t(e[s],s)}static getValue(e,t){return e instanceof Map?e.get(t):"object"==typeof e?e[t]:null}}class aa{constructor(e,t,s){this.text=e,this.startPos=t,this.endPos=s}}class ra{constructor(e){this.style="normal",this.variant="normal",this.weight="normal",this.stretch="normal",this.lineHeight="normal",this.size="1rem",this.families=[],this.parseOnlyFamilies=!1,this._currentTokenIndex=-1,this._input="",this._currentToken=null,this._input=e,this._tokens=this.splitToTokens(e)}splitToTokens(e){const t=[];let s=0;for(;s<e.length;){let i=s;for(;i<e.length&&" "!==e.charAt(i);)i++;i>s&&t.push(new aa(e.substring(s,i),s,i)),s=i+1}return t}parse(){if(this.reset(),1===this._tokens.length)switch(this._currentToken?.text){case"caption":case"icon":case"menu":case"message-box":case"small-caption":case"status-bar":case"inherit":return}this.parseOnlyFamilies||(this.fontStyleVariantWeight(),this.fontSizeLineHeight()),this.fontFamily()}static parseFamilies(e){const t=new ra(e);return t.parseOnlyFamilies=!0,t.parse(),t.families}fontFamily(){if(!this._currentToken){if(this.parseOnlyFamilies)return;throw new Error("Missing font list")}const e=this._input.substr(this._currentToken.startPos).trim();let t=0;for(;t<e.length;){const s=e.charAt(t);if(" "===s||","===s)t++;else if('"'===s||"'"===s){const i=this.findEndOfQuote(e,t+1,s);this.families.push(e.substring(t+1,i).split(`\\${s}`).join(s)),t=i+1}else{const s=this.findEndOfQuote(e,t+1,",");this.families.push(e.substring(t,s).trim()),t=s+1}}}findEndOfQuote(e,t,s){let i=!1;for(;t<e.length;){const a=e.charAt(t);if(!i&&a===s)return t;i=!i&&"\\"===a,t+=1}return e.length}fontSizeLineHeight(){if(!this._currentToken)throw new Error("Missing font size");const e=this._currentToken.text.split("/");if(e.length>=3)throw new Error(`Invalid font size '${this._currentToken}' specified`);if(this.nextToken(),e.length>=2)if("/"===e[1]){if(!this._currentToken)throw new Error("Missing line-height after font size");this.lineHeight=this._currentToken.text,this.nextToken()}else this.size=e[0],this.lineHeight=e[1];else{if(!(e.length>=1))throw new Error("Missing font size");if(this.size=e[0],this._currentToken&&0===this._currentToken.text.indexOf("/"))if("/"===this._currentToken.text){if(this.nextToken(),!this._currentToken)throw new Error("Missing line-height after font size");this.lineHeight=this._currentToken.text,this.nextToken()}else this.lineHeight=this._currentToken.text.substr(1),this.nextToken()}}nextToken(){this._currentTokenIndex++,this._currentTokenIndex<this._tokens.length?this._currentToken=this._tokens[this._currentTokenIndex]:this._currentToken=null}fontStyleVariantWeight(){let e=!1,t=!1,s=!1,i=3;const a=[];for(;;){if(!this._currentToken)return;const r=this._currentToken.text;switch(r){case"normal":case"inherit":a.push(r),i--,this.nextToken();break;case"italic":case"oblique":this.style=r,e=!0,i--,this.nextToken();break;case"small-caps":this.variant=r,t=!0,i--,this.nextToken();break;case"bold":case"bolder":case"lighter":case"100":case"200":case"300":case"400":case"500":case"600":case"700":case"800":case"900":this.weight=r,s=!0,i--,this.nextToken();break;default:return}if(0===i)break}for(;a.length>0;){const i=a.pop();s?t?e||(this.style=i):this.variant=i:this.weight=i}}reset(){this._currentTokenIndex=-1,this.nextToken()}static quoteFont(e){if(-1===e.indexOf(" "))return e;return`"${e.replaceAll('"','\\"')}"`}}!function(e){e[e.Plain=0]="Plain",e[e.Italic=1]="Italic"}(Jt||(Jt={})),function(e){e[e.Regular=0]="Regular",e[e.Bold=1]="Bold"}(Yt||(Yt={}));class na{reset(){this._cssScale=0,this._css=this.toCssString()}get family(){return this._families[0]}set family(e){this.families=ra.parseFamilies(e)}get families(){return this._families}set families(e){this._families=e,this.reset()}get size(){return this._size}set size(e){this._size=e,this.reset()}get style(){return this._style}set style(e){this._style=e,this.reset()}get weight(){return this._weight}set weight(e){this._weight=e,this.reset()}get isBold(){return this.weight===Yt.Bold}get isItalic(){return this.style===Jt.Italic}constructor(e,t,s=Jt.Plain,i=Yt.Regular){this._cssScale=0,this._families=ra.parseFamilies(e),this._size=t,this._style=s,this._weight=i,this._css=this.toCssString()}withSize(e){return na.withFamilyList(this._families,e,this._style,this._weight)}static withFamilyList(e,t,s=Jt.Plain,i=Yt.Regular){const a=new na("",t,s,i);return a.families=e,a}toCssString(e=1){if(!(this._css&&Math.abs(e-this._cssScale)<.01)){let t="";this.isBold&&(t+="bold "),this.isItalic&&(t+="italic "),t+=this.size*e,t+="px ",t+=this.families.map((e=>ra.quoteFont(e))).join(", "),this._css=t,this._cssScale=e}return this._css}static fromJson(e){if(e instanceof na)return e;switch(typeof e){case"undefined":default:return null;case"object":{const t=e,s=t.get("families"),i=t.get("size"),a=ia.parseEnum(t.get("style"),Jt),r=ia.parseEnum(t.get("weight"),Yt);return na.withFamilyList(s,i,a,r)}case"string":{const t=new ra(e);t.parse();const s=t.families,i=t.size.toLowerCase();let a=0;switch(i){case"xx-small":a=7;break;case"x-small":a=10;break;case"small":case"smaller":a=13;break;case"medium":a=16;break;case"large":case"larger":a=18;break;case"x-large":a=24;break;case"xx-large":a=32;break;default:try{a=i.endsWith("em")?16*Number.parseFloat(i.substr(0,i.length-2)):i.endsWith("pt")?16*Number.parseFloat(i.substr(0,i.length-2))/12:i.endsWith("px")?Number.parseFloat(i.substr(0,i.length-2)):12}catch(e){a=12}}let r=Jt.Plain;"italic"===t.style&&(r=Jt.Italic);let n=Yt.Regular;switch(t.weight.toLowerCase()){case"normal":case"lighter":break;default:n=Yt.Bold}return na.withFamilyList(s,a,r,n)}}}static toJson(e){const t=new Map;return t.set("families",e.families),t.set("size",e.size),t.set("style",e.style),t.set("weight",e.weight),t}}class oa{constructor(){this.copyrightFont=new na(oa.sansFont,12,Jt.Plain,Yt.Bold),this.titleFont=new na(oa.serifFont,32,Jt.Plain),this.subTitleFont=new na(oa.serifFont,20,Jt.Plain),this.wordsFont=new na(oa.serifFont,15,Jt.Plain),this.effectFont=new na(oa.serifFont,12,Jt.Italic),this.timerFont=new na(oa.serifFont,12,Jt.Plain),this.directionsFont=new na(oa.serifFont,14,Jt.Plain),this.fretboardNumberFont=new na(oa.sansFont,11,Jt.Plain),this.numberedNotationFont=new na(oa.sansFont,16,Jt.Plain),this.numberedNotationGraceFont=new na(oa.sansFont,14,Jt.Plain),this.tablatureFont=new na(oa.sansFont,13,Jt.Plain),this.graceFont=new na(oa.sansFont,11,Jt.Plain),this.staffLineColor=new et(165,165,165,255),this.barSeparatorColor=new et(34,34,17,255),this.barNumberFont=new na(oa.sansFont,11,Jt.Plain),this.barNumberColor=new et(200,0,0,255),this.fingeringFont=new na(oa.serifFont,14,Jt.Plain),this.inlineFingeringFont=new na(oa.serifFont,12,Jt.Plain),this.markerFont=new na(oa.serifFont,14,Jt.Plain,Yt.Bold),this.mainGlyphColor=new et(0,0,0,255),this.secondaryGlyphColor=new et(0,0,0,100),this.scoreInfoColor=new et(0,0,0,255)}getFontForElement(e){switch(e){case be.Title:return this.titleFont;case be.SubTitle:case be.Artist:case be.Album:return this.subTitleFont;case be.Words:case be.Music:case be.WordsAndMusic:case be.Transcriber:return this.wordsFont;case be.Copyright:case be.CopyrightSecondLine:return this.copyrightFont}return this.wordsFont}}oa.sansFont="Arial, sans-serif",oa.serifFont="Georgia, serif",function(e){e[e.Automatic=0]="Automatic",e[e.UseModelLayout=1]="UseModelLayout"}($t||($t={}));class ha{constructor(){this.scale=1,this.stretchForce=1,this.layoutMode=e.Page,this.staveProfile=t.Default,this.barsPerRow=-1,this.startBar=1,this.barCount=-1,this.barCountPerPartial=10,this.justifyLastSystem=!1,this.resources=new oa,this.padding=[35,35],this.firstSystemPaddingTop=5,this.systemPaddingTop=10,this.systemPaddingBottom=20,this.lastSystemPaddingBottom=0,this.systemLabelPaddingLeft=0,this.systemLabelPaddingRight=3,this.accoladeBarPaddingRight=3,this.notationStaffPaddingTop=5,this.notationStaffPaddingBottom=5,this.effectStaffPaddingTop=0,this.effectStaffPaddingBottom=0,this.firstStaffPaddingLeft=6,this.staffPaddingLeft=2,this.systemsLayoutMode=$t.Automatic}}class la{constructor(){this.encoding="utf-8",this.mergePartGroupsInMusicXml=!1,this.beatTextAsLyrics=!1}}!function(e){e[e.Off=0]="Off",e[e.Continuous=1]="Continuous",e[e.OffScreen=2]="OffScreen"}(qt||(qt={}));class ca{constructor(){this.noteWideLength=240,this.noteWideAmplitude=1,this.noteSlightLength=360,this.noteSlightAmplitude=.5,this.beatWideLength=480,this.beatWideAmplitude=2,this.beatSlightLength=480,this.beatSlightAmplitude=2}}class da{constructor(){this.simpleSlidePitchOffset=6,this.simpleSlideDurationRatio=.25,this.shiftSlideDurationRatio=.5}}!function(e){e[e.WebAudioAudioWorklets=0]="WebAudioAudioWorklets",e[e.WebAudioScriptProcessor=1]="WebAudioScriptProcessor"}(jt||(jt={}));class ua{constructor(){this.soundFont=null,this.scrollElement="html,body",this.outputMode=jt.WebAudioAudioWorklets,this.enablePlayer=!1,this.enableCursor=!0,this.enableAnimatedBeatCursor=!0,this.enableElementHighlighting=!0,this.enableUserInteraction=!0,this.scrollOffsetX=0,this.scrollOffsetY=0,this.scrollMode=qt.Continuous,this.scrollSpeed=300,this.nativeBrowserSmoothScroll=!0,this.songBookBendDuration=75,this.songBookDipDuration=150,this.vibrato=new ca,this.slide=new da,this.playTripletFeel=!0,this.bufferTimeInMilliseconds=500}}class pa{static fromJson(e,t){t&&ia.forEach(t,((t,s)=>pa.setProperty(e,s.toLowerCase(),t)))}static toJson(e){if(!e)return null;const t=new Map;return t.set("scriptfile",e.scriptFile),t.set("fontdirectory",e.fontDirectory),t.set("file",e.file),t.set("tex",e.tex),t.set("tracks",e.tracks),t.set("enablelazyloading",e.enableLazyLoading),t.set("engine",e.engine),t.set("loglevel",e.logLevel),t.set("useworkers",e.useWorkers),t.set("includenotebounds",e.includeNoteBounds),t}static setProperty(e,t,s){switch(t){case"scriptfile":return e.scriptFile=s,!0;case"fontdirectory":return e.fontDirectory=s,!0;case"file":return e.file=s,!0;case"tex":return e.tex=s,!0;case"tracks":return e.tracks=s,!0;case"enablelazyloading":return e.enableLazyLoading=s,!0;case"engine":return e.engine=s,!0;case"loglevel":return e.logLevel=ia.parseEnum(s,L),!0;case"useworkers":return e.useWorkers=s,!0;case"includenotebounds":return e.includeNoteBounds=s,!0}return!1}}class ga{static fromJson(e,t){t&&ia.forEach(t,((t,s)=>ga.setProperty(e,s.toLowerCase(),t)))}static toJson(e){if(!e)return null;const t=new Map;return t.set("copyrightfont",na.toJson(e.copyrightFont)),t.set("titlefont",na.toJson(e.titleFont)),t.set("subtitlefont",na.toJson(e.subTitleFont)),t.set("wordsfont",na.toJson(e.wordsFont)),t.set("effectfont",na.toJson(e.effectFont)),t.set("timerfont",na.toJson(e.timerFont)),t.set("directionsfont",na.toJson(e.directionsFont)),t.set("fretboardnumberfont",na.toJson(e.fretboardNumberFont)),t.set("numberednotationfont",na.toJson(e.numberedNotationFont)),t.set("numberednotationgracefont",na.toJson(e.numberedNotationGraceFont)),t.set("tablaturefont",na.toJson(e.tablatureFont)),t.set("gracefont",na.toJson(e.graceFont)),t.set("stafflinecolor",et.toJson(e.staffLineColor)),t.set("barseparatorcolor",et.toJson(e.barSeparatorColor)),t.set("barnumberfont",na.toJson(e.barNumberFont)),t.set("barnumbercolor",et.toJson(e.barNumberColor)),t.set("fingeringfont",na.toJson(e.fingeringFont)),t.set("inlinefingeringfont",na.toJson(e.inlineFingeringFont)),t.set("markerfont",na.toJson(e.markerFont)),t.set("mainglyphcolor",et.toJson(e.mainGlyphColor)),t.set("secondaryglyphcolor",et.toJson(e.secondaryGlyphColor)),t.set("scoreinfocolor",et.toJson(e.scoreInfoColor)),t}static setProperty(e,t,s){switch(t){case"copyrightfont":return e.copyrightFont=na.fromJson(s),!0;case"titlefont":return e.titleFont=na.fromJson(s),!0;case"subtitlefont":return e.subTitleFont=na.fromJson(s),!0;case"wordsfont":return e.wordsFont=na.fromJson(s),!0;case"effectfont":return e.effectFont=na.fromJson(s),!0;case"timerfont":return e.timerFont=na.fromJson(s),!0;case"directionsfont":return e.directionsFont=na.fromJson(s),!0;case"fretboardnumberfont":return e.fretboardNumberFont=na.fromJson(s),!0;case"numberednotationfont":return e.numberedNotationFont=na.fromJson(s),!0;case"numberednotationgracefont":return e.numberedNotationGraceFont=na.fromJson(s),!0;case"tablaturefont":return e.tablatureFont=na.fromJson(s),!0;case"gracefont":return e.graceFont=na.fromJson(s),!0;case"stafflinecolor":return e.staffLineColor=et.fromJson(s),!0;case"barseparatorcolor":return e.barSeparatorColor=et.fromJson(s),!0;case"barnumberfont":return e.barNumberFont=na.fromJson(s),!0;case"barnumbercolor":return e.barNumberColor=et.fromJson(s),!0;case"fingeringfont":return e.fingeringFont=na.fromJson(s),!0;case"inlinefingeringfont":return e.inlineFingeringFont=na.fromJson(s),!0;case"markerfont":return e.markerFont=na.fromJson(s),!0;case"mainglyphcolor":return e.mainGlyphColor=et.fromJson(s),!0;case"secondaryglyphcolor":return e.secondaryGlyphColor=et.fromJson(s),!0;case"scoreinfocolor":return e.scoreInfoColor=et.fromJson(s),!0}return!1}}class ma{static fromJson(e,t){t&&ia.forEach(t,((t,s)=>ma.setProperty(e,s.toLowerCase(),t)))}static toJson(e){if(!e)return null;const t=new Map;return t.set("scale",e.scale),t.set("stretchforce",e.stretchForce),t.set("layoutmode",e.layoutMode),t.set("staveprofile",e.staveProfile),t.set("barsperrow",e.barsPerRow),t.set("startbar",e.startBar),t.set("barcount",e.barCount),t.set("barcountperpartial",e.barCountPerPartial),t.set("justifylastsystem",e.justifyLastSystem),t.set("resources",ga.toJson(e.resources)),t.set("padding",e.padding),t.set("firstsystempaddingtop",e.firstSystemPaddingTop),t.set("systempaddingtop",e.systemPaddingTop),t.set("systempaddingbottom",e.systemPaddingBottom),t.set("lastsystempaddingbottom",e.lastSystemPaddingBottom),t.set("systemlabelpaddingleft",e.systemLabelPaddingLeft),t.set("systemlabelpaddingright",e.systemLabelPaddingRight),t.set("accoladebarpaddingright",e.accoladeBarPaddingRight),t.set("notationstaffpaddingtop",e.notationStaffPaddingTop),t.set("notationstaffpaddingbottom",e.notationStaffPaddingBottom),t.set("effectstaffpaddingtop",e.effectStaffPaddingTop),t.set("effectstaffpaddingbottom",e.effectStaffPaddingBottom),t.set("firststaffpaddingleft",e.firstStaffPaddingLeft),t.set("staffpaddingleft",e.staffPaddingLeft),t.set("systemslayoutmode",e.systemsLayoutMode),t}static setProperty(s,i,a){switch(i){case"scale":return s.scale=a,!0;case"stretchforce":return s.stretchForce=a,!0;case"layoutmode":return s.layoutMode=ia.parseEnum(a,e),!0;case"staveprofile":return s.staveProfile=ia.parseEnum(a,t),!0;case"barsperrow":return s.barsPerRow=a,!0;case"startbar":return s.startBar=a,!0;case"barcount":return s.barCount=a,!0;case"barcountperpartial":return s.barCountPerPartial=a,!0;case"justifylastsystem":return s.justifyLastSystem=a,!0;case"padding":return s.padding=a,!0;case"firstsystempaddingtop":return s.firstSystemPaddingTop=a,!0;case"systempaddingtop":return s.systemPaddingTop=a,!0;case"systempaddingbottom":return s.systemPaddingBottom=a,!0;case"lastsystempaddingbottom":return s.lastSystemPaddingBottom=a,!0;case"systemlabelpaddingleft":return s.systemLabelPaddingLeft=a,!0;case"systemlabelpaddingright":return s.systemLabelPaddingRight=a,!0;case"accoladebarpaddingright":return s.accoladeBarPaddingRight=a,!0;case"notationstaffpaddingtop":return s.notationStaffPaddingTop=a,!0;case"notationstaffpaddingbottom":return s.notationStaffPaddingBottom=a,!0;case"effectstaffpaddingtop":return s.effectStaffPaddingTop=a,!0;case"effectstaffpaddingbottom":return s.effectStaffPaddingBottom=a,!0;case"firststaffpaddingleft":return s.firstStaffPaddingLeft=a,!0;case"staffpaddingleft":return s.staffPaddingLeft=a,!0;case"systemslayoutmode":return s.systemsLayoutMode=ia.parseEnum(a,$t),!0}if(["resources"].indexOf(i)>=0)return ga.fromJson(s.resources,a),!0;for(const e of["resources"])if(0===i.indexOf(e)&&ga.setProperty(s.resources,i.substring(e.length),a))return!0;return!1}}class fa{static fromJson(e,t){t&&ia.forEach(t,((t,s)=>fa.setProperty(e,s.toLowerCase(),t)))}static toJson(e){if(!e)return null;const t=new Map;t.set("notationmode",e.notationMode),t.set("fingeringmode",e.fingeringMode);{const s=new Map;t.set("elements",s);for(const[t,i]of e.elements)s.set(t.toString(),i)}return t.set("rhythmmode",e.rhythmMode),t.set("rhythmheight",e.rhythmHeight),t.set("transpositionpitches",e.transpositionPitches),t.set("displaytranspositionpitches",e.displayTranspositionPitches),t.set("smallgracetabnotes",e.smallGraceTabNotes),t.set("extendbendarrowsontiednotes",e.extendBendArrowsOnTiedNotes),t.set("extendlineeffectstobeatend",e.extendLineEffectsToBeatEnd),t.set("slurheight",e.slurHeight),t}static setProperty(e,t,s){switch(t){case"notationmode":return e.notationMode=ia.parseEnum(s,D),!0;case"fingeringmode":return e.fingeringMode=ia.parseEnum(s,C),!0;case"elements":return e.elements=new Map,ia.forEach(s,((t,s)=>{e.elements.set(ia.parseEnum(s,E),t)})),!0;case"rhythmmode":return e.rhythmMode=ia.parseEnum(s,F),!0;case"rhythmheight":return e.rhythmHeight=s,!0;case"transpositionpitches":return e.transpositionPitches=s,!0;case"displaytranspositionpitches":return e.displayTranspositionPitches=s,!0;case"smallgracetabnotes":return e.smallGraceTabNotes=s,!0;case"extendbendarrowsontiednotes":return e.extendBendArrowsOnTiedNotes=s,!0;case"extendlineeffectstobeatend":return e.extendLineEffectsToBeatEnd=s,!0;case"slurheight":return e.slurHeight=s,!0}return!1}}class ya{static fromJson(e,t){t&&ia.forEach(t,((t,s)=>ya.setProperty(e,s.toLowerCase(),t)))}static toJson(e){if(!e)return null;const t=new Map;return t.set("encoding",e.encoding),t.set("mergepartgroupsinmusicxml",e.mergePartGroupsInMusicXml),t.set("beattextaslyrics",e.beatTextAsLyrics),t}static setProperty(e,t,s){switch(t){case"encoding":return e.encoding=s,!0;case"mergepartgroupsinmusicxml":return e.mergePartGroupsInMusicXml=s,!0;case"beattextaslyrics":return e.beatTextAsLyrics=s,!0}return!1}}class ba{static fromJson(e,t){t&&ia.forEach(t,((t,s)=>ba.setProperty(e,s.toLowerCase(),t)))}static toJson(e){if(!e)return null;const t=new Map;return t.set("notewidelength",e.noteWideLength),t.set("notewideamplitude",e.noteWideAmplitude),t.set("noteslightlength",e.noteSlightLength),t.set("noteslightamplitude",e.noteSlightAmplitude),t.set("beatwidelength",e.beatWideLength),t.set("beatwideamplitude",e.beatWideAmplitude),t.set("beatslightlength",e.beatSlightLength),t.set("beatslightamplitude",e.beatSlightAmplitude),t}static setProperty(e,t,s){switch(t){case"notewidelength":return e.noteWideLength=s,!0;case"notewideamplitude":return e.noteWideAmplitude=s,!0;case"noteslightlength":return e.noteSlightLength=s,!0;case"noteslightamplitude":return e.noteSlightAmplitude=s,!0;case"beatwidelength":return e.beatWideLength=s,!0;case"beatwideamplitude":return e.beatWideAmplitude=s,!0;case"beatslightlength":return e.beatSlightLength=s,!0;case"beatslightamplitude":return e.beatSlightAmplitude=s,!0}return!1}}class Sa{static fromJson(e,t){t&&ia.forEach(t,((t,s)=>Sa.setProperty(e,s.toLowerCase(),t)))}static toJson(e){if(!e)return null;const t=new Map;return t.set("simpleslidepitchoffset",e.simpleSlidePitchOffset),t.set("simpleslidedurationratio",e.simpleSlideDurationRatio),t.set("shiftslidedurationratio",e.shiftSlideDurationRatio),t}static setProperty(e,t,s){switch(t){case"simpleslidepitchoffset":return e.simpleSlidePitchOffset=s,!0;case"simpleslidedurationratio":return e.simpleSlideDurationRatio=s,!0;case"shiftslidedurationratio":return e.shiftSlideDurationRatio=s,!0}return!1}}class _a{static fromJson(e,t){t&&ia.forEach(t,((t,s)=>_a.setProperty(e,s.toLowerCase(),t)))}static toJson(e){if(!e)return null;const t=new Map;return t.set("soundfont",e.soundFont),t.set("outputmode",e.outputMode),t.set("enableplayer",e.enablePlayer),t.set("enablecursor",e.enableCursor),t.set("enableanimatedbeatcursor",e.enableAnimatedBeatCursor),t.set("enableelementhighlighting",e.enableElementHighlighting),t.set("enableuserinteraction",e.enableUserInteraction),t.set("scrolloffsetx",e.scrollOffsetX),t.set("scrolloffsety",e.scrollOffsetY),t.set("scrollmode",e.scrollMode),t.set("scrollspeed",e.scrollSpeed),t.set("nativebrowsersmoothscroll",e.nativeBrowserSmoothScroll),t.set("songbookbendduration",e.songBookBendDuration),t.set("songbookdipduration",e.songBookDipDuration),t.set("vibrato",ba.toJson(e.vibrato)),t.set("slide",Sa.toJson(e.slide)),t.set("playtripletfeel",e.playTripletFeel),t.set("buffertimeinmilliseconds",e.bufferTimeInMilliseconds),t}static setProperty(e,t,s){switch(t){case"soundfont":return e.soundFont=s,!0;case"scrollelement":return e.scrollElement=s,!0;case"outputmode":return e.outputMode=ia.parseEnum(s,jt),!0;case"enableplayer":return e.enablePlayer=s,!0;case"enablecursor":return e.enableCursor=s,!0;case"enableanimatedbeatcursor":return e.enableAnimatedBeatCursor=s,!0;case"enableelementhighlighting":return e.enableElementHighlighting=s,!0;case"enableuserinteraction":return e.enableUserInteraction=s,!0;case"scrolloffsetx":return e.scrollOffsetX=s,!0;case"scrolloffsety":return e.scrollOffsetY=s,!0;case"scrollmode":return e.scrollMode=ia.parseEnum(s,qt),!0;case"scrollspeed":return e.scrollSpeed=s,!0;case"nativebrowsersmoothscroll":return e.nativeBrowserSmoothScroll=s,!0;case"songbookbendduration":return e.songBookBendDuration=s,!0;case"songbookdipduration":return e.songBookDipDuration=s,!0;case"playtripletfeel":return e.playTripletFeel=s,!0;case"buffertimeinmilliseconds":return e.bufferTimeInMilliseconds=s,!0}if(["vibrato"].indexOf(t)>=0)return ba.fromJson(e.vibrato,s),!0;for(const i of["vibrato"])if(0===t.indexOf(i)&&ba.setProperty(e.vibrato,t.substring(i.length),s))return!0;if(["slide"].indexOf(t)>=0)return Sa.fromJson(e.slide,s),!0;for(const i of["slide"])if(0===t.indexOf(i)&&Sa.setProperty(e.slide,t.substring(i.length),s))return!0;return!1}}class wa{static fromJson(e,t){t&&ia.forEach(t,((t,s)=>wa.setProperty(e,s.toLowerCase(),t)))}static toJson(e){if(!e)return null;const t=new Map;return t.set("core",pa.toJson(e.core)),t.set("display",ma.toJson(e.display)),t.set("notation",fa.toJson(e.notation)),t.set("importer",ya.toJson(e.importer)),t.set("player",_a.toJson(e.player)),t}static setProperty(e,t,s){if(["core",""].indexOf(t)>=0)return pa.fromJson(e.core,s),!0;for(const i of["core",""])if(0===t.indexOf(i)&&pa.setProperty(e.core,t.substring(i.length),s))return!0;if(["display",""].indexOf(t)>=0)return ma.fromJson(e.display,s),!0;for(const i of["display",""])if(0===t.indexOf(i)&&ma.setProperty(e.display,t.substring(i.length),s))return!0;if(["notation"].indexOf(t)>=0)return fa.fromJson(e.notation,s),!0;for(const i of["notation"])if(0===t.indexOf(i)&&fa.setProperty(e.notation,t.substring(i.length),s))return!0;if(["importer"].indexOf(t)>=0)return ya.fromJson(e.importer,s),!0;for(const i of["importer"])if(0===t.indexOf(i)&&ya.setProperty(e.importer,t.substring(i.length),s))return!0;if(["player"].indexOf(t)>=0)return _a.fromJson(e.player,s),!0;for(const i of["player"])if(0===t.indexOf(i)&&_a.setProperty(e.player,t.substring(i.length),s))return!0;return!1}}class Ba{constructor(){this.core=new nc,this.display=new ha,this.notation=new J,this.importer=new la,this.player=new ua}setSongBookModeSettings(){this.notation.notationMode=D.SongBook,this.notation.smallGraceTabNotes=!1,this.notation.fingeringMode=C.SingleNoteEffectBand,this.notation.extendBendArrowsOnTiedNotes=!1,this.notation.elements.set(E.ParenthesisOnTiedBends,!1),this.notation.elements.set(E.TabNotesOnTiedBends,!1),this.notation.elements.set(E.ZerosOnDiveWhammys,!0)}static get songBook(){const e=new Ba;return e.setSongBookModeSettings(),e}fillFromJson(e){wa.fromJson(this,e)}}class ka{static fromJson(e,t){t&&ia.forEach(t,((t,s)=>ka.setProperty(e,s,t)))}static toJson(e){if(!e)return null;const t=new Map;return t.set("marker",e.marker),t.set("text",e.text),t}static setProperty(e,t,s){switch(t){case"marker":return e.marker=s,!0;case"text":return e.text=s,!0}return!1}}class Ta{static fromJson(e,t){t&&ia.forEach(t,((t,s)=>Ta.setProperty(e,s,t)))}static toJson(e){if(!e)return null;const t=new Map;return t.set("islinear",e.isLinear),t.set("type",e.type),t.set("value",e.value),t.set("ratioposition",e.ratioPosition),t.set("text",e.text),t}static setProperty(e,t,s){switch(t){case"islinear":return e.isLinear=s,!0;case"type":return e.type=ia.parseEnum(s,m),!0;case"value":return e.value=s,!0;case"ratioposition":return e.ratioPosition=s,!0;case"text":return e.text=s,!0}return!1}}class Na{static fromJson(e,t){t&&ia.forEach(t,((t,s)=>Na.setProperty(e,s,t)))}static toJson(e){if(!e)return null;const t=new Map;return t.set("type",e.type),t.set("length",e.length),t}static setProperty(e,t,s){switch(t){case"type":return e.type=ia.parseEnum(s,ke),!0;case"length":return e.length=s,!0}return!1}}class xa{static fromJson(e,t){t&&ia.forEach(t,((t,s)=>xa.setProperty(e,s,t)))}static toJson(e){if(!e)return null;const t=new Map;if(t.set("alternateendings",e.alternateEndings),t.set("isdoublebar",e.isDoubleBar),t.set("isrepeatstart",e.isRepeatStart),t.set("repeatcount",e.repeatCount),t.set("timesignaturenumerator",e.timeSignatureNumerator),t.set("timesignaturedenominator",e.timeSignatureDenominator),t.set("timesignaturecommon",e.timeSignatureCommon),t.set("isfreetime",e.isFreeTime),t.set("tripletfeel",e.tripletFeel),e.section&&t.set("section",ka.toJson(e.section)),t.set("tempoautomations",e.tempoAutomations.map((e=>Ta.toJson(e)))),null!==e.fermata){const s=new Map;t.set("fermata",s);for(const[t,i]of e.fermata)s.set(t.toString(),Na.toJson(i))}if(t.set("start",e.start),t.set("isanacrusis",e.isAnacrusis),t.set("displayscale",e.displayScale),t.set("displaywidth",e.displayWidth),null!==e.directions){const s=[];t.set("directions",s);for(const t of e.directions)s.push(t)}return t}static setProperty(e,t,s){switch(t){case"alternateendings":return e.alternateEndings=s,!0;case"isdoublebar":return e.isDoubleBar=s,!0;case"isrepeatstart":return e.isRepeatStart=s,!0;case"repeatcount":return e.repeatCount=s,!0;case"timesignaturenumerator":return e.timeSignatureNumerator=s,!0;case"timesignaturedenominator":return e.timeSignatureDenominator=s,!0;case"timesignaturecommon":return e.timeSignatureCommon=s,!0;case"isfreetime":return e.isFreeTime=s,!0;case"tripletfeel":return e.tripletFeel=ia.parseEnum(s,M),!0;case"section":return s?(e.section=new Qe,ka.fromJson(e.section,s)):e.section=null,!0;case"tempoautomations":e.tempoAutomations=[];for(const t of s){const s=new U;Ta.fromJson(s,t),e.tempoAutomations.push(s)}return!0;case"fermata":return e.fermata=new Map,ia.forEach(s,((t,s)=>{const i=new lt;Na.fromJson(i,t),e.addFermata(Number.parseInt(s),i)})),!0;case"start":return e.start=s,!0;case"isanacrusis":return e.isAnacrusis=s,!0;case"displayscale":return e.displayScale=s,!0;case"displaywidth":return e.displayWidth=s,!0;case"directions":for(const t of s)e.addDirection(ia.parseEnum(t,Be));return!0}return!1}}class va{static fromJson(e,t){t&&ia.forEach(t,((t,s)=>va.setProperty(e,s,t)))}static toJson(e){if(!e)return null;const t=new Map;return t.set("offset",e.offset),t.set("value",e.value),t}static setProperty(e,t,s){switch(t){case"offset":return e.offset=s,!0;case"value":return e.value=s,!0}return!1}}class Pa{static fromJson(e,t){t&&ia.forEach(t,((t,s)=>Pa.setProperty(e,s,t)))}static toJson(e){if(!e)return null;const t=new Map;t.set("notehead",e.noteHead),t.set("noteheadcenteronstem",e.noteHeadCenterOnStem);{const s=new Map;t.set("colors",s);for(const[t,i]of e.colors)s.set(t.toString(),et.toJson(i))}return t}static setProperty(e,t,s){switch(t){case"notehead":return e.noteHead=ia.parseEnum(s,re),!0;case"noteheadcenteronstem":return e.noteHeadCenterOnStem=s,!0;case"colors":return e.colors=new Map,ia.forEach(s,((t,s)=>{e.colors.set(ia.parseEnum(s,le),et.fromJson(t))})),!0}return!1}}class Fa{static fromJson(e,t){t&&ia.forEach(t,((t,s)=>Fa.setProperty(e,s,t)))}static toJson(e){if(!e)return null;const t=new Map;return t.set("id",e.id),t.set("accentuated",e.accentuated),t.set("bendtype",e.bendType),t.set("bendstyle",e.bendStyle),t.set("iscontinuedbend",e.isContinuedBend),null!==e.bendPoints&&t.set("bendpoints",e.bendPoints?.map((e=>va.toJson(e)))),t.set("fret",e.fret),t.set("string",e.string),t.set("showstringnumber",e.showStringNumber),t.set("octave",e.octave),t.set("tone",e.tone),t.set("percussionarticulation",e.percussionArticulation),t.set("isvisible",e.isVisible),t.set("islefthandtapped",e.isLeftHandTapped),t.set("ishammerpullorigin",e.isHammerPullOrigin),t.set("isslurdestination",e.isSlurDestination),t.set("harmonictype",e.harmonicType),t.set("harmonicvalue",e.harmonicValue),t.set("isghost",e.isGhost),t.set("isletring",e.isLetRing),t.set("ispalmmute",e.isPalmMute),t.set("isdead",e.isDead),t.set("isstaccato",e.isStaccato),t.set("slideintype",e.slideInType),t.set("slideouttype",e.slideOutType),t.set("vibrato",e.vibrato),t.set("istiedestination",e.isTieDestination),t.set("lefthandfinger",e.leftHandFinger),t.set("righthandfinger",e.rightHandFinger),t.set("trillvalue",e.trillValue),t.set("trillspeed",e.trillSpeed),t.set("durationpercent",e.durationPercent),t.set("accidentalmode",e.accidentalMode),t.set("dynamics",e.dynamics),t.set("ornament",e.ornament),e.style&&t.set("style",Pa.toJson(e.style)),e.toJson(t),t}static setProperty(e,t,s){switch(t){case"id":return e.id=s,!0;case"accentuated":return e.accentuated=ia.parseEnum(s,B),!0;case"bendtype":return e.bendType=ia.parseEnum(s,y),!0;case"bendstyle":return e.bendStyle=ia.parseEnum(s,f),!0;case"iscontinuedbend":return e.isContinuedBend=s,!0;case"bendpoints":if(s){e.bendPoints=[];for(const t of s){const s=new X;va.fromJson(s,t),e.addBendPoint(s)}}return!0;case"fret":return e.fret=s,!0;case"string":return e.string=s,!0;case"showstringnumber":return e.showStringNumber=s,!0;case"octave":return e.octave=s,!0;case"tone":return e.tone=s,!0;case"percussionarticulation":return e.percussionArticulation=s,!0;case"isvisible":return e.isVisible=s,!0;case"islefthandtapped":return e.isLeftHandTapped=s,!0;case"ishammerpullorigin":return e.isHammerPullOrigin=s,!0;case"isslurdestination":return e.isSlurDestination=s,!0;case"harmonictype":return e.harmonicType=ia.parseEnum(s,T),!0;case"harmonicvalue":return e.harmonicValue=s,!0;case"isghost":return e.isGhost=s,!0;case"isletring":return e.isLetRing=s,!0;case"ispalmmute":return e.isPalmMute=s,!0;case"isdead":return e.isDead=s,!0;case"isstaccato":return e.isStaccato=s,!0;case"slideintype":return e.slideInType=ia.parseEnum(s,x),!0;case"slideouttype":return e.slideOutType=ia.parseEnum(s,v),!0;case"vibrato":return e.vibrato=ia.parseEnum(s,P),!0;case"istiedestination":return e.isTieDestination=s,!0;case"lefthandfinger":return e.leftHandFinger=ia.parseEnum(s,k),!0;case"righthandfinger":return e.rightHandFinger=ia.parseEnum(s,k),!0;case"trillvalue":return e.trillValue=s,!0;case"trillspeed":return e.trillSpeed=ia.parseEnum(s,_),!0;case"durationpercent":return e.durationPercent=s,!0;case"accidentalmode":return e.accidentalMode=ia.parseEnum(s,N),!0;case"dynamics":return e.dynamics=ia.parseEnum(s,g),!0;case"ornament":return e.ornament=ia.parseEnum(s,he),!0;case"style":return s?(e.style=new Ie,Pa.fromJson(e.style,s)):e.style=void 0,!0}return e.setProperty(t,s)}}class Ca{static fromJson(e,t){t&&ia.forEach(t,((t,s)=>Ca.setProperty(e,s,t)))}static toJson(e){if(!e)return null;const t=new Map;{const s=new Map;t.set("colors",s);for(const[t,i]of e.colors)s.set(t.toString(),et.toJson(i))}return t}static setProperty(e,t,s){return"colors"===t&&(e.colors=new Map,ia.forEach(s,((t,s)=>{e.colors.set(ia.parseEnum(s,ye),et.fromJson(t))})),!0)}}class Da{static fromJson(e,t){t&&ia.forEach(t,((t,s)=>Da.setProperty(e,s,t)))}static toJson(e){if(!e)return null;const t=new Map;return t.set("id",e.id),t.set("notes",e.notes.map((e=>Fa.toJson(e)))),t.set("isempty",e.isEmpty),t.set("whammystyle",e.whammyStyle),t.set("ottava",e.ottava),t.set("islegatoorigin",e.isLegatoOrigin),t.set("duration",e.duration),t.set("automations",e.automations.map((e=>Ta.toJson(e)))),t.set("dots",e.dots),t.set("fade",e.fade),t.set("lyrics",e.lyrics),t.set("pop",e.pop),t.set("slap",e.slap),t.set("tap",e.tap),t.set("text",e.text),t.set("slashed",e.slashed),t.set("deadslapped",e.deadSlapped),t.set("brushtype",e.brushType),t.set("brushduration",e.brushDuration),t.set("tupletdenominator",e.tupletDenominator),t.set("tupletnumerator",e.tupletNumerator),t.set("iscontinuedwhammy",e.isContinuedWhammy),t.set("whammybartype",e.whammyBarType),null!==e.whammyBarPoints&&t.set("whammybarpoints",e.whammyBarPoints?.map((e=>va.toJson(e)))),t.set("vibrato",e.vibrato),t.set("chordid",e.chordId),t.set("gracetype",e.graceType),t.set("pickstroke",e.pickStroke),t.set("tremolospeed",e.tremoloSpeed),t.set("crescendo",e.crescendo),t.set("displaystart",e.displayStart),t.set("playbackstart",e.playbackStart),t.set("displayduration",e.displayDuration),t.set("playbackduration",e.playbackDuration),t.set("overridedisplayduration",e.overrideDisplayDuration),t.set("golpe",e.golpe),t.set("dynamics",e.dynamics),t.set("invertbeamdirection",e.invertBeamDirection),t.set("preferredbeamdirection",e.preferredBeamDirection),t.set("beamingmode",e.beamingMode),t.set("wahpedal",e.wahPedal),t.set("barrefret",e.barreFret),t.set("barreshape",e.barreShape),t.set("rasgueado",e.rasgueado),t.set("showtimer",e.showTimer),t.set("timer",e.timer),e.style&&t.set("style",Ca.toJson(e.style)),t}static setProperty(e,t,s){switch(t){case"id":return e.id=s,!0;case"notes":e.notes=[];for(const t of s){const s=new Ae;Fa.fromJson(s,t),e.addNote(s)}return!0;case"isempty":return e.isEmpty=s,!0;case"whammystyle":return e.whammyStyle=ia.parseEnum(s,f),!0;case"ottava":return e.ottava=ia.parseEnum(s,o),!0;case"islegatoorigin":return e.isLegatoOrigin=s,!0;case"duration":return e.duration=ia.parseEnum(s,_),!0;case"automations":e.automations=[];for(const t of s){const s=new U;Ta.fromJson(s,t),e.automations.push(s)}return!0;case"dots":return e.dots=s,!0;case"fade":return e.fade=ia.parseEnum(s,ue),!0;case"lyrics":return e.lyrics=s,!0;case"pop":return e.pop=s,!0;case"slap":return e.slap=s,!0;case"tap":return e.tap=s,!0;case"text":return e.text=s,!0;case"slashed":return e.slashed=s,!0;case"deadslapped":return e.deadSlapped=s,!0;case"brushtype":return e.brushType=ia.parseEnum(s,b),!0;case"brushduration":return e.brushDuration=s,!0;case"tupletdenominator":return e.tupletDenominator=s,!0;case"tupletnumerator":return e.tupletNumerator=s,!0;case"iscontinuedwhammy":return e.isContinuedWhammy=s,!0;case"whammybartype":return e.whammyBarType=ia.parseEnum(s,ce),!0;case"whammybarpoints":if(s){e.whammyBarPoints=[];for(const t of s){const s=new X;va.fromJson(s,t),e.addWhammyBarPoint(s)}}return!0;case"vibrato":return e.vibrato=ia.parseEnum(s,P),!0;case"chordid":return e.chordId=s,!0;case"gracetype":return e.graceType=ia.parseEnum(s,w),!0;case"pickstroke":return e.pickStroke=ia.parseEnum(s,ae),!0;case"tremolospeed":return e.tremoloSpeed=ia.parseEnum(s,_)??null,!0;case"crescendo":return e.crescendo=ia.parseEnum(s,S),!0;case"displaystart":return e.displayStart=s,!0;case"playbackstart":return e.playbackStart=s,!0;case"displayduration":return e.displayDuration=s,!0;case"playbackduration":return e.playbackDuration=s,!0;case"overridedisplayduration":return e.overrideDisplayDuration=s,!0;case"golpe":return e.golpe=ia.parseEnum(s,de),!0;case"dynamics":return e.dynamics=ia.parseEnum(s,g),!0;case"invertbeamdirection":return e.invertBeamDirection=s,!0;case"preferredbeamdirection":return e.preferredBeamDirection=ia.parseEnum(s,Te)??null,!0;case"beamingmode":return e.beamingMode=ia.parseEnum(s,fe),!0;case"wahpedal":return e.wahPedal=ia.parseEnum(s,pe),!0;case"barrefret":return e.barreFret=s,!0;case"barreshape":return e.barreShape=ia.parseEnum(s,ge),!0;case"rasgueado":return e.rasgueado=ia.parseEnum(s,me),!0;case"showtimer":return e.showTimer=s,!0;case"timer":return e.timer=s,!0;case"style":return s?(e.style=new Ge,Ca.fromJson(e.style,s)):e.style=void 0,!0}return!1}}class Ea{static fromJson(e,t){t&&ia.forEach(t,((t,s)=>Ea.setProperty(e,s,t)))}static toJson(e){if(!e)return null;const t=new Map;{const s=new Map;t.set("colors",s);for(const[t,i]of e.colors)s.set(t.toString(),et.toJson(i))}return t}static setProperty(e,t,s){return"colors"===t&&(e.colors=new Map,ia.forEach(s,((t,s)=>{e.colors.set(ia.parseEnum(s,I),et.fromJson(t))})),!0)}}class La{static fromJson(e,t){t&&ia.forEach(t,((t,s)=>La.setProperty(e,s,t)))}static toJson(e){if(!e)return null;const t=new Map;return t.set("id",e.id),t.set("beats",e.beats.map((e=>Da.toJson(e)))),e.style&&t.set("style",Ea.toJson(e.style)),t}static setProperty(e,t,s){switch(t){case"id":return e.id=s,!0;case"beats":e.beats=[];for(const t of s){const s=new ze;Da.fromJson(s,t),e.addBeat(s)}return!0;case"style":return s?(e.style=new Z,Ea.fromJson(e.style,s)):e.style=void 0,!0}return!1}}class Ma{static fromJson(e,t){t&&ia.forEach(t,((t,s)=>Ma.setProperty(e,s,t)))}static toJson(e){if(!e)return null;const t=new Map;return t.set("ratioposition",e.ratioPosition),t.set("pedaltype",e.pedalType),t}static setProperty(e,t,s){switch(t){case"ratioposition":return e.ratioPosition=s,!0;case"pedaltype":return e.pedalType=ia.parseEnum(s,d),!0}return!1}}class Ia{static fromJson(e,t){t&&ia.forEach(t,((t,s)=>Ia.setProperty(e,s,t)))}static toJson(e){if(!e)return null;const t=new Map;{const s=new Map;t.set("colors",s);for(const[t,i]of e.colors)s.set(t.toString(),et.toJson(i))}return t}static setProperty(e,t,s){return"colors"===t&&(e.colors=new Map,ia.forEach(s,((t,s)=>{e.colors.set(ia.parseEnum(s,u),et.fromJson(t))})),!0)}}class Aa{static fromJson(e,t){t&&ia.forEach(t,((t,s)=>Aa.setProperty(e,s,t)))}static toJson(e){if(!e)return null;const t=new Map;return t.set("id",e.id),t.set("clef",e.clef),t.set("clefottava",e.clefOttava),t.set("voices",e.voices.map((e=>La.toJson(e)))),t.set("similemark",e.simileMark),t.set("displayscale",e.displayScale),t.set("displaywidth",e.displayWidth),t.set("sustainpedals",e.sustainPedals.map((e=>Ma.toJson(e)))),t.set("barlineleft",e.barLineLeft),t.set("barlineright",e.barLineRight),t.set("keysignature",e.keySignature),t.set("keysignaturetype",e.keySignatureType),e.style&&t.set("style",Ia.toJson(e.style)),t}static setProperty(e,t,s){switch(t){case"id":return e.id=s,!0;case"clef":return e.clef=ia.parseEnum(s,n),!0;case"clefottava":return e.clefOttava=ia.parseEnum(s,o),!0;case"voices":e.voices=[];for(const t of s){const s=new ee;La.fromJson(s,t),e.addVoice(s)}return!0;case"similemark":return e.simileMark=ia.parseEnum(s,h),!0;case"displayscale":return e.displayScale=s,!0;case"displaywidth":return e.displayWidth=s,!0;case"sustainpedals":e.sustainPedals=[];for(const t of s){const s=new W;Ma.fromJson(s,t),e.sustainPedals.push(s)}return!0;case"barlineleft":return e.barLineLeft=ia.parseEnum(s,p),!0;case"barlineright":return e.barLineRight=ia.parseEnum(s,p),!0;case"keysignature":return e.keySignature=ia.parseEnum(s,l),!0;case"keysignaturetype":return e.keySignatureType=ia.parseEnum(s,c),!0;case"style":return s?(e.style=new V,Ia.fromJson(e.style,s)):e.style=void 0,!0}return!1}}class Ra{static fromJson(e,t){t&&ia.forEach(t,((t,s)=>Ra.setProperty(e,s,t)))}static toJson(e){if(!e)return null;const t=new Map;return t.set("name",e.name),t.set("firstfret",e.firstFret),t.set("strings",e.strings),t.set("barrefrets",e.barreFrets),t.set("showname",e.showName),t.set("showdiagram",e.showDiagram),t.set("showfingering",e.showFingering),t}static setProperty(e,t,s){switch(t){case"name":return e.name=s,!0;case"firstfret":return e.firstFret=s,!0;case"strings":return e.strings=s,!0;case"barrefrets":return e.barreFrets=s,!0;case"showname":return e.showName=s,!0;case"showdiagram":return e.showDiagram=s,!0;case"showfingering":return e.showFingering=s,!0}return!1}}class Oa{static fromJson(e,t){t&&ia.forEach(t,((t,s)=>Oa.setProperty(e,s,t)))}static toJson(e){if(!e)return null;const t=new Map;return t.set("isstandard",e.isStandard),t.set("name",e.name),t.set("tunings",e.tunings),t}static setProperty(e,t,s){switch(t){case"isstandard":return e.isStandard=s,!0;case"name":return e.name=s,!0;case"tunings":return e.tunings=s,!0}return!1}}class Ha{static fromJson(e,t){t&&ia.forEach(t,((t,s)=>Ha.setProperty(e,s,t)))}static toJson(e){if(!e)return null;const t=new Map;if(t.set("bars",e.bars.map((e=>Aa.toJson(e)))),null!==e.chords){const s=new Map;t.set("chords",s);for(const[t,i]of e.chords)s.set(t.toString(),Ra.toJson(i))}return t.set("capo",e.capo),t.set("transpositionpitch",e.transpositionPitch),t.set("displaytranspositionpitch",e.displayTranspositionPitch),t.set("stringtuning",Oa.toJson(e.stringTuning)),t.set("showslash",e.showSlash),t.set("shownumbered",e.showNumbered),t.set("showtablature",e.showTablature),t.set("showstandardnotation",e.showStandardNotation),t.set("ispercussion",e.isPercussion),t.set("standardnotationlinecount",e.standardNotationLineCount),t}static setProperty(e,t,s){switch(t){case"bars":e.bars=[];for(const t of s){const s=new G;Aa.fromJson(s,t),e.addBar(s)}return!0;case"chords":return e.chords=new Map,ia.forEach(s,((t,s)=>{const i=new je;Ra.fromJson(i,t),e.addChord(s,i)})),!0;case"capo":return e.capo=s,!0;case"transpositionpitch":return e.transpositionPitch=s,!0;case"displaytranspositionpitch":return e.displayTranspositionPitch=s,!0;case"stringtuning":return Oa.fromJson(e.stringTuning,s),!0;case"showslash":return e.showSlash=s,!0;case"shownumbered":return e.showNumbered=s,!0;case"showtablature":return e.showTablature=s,!0;case"showstandardnotation":return e.showStandardNotation=s,!0;case"ispercussion":return e.isPercussion=s,!0;case"standardnotationlinecount":return e.standardNotationLineCount=s,!0}return!1}}class Wa{static fromJson(e,t){t&&ia.forEach(t,((t,s)=>Wa.setProperty(e,s,t)))}static toJson(e){if(!e)return null;const t=new Map;return t.set("volume",e.volume),t.set("balance",e.balance),t.set("port",e.port),t.set("program",e.program),t.set("primarychannel",e.primaryChannel),t.set("secondarychannel",e.secondaryChannel),t.set("ismute",e.isMute),t.set("issolo",e.isSolo),t}static setProperty(e,t,s){switch(t){case"volume":return e.volume=s,!0;case"balance":return e.balance=s,!0;case"port":return e.port=s,!0;case"program":return e.program=s,!0;case"primarychannel":return e.primaryChannel=s,!0;case"secondarychannel":return e.secondaryChannel=s,!0;case"ismute":return e.isMute=s,!0;case"issolo":return e.isSolo=s,!0}return!1}}class Va{static fromJson(e,t){t&&ia.forEach(t,((t,s)=>Va.setProperty(e,s,t)))}static toJson(e){if(!e)return null;const t=new Map;return t.set("elementtype",e.elementType),t.set("staffline",e.staffLine),t.set("noteheaddefault",e.noteHeadDefault),t.set("noteheadhalf",e.noteHeadHalf),t.set("noteheadwhole",e.noteHeadWhole),t.set("techniquesymbol",e.techniqueSymbol),t.set("techniquesymbolplacement",e.techniqueSymbolPlacement),t.set("outputmidinumber",e.outputMidiNumber),t}static setProperty(e,t,s){switch(t){case"elementtype":return e.elementType=s,!0;case"staffline":return e.staffLine=s,!0;case"noteheaddefault":return e.noteHeadDefault=ia.parseEnum(s,re),!0;case"noteheadhalf":return e.noteHeadHalf=ia.parseEnum(s,re),!0;case"noteheadwhole":return e.noteHeadWhole=ia.parseEnum(s,re),!0;case"techniquesymbol":return e.techniqueSymbol=ia.parseEnum(s,re),!0;case"techniquesymbolplacement":return e.techniqueSymbolPlacement=ia.parseEnum(s,oe),!0;case"outputmidinumber":return e.outputMidiNumber=s,!0}return!1}}class Ga{static fromJson(e,t){t&&ia.forEach(t,((t,s)=>Ga.setProperty(e,s,t)))}static toJson(e){if(!e)return null;const t=new Map;{const s=new Map;t.set("colors",s);for(const[t,i]of e.colors)s.set(t.toString(),et.toJson(i))}return t}static setProperty(e,t,s){return"colors"===t&&(e.colors=new Map,ia.forEach(s,((t,s)=>{e.colors.set(ia.parseEnum(s,we),et.fromJson(t))})),!0)}}class za{static fromJson(e,t){t&&ia.forEach(t,((t,s)=>za.setProperty(e,s,t)))}static toJson(e){if(!e)return null;const t=new Map;if(t.set("staves",e.staves.map((e=>Ha.toJson(e)))),t.set("playbackinfo",Wa.toJson(e.playbackInfo)),t.set("color",et.toJson(e.color)),t.set("name",e.name),t.set("isvisibleonmultitrack",e.isVisibleOnMultiTrack),t.set("shortname",e.shortName),t.set("defaultsystemslayout",e.defaultSystemsLayout),t.set("systemslayout",e.systemsLayout),void 0!==e.lineBreaks){const s=[];t.set("linebreaks",s);for(const t of e.lineBreaks)s.push(t)}return t.set("percussionarticulations",e.percussionArticulations.map((e=>Va.toJson(e)))),e.style&&t.set("style",Ga.toJson(e.style)),t}static setProperty(e,t,s){switch(t){case"staves":e.staves=[];for(const t of s){const s=new it;Ha.fromJson(s,t),e.addStaff(s)}return!0;case"playbackinfo":return Wa.fromJson(e.playbackInfo,s),!0;case"color":return e.color=et.fromJson(s),!0;case"name":return e.name=s,!0;case"isvisibleonmultitrack":return e.isVisibleOnMultiTrack=s,!0;case"shortname":return e.shortName=s,!0;case"defaultsystemslayout":return e.defaultSystemsLayout=s,!0;case"systemslayout":return e.systemsLayout=s,!0;case"linebreaks":for(const t of s)e.addLineBreaks(t);return!0;case"percussionarticulations":e.percussionArticulations=[];for(const t of s){const s=new Ee;Va.fromJson(s,t),e.percussionArticulations.push(s)}return!0;case"style":return s?(e.style=new at,Ga.fromJson(e.style,s)):e.style=void 0,!0}return!1}}class Ua{static fromJson(e,t){t&&ia.forEach(t,((t,s)=>Ua.setProperty(e,s,t)))}static toJson(e){if(!e)return null;const t=new Map;if(t.set("hidedynamics",e.hideDynamics),t.set("bracketextendmode",e.bracketExtendMode),t.set("usesystemsignseparator",e.useSystemSignSeparator),t.set("globaldisplaytuning",e.globalDisplayTuning),null!==e.perTrackDisplayTuning){const s=new Map;t.set("pertrackdisplaytuning",s);for(const[t,i]of e.perTrackDisplayTuning)s.set(t.toString(),i)}if(t.set("globaldisplaychorddiagramsontop",e.globalDisplayChordDiagramsOnTop),null!==e.perTrackChordDiagramsOnTop){const s=new Map;t.set("pertrackchorddiagramsontop",s);for(const[t,i]of e.perTrackChordDiagramsOnTop)s.set(t.toString(),i)}if(t.set("singletracktracknamepolicy",e.singleTrackTrackNamePolicy),t.set("multitracktracknamepolicy",e.multiTrackTrackNamePolicy),t.set("firstsystemtracknamemode",e.firstSystemTrackNameMode),t.set("othersystemstracknamemode",e.otherSystemsTrackNameMode),t.set("firstsystemtracknameorientation",e.firstSystemTrackNameOrientation),t.set("othersystemstracknameorientation",e.otherSystemsTrackNameOrientation),t.set("multitrackmultibarrest",e.multiTrackMultiBarRest),null!==e.perTrackMultiBarRest){const s=[];t.set("pertrackmultibarrest",s);for(const t of e.perTrackMultiBarRest)s.push(t)}return t}static setProperty(e,t,n){switch(t){case"hidedynamics":return e.hideDynamics=n,!0;case"bracketextendmode":return e.bracketExtendMode=ia.parseEnum(n,s),!0;case"usesystemsignseparator":return e.useSystemSignSeparator=n,!0;case"globaldisplaytuning":return e.globalDisplayTuning=n,!0;case"pertrackdisplaytuning":return e.perTrackDisplayTuning=new Map,ia.forEach(n,((t,s)=>{e.perTrackDisplayTuning.set(Number.parseInt(s),t)})),!0;case"globaldisplaychorddiagramsontop":return e.globalDisplayChordDiagramsOnTop=n,!0;case"pertrackchorddiagramsontop":return e.perTrackChordDiagramsOnTop=new Map,ia.forEach(n,((t,s)=>{e.perTrackChordDiagramsOnTop.set(Number.parseInt(s),t)})),!0;case"singletracktracknamepolicy":return e.singleTrackTrackNamePolicy=ia.parseEnum(n,i),!0;case"multitracktracknamepolicy":return e.multiTrackTrackNamePolicy=ia.parseEnum(n,i),!0;case"firstsystemtracknamemode":return e.firstSystemTrackNameMode=ia.parseEnum(n,a),!0;case"othersystemstracknamemode":return e.otherSystemsTrackNameMode=ia.parseEnum(n,a),!0;case"firstsystemtracknameorientation":return e.firstSystemTrackNameOrientation=ia.parseEnum(n,r),!0;case"othersystemstracknameorientation":return e.otherSystemsTrackNameOrientation=ia.parseEnum(n,r),!0;case"multitrackmultibarrest":return e.multiTrackMultiBarRest=n,!0;case"pertrackmultibarrest":return e.perTrackMultiBarRest=new Set(n),!0}return!1}}class Xa{static fromJson(e,t){t&&ia.forEach(t,((t,s)=>Xa.setProperty(e,s,t)))}static toJson(e){if(!e)return null;const t=new Map;return t.set("template",e.template),t.set("isvisible",e.isVisible),t.set("textalign",e.textAlign),t}static setProperty(e,t,s){switch(t){case"template":return e.template=s,!0;case"isvisible":return e.isVisible=s,!0;case"textalign":return e.textAlign=ia.parseEnum(s,ne),!0}return!1}}class Ja{static fromJson(e,t){t&&ia.forEach(t,((t,s)=>Ja.setProperty(e,s,t)))}static toJson(e){if(!e)return null;const t=new Map;{const s=new Map;t.set("headerandfooter",s);for(const[t,i]of e.headerAndFooter)s.set(t.toString(),Xa.toJson(i))}{const s=new Map;t.set("colors",s);for(const[t,i]of e.colors)s.set(t.toString(),et.toJson(i))}return t}static setProperty(e,t,s){switch(t){case"headerandfooter":return e.headerAndFooter=new Map,ia.forEach(s,((t,s)=>{const i=new Ue;Xa.fromJson(i,t),e.headerAndFooter.set(ia.parseEnum(s,be),i)})),!0;case"colors":return e.colors=new Map,ia.forEach(s,((t,s)=>{e.colors.set(ia.parseEnum(s,be),et.fromJson(t))})),!0}return!1}}class Ya{static fromJson(e,t){t&&ia.forEach(t,((t,s)=>Ya.setProperty(e,s,t)))}static toJson(e){if(!e)return null;const t=new Map;return t.set("album",e.album),t.set("artist",e.artist),t.set("copyright",e.copyright),t.set("instructions",e.instructions),t.set("music",e.music),t.set("notices",e.notices),t.set("subtitle",e.subTitle),t.set("title",e.title),t.set("words",e.words),t.set("tab",e.tab),t.set("tempo",e.tempo),t.set("tempolabel",e.tempoLabel),t.set("masterbars",e.masterBars.map((e=>xa.toJson(e)))),t.set("tracks",e.tracks.map((e=>za.toJson(e)))),t.set("defaultsystemslayout",e.defaultSystemsLayout),t.set("systemslayout",e.systemsLayout),t.set("stylesheet",Ua.toJson(e.stylesheet)),e.style&&t.set("style",Ja.toJson(e.style)),t}static setProperty(e,t,s){switch(t){case"album":return e.album=s,!0;case"artist":return e.artist=s,!0;case"copyright":return e.copyright=s,!0;case"instructions":return e.instructions=s,!0;case"music":return e.music=s,!0;case"notices":return e.notices=s,!0;case"subtitle":return e.subTitle=s,!0;case"title":return e.title=s,!0;case"words":return e.words=s,!0;case"tab":return e.tab=s,!0;case"tempo":return e.tempo=s,!0;case"tempolabel":return e.tempoLabel=s,!0;case"masterbars":e.masterBars=[];for(const t of s){const s=new j;xa.fromJson(s,t),e.addMasterBar(s)}return!0;case"tracks":e.tracks=[];for(const t of s){const s=new rt;za.fromJson(s,t),e.addTrack(s)}return!0;case"defaultsystemslayout":return e.defaultSystemsLayout=s,!0;case"systemslayout":return e.systemsLayout=s,!0;case"stylesheet":return Ua.fromJson(e.stylesheet,s),!0;case"style":return s?(e.style=new Xe,Ja.fromJson(e.style,s)):e.style=void 0,!0}return!1}}class $a{static jsonReplacer(e,t){if(t instanceof Map){if("fromEntries"in Object)return Object.fromEntries(t);const e={};for(const[s,i]of t)e[s]=i;return e}return ArrayBuffer.isView(t)?Array.apply([],[t]):t}static scoreToJson(e){const t=$a.scoreToJsObject(e);return JSON.stringify(t,$a.jsonReplacer)}static jsonToScore(e,t){return $a.jsObjectToScore(JSON.parse(e),t)}static scoreToJsObject(e){return Ya.toJson(e)}static jsObjectToScore(e,t){const s=new Je;return Ya.fromJson(s,e),s.finish(t??new Ba),s}static settingsToJson(e){const t=$a.settingsToJsObject(e);return JSON.stringify(t,$a.jsonReplacer)}static jsonToSettings(e){return $a.jsObjectToSettings(JSON.parse(e))}static settingsToJsObject(e){return wa.toJson(e)}static jsObjectToSettings(e){const t=new Ba;return wa.fromJson(t,e),t}static jsObjectToMidiFile(e){const t=new Ps;return ia.forEach(e,((e,s)=>{switch(s){case"division":t.division=e;break;case"tracks":for(const s of e){const e=$a.jsObjectToMidiTrack(s);t.tracks.push(e)}}})),t}static jsObjectToMidiTrack(e){const t=new vs;return ia.forEach(e,((e,s)=>{if("events"===s)for(const s of e){const e=$a.jsObjectToMidiEvent(s);t.events.push(e)}})),t}static jsObjectToMidiEvent(e){const t=ia.getValue(e,"track"),s=ia.getValue(e,"tick"),i=ia.getValue(e,"type");switch(i){case Rt.TimeSignature:return new Cs(t,s,ia.getValue(e,"numerator"),ia.getValue(e,"denominatorIndex"),ia.getValue(e,"midiClocksPerMetronomeClick"),ia.getValue(e,"thirdySecondNodesInQuarter"));case Rt.AlphaTabRest:return new Ls(t,s,ia.getValue(e,"channel"));case Rt.AlphaTabMetronome:return new Es(t,s,ia.getValue(e,"metronomeNumerator"),ia.getValue(e,"metronomeDurationInTicks"),ia.getValue(e,"metronomeDurationInMilliseconds"));case Rt.NoteOn:return new Is(t,s,ia.getValue(e,"channel"),ia.getValue(e,"noteKey"),ia.getValue(e,"noteVelocity"));case Rt.NoteOff:return new As(t,s,ia.getValue(e,"channel"),ia.getValue(e,"noteKey"),ia.getValue(e,"noteVelocity"));case Rt.ControlChange:return new Rs(t,s,ia.getValue(e,"channel"),ia.getValue(e,"controller"),ia.getValue(e,"value"));case Rt.ProgramChange:return new Os(t,s,ia.getValue(e,"channel"),ia.getValue(e,"program"));case Rt.TempoChange:return new Hs(s,ia.getValue(e,"microSecondsPerQuarterNote"));case Rt.PitchBend:return new Ws(t,s,ia.getValue(e,"channel"),ia.getValue(e,"value"));case Rt.PerNotePitchBend:return new Vs(t,s,ia.getValue(e,"channel"),ia.getValue(e,"noteKey"),ia.getValue(e,"value"));case Rt.EndOfTrack:return new Gs(t,s)}throw new $e(Se.Format,`Unknown Midi Event type: ${i}`)}static midiFileToJsObject(e){const t=new Map;t.set("division",e.division);const s=[];for(const t of e.tracks)s.push($a.midiTrackToJsObject(t));return t.set("tracks",s),t}static midiTrackToJsObject(e){const t=new Map,s=[];for(const t of e.events)s.push($a.midiEventToJsObject(t));return t.set("events",s),t}static midiEventToJsObject(e){const t=new Map;switch(t.set("track",e.track),t.set("tick",e.tick),t.set("type",e.type),e.type){case Rt.TimeSignature:t.set("numerator",e.numerator),t.set("denominatorIndex",e.denominatorIndex),t.set("midiClocksPerMetronomeClick",e.midiClocksPerMetronomeClick),t.set("thirdySecondNodesInQuarter",e.thirtySecondNodesInQuarter);break;case Rt.AlphaTabRest:t.set("channel",e.channel);break;case Rt.AlphaTabMetronome:t.set("metronomeNumerator",e.metronomeNumerator),t.set("metronomeDurationInMilliseconds",e.metronomeDurationInMilliseconds),t.set("metronomeDurationInTicks",e.metronomeDurationInTicks);break;case Rt.NoteOn:case Rt.NoteOff:t.set("channel",e.channel),t.set("noteKey",e.noteKey),t.set("noteVelocity",e.noteVelocity);break;case Rt.ControlChange:t.set("channel",e.channel),t.set("controller",e.controller),t.set("value",e.value);break;case Rt.ProgramChange:t.set("channel",e.channel),t.set("program",e.program);break;case Rt.TempoChange:t.set("microSecondsPerQuarterNote",e.microSecondsPerQuarterNote);break;case Rt.PitchBend:t.set("channel",e.channel),t.set("value",e.value);break;case Rt.PerNotePitchBend:t.set("channel",e.channel),t.set("noteKey",e.noteKey),t.set("value",e.value);case Rt.EndOfTrack:}return t}}class qa{constructor(){this.ready=new Qi,this.samplesPlayed=new Zi,this.sampleRequest=new Qi}get sampleRate(){return qa.preferredSampleRate}open(){q.debug("AlphaSynth","Initializing synth worker"),this._worker=rc.globalThis,this._worker.addEventListener("message",this.handleMessage.bind(this)),this.ready.trigger()}destroy(){this._worker.postMessage({cmd:"alphaSynth.output.destroy"})}handleMessage(e){const t=e.data;switch(t.cmd){case qa.CmdOutputSampleRequest:this.sampleRequest.trigger();break;case qa.CmdOutputSamplesPlayed:this.samplesPlayed.trigger(t.samples)}}addSamples(e){this._worker.postMessage({cmd:"alphaSynth.output.addSamples",samples:e})}play(){this._worker.postMessage({cmd:"alphaSynth.output.play"})}pause(){this._worker.postMessage({cmd:"alphaSynth.output.pause"})}resetSamples(){this._worker.postMessage({cmd:"alphaSynth.output.resetSamples"})}activate(){}async enumerateOutputDevices(){return[]}async setOutputDevice(e){}async getOutputDevice(){return null}}qa.CmdOutputPrefix="alphaSynth.output.",qa.CmdOutputAddSamples=`${qa.CmdOutputPrefix}addSamples`,qa.CmdOutputPlay=`${qa.CmdOutputPrefix}play`,qa.CmdOutputPause=`${qa.CmdOutputPrefix}pause`,qa.CmdOutputResetSamples=`${qa.CmdOutputPrefix}resetSamples`,qa.CmdOutputStop=`${qa.CmdOutputPrefix}stop`,qa.CmdOutputSampleRequest=`${qa.CmdOutputPrefix}sampleRequest`,qa.CmdOutputSamplesPlayed=`${qa.CmdOutputPrefix}samplesPlayed`,qa.preferredSampleRate=0;class ja{constructor(e,t){this._main=e,this._main.addEventListener("message",this.handleMessage.bind(this)),this._player=new sa(new qa,t),this._player.positionChanged.on(this.onPositionChanged.bind(this)),this._player.stateChanged.on(this.onPlayerStateChanged.bind(this)),this._player.finished.on(this.onFinished.bind(this)),this._player.soundFontLoaded.on(this.onSoundFontLoaded.bind(this)),this._player.soundFontLoadFailed.on(this.onSoundFontLoadFailed.bind(this)),this._player.soundFontLoadFailed.on(this.onSoundFontLoadFailed.bind(this)),this._player.midiLoaded.on(this.onMidiLoaded.bind(this)),this._player.midiLoadFailed.on(this.onMidiLoadFailed.bind(this)),this._player.readyForPlayback.on(this.onReadyForPlayback.bind(this)),this._player.midiEventsPlayed.on(this.onMidiEventsPlayed.bind(this)),this._player.playbackRangeChanged.on(this.onPlaybackRangeChanged.bind(this)),this._main.postMessage({cmd:"alphaSynth.ready"})}static init(){const e=rc.globalThis;e.addEventListener("message",(t=>{const s=t.data;if("alphaSynth.initialize"===s.cmd)qa.preferredSampleRate=s.sampleRate,q.logLevel=s.logLevel,rc.globalThis.alphaSynthWebWorker=new ja(e,s.bufferTimeInMilliseconds)}))}handleMessage(e){const t=e.data;switch(t.cmd){case"alphaSynth.setLogLevel":q.logLevel=t.value;break;case"alphaSynth.setMasterVolume":this._player.masterVolume=t.value;break;case"alphaSynth.setMetronomeVolume":this._player.metronomeVolume=t.value;break;case"alphaSynth.setPlaybackSpeed":this._player.playbackSpeed=t.value;break;case"alphaSynth.setTickPosition":this._player.tickPosition=t.value;break;case"alphaSynth.setTimePosition":this._player.timePosition=t.value;break;case"alphaSynth.setPlaybackRange":this._player.playbackRange=t.value;break;case"alphaSynth.setIsLooping":this._player.isLooping=t.value;break;case"alphaSynth.setCountInVolume":this._player.countInVolume=t.value;break;case"alphaSynth.setMidiEventsPlayedFilter":this._player.midiEventsPlayedFilter=t.value;break;case"alphaSynth.play":this._player.play();break;case"alphaSynth.pause":this._player.pause();break;case"alphaSynth.playPause":this._player.playPause();break;case"alphaSynth.stop":this._player.stop();break;case"alphaSynth.playOneTimeMidiFile":this._player.playOneTimeMidiFile($a.jsObjectToMidiFile(t.midi));break;case"alphaSynth.loadSoundFontBytes":this._player.loadSoundFont(t.data,t.append);break;case"alphaSynth.resetSoundFonts":this._player.resetSoundFonts();break;case"alphaSynth.loadMidi":this._player.loadMidiFile($a.jsObjectToMidiFile(t.midi));break;case"alphaSynth.setChannelMute":this._player.setChannelMute(t.channel,t.mute);break;case"alphaSynth.setChannelTranspositionPitch":this._player.setChannelTranspositionPitch(t.channel,t.semitones);break;case"alphaSynth.setChannelSolo":this._player.setChannelSolo(t.channel,t.solo);break;case"alphaSynth.setChannelVolume":this._player.setChannelVolume(t.channel,t.volume);break;case"alphaSynth.resetChannelStates":this._player.resetChannelStates();break;case"alphaSynth.destroy":this._player.destroy(),this._main.postMessage({cmd:"alphaSynth.destroyed"});break;case"alphaSynth.applyTranspositionPitches":this._player.applyTranspositionPitches(new Map(JSON.parse(t.transpositionPitches)))}}onPositionChanged(e){this._main.postMessage({cmd:"alphaSynth.positionChanged",currentTime:e.currentTime,endTime:e.endTime,currentTick:e.currentTick,endTick:e.endTick,isSeek:e.isSeek})}onPlayerStateChanged(e){this._main.postMessage({cmd:"alphaSynth.playerStateChanged",state:e.state,stopped:e.stopped})}onFinished(){this._main.postMessage({cmd:"alphaSynth.finished"})}onSoundFontLoaded(){this._main.postMessage({cmd:"alphaSynth.soundFontLoaded"})}onSoundFontLoadFailed(e){this._main.postMessage({cmd:"alphaSynth.soundFontLoadFailed",error:this.serializeException(e)})}serializeException(e){const t=JSON.parse(JSON.stringify(e));return e.message&&(t.message=e.message),e.stack&&(t.stack=e.stack),e.constructor&&e.constructor.name&&(t.type=e.constructor.name),t}onMidiLoaded(e){this._main.postMessage({cmd:"alphaSynth.midiLoaded",currentTime:e.currentTime,endTime:e.endTime,currentTick:e.currentTick,endTick:e.endTick,isSeek:e.isSeek})}onMidiLoadFailed(e){this._main.postMessage({cmd:"alphaSynth.midiLoaded",error:this.serializeException(e)})}onReadyForPlayback(){this._main.postMessage({cmd:"alphaSynth.readyForPlayback"})}onMidiEventsPlayed(e){this._main.postMessage({cmd:"alphaSynth.midiEventsPlayed",events:e.events.map($a.midiEventToJsObject)})}onPlaybackRangeChanged(e){this._main.postMessage({cmd:"alphaSynth.playbackRangeChanged",playbackRange:e.playbackRange})}}!function(e){e[e.Browser=0]="Browser",e[e.NodeJs=1]="NodeJs",e[e.BrowserModule=2]="BrowserModule"}(Kt||(Kt={}));class Ka{constructor(e,t){this.characterWidths=e,this.fontSizeToHeight=t}}class Qa{static generateFontLookup(e){if(!Qa.FontSizeLookupTables.has(e))if(rc.isRunningInWorker||rc.webPlatform===Kt.NodeJs){const t=new Ka(new Uint8Array([8]),1.2);Qa.FontSizeLookupTables.set(e,t)}else{const t=document.createElement("canvas").getContext("2d"),s=11;t.font=`${s}px ${e}`;const i=[];let a="";for(let e=Qa.ControlChars;e<255;e++){const s=String.fromCharCode(e);a+=s;const r=t.measureText(s);i.push(r.width)}const r=t.measureText(`${a}ÄÖÜÁÈ`),n=0-Math.abs(r.fontBoundingBoxAscent),o=0+Math.abs(r.fontBoundingBoxDescent)-n,h=new Ka(new Uint8Array(i),o/s);Qa.FontSizeLookupTables.set(e,h)}}static measureString(e,t,s,i,a){let r;let n=t[0];for(let e=0;e<t.length;e++)if(Qa.FontSizeLookupTables.has(t[e])){n=t[e];break}Qa.FontSizeLookupTables.has(n)||Qa.generateFontLookup(n),r=Qa.FontSizeLookupTables.get(n);let o=1;i===Jt.Italic&&(o*=1.1),a===Yt.Bold&&(o*=1.1);let h=0;for(let t=0;t<e.length;t++){const i=Math.min(r.characterWidths.length-1,e.charCodeAt(t)-Qa.ControlChars);i>=0&&(h+=r.characterWidths[i]*s/11)}return o*=1.07,new De(h*o,s*r.fontSizeToHeight)}}Qa.FontSizeLookupTables=new Map,Qa.ControlChars=32;class Za{constructor(){this.id=ie.newGuid(),this.x=0,this.y=0,this.width=0,this.height=0,this.totalWidth=0,this.totalHeight=0,this.firstMasterBarIndex=-1,this.lastMasterBarIndex=-1,this.renderResult=null}}class er{constructor(){this.beats=[]}addBeat(e){e.barBounds=this,this.beats.push(e),this.masterBarBounds.addBeat(e)}findBeatAtPos(e){let t=null;for(const s of this.beats)if(!t||s.realBounds.x<e)t=s;else if(s.realBounds.x>e)break;return t}finish(e=1){this.realBounds.scaleWith(e),this.visualBounds.scaleWith(e),this.beats.sort(((e,t)=>e.realBounds.x-t.realBounds.x));for(const t of this.beats)t.finish(e)}}class tr{constructor(){this.onNotesX=0,this.notes=null}addNote(e){this.notes||(this.notes=[]),e.beatBounds=this,this.notes.push(e)}findNoteAtPos(e,t){const s=this.notes;if(!s)return null;for(const i of s){const s=i.noteHeadBounds.y+i.noteHeadBounds.h,a=i.noteHeadBounds.x+i.noteHeadBounds.w;if(i.noteHeadBounds.x<=e&&i.noteHeadBounds.y<=t&&e<=a&&t<=s)return i.note}return null}finish(e=1){if(this.realBounds.scaleWith(e),this.visualBounds.scaleWith(e),this.onNotesX*=e,this.notes)for(const t of this.notes)t.finish(e)}}class sr{constructor(){this.index=0,this.isFirstOfLine=!1,this.bars=[],this.staffSystemBounds=null}get staveGroupBounds(){return this.staffSystemBounds}addBar(e){e.masterBarBounds=this,this.bars.push(e)}findBeatAtPos(e,t){let s=null;for(const t of this.bars){const i=t.findBeatAtPos(e);if(i&&(!s||s.realBounds.x<i.realBounds.x)){const t=Math.abs(i.realBounds.x-e);(!s||t<1e7)&&(s=i)}}return s?s.beat:null}finish(e=1){this.realBounds.scaleWith(e),this.visualBounds.scaleWith(e),this.lineAlignedBounds.scaleWith(e),this.bars.sort(((e,t)=>e.realBounds.y<t.realBounds.y?-1:e.realBounds.y>t.realBounds.y?1:e.realBounds.x<t.realBounds.x?-1:e.realBounds.x>t.realBounds.x?1:0));for(const t of this.bars)t.finish(e)}addBeat(e){this.staffSystemBounds.boundsLookup.addBeat(e)}}class ir{finish(e=1){this.noteHeadBounds.scaleWith(e)}}class ar{constructor(){this.index=0,this.bars=[]}finish(e=1){this.realBounds.scaleWith(e),this.visualBounds.scaleWith(e);for(const t of this.bars)t.finish(e)}addBar(e){this.boundsLookup.addMasterBar(e),e.staffSystemBounds=this,this.bars.push(e)}findBarAtPos(e){let t=null;for(const s of this.bars)if(!t||s.realBounds.x<e)t=s;else if(e>s.realBounds.x+s.realBounds.w)break;return t}}class rr{constructor(){this._beatLookup=new Map,this._masterBarLookup=new Map,this._currentStaffSystem=null,this.staffSystems=[],this.isFinished=!1}toJson(){const e={},t=[];e.staffSystems=t;for(const e of this.staffSystems){const s={};s.visualBounds=this.boundsToJson(e.visualBounds),s.realBounds=this.boundsToJson(e.realBounds),s.bars=[];for(const t of e.bars){const e={};e.lineAlignedBounds=this.boundsToJson(t.lineAlignedBounds),e.visualBounds=this.boundsToJson(t.visualBounds),e.realBounds=this.boundsToJson(t.realBounds),e.index=t.index,e.bars=[];for(const s of t.bars){const t={};t.visualBounds=this.boundsToJson(s.visualBounds),t.realBounds=this.boundsToJson(s.realBounds),t.beats=[];for(const e of s.beats){const s={};s.visualBounds=this.boundsToJson(e.visualBounds),s.realBounds=this.boundsToJson(e.realBounds),s.onNotesX=e.onNotesX;const i=s;if(i.beatIndex=e.beat.index,i.voiceIndex=e.beat.voice.index,i.barIndex=e.beat.voice.bar.index,i.staffIndex=e.beat.voice.bar.staff.index,i.trackIndex=e.beat.voice.bar.staff.track.index,e.notes){const t=[];s.notes=t;for(const s of e.notes){const e={};e.index=s.note.index,e.noteHeadBounds=this.boundsToJson(s.noteHeadBounds),t.push(e)}}t.beats.push(s)}e.bars.push(t)}s.bars.push(e)}t.push(s)}return e}static fromJson(e,t){const s=new rr,i=e.staffSystems;for(const e of i){const i=new ar;i.visualBounds=rr.boundsFromJson(e.visualBounds),i.realBounds=rr.boundsFromJson(e.realBounds),s.addStaffSystem(i);for(const s of e.bars){const e=new sr;e.index=s.index,e.isFirstOfLine=s.isFirstOfLine,e.lineAlignedBounds=rr.boundsFromJson(s.lineAlignedBounds),e.visualBounds=rr.boundsFromJson(s.visualBounds),e.realBounds=rr.boundsFromJson(s.realBounds),i.addBar(e);for(const i of s.bars){const s=new er;s.visualBounds=rr.boundsFromJson(i.visualBounds),s.realBounds=rr.boundsFromJson(i.realBounds),e.addBar(s);for(const e of i.beats){const i=new tr;i.visualBounds=rr.boundsFromJson(e.visualBounds),i.realBounds=rr.boundsFromJson(e.realBounds),i.onNotesX=e.onNotesX;const a=e;if(i.beat=t.tracks[a.trackIndex].staves[a.staffIndex].bars[a.barIndex].voices[a.voiceIndex].beats[a.beatIndex],e.notes){i.notes=[];for(const t of e.notes){const e=new ir,s=t;e.note=i.beat.notes[s.index],e.noteHeadBounds=rr.boundsFromJson(t.noteHeadBounds),i.addNote(e)}}s.addBeat(i)}}}}return s}static boundsFromJson(e){const t=new mt;return t.x=e.x,t.y=e.y,t.w=e.w,t.h=e.h,t}boundsToJson(e){const t={};return t.x=e.x,t.y=e.y,t.w=e.w,t.h=e.h,t}finish(e=1){for(const t of this.staffSystems)t.finish(e);this.isFinished=!0}addStaffSystem(e){e.index=this.staffSystems.length,e.boundsLookup=this,this.staffSystems.push(e),this._currentStaffSystem=e}addMasterBar(e){e.staffSystemBounds?this._masterBarLookup.set(e.index,e):(e.staffSystemBounds=this._currentStaffSystem,this._masterBarLookup.set(e.index,e),this._currentStaffSystem.addBar(e))}addBeat(e){this._beatLookup.has(e.beat.id)||this._beatLookup.set(e.beat.id,[]),this._beatLookup.get(e.beat.id)?.push(e)}findMasterBarByIndex(e){return this._masterBarLookup.has(e)?this._masterBarLookup.get(e):null}findMasterBar(e){const t=e.index;return this._masterBarLookup.has(t)?this._masterBarLookup.get(t):null}findBeat(e){const t=this.findBeats(e);return t?t[0]:null}findBeats(e){const t=e.id;return this._beatLookup.has(t)?this._beatLookup.get(t):null}getBeatAtPos(e,t){let s=0,i=this.staffSystems.length-1,a=-1;for(;s<=i;){const e=(i+s)/2|0,r=this.staffSystems[e];if(t>=r.realBounds.y&&t<=r.realBounds.y+r.realBounds.h){a=e;break}t<r.realBounds.y?i=e-1:s=e+1}if(-1===a)return null;const r=this.staffSystems[a].findBarAtPos(e);return r?r.findBeatAtPos(e,t):null}getNoteAtPos(e,t,s){const i=this.findBeats(e);if(i)for(const e of i){const i=e.findNoteAtPos(t,s);if(i)return i}return null}}class nr{constructor(t){this._currentLayoutMode=e.Page,this._currentRenderEngine=null,this._renderedTracks=null,this.canvas=null,this.score=null,this.tracks=null,this.layout=null,this.boundsLookup=null,this.width=0,this.preRender=new Zi,this.renderFinished=new Zi,this.partialRenderFinished=new Zi,this.partialLayoutFinished=new Zi,this.postRenderFinished=new Qi,this.error=new Zi,this.settings=t,this.recreateCanvas(),this.recreateLayout()}destroy(){this.score=null,this.canvas?.destroy(),this.canvas=null,this.layout=null,this.boundsLookup=null,this.tracks=null}recreateCanvas(){return this._currentRenderEngine!==this.settings.core.engine&&(this.canvas?.destroy(),this.canvas=rc.getRenderEngineFactory(this.settings.core.engine).createCanvas(),this._currentRenderEngine=this.settings.core.engine,!0)}recreateLayout(){return(!this.layout||this._currentLayoutMode!==this.settings.display.layoutMode)&&(this.layout=rc.getLayoutEngineFactory(this.settings.display.layoutMode).createLayout(this),this._currentLayoutMode=this.settings.display.layoutMode,!0)}renderScore(e,t){try{this.score=e;let s=null;if(null!=e&&null!=t){if(t){s=[];for(const i of t)i>=0&&i<e.tracks.length&&s.push(e.tracks[i])}else s=e.tracks.slice(0);0===s.length&&e.tracks.length>0&&s.push(e.tracks[0])}this.tracks=s,this.render()}catch(e){this.error.trigger(e)}}renderTracks(e){0===e.length?this.score=null:this.score=e[0].score,this.tracks=e,this.render()}updateSettings(e){this.settings=e}renderResult(e){try{const t=this.layout;t?(q.debug("Rendering",`Request render of lazy partial ${e}`),t.renderLazyPartial(e)):q.warning("Rendering",`Request render of lazy partial ${e} ignored, no layout exists`)}catch(e){this.error.trigger(e)}}render(){if(0!==this.width)if(this.boundsLookup=new rr,this.recreateCanvas(),this.canvas.lineWidth=1,this.canvas.settings=this.settings,this.tracks&&0!==this.tracks.length&&this.score){q.debug("Rendering",`Rendering ${this.tracks.length} tracks`);for(let e=0;e<this.tracks.length;e++){const t=this.tracks[e];q.debug("Rendering",`Track ${e}: ${t.name}`)}this.preRender.trigger(!1),this.recreateLayout(),this.layoutAndRender(),q.debug("Rendering","Rendering finished")}else q.debug("Rendering","Clearing rendered tracks because no score or tracks are set"),this.preRender.trigger(!1),this._renderedTracks=null,this.onRenderFinished(),this.postRenderFinished.trigger(),q.debug("Rendering","Clearing finished");else q.warning("Rendering","AlphaTab skipped rendering because of width=0 (element invisible)",null)}resizeRender(){this.recreateLayout()||this.recreateCanvas()||this._renderedTracks!==this.tracks||!this.tracks?(q.debug("Rendering","Starting full rerendering due to layout or canvas change",null),this.render()):this.layout.supportsResize?(q.debug("Rendering","Starting optimized rerendering for resize"),this.boundsLookup=new rr,this.preRender.trigger(!0),this.canvas.settings=this.settings,this.layout.resize(),this.onRenderFinished(),this.postRenderFinished.trigger()):q.debug("Rendering","Current layout does not support dynamic resizing, nothing was done",null),q.debug("Rendering","Resize finished")}layoutAndRender(){q.debug("Rendering",`Rendering at scale ${this.settings.display.scale} with layout ${this.layout.name}`,null),this.layout.layoutAndRender(),this._renderedTracks=this.tracks,this.onRenderFinished(),this.postRenderFinished.trigger()}onRenderFinished(){this.boundsLookup?.finish(this.settings.display.scale);const e=new Za;e.totalHeight=this.layout.height,e.totalWidth=this.layout.width,e.renderResult=this.canvas.onRenderFinished(),this.renderFinished.trigger(e)}}class or{constructor(e){this._main=e,this._main.addEventListener("message",this.handleMessage.bind(this),!1)}static init(){rc.globalThis.alphaTabWebWorker=new or(rc.globalThis)}handleMessage(e){const t=e.data;switch(t?t.cmd:""){case"alphaTab.initialize":const e=$a.jsObjectToSettings(t.settings);q.logLevel=e.core.logLevel,this._renderer=new nr(e),this._renderer.partialRenderFinished.on((e=>{this._main.postMessage({cmd:"alphaTab.partialRenderFinished",result:e})})),this._renderer.partialLayoutFinished.on((e=>{this._main.postMessage({cmd:"alphaTab.partialLayoutFinished",result:e})})),this._renderer.renderFinished.on((e=>{this._main.postMessage({cmd:"alphaTab.renderFinished",result:e})})),this._renderer.postRenderFinished.on((()=>{this._main.postMessage({cmd:"alphaTab.postRenderFinished",boundsLookup:this._renderer.boundsLookup?.toJson()??null})})),this._renderer.preRender.on((e=>{this._main.postMessage({cmd:"alphaTab.preRender",resize:e})})),this._renderer.error.on(this.error.bind(this));break;case"alphaTab.invalidate":this._renderer.render();break;case"alphaTab.resizeRender":this._renderer.resizeRender();break;case"alphaTab.renderResult":this._renderer.renderResult(t.resultId);break;case"alphaTab.setWidth":this._renderer.width=t.width;break;case"alphaTab.renderScore":this.updateFontSizes(t.fontSizes);const s=null==t.score?null:$a.jsObjectToScore(t.score,this._renderer.settings);this.renderMultiple(s,t.trackIndexes);break;case"alphaTab.updateSettings":this.updateSettings(t.settings)}}updateFontSizes(e){if(!(e instanceof Map)){const t=e;e=new Map;for(const s in t)e.set(s,t[s])}if(e){Qa.FontSizeLookupTables||(Qa.FontSizeLookupTables=new Map);for(const[t,s]of e)Qa.FontSizeLookupTables.set(t,s)}}updateSettings(e){wa.fromJson(this._renderer.settings,e)}renderMultiple(e,t){try{this._renderer.renderScore(e,t)}catch(e){this.error(e)}}error(e){q.error("Worker","An unexpected error occurred in worker",e),this._main.postMessage({cmd:"alphaTab.error",error:e})}}class hr{constructor(){this._canvas=null,this._color=new et(0,0,0,255),this._font=new na("Arial",10,Jt.Plain),this._lineWidth=0;const e=document.createElement("span");e.classList.add("at"),document.body.appendChild(e);const t=window.getComputedStyle(e);let s=t.fontFamily;(s.startsWith('"')||s.startsWith("'"))&&(s=s.substr(1,s.length-2)),this._musicFont=new na(s,Number.parseFloat(t.fontSize),Jt.Plain),this._measureCanvas=document.createElement("canvas"),this._measureCanvas.width=10,this._measureCanvas.height=10,this._measureCanvas.style.width="10px",this._measureCanvas.style.height="10px",this._measureContext=this._measureCanvas.getContext("2d"),this._measureContext.textBaseline="hanging"}destroy(){}onRenderFinished(){return null}beginRender(e,t){const s=this.settings.display.scale;this._canvas=document.createElement("canvas"),this._canvas.width=e*rc.HighDpiFactor|0,this._canvas.height=t*rc.HighDpiFactor|0,this._canvas.style.width=`${e}px`,this._canvas.style.height=`${t}px`,this._context=this._canvas.getContext("2d"),this._context.textBaseline="hanging",this._context.scale(rc.HighDpiFactor*s,rc.HighDpiFactor*s),this._context.lineWidth=this._lineWidth}endRender(){const e=this._canvas;return this._canvas=null,e}get color(){return this._color}set color(e){this._color.rgba!==e.rgba&&(this._color=e,this._context.strokeStyle=e.rgba,this._context.fillStyle=e.rgba)}get lineWidth(){return this._lineWidth}set lineWidth(e){this._lineWidth=e,this._context&&(this._context.lineWidth=e)}fillRect(e,t,s,i){s>0&&this._context.fillRect(0|e,0|t,s,i)}strokeRect(e,t,s,i){const a=this.lineWidth%2==0?0:.5;this._context.strokeRect((0|e)+a,(0|t)+a,s,i)}beginPath(){this._context.beginPath()}closePath(){this._context.closePath()}moveTo(e,t){this._context.moveTo(e,t)}lineTo(e,t){this._context.lineTo(e,t)}quadraticCurveTo(e,t,s,i){this._context.quadraticCurveTo(e,t,s,i)}bezierCurveTo(e,t,s,i,a,r){this._context.bezierCurveTo(e,t,s,i,a,r)}fillCircle(e,t,s){this._context.beginPath(),this._context.arc(e,t,s,0,2*Math.PI,!0),this.fill()}strokeCircle(e,t,s){this._context.beginPath(),this._context.arc(e,t,s,0,2*Math.PI,!0),this.stroke()}fill(){this._context.fill(),this._context.beginPath()}stroke(){this._context.stroke(),this._context.beginPath()}get font(){return this._font}set font(e){this._font=e,this._context&&(this._context.font=e.toCssString(1)),this._measureContext.font=e.toCssString(1)}get textAlign(){switch(this._context.textAlign){case"left":default:return ne.Left;case"center":return ne.Center;case"right":return ne.Right}}set textAlign(e){switch(e){case ne.Left:this._context.textAlign="left";break;case ne.Center:this._context.textAlign="center";break;case ne.Right:this._context.textAlign="right"}}get textBaseline(){switch(this._context.textBaseline){case"hanging":default:return oe.Top;case"middle":return oe.Middle;case"bottom":return oe.Bottom}}set textBaseline(e){switch(e){case oe.Top:this._context.textBaseline="hanging";break;case oe.Middle:this._context.textBaseline="middle";break;case oe.Bottom:this._context.textBaseline="bottom"}}beginGroup(e){}endGroup(){}fillText(e,t,s){this._context.fillText(e,t,s)}measureText(e){const t=this._measureContext.measureText(e);return new De(t.width,t.actualBoundingBoxDescent+t.actualBoundingBoxAscent)}fillMusicFontSymbol(e,t,s,i,a=!1){i!==re.None&&this.fillMusicFontSymbolText(e,t,s,String.fromCharCode(i),a)}fillMusicFontSymbols(e,t,s,i,a=!1){let r="";for(const e of i)e!==re.None&&(r+=String.fromCharCode(e));this.fillMusicFontSymbolText(e,t,s,r,a)}fillMusicFontSymbolText(e,t,s,i,a){const r=this._context.textAlign,n=this._context.textBaseline,o=this._context.font;this._context.font=this._musicFont.toCssString(s),this._context.textBaseline="middle",this._context.textAlign=a?"center":"left",this._context.fillText(i,e,t),this._context.textBaseline=n,this._context.font=o,this._context.textAlign=r}beginRotate(e,t,s){this._context.save(),this._context.translate(e,t),this._context.rotate(s*Math.PI/180)}endRotate(){this._context.restore()}}class lr{constructor(e,t=!1){this._midiFile=e,this._smf1Mode=t}addTimeSignature(e,t,s){let i=0,a=s;for(;a>>=1,a>0;)i++;this._midiFile.addEvent(new Cs(0,e,t,i,48,8))}addRest(e,t,s){this._smf1Mode||this._midiFile.addEvent(new Ls(e,t,s))}addNote(e,t,s,i,a,r){this._midiFile.addEvent(new Is(e,t,r,lr.fixValue(i),lr.fixValue(a))),this._midiFile.addEvent(new As(e,t+s,r,lr.fixValue(i),lr.fixValue(a)))}static fixValue(e){return e>127?127:e<0?0:e}addControlChange(e,t,s,i,a){this._midiFile.addEvent(new Rs(e,t,s,i,lr.fixValue(a)))}addProgramChange(e,t,s,i){this._midiFile.addEvent(new Os(e,t,s,i))}addTempo(e,t){const s=6e7/t|0;this._midiFile.addEvent(new Hs(e,s))}addBend(e,t,s,i){i=i>=K.MaxPitchWheel?K.MaxPitchWheel:Math.floor(i),this._midiFile.addEvent(new Ws(e,t,s,i))}addNoteBend(e,t,s,i,a){this._smf1Mode?this.addBend(e,t,s,a):(a=a*K.MaxPitchWheel20/K.MaxPitchWheel,this._midiFile.addEvent(new Vs(e,t,s,i,a)))}finishTrack(e,t){this._midiFile.format!==At.MultiTrack&&0!==e||this._midiFile.addEvent(new Gs(e,t))}}class cr{constructor(e,t){this.closingIndex=0,this.group=e,this.opening=t,e.closings=e.closings.sort(((e,t)=>e.index-t.index)),this.iterations=e.closings.map((e=>0))}}!function(e){e[e.PlayingNormally=0]="PlayingNormally",e[e.DirectionJumped=1]="DirectionJumped",e[e.DirectionJumpedAlCoda=2]="DirectionJumpedAlCoda",e[e.DirectionJumpedAlDoubleCoda=3]="DirectionJumpedAlDoubleCoda",e[e.DirectionJumpedAlFine=4]="DirectionJumpedAlFine"}(Qt||(Qt={}));class dr{get finished(){return this.index>=this._score.masterBars.length}constructor(e){this._repeatStack=[],this._groupsOnStack=new Set,this._previousAlternateEndings=0,this._state=Qt.PlayingNormally,this.shouldPlay=!0,this.index=0,this.currentTick=0,this._score=e}processCurrent(){const e=this._score.masterBars[this.index];if(this._state===Qt.PlayingNormally){let t=e.alternateEndings;if(0===t&&(t=this._previousAlternateEndings),e===e.repeatGroup.opening&&e.repeatGroup.isClosed&&!this._groupsOnStack.has(e.repeatGroup)){const s=new cr(e.repeatGroup,e);this._repeatStack.push(s),this._groupsOnStack.add(e.repeatGroup),this._previousAlternateEndings=0,t=e.alternateEndings}if(0===this._repeatStack.length||0===t)this.shouldPlay=!0;else{const e=this._repeatStack[this._repeatStack.length-1],s=e.iterations[e.closingIndex];this._previousAlternateEndings=t,this.shouldPlay=!!(t&1<<s)}}else this.shouldPlay=!0;this.shouldPlay&&(this.currentTick+=e.calculateDuration())}moveNext(){this.moveNextWithDirections()||this.moveNextWithNormalRepeats()}resetRepeats(){this._groupsOnStack.clear(),this._previousAlternateEndings=0,this._repeatStack=[]}handleDaCapo(e,t,s){return!!e.has(t)&&(this.index=0,this._state=s,this.resetRepeats(),!0)}handleDalSegno(e,t,s,i){if(e.has(t)){const e=this.findJumpTarget(i,this.index,!0);return-1!==e&&(this.index=e,this._state=s,this.resetRepeats(),!0)}return!1}handleDaCoda(e,t,s){if(e.has(t)){const e=this.findJumpTarget(s,this.index,!1);return-1===e?(this.index++,!0):(this.index=e,this._state=Qt.PlayingNormally,!0)}return!1}moveNextWithDirections(){const e=this._score.masterBars[this.index],t=null!==e.directions&&e.directions.size>0;if(this._state===Qt.PlayingNormally&&!t)return!1;if(!t)return this.index++,!0;switch(this._state){case Qt.PlayingNormally:return!!(this.handleDaCapo(e.directions,Be.JumpDaCapo,Qt.DirectionJumped)||this.handleDaCapo(e.directions,Be.JumpDaCapoAlCoda,Qt.DirectionJumpedAlCoda)||this.handleDaCapo(e.directions,Be.JumpDaCapoAlDoubleCoda,Qt.DirectionJumpedAlDoubleCoda)||this.handleDaCapo(e.directions,Be.JumpDaCapoAlFine,Qt.DirectionJumpedAlFine))||(!!(this.handleDalSegno(e.directions,Be.JumpDalSegno,Qt.DirectionJumped,Be.TargetSegno)||this.handleDalSegno(e.directions,Be.JumpDalSegnoAlCoda,Qt.DirectionJumpedAlCoda,Be.TargetSegno)||this.handleDalSegno(e.directions,Be.JumpDalSegnoAlDoubleCoda,Qt.DirectionJumpedAlDoubleCoda,Be.TargetSegno)||this.handleDalSegno(e.directions,Be.JumpDalSegnoAlFine,Qt.DirectionJumpedAlFine,Be.TargetSegno))||!!(this.handleDalSegno(e.directions,Be.JumpDalSegnoSegno,Qt.DirectionJumped,Be.TargetSegnoSegno)||this.handleDalSegno(e.directions,Be.JumpDalSegnoSegnoAlCoda,Qt.DirectionJumpedAlCoda,Be.TargetSegnoSegno)||this.handleDalSegno(e.directions,Be.JumpDalSegnoSegnoAlDoubleCoda,Qt.DirectionJumpedAlDoubleCoda,Be.TargetSegnoSegno)||this.handleDalSegno(e.directions,Be.JumpDalSegnoSegnoAlFine,Qt.DirectionJumpedAlFine,Be.TargetSegnoSegno)));case Qt.DirectionJumped:return this.index++,!0;case Qt.DirectionJumpedAlCoda:return this.handleDaCoda(e.directions,Be.JumpDaCoda,Be.TargetCoda)||this.index++,!0;case Qt.DirectionJumpedAlDoubleCoda:return this.handleDaCoda(e.directions,Be.JumpDaDoubleCoda,Be.TargetDoubleCoda)||this.index++,!0;case Qt.DirectionJumpedAlFine:return e.directions.has(Be.TargetFine)?(this.index=this._score.masterBars.length,!0):(this.index++,!0)}return!0}findJumpTarget(e,t,s){let i;return s?(i=this.findJumpTargetBackwards(e,t),-1===i&&(i=this.findJumpTargetForwards(e,t)),i):(i=this.findJumpTargetForwards(e,t),-1===i&&(i=this.findJumpTargetBackwards(e,t)),i)}findJumpTargetForwards(e,t){let s=t;for(;s<this._score.masterBars.length;){const t=this._score.masterBars[s].directions;if(t&&t.has(e))return s;s++}return-1}findJumpTargetBackwards(e,t){let s=t;for(;s>=0;){const t=this._score.masterBars[s].directions;if(t&&t.has(e))return s;s--}return-1}moveNextWithNormalRepeats(){const e=this._score.masterBars[this.index].repeatCount-1;if(this._repeatStack.length>0&&e>0){const t=this._repeatStack[this._repeatStack.length-1];if(t.iterations[t.closingIndex]<e){this.index=t.opening.index,t.iterations[t.closingIndex]++;for(let e=0;e<t.closingIndex;e++)t.iterations[e]=0;t.closingIndex=0,this._previousAlternateEndings=0}else t.closingIndex<t.group.closings.length-1?(t.closingIndex++,this.index++):(this._repeatStack.pop(),this._groupsOnStack.delete(t.group),this.index++)}else this.index++}}class ur{constructor(e,t){this.beat=e,this.playbackStart=t}}class pr{get duration(){return this.end-this.start}constructor(e,t){this._highlightedBeats=new Map,this.highlightedBeats=[],this.nextBeat=null,this.previousBeat=null,this.start=e,this.end=t}highlightBeat(e,t){e.isEmpty&&!e.voice.isEmpty||this._highlightedBeats.has(e.id)||(this._highlightedBeats.set(e.id,!0),this.highlightedBeats.push(new ur(e,t)))}getVisibleBeatAtStart(e){for(const t of this.highlightedBeats)if(t.playbackStart===this.start&&e.has(t.beat.voice.bar.staff.track.index))return t.beat;return null}}class gr{constructor(e,t){this.tick=e,this.tempo=t}}class mr{constructor(){this.start=0,this.end=0,this.tempoChanges=[],this.firstBeat=null,this.lastBeat=null,this.nextMasterBar=null,this.previousMasterBar=null}get tempo(){return this.tempoChanges[0].tempo}insertAfter(e,t){null==this.firstBeat||null==e||null==this.lastBeat?(this.firstBeat=t,this.lastBeat=t):(t.nextBeat=e.nextBeat,t.previousBeat=e,e.nextBeat&&(e.nextBeat.previousBeat=t),e.nextBeat=t,e===this.lastBeat&&(this.lastBeat=t))}insertBefore(e,t){null==this.firstBeat||null==e||null==this.lastBeat?(this.firstBeat=t,this.lastBeat=t):(t.previousBeat=e.previousBeat,t.nextBeat=e,e.previousBeat&&(e.previousBeat.nextBeat=t),e.previousBeat=t,e===this.firstBeat&&(this.firstBeat=t))}addBeat(e,t,s,i){const a=s+i;if(null==this.firstBeat){const i=new pr(s,a);i.highlightBeat(e,t),this.insertAfter(this.firstBeat,i)}else if(s>=this.lastBeat.end){const s=new pr(this.lastBeat.end,a);s.highlightBeat(e,t),this.insertAfter(this.lastBeat,s)}else{let i=null;if(s<this.firstBeat.start)i=this.firstBeat;else{let e=this.firstBeat;for(;null!=e;){if(s>=e.start&&s<e.end){i=e;break}e=e.nextBeat}if(null===i)throw new $e(Se.General,"Error on building lookup, unknown variant")}if(s<i.start)if(a===i.start){const a=new pr(s,i.start);a.highlightBeat(e,t),this.insertBefore(this.firstBeat,a)}else if(a<i.end){const r=new pr(s,i.start);r.highlightBeat(e,t),this.insertBefore(i,r);const n=new pr(i.start,a);for(const e of i.highlightedBeats)n.highlightBeat(e.beat,e.playbackStart);n.highlightBeat(e,t),this.insertBefore(i,n),i.start=a}else if(a===i.end){const a=new pr(s,i.start);a.highlightBeat(e,t),i.highlightBeat(e,t),this.insertBefore(i,a)}else{const r=new pr(s,i.start);r.highlightBeat(e,t),i.highlightBeat(e,t),this.insertBefore(i,r),this.addBeat(e,t,i.end,a-i.end)}else if(s>i.start)if(a===i.end){const a=new pr(i.start,s);for(const e of i.highlightedBeats)a.highlightBeat(e.beat,e.playbackStart);i.start=s,i.highlightBeat(e,t),this.insertBefore(i,a)}else if(a<i.end){const r=new pr(i.start,s);this.insertBefore(i,r);const n=new pr(s,a);this.insertBefore(i,n);for(const e of i.highlightedBeats)r.highlightBeat(e.beat,e.playbackStart),n.highlightBeat(e.beat,e.playbackStart);n.highlightBeat(e,t),i.start=a}else{const r=new pr(i.start,s);for(const e of i.highlightedBeats)r.highlightBeat(e.beat,e.playbackStart);i.start=s,i.highlightBeat(e,t),this.insertBefore(i,r),this.addBeat(e,t,i.end,a-i.end)}else if(a===i.end)i.highlightBeat(e,t);else if(a<i.end){const s=new pr(i.start,a);for(const e of i.highlightedBeats)s.highlightBeat(e.beat,e.playbackStart);s.highlightBeat(e,t),i.start=a,this.insertBefore(i,s)}else i.highlightBeat(e,t),this.addBeat(e,t,i.end,a-i.end)}}}!function(e){e[e.Unknown=0]="Unknown",e[e.ToNextBext=1]="ToNextBext",e[e.ToEndOfBar=2]="ToEndOfBar"}(Zt||(Zt={}));class fr{get start(){return this.masterBar.start+this.beatLookup.start}get end(){return this.start+this.tickDuration}constructor(e){this.nextBeat=null,this.tickDuration=0,this.duration=0,this.cursorMode=Zt.Unknown,this.masterBar=e}calculateDuration(){if(1===this.masterBar.tempoChanges.length)this.duration=z.ticksToMillis(this.tickDuration,this.masterBar.tempoChanges[0].tempo);else{let e=0,t=this.start,s=this.masterBar.tempoChanges[0].tempo;const i=this.end;for(const a of this.masterBar.tempoChanges)if(a.tick<t)s=a.tempo;else{if(a.tick>i)break;e+=z.ticksToMillis(a.tick-t,s),s=a.tempo,t=a.tick}i>t&&(e+=z.ticksToMillis(i-t,s)),this.duration=e}}}class yr{constructor(){this._currentMasterBar=null,this.masterBarLookup=new Map,this.masterBars=[],this.multiBarRestInfo=null}findBeat(e,t,s=null){let i=null;return s&&(i=this.findBeatFast(e,s,t)),i||(i=this.findBeatSlow(e,s,t,!1)),i}findBeatFast(e,t,s){if(s>=t.start&&s<t.end)return t;if(t.nextBeat&&s>=t.nextBeat.start&&s<t.nextBeat.end){const s=t.nextBeat;return this.fillNextBeat(s,e),s}return null}fillNextBeatMultiBarRest(e,t){const s=this.multiBarRestInfo.get(e.masterBar.masterBar.index);let i=e.masterBar;for(let e=0;e<s.length&&i;e++)i=i.nextMasterBar;i?i.nextMasterBar?(e.nextBeat=this.firstBeatInMasterBar(t,i.nextMasterBar,i.nextMasterBar.start,!0),e.nextBeat?(e.tickDuration=e.nextBeat.start-e.start,e.cursorMode=Zt.ToNextBext,e.nextBeat.masterBar.masterBar.index!==i.masterBar.index+1&&(e.nextBeat.masterBar.masterBar.index!==i.masterBar.index||e.nextBeat.beat.playbackStart<=e.beat.playbackStart)&&(e.cursorMode=Zt.ToEndOfBar)):(e.tickDuration=i.nextMasterBar.end-e.start,e.cursorMode=Zt.ToEndOfBar)):(e.tickDuration=i.end-e.start,e.cursorMode=Zt.ToEndOfBar):(q.warning("Synth","MultiBar Rest Info and the nextMasterBar are out of sync, this is an unexpected error. Please report it as bug. (broken chain fill-next)"),e.tickDuration=(e.masterBar.end-e.masterBar.start)*(s.length+1),e.cursorMode=Zt.ToEndOfBar),e.calculateDuration()}fillNextBeat(e,t){this.isMultiBarRestResult(e)?this.fillNextBeatMultiBarRest(e,t):this.fillNextBeatDefault(e,t)}fillNextBeatDefault(e,t){e.nextBeat=this.findBeatInMasterBar(e.masterBar,e.beatLookup.nextBeat,e.end,t,!0),null==e.nextBeat&&(e.nextBeat=this.findBeatSlow(t,e,e.end,!0)),e.nextBeat?(e.tickDuration=e.nextBeat.start-e.start,e.cursorMode=Zt.ToNextBext,e.calculateDuration()):(e.tickDuration=e.masterBar.end-e.start,e.cursorMode=Zt.ToEndOfBar,e.calculateDuration()),e.nextBeat&&e.nextBeat.masterBar.masterBar.index!==e.masterBar.masterBar.index+1&&(e.nextBeat.masterBar.masterBar.index!==e.masterBar.masterBar.index||e.nextBeat.beat.playbackStart<=e.beat.playbackStart)&&(e.cursorMode=Zt.ToEndOfBar)}isMultiBarRestResult(e){return this.internalIsMultiBarRestResult(e.masterBar.masterBar.index,e.beat)}internalIsMultiBarRestResult(e,t){return this.multiBarRestInfo&&this.multiBarRestInfo.has(e)&&t.isRest&&t.voice.bar.isRestOnly}findBeatSlow(e,t,s,i){let a=null;return null!=t&&(t.masterBar.start<=s&&t.masterBar.end>s?a=t.masterBar:t.masterBar.nextMasterBar&&t.masterBar.nextMasterBar.start<=s&&t.masterBar.nextMasterBar.end>s&&(a=t.masterBar.nextMasterBar)),a||(a=this.findMasterBar(s)),a?this.firstBeatInMasterBar(e,a,s,i):null}firstBeatInMasterBar(e,t,s,i){let a=t;for(;a;){if(a.firstBeat){const t=this.findBeatInMasterBar(a,a.firstBeat,s,e,i);if(t)return t}a=a.nextMasterBar}return null}findBeatInMasterBar(e,t,s,i,a){if(!t)return null;let r=null,n=null;const o=s-e.start;for(;null!=t&&null==n;){if((t.start<=o||a&&o<0)&&o<t.end){if(r=t,n=t.getVisibleBeatAtStart(i),!n)if(a){let s=e;for(;null!=s&&null==n;){for(;null!=t;){if(n=t.getVisibleBeatAtStart(i),n){r=t,e=s;break}t=t.nextBeat}n&&r||(s=s.nextMasterBar,t=s?.firstBeat??null)}}else{let s=e;for(;null!=s&&null==n;){for(;null!=t;){if(n=t.getVisibleBeatAtStart(i),n){r=t,e=s;break}t=t.previousBeat}n&&r||(s=s.previousMasterBar,t=s?.firstBeat??null)}}}else if(t.end>o)break;t=t?.nextBeat??null}if(null==n)return null;return this.createResult(e,r,n,a,i)}createResult(e,t,s,i,a){const r=new fr(e);if(r.beat=s,r.beatLookup=t,r.tickDuration=t.end-t.start,i){if(this.isMultiBarRestResult(r)){const s=this.multiBarRestInfo.get(e.masterBar.index);let i=e;for(let e=0;e<s.length&&i;e++)i=i.nextMasterBar;i?i.nextMasterBar?r.tickDuration=i.nextMasterBar.start-t.start:r.tickDuration=i.end-t.start:q.warning("Synth","MultiBar Rest Info and the nextMasterBar are out of sync, this is an unexpected error. Please report it as bug. (broken chain stretch-result)")}}else this.fillNextBeat(r,a);return r.calculateDuration(),r}findMasterBar(e){const t=this.masterBars;let s=0,i=t.length-1;for(;s<=i;){const a=(i+s)/2|0,r=t[a];if(e>=r.start&&e<r.end)return r;e<r.start?i=a-1:s=a+1}return null}getMasterBar(e){if(!this.masterBarLookup.has(e.index)){const t=new mr;return t.masterBar=e,t}return this.masterBarLookup.get(e.index)}getMasterBarStart(e){return this.masterBarLookup.has(e.index)?this.masterBarLookup.get(e.index).start:0}getBeatStart(e){return this.masterBarLookup.has(e.voice.bar.index)?this.masterBarLookup.get(e.voice.bar.index).start+e.playbackStart:0}addMasterBar(e){this.masterBars.push(e),this._currentMasterBar&&(e.previousMasterBar=this._currentMasterBar,this._currentMasterBar.nextMasterBar=e),this._currentMasterBar=e,this.masterBarLookup.has(e.masterBar.index)||this.masterBarLookup.set(e.masterBar.index,e)}addBeat(e,t,s){const i=this._currentMasterBar;if(i)if(t<0&&i.previousMasterBar){const a=i.previousMasterBar.end-i.previousMasterBar.start,r=a+t,n=r+s;if(i.previousMasterBar.addBeat(e,r,r,s),n>a){const a=s+t;i.addBeat(e,t,0,a)}}else i.addBeat(e,t,t,s)}}class br{constructor(){this.noteOnly=0,this.untilTieOrSlideEnd=0,this.letRingEnd=0}}class Sr{constructor(){this.firstBeatDuration=0,this.secondBeatStartOffset=0,this.secondBeatDuration=0}}class _r{constructor(){this.durations=[],this.brushInfos=[]}}class wr{constructor(e,t,s){this._programsPerChannel=new Map,this._currentTime=0,this._calculatedBeatTimers=new Set,this.tickLookup=new yr,this.applyTranspositionPitches=!0,this.transpositionPitches=new Map,this._currentTripletFeel=null,this.vibratoResolution=16,this._score=e,this._settings=t||new Ba,this._handler=s}generate(){this.transpositionPitches.clear(),this._calculatedBeatTimers.clear(),this._currentTime=0;for(const e of this._score.tracks)this.generateTrack(e);q.debug("Midi","Begin midi generation");const e=new dr(this._score);let t=null,s=this._score.tempo;for(;!e.finished;){const i=e.index,a=this._score.masterBars[i],r=e.currentTick;if(e.processCurrent(),e.shouldPlay){this.generateMasterBar(a,t,r,s),a.tempoAutomations.length>0&&(s=a.tempoAutomations[0].value);for(const e of this._score.tracks)for(const t of e.staves)i<t.bars.length&&this.generateBar(t.bars[i],r,s);a.tempoAutomations.length>0&&(s=a.tempoAutomations[a.tempoAutomations.length-1].value)}e.moveNext(),t=a}for(const t of this._score.tracks)this._handler.finishTrack(t.index,e.currentTick);q.debug("Midi","Midi generation done")}generateTrack(e){this.generateChannel(e,e.playbackInfo.primaryChannel,e.playbackInfo),e.playbackInfo.primaryChannel!==e.playbackInfo.secondaryChannel&&this.generateChannel(e,e.playbackInfo.secondaryChannel,e.playbackInfo)}addProgramChange(e,t,s,i){this._programsPerChannel.has(s)&&this._programsPerChannel.get(s)===i||(this._handler.addProgramChange(e.index,t,s,i),this._programsPerChannel.set(s,i))}static buildTranspositionPitches(e,t){const s=new Map;for(const i of e.tracks){const e=i.index<t.notation.transpositionPitches.length?t.notation.transpositionPitches[i.index]:-i.staves[0].transpositionPitch;s.set(i.playbackInfo.primaryChannel,e),s.set(i.playbackInfo.secondaryChannel,e)}return s}generateChannel(e,t,s){const i=e.index<this._settings.notation.transpositionPitches.length?this._settings.notation.transpositionPitches[e.index]:-e.staves[0].transpositionPitch;this.transpositionPitches.set(t,i);const a=wr.toChannelShort(s.volume),r=wr.toChannelShort(s.balance);this._handler.addControlChange(e.index,0,t,Xt.VolumeCoarse,a),this._handler.addControlChange(e.index,0,t,Xt.PanCoarse,r),this._handler.addControlChange(e.index,0,t,Xt.ExpressionControllerCoarse,127),this._handler.addControlChange(e.index,0,t,Xt.RegisteredParameterFine,0),this._handler.addControlChange(e.index,0,t,Xt.RegisteredParameterCourse,0),this._handler.addControlChange(e.index,0,t,Xt.DataEntryFine,0),this._handler.addControlChange(e.index,0,t,Xt.DataEntryCoarse,wr.PitchBendRangeInSemitones),this.addProgramChange(e,0,t,s.program)}static toChannelShort(e){const t=Math.max(-32768,Math.min(32767,8*e-1));return Math.max(t,-1)+1}generateMasterBar(e,t,s,i){t&&t.timeSignatureDenominator===e.timeSignatureDenominator&&t.timeSignatureNumerator===e.timeSignatureNumerator||this._handler.addTimeSignature(s,e.timeSignatureNumerator,e.timeSignatureDenominator);const a=e.calculateDuration(),r=new mr;if(e.tempoAutomations.length>0){e.tempoAutomations[0].ratioPosition>0&&r.tempoChanges.push(new gr(s,i));for(const t of e.tempoAutomations){const e=s+a*t.ratioPosition;this._handler.addTempo(e,t.value),r.tempoChanges.push(new gr(e,t.value))}}else t?r.tempoChanges.push(new gr(s,i)):(this._handler.addTempo(s,e.score.tempo),r.tempoChanges.push(new gr(s,e.score.tempo)));r.masterBar=e,r.start=s,r.end=r.start+a,this.tickLookup.addMasterBar(r)}generateBar(e,t,s){const i=this.getPlaybackBar(e),a=this._currentTime;for(const r of i.voices)this._currentTime=a,this.generateVoice(r,t,e,s);const r=i.masterBar,n=r.calculateDuration(),o=r.tempoAutomations.slice();if(0===o.length)this._currentTime=a+z.ticksToMillis(n,s);else{this._currentTime=a;let e=t,i=s;const r=t+n;for(const t of o){const s=n*t.ratioPosition-e;s>0&&(this._currentTime+=z.ticksToMillis(s,i)),i=t.value,e+=s}const h=r-e;h>0&&(this._currentTime+=z.ticksToMillis(h,i))}i.id!==e.id&&this.tickLookup.addBeat(e.voices[0].beats[0],0,n)}getPlaybackBar(e){switch(e.simileMark){case h.Simple:e.previousBar&&(e=this.getPlaybackBar(e.previousBar));break;case h.FirstOfDouble:case h.SecondOfDouble:e.previousBar&&e.previousBar.previousBar&&(e=this.getPlaybackBar(e.previousBar.previousBar))}return e}generateVoice(e,t,s,i){if(e.isEmpty&&(!e.bar.isEmpty||0!==e.index))return;const a=s.masterBar.tempoAutomations.slice();let r=i;const n=s.masterBar.calculateDuration();for(const i of e.beats){const e=i.playbackStart/n;for(;a.length>0&&a[0].ratioPosition<=e;)r=a.shift().value;this.generateBeat(i,t,s,r)}}generateBeat(e,t,s,i){let a=e.playbackStart,r=e.playbackDuration;const n=e.voice.bar.masterBar.calculateDuration();e.voice.bar.isEmpty?r=n:e.voice.bar.masterBar.tripletFeel!==M.NoTripletFeel&&this._settings.player.playTripletFeel&&(this._currentTripletFeel?(a-=this._currentTripletFeel.secondBeatStartOffset,r=this._currentTripletFeel.secondBeatDuration,this._currentTripletFeel=null):(this._currentTripletFeel=wr.calculateTripletFeelInfo(a,r,e),this._currentTripletFeel&&(r=this._currentTripletFeel.firstBeatDuration))),e.showTimer&&!this._calculatedBeatTimers.has(e.id)&&(e.timer=this._currentTime,this._calculatedBeatTimers.add(e.id)),this._currentTime+=z.ticksToMillis(r,i),s===e.voice.bar&&this.tickLookup.addBeat(e,a,r);const o=e.voice.bar.staff.track;for(const s of e.automations)this.generateNonTempoAutomation(e,s,t);if(e.isRest)this._handler.addRest(o.index,t+a,o.playbackInfo.primaryChannel);else if(e.deadSlapped)this.generateDeadSlap(e,t+a);else{const s=this.getBrushInfo(e),n=this.getRasgueadoInfo(e,r);for(const o of e.notes)this.generateNote(o,t+a,r,i,s,n)}if(e.fade!==ue.None&&this.generateFade(e,t+a,r),e.vibrato!==P.None){let s=240,i=3;switch(e.vibrato){case P.Slight:s=this._settings.player.vibrato.beatSlightLength,i=this._settings.player.vibrato.beatSlightAmplitude;break;case P.Wide:s=this._settings.player.vibrato.beatWideLength,i=this._settings.player.vibrato.beatWideAmplitude}this.generateVibratorWithParams(t+a,e.playbackDuration,s,0,i,((t,s)=>{this._handler.addBend(e.voice.bar.staff.track.index,t,o.playbackInfo.secondaryChannel,s)}))}}static calculateTripletFeelInfo(e,t,s){let i;switch(s.voice.bar.masterBar.tripletFeel){case M.Triplet8th:case M.Dotted8th:case M.Scottish8th:i=_.Eighth;break;case M.Triplet16th:case M.Dotted16th:case M.Scottish16th:i=_.Sixteenth;break;default:return null}const a=z.toTicks(i);if(t!==a)return null;if(e%a!=0)return null;if(!s.nextBeat||s.nextBeat.voice!==s.voice||s.playbackDuration!==a)return null;const r=new Sr;switch(s.voice.bar.masterBar.tripletFeel){case M.Triplet8th:r.firstBeatDuration=z.applyTuplet(z.toTicks(_.Quarter),3,2),r.secondBeatDuration=z.applyTuplet(z.toTicks(_.Eighth),3,2);break;case M.Dotted8th:r.firstBeatDuration=z.applyDot(z.toTicks(_.Eighth),!1),r.secondBeatDuration=z.toTicks(_.Sixteenth);break;case M.Scottish8th:r.firstBeatDuration=z.toTicks(_.Sixteenth),r.secondBeatDuration=z.applyDot(z.toTicks(_.Eighth),!1);break;case M.Triplet16th:r.firstBeatDuration=z.applyTuplet(z.toTicks(_.Eighth),3,2),r.secondBeatDuration=z.applyTuplet(z.toTicks(_.Sixteenth),3,2);break;case M.Dotted16th:r.firstBeatDuration=z.applyDot(z.toTicks(_.Sixteenth),!1),r.secondBeatDuration=z.toTicks(_.ThirtySecond);break;case M.Scottish16th:r.firstBeatDuration=z.toTicks(_.ThirtySecond),r.secondBeatDuration=z.applyDot(z.toTicks(_.Sixteenth),!1)}return r.secondBeatStartOffset=t-r.firstBeatDuration,r}generateDeadSlap(e,t){const s=z.toTicks(_.SixtyFourth),i=e.voice.bar.staff;if(i.tuning.length>0)for(const e of i.tuning)this._handler.addNote(i.track.index,t,s,e,z.dynamicToVelocity(g.F),i.track.playbackInfo.primaryChannel)}needsSecondaryChannel(e){return e.hasBend||e.beat.hasWhammyBar||e.beat.vibrato!==P.None}determineChannel(e,t){if(this.needsSecondaryChannel(t))return e.playbackInfo.secondaryChannel;let s=t;for(;s.isTieDestination;)if(s=s.tieOrigin,this.needsSecondaryChannel(s))return e.playbackInfo.secondaryChannel;for(s=t;s.isTieOrigin;)if(s=s.tieDestination,this.needsSecondaryChannel(s))return e.playbackInfo.secondaryChannel;return e.playbackInfo.primaryChannel}generateNote(e,t,s,i,a,r){const n=e.beat.voice.bar.staff.track,o=e.beat.voice.bar.staff;let h=e.calculateRealValue(this.applyTranspositionPitches,!0);if(e.isPercussion){const t=Le.getArticulation(e);t&&(h=t.outputMidiNumber)}const l=null==r&&e.isStringed&&e.string<=a.length?a[e.string-1]:0,c=t+l,d=this.getNoteDuration(e,s,i);d.untilTieOrSlideEnd-=l,d.noteOnly-=l,d.letRingEnd-=l;const u=wr.getNoteVelocity(e),p=this.determineChannel(n,e);let g=0;const m=Math.max(d.untilTieOrSlideEnd,d.letRingEnd);g=e.hasBend?wr.getPitchWheel(e.bendPoints[0].value):e.beat.hasWhammyBar?wr.getPitchWheel(e.beat.whammyBarPoints[0].value):e.isTieDestination||e.slideOrigin&&e.slideOrigin.slideOutType===v.Legato?-1:wr.getPitchWheel(0),g>=0&&this._handler.addNoteBend(n.index,c,p,h,g),e.beat.hasRasgueado?this.generateRasgueado(n,e,c,h,u,p,r):e.ornament===he.None?!e.isTrill||o.isPercussion?e.beat.isTremolo?this.generateTremoloPicking(e,c,d,h,u,p):(e.hasBend?this.generateBend(e,c,d,h,p,i):e.beat.hasWhammyBar&&0===e.index?this.generateWhammy(e.beat,c,d,p,i):e.slideInType!==x.None||e.slideOutType!==v.None?this.generateSlide(e,c,d,h,p,i):(e.vibrato!==P.None||e.isTieDestination&&e.tieOrigin.vibrato!==P.None)&&this.generateVibrato(e,c,d,h,p),e.isTieDestination||e.slideOrigin&&e.slideOrigin.slideOutType===v.Legato||this._handler.addNote(n.index,c,m,h,u,p)):this.generateTrill(e,c,d,h,u,p):this.generateOrnament(n,e,c,m,h,u,p)}generateOrnament(e,t,s,i,a,r,n){let o,h;const l=a%12,c=1/3;switch(t.ornament){case he.Turn:o=[a+wr.OrnamentKeysUp[l],a,a+wr.OrnamentKeysDown[l]],h=[z.toTicks(_.Sixteenth)*c,z.toTicks(_.Sixteenth)*c,z.toTicks(_.Sixteenth)*c];break;case he.InvertedTurn:o=[a+wr.OrnamentKeysDown[l],a,a+wr.OrnamentKeysUp[l]],h=[z.toTicks(_.Sixteenth)*c,z.toTicks(_.Sixteenth)*c,z.toTicks(_.Sixteenth)*c];break;case he.UpperMordent:o=[a,a+wr.OrnamentKeysUp[l]],h=[z.toTicks(_.ThirtySecond),z.toTicks(_.ThirtySecond)];break;case he.LowerMordent:o=[a,a+wr.OrnamentKeysDown[l]],h=[z.toTicks(_.ThirtySecond),z.toTicks(_.ThirtySecond)];break;default:return}let d=1;i<z.QuarterTime&&(d=i/z.QuarterTime),r-=z.VelocityIncrement;let u=0;for(let t=0;t<o.length;t++){const i=h[t]*d;this._handler.addNote(e.index,s,i,o[t],r,n),s+=i,u+=i}const p=i-u;this._handler.addNote(e.index,s,p,a,r,n)}getNoteDuration(e,t,s){const i=new br;if(i.noteOnly=t,i.untilTieOrSlideEnd=t,i.letRingEnd=t,e.isDead)return i.noteOnly=this.applyStaticDuration(wr.DefaultDurationDead,t,s),i.untilTieOrSlideEnd=i.noteOnly,i.letRingEnd=i.noteOnly,i;if(e.isPalmMute)return i.noteOnly=this.applyStaticDuration(wr.DefaultDurationPalmMute,t,s),i.untilTieOrSlideEnd=i.noteOnly,i.letRingEnd=i.noteOnly,i;if(e.isStaccato)return i.noteOnly=t/2|0,i.untilTieOrSlideEnd=i.noteOnly,i.letRingEnd=i.noteOnly,i;if(e.isTieOrigin){const a=e.tieDestination;if(a)if(e.isTieDestination){const e=this.getNoteDuration(a,a.beat.playbackDuration,s);i.untilTieOrSlideEnd=t+e.untilTieOrSlideEnd}else{const t=e.beat.absolutePlaybackStart,r=this.getNoteDuration(a,a.beat.playbackDuration,s),n=a.beat.absolutePlaybackStart+r.untilTieOrSlideEnd;i.untilTieOrSlideEnd=n-t}}else if(e.slideOutType===v.Legato){const t=e.slideTarget;if(t){const a=e.beat.absolutePlaybackStart,r=this.getNoteDuration(t,t.beat.playbackDuration,s),n=t.beat.absolutePlaybackStart+r.untilTieOrSlideEnd;i.untilTieOrSlideEnd=n-a}}if(e.isLetRing&&this._settings.notation.notationMode===D.GuitarPro){let s=e.beat,a=0;const r=e.beat.voice.bar.masterBar.calculateDuration();for(;s.nextBeat;){const t=s.nextBeat;if(t.isRest)break;if(e.isStringed&&t.hasNoteOnString(e.string))break;if(s=s.nextBeat,a=s.absolutePlaybackStart-e.beat.absolutePlaybackStart+s.playbackDuration,a>r){a=r;break}}s===e.beat?i.letRingEnd=t:i.letRingEnd=a}else i.letRingEnd=i.untilTieOrSlideEnd;return i}applyStaticDuration(e,t,s){const i=s*e/X.MaxPosition|0;return Math.min(i,t)}static getNoteVelocity(e){let t=0;switch(!e.beat.voice.bar.staff.isPercussion&&e.hammerPullOrigin&&t--,e.isGhost&&t--,e.accentuated){case B.Normal:t++;break;case B.Heavy:t+=2}return z.dynamicToVelocity(e.dynamics,t)}generateFade(e,t,s){const i=e.voice.bar.staff.track;switch(e.fade){case ue.FadeIn:this.generateFadeSteps(i,t,s,0,wr.toChannelShort(i.playbackInfo.volume));break;case ue.FadeOut:this.generateFadeSteps(i,t,s,wr.toChannelShort(i.playbackInfo.volume),0);break;case ue.VolumeSwell:const e=s/2|0;this.generateFadeSteps(i,t,e,0,wr.toChannelShort(i.playbackInfo.volume)),this.generateFadeSteps(i,t+e,e,wr.toChannelShort(i.playbackInfo.volume),0)}}generateFadeSteps(e,t,s,i,a){const r=(a-i)/(s=.8*s|0),n=s/120+1|0,o=t+s;for(let s=0;s<n;s++){const h=s===n-1,l=h?o:t+120*s,c=h?a:Math.round(i+(l-t)*r);this._handler.addControlChange(e.index,l,e.playbackInfo.primaryChannel,Xt.VolumeCoarse,c),this._handler.addControlChange(e.index,l,e.playbackInfo.secondaryChannel,Xt.VolumeCoarse,c)}}generateVibrato(e,t,s,i,a){let r=0,n=0;switch(e.vibrato!==P.None?e.vibrato:e.isTieDestination?e.tieOrigin.vibrato:P.Slight){case P.Slight:r=this._settings.player.vibrato.noteSlightLength,n=this._settings.player.vibrato.noteSlightAmplitude;break;case P.Wide:r=this._settings.player.vibrato.noteWideLength,n=this._settings.player.vibrato.noteWideAmplitude;break;default:return}const o=e.beat.voice.bar.staff.track;let h=0;if(e.isTieDestination&&e.tieOrigin.hasBend){const t=e.tieOrigin.bendPoints;h=t[t.length-1].value}this.generateVibratorWithParams(t,s.noteOnly,r,h,n,((e,t)=>{this._handler.addNoteBend(o.index,e,a,i,t)}))}generateVibratorWithParams(e,t,s,i,a,r){const n=this.vibratoResolution,o=s/2|0,h=e+t;for(;e<h;){let t=0;const l=e+s<h?s:h-e;for(;t<l;){const s=i+a*Math.sin(t*Math.PI/o);r(e+t|0,wr.getPitchWheel(s)),t+=n}e+=s}r(0|h,wr.getPitchWheel(i))}static getPitchWheel(e){return K.DefaultPitchWheel+e/2*wr.PitchValuePerSemitone}generateSlide(e,t,s,i,a,r){const n=e.slideOutType===v.Legato?s.noteOnly:s.untilTieOrSlideEnd,o=[],h=e.beat.voice.bar.staff.track,l=this._settings.player.slide.simpleSlidePitchOffset,c=Math.floor(X.MaxPosition*this._settings.player.slide.simpleSlideDurationRatio),d=Math.floor(X.MaxPosition*this._settings.player.slide.shiftSlideDurationRatio);switch(e.slideInType){case x.IntoFromAbove:o.push(new X(0,l)),o.push(new X(c,0));break;case x.IntoFromBelow:o.push(new X(0,-l)),o.push(new X(c,0))}switch(e.slideOutType){case v.Legato:case v.Shift:o.push(new X(d,0));const t=2*(e.slideTarget.calculateRealValue(this.applyTranspositionPitches,!0)-e.calculateRealValue(this.applyTranspositionPitches,!0));o.push(new X(X.MaxPosition,t));break;case v.OutDown:o.push(new X(X.MaxPosition-c,0)),o.push(new X(X.MaxPosition,-l));break;case v.OutUp:o.push(new X(X.MaxPosition-c,0)),o.push(new X(X.MaxPosition,l))}this.generateWhammyOrBend(t,n,o,r,((e,t)=>{this._handler.addNoteBend(h.index,e,a,i,t)}))}generateBend(e,t,s,i,a,r){const n=e.bendPoints,o=e.beat.voice.bar.staff.track,h=(e,t)=>{this._handler.addNoteBend(o.index,e,a,i,t)};let l,c=null;if(e.isTieOrigin&&this._settings.notation.extendBendArrowsOnTiedNotes){let t=e;for(;t.isTieOrigin&&!t.tieDestination.hasBend&&t.tieDestination.vibrato===P.None;)t=t.tieDestination;l=t.beat.absolutePlaybackStart-e.beat.absolutePlaybackStart+this.getNoteDuration(t,t.beat.playbackDuration,r).noteOnly}else if(e.isTieOrigin&&e.beat.graceType!==w.None){switch(e.tieDestination.bendType){case y.Bend:case y.BendRelease:case y.PrebendBend:c=e.tieDestination.bendPoints[1].value;break;case y.Prebend:case y.PrebendRelease:c=e.tieDestination.bendPoints[0].value}l=Math.max(s.noteOnly,z.millisToTicks(this._settings.player.songBookBendDuration,r))}else l=s.noteOnly;n[0].value>0&&!e.isContinuedBend&&t>0&&t--;const d=Math.min(l,z.millisToTicks(this._settings.player.songBookBendDuration,r));let u=[];switch(e.bendType){case y.Custom:u=n;break;case y.Bend:case y.Release:switch(e.bendStyle){case f.Default:u=n;break;case f.Gradual:u.push(new X(0,e.bendPoints[0].value)),(!c||c<e.bendPoints[1].value)&&(c=e.bendPoints[1].value),u.push(new X(X.MaxPosition,c));break;case f.Fast:return(!c||c<e.bendPoints[1].value)&&(c=e.bendPoints[1].value),void(e.beat.graceType===w.BendGrace?this.generateSongBookWhammyOrBend(t,l,!0,[e.bendPoints[0].value,c],d,r,h):this.generateSongBookWhammyOrBend(t,l,!1,[e.bendPoints[0].value,c],d,r,h))}break;case y.BendRelease:switch(e.bendStyle){case f.Default:u=n;break;case f.Gradual:u.push(new X(0,e.bendPoints[0].value)),u.push(new X(X.MaxPosition/2|0,e.bendPoints[1].value)),u.push(new X(X.MaxPosition,e.bendPoints[2].value));break;case f.Fast:return void this.generateSongBookWhammyOrBend(t,l,!1,[e.bendPoints[0].value,e.bendPoints[1].value,e.bendPoints[2].value],d,r,h)}break;case y.Hold:case y.Prebend:u=n;break;case y.PrebendBend:switch(e.bendStyle){case f.Default:u=n;break;case f.Gradual:u.push(new X(0,e.bendPoints[0].value)),u.push(new X(X.MaxPosition,e.bendPoints[1].value));break;case f.Fast:return h(t,0|wr.getPitchWheel(e.bendPoints[0].value)),(!c||c<e.bendPoints[1].value)&&(c=e.bendPoints[1].value),void this.generateSongBookWhammyOrBend(t,l,!1,[e.bendPoints[0].value,c],d,r,h)}break;case y.PrebendRelease:switch(e.bendStyle){case f.Default:u=n;break;case f.Gradual:u.push(new X(0,e.bendPoints[0].value)),u.push(new X(X.MaxPosition,e.bendPoints[1].value));break;case f.Fast:return h(t,0|wr.getPitchWheel(e.bendPoints[0].value)),void this.generateSongBookWhammyOrBend(t,l,!1,[e.bendPoints[0].value,e.bendPoints[1].value],d,r,h)}}this.generateWhammyOrBend(t,l,u,r,h)}generateSongBookWhammyOrBend(e,t,s,i,a,r,n){const o=s?e:e+t-a,h=a/(i.length-1);for(let e=0;e<i.length-1;e++){const t=wr.getPitchWheel(i[e]),s=wr.getPitchWheel(i[e+1]),a=o+h*e;this.generateBendValues(a,h,t,s,r,n)}}generateWhammy(e,t,s,i,a){const r=e.whammyBarPoints,n=e.voice.bar.staff.track,o=s.noteOnly;r[0].value>0&&!e.isContinuedWhammy&&t--;const h=(e,t)=>{this._handler.addBend(n.index,e,i,t)};let l=[];switch(e.whammyBarType){case ce.Custom:l=r;break;case ce.Dive:switch(e.whammyStyle){case f.Default:l=r;break;case f.Gradual:l.push(new X(0,r[0].value)),l.push(new X(X.MaxPosition,r[1].value));break;case f.Fast:const e=Math.min(o,z.millisToTicks(this._settings.player.songBookBendDuration,a));return void this.generateSongBookWhammyOrBend(t,o,!1,[r[0].value,r[1].value],e,a,h)}break;case ce.Dip:switch(e.whammyStyle){case f.Default:l=r;break;case f.Gradual:l.push(new X(0,r[0].value)),l.push(new X(X.MaxPosition/2|0,r[1].value)),l.push(new X(X.MaxPosition,r[2].value));break;case f.Fast:const e=Math.min(o,z.millisToTicks(this._settings.player.songBookDipDuration,a));return void this.generateSongBookWhammyOrBend(t,o,!0,[r[0].value,r[1].value,r[2].value],e,a,h)}break;case ce.Hold:case ce.Predive:l=r;break;case ce.PrediveDive:switch(e.whammyStyle){case f.Default:l=r;break;case f.Gradual:l.push(new X(0,r[0].value)),l.push(new X(X.MaxPosition/2|0,r[0].value)),l.push(new X(X.MaxPosition,r[1].value));break;case f.Fast:const e=wr.getPitchWheel(r[0].value);this._handler.addBend(n.index,t,i,0|e);const s=Math.min(o,z.millisToTicks(this._settings.player.songBookBendDuration,a));return void this.generateSongBookWhammyOrBend(t,o,!1,[r[0].value,r[1].value],s,a,h)}}this.generateWhammyOrBend(t,o,l,a,h)}generateWhammyOrBend(e,t,s,i,a){const r=t/X.MaxPosition;for(let t=0;t<s.length-1;t++){const n=s[t],o=s[t+1],h=wr.getPitchWheel(n.value),l=wr.getPitchWheel(o.value),c=r*(o.offset-n.offset),d=e+r*n.offset;this.generateBendValues(d,c,h,l,i,a)}}generateBendValues(e,t,s,i,a,r){const n=z.ticksToMillis(t,a),o=Math.abs(i-s)/wr.PitchValuePerSemitone,h=Math.max(wr.MinBreakpointsPerSemitone*o,n/wr.MillisecondsPerBreakpoint),l=t/h,c=(i-s)/h,d=e+t;for(let t=0;t<h;t++)r(0|e,Math.round(s)),s+=c,e+=l;r(0|d,i)}generateRasgueado(e,t,s,i,a,r,n){let o=s;for(let s=0;s<n.durations.length;s++){const h=n.brushInfos[s],l=t.isStringed&&t.string<=h.length?h[t.string-1]:0,c=n.durations[s];this._handler.addNote(e.index,o+l,c-l,i,a,r),o+=c}}generateTrill(e,t,s,i,a,r){const n=e.beat.voice.bar.staff.track,o=e.stringTuning+e.trillFret;let h=z.toTicks(e.trillSpeed),l=!0,c=t;const d=t+s.untilTieOrSlideEnd;for(;c+10<d;)c+h>=d&&(h=d-c),this._handler.addNote(n.index,c,h,l?o:i,a,r),l=!l,c+=h}generateTremoloPicking(e,t,s,i,a,r){const n=e.beat.voice.bar.staff.track;let o=z.toTicks(e.beat.tremoloSpeed),h=t;const l=t+s.untilTieOrSlideEnd;for(;h+10<l;)h+o>=l&&(o=l-h),this._handler.addNote(n.index,h,o,i,a,r),h+=o}getRasgueadoInfo(e,t){if(!e.hasRasgueado)return null;const s=new _r,i=wr.RasgueadoDurations.get(e.rasgueado).reduce(((e,t)=>e+t),0);s.durations=wr.RasgueadoDurations.get(e.rasgueado).map((e=>t*e/i)),s.brushInfos=new Array(s.durations.length);const a=z.toTicks(_.Sixteenth);let r=0,n=0;for(const t of e.notes)t.isTieDestination||(r|=1<<t.string-1,n++);const o=wr.RasgueadoDirections.get(e.rasgueado);for(let t=0;t<s.durations.length;t++){const i=s.durations[t]*a/z.QuarterTime,h=new Int32Array(e.voice.bar.staff.tuning.length);s.brushInfos[t]=h;const l=o[t];l!==b.None&&this.fillBrushInfo(e,h,l===b.ArpeggioDown||l===b.BrushDown,r,n,i)}return s}getBrushInfo(e){const t=new Int32Array(e.voice.bar.staff.tuning.length);if(e.brushType){let s=0,i=0;for(const t of e.notes)t.isTieDestination||(s|=1<<t.string-1,i++);this.fillBrushInfo(e,t,e.brushType===b.ArpeggioDown||e.brushType===b.BrushDown,s,i,e.brushDuration)}return t}fillBrushInfo(e,t,s,i,a,r){if(e.notes.length>0){let n=0;const o=r/(a-1)|0;for(let a=0;a<e.voice.bar.staff.tuning.length;a++){const e=s?a:t.length-1-a;i&1<<e&&(t[e]=n,n+=o)}}return t}generateNonTempoAutomation(e,t,s){switch(t.type){case m.Instrument:this.addProgramChange(e.voice.bar.staff.track,e.playbackStart+s,e.voice.bar.staff.track.playbackInfo.primaryChannel,255&t.value),this.addProgramChange(e.voice.bar.staff.track,e.playbackStart+s,e.voice.bar.staff.track.playbackInfo.secondaryChannel,255&t.value);break;case m.Balance:const i=wr.toChannelShort(t.value);this._handler.addControlChange(e.voice.bar.staff.track.index,e.playbackStart+s,e.voice.bar.staff.track.playbackInfo.primaryChannel,Xt.PanCoarse,i),this._handler.addControlChange(e.voice.bar.staff.track.index,e.playbackStart+s,e.voice.bar.staff.track.playbackInfo.secondaryChannel,Xt.PanCoarse,i);break;case m.Volume:const a=wr.toChannelShort(t.value);this._handler.addControlChange(e.voice.bar.staff.track.index,e.playbackStart+s,e.voice.bar.staff.track.playbackInfo.primaryChannel,Xt.VolumeCoarse,a),this._handler.addControlChange(e.voice.bar.staff.track.index,e.playbackStart+s,e.voice.bar.staff.track.playbackInfo.secondaryChannel,Xt.VolumeCoarse,a)}}prepareSingleBeat(e){let t=-1,s=-1,i=e;for(;i&&(-1===t||-1===s);){for(const i of e.automations)switch(i.type){case m.Instrument:s=i.value;break;case m.Tempo:t=i.value}i=i.previousBeat}const a=e.voice.bar.staff.track,r=e.voice.bar.masterBar;-1===t&&(t=r.score.tempo);const n=e.playbackStart/r.calculateDuration();for(const e of r.tempoAutomations){if(!(e.ratioPosition<=n))break;t=e.value}-1===s&&(s=a.playbackInfo.program);const o=a.playbackInfo.volume;this.generateTrack(a),this._handler.addTimeSignature(0,r.timeSignatureNumerator,r.timeSignatureDenominator),this._handler.addTempo(0,t);const h=wr.toChannelShort(o);return this._handler.addControlChange(0,0,a.playbackInfo.primaryChannel,Xt.VolumeCoarse,h),this._handler.addControlChange(0,0,a.playbackInfo.secondaryChannel,Xt.VolumeCoarse,h),t}generateSingleBeat(e){const t=this.prepareSingleBeat(e);this.generateBeat(e,-e.playbackStart,e.voice.bar,t)}generateSingleNote(e){const t=this.prepareSingleBeat(e.beat);this.generateNote(e,0,e.beat.playbackDuration,t,new Int32Array(e.beat.voice.bar.staff.tuning.length),null)}}wr.DefaultDurationDead=30,wr.DefaultDurationPalmMute=80,wr.OrnamentKeysUp=[2,2,2,1,1,2,2,2,2,2,1,1],wr.OrnamentKeysDown=[-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1],wr.PitchBendRangeInSemitones=16,wr.PitchValuePerSemitone=K.DefaultPitchWheel/wr.PitchBendRangeInSemitones,wr.MinBreakpointsPerSemitone=6,wr.MillisecondsPerBreakpoint=150,wr.RasgueadoDirections=new Map([[me.Ii,[b.BrushDown,b.BrushUp]],[me.Mi,[b.BrushDown,b.BrushDown]],[me.MiiTriplet,[b.BrushDown,b.BrushDown,b.BrushUp]],[me.MiiAnapaest,[b.BrushDown,b.BrushDown,b.BrushUp]],[me.PmpTriplet,[b.BrushUp,b.BrushDown,b.BrushDown]],[me.PmpAnapaest,[b.BrushUp,b.BrushDown,b.BrushDown]],[me.PeiTriplet,[b.BrushUp,b.BrushDown,b.BrushDown]],[me.PeiAnapaest,[b.BrushUp,b.BrushDown,b.BrushDown]],[me.PaiTriplet,[b.BrushUp,b.BrushDown,b.BrushDown]],[me.PaiAnapaest,[b.BrushUp,b.BrushDown,b.BrushDown]],[me.AmiTriplet,[b.BrushDown,b.BrushDown,b.BrushDown]],[me.AmiAnapaest,[b.BrushDown,b.BrushDown,b.BrushDown]],[me.Ppp,[b.None,b.BrushDown,b.BrushUp]],[me.Amii,[b.BrushDown,b.BrushDown,b.BrushDown,b.BrushUp]],[me.Amip,[b.BrushDown,b.BrushDown,b.BrushDown,b.BrushUp]],[me.Eami,[b.BrushDown,b.BrushDown,b.BrushDown,b.BrushDown]],[me.Eamii,[b.BrushDown,b.BrushDown,b.BrushDown,b.BrushDown,b.BrushUp]],[me.Peami,[b.BrushDown,b.BrushDown,b.BrushDown,b.BrushDown,b.BrushUp]]]),wr.RasgueadoDurations=new Map([[me.Ii,[z.toTicks(_.Eighth),z.toTicks(_.Eighth)]],[me.Mi,[z.toTicks(_.Eighth),z.toTicks(_.Eighth)]],[me.MiiTriplet,[z.toTicks(_.Eighth)/3,z.toTicks(_.Eighth)/3,z.toTicks(_.Eighth)/3]],[me.MiiAnapaest,[z.toTicks(_.Sixteenth),z.toTicks(_.Sixteenth),z.toTicks(_.Eighth)]],[me.PmpTriplet,[z.toTicks(_.Eighth)/3,z.toTicks(_.Eighth)/3,z.toTicks(_.Eighth)/3]],[me.PmpAnapaest,[z.toTicks(_.Sixteenth)/3,z.toTicks(_.Sixteenth)/3,z.toTicks(_.Eighth)/3]],[me.PeiTriplet,[z.toTicks(_.Eighth)/3,z.toTicks(_.Eighth)/3,z.toTicks(_.Eighth)/3]],[me.PeiAnapaest,[z.toTicks(_.Sixteenth),z.toTicks(_.Sixteenth),z.toTicks(_.Eighth)]],[me.PaiTriplet,[z.toTicks(_.Eighth)/3,z.toTicks(_.Eighth)/3,z.toTicks(_.Eighth)/3]],[me.PaiAnapaest,[z.toTicks(_.Sixteenth),z.toTicks(_.Sixteenth),z.toTicks(_.Eighth)]],[me.AmiTriplet,[z.toTicks(_.Eighth)/3,z.toTicks(_.Eighth)/3,z.toTicks(_.Eighth)/3]],[me.AmiAnapaest,[z.toTicks(_.Sixteenth)/3,z.toTicks(_.Sixteenth)/3,z.toTicks(_.Eighth)/3]],[me.Ppp,[z.toTicks(_.Sixteenth)/3,z.toTicks(_.Sixteenth)/3,z.toTicks(_.Eighth)/3]],[me.Amii,[z.toTicks(_.Sixteenth)/3,z.toTicks(_.Sixteenth)/3,z.toTicks(_.Sixteenth)/3,z.toTicks(_.Eighth)]],[me.Amip,[z.toTicks(_.Sixteenth)/3,z.toTicks(_.Sixteenth)/3,z.toTicks(_.Sixteenth)/3,z.toTicks(_.Eighth)]],[me.Eami,[z.toTicks(_.Sixteenth),z.toTicks(_.Sixteenth),z.toTicks(_.Sixteenth),z.toTicks(_.Sixteenth)]],[me.Eamii,[z.toTicks(_.Sixteenth)/5,z.toTicks(_.Sixteenth)/5,z.toTicks(_.Sixteenth)/5,z.toTicks(_.Sixteenth)/5,z.toTicks(_.Sixteenth)/5]],[me.Peami,[z.toTicks(_.Sixteenth)/5,z.toTicks(_.Sixteenth)/5,z.toTicks(_.Sixteenth)/5,z.toTicks(_.Sixteenth)/5,z.toTicks(_.Sixteenth)/5]]]);class Br{constructor(){this.startTick=0,this.endTick=0}}class kr{constructor(e,t){this.width=0,this.height=0,this.x=e,this.y=t}doLayout(){}paint(e,t,s){}}class Tr extends kr{constructor(e=0,t=0){super(e,t),this.beat=null,this.nextGlyph=null,this.previousGlyph=null}}class Nr{}Nr.Widths=new Map([[re.Brace,3],[re.BracketTop,0],[re.BracketBottom,0],[re.SystemDivider,0],[re.GClef,28],[re.CClef,28],[re.FClef,28],[re.UnpitchedPercussionClef1,15],[re.SixStringTabClef,28],[re.FourStringTabClef,28],[re.TimeSig0,14],[re.TimeSig1,10],[re.TimeSig2,14],[re.TimeSig3,14],[re.TimeSig4,14],[re.TimeSig5,14],[re.TimeSig6,14],[re.TimeSig7,14],[re.TimeSig8,14],[re.TimeSig9,14],[re.TimeSigCommon,14],[re.TimeSigCutCommon,14],[re.NoteheadDoubleWholeSquare,14],[re.NoteheadDoubleWhole,14],[re.NoteheadWhole,14],[re.NoteheadHalf,9],[re.NoteheadBlack,9],[re.NoteheadNull,9],[re.NoteheadXOrnate,9],[re.NoteheadPlusDoubleWhole,16],[re.NoteheadPlusWhole,10],[re.NoteheadPlusHalf,10],[re.NoteheadPlusBlack,10],[re.NoteheadSquareWhite,11],[re.NoteheadSquareBlack,11],[re.NoteheadTriangleUpDoubleWhole,16],[re.NoteheadTriangleUpWhole,11],[re.NoteheadTriangleUpHalf,11],[re.NoteheadTriangleUpBlack,11],[re.NoteheadTriangleRightWhite,11],[re.NoteheadTriangleRightBlack,11],[re.NoteheadTriangleDownDoubleWhole,16],[re.NoteheadTriangleDownWhole,11],[re.NoteheadTriangleDownHalf,11],[re.NoteheadTriangleDownBlack,11],[re.NoteheadDiamondDoubleWhole,16],[re.NoteheadDiamondWhole,9],[re.NoteheadDiamondHalf,9],[re.NoteheadDiamondBlack,9],[re.NoteheadDiamondBlackWide,10],[re.NoteheadDiamondWhite,9],[re.NoteheadDiamondWhiteWide,9],[re.NoteheadCircleXDoubleWhole,16],[re.NoteheadCircleXWhole,9],[re.NoteheadCircleXHalf,9],[re.NoteheadCircleX,9],[re.NoteheadXDoubleWhole,16],[re.NoteheadXWhole,9],[re.NoteheadXHalf,9],[re.NoteheadXBlack,9],[re.NoteheadParenthesis,9],[re.NoteheadSlashedBlack1,9],[re.NoteheadSlashedBlack2,9],[re.NoteheadSlashedHalf1,9],[re.NoteheadSlashedHalf2,9],[re.NoteheadSlashedWhole1,9],[re.NoteheadSlashedWhole2,9],[re.NoteheadSlashedDoubleWhole1,16],[re.NoteheadSlashedDoubleWhole2,16],[re.NoteheadCircledBlack,9],[re.NoteheadCircledHalf,9],[re.NoteheadCircledWhole,9],[re.NoteheadCircledDoubleWhole,16],[re.NoteheadCircleSlash,9],[re.NoteheadHeavyX,13],[re.NoteheadHeavyXHat,13],[re.NoteheadSlashVerticalEnds,12],[re.NoteheadSlashWhiteWhole,32],[re.NoteheadSlashWhiteHalf,25],[re.NoteheadRoundWhiteWithDot,9],[re.NoteheadSquareBlackLarge,9],[re.NoteheadSquareBlackWhite,9],[re.NoteheadClusterDoubleWhole3rd,16],[re.NoteheadClusterWhole3rd,12],[re.NoteheadClusterHalf3rd,12],[re.NoteheadClusterQuarter3rd,12],[re.NoteShapeRoundWhite,9],[re.NoteShapeRoundBlack,9],[re.NoteShapeSquareWhite,12],[re.NoteShapeSquareBlack,12],[re.NoteShapeTriangleRightWhite,12],[re.NoteShapeTriangleRightBlack,12],[re.NoteShapeTriangleLeftWhite,12],[re.NoteShapeTriangleLeftBlack,12],[re.NoteShapeDiamondWhite,9],[re.NoteShapeDiamondBlack,9],[re.NoteShapeTriangleUpWhite,12],[re.NoteShapeTriangleUpBlack,12],[re.NoteShapeMoonWhite,12],[re.NoteShapeMoonBlack,12],[re.NoteShapeTriangleRoundWhite,12],[re.NoteShapeTriangleRoundBlack,12],[re.NoteQuarterUp,10],[re.NoteEighthUp,10],[re.TextBlackNoteLongStem,0],[re.TextBlackNoteFrac8thLongStem,0],[re.TextBlackNoteFrac16thLongStem,0],[re.TextBlackNoteFrac32ndLongStem,0],[re.TextCont8thBeamLongStem,0],[re.TextCont16thBeamLongStem,0],[re.TextCont32ndBeamLongStem,0],[re.TextAugmentationDot,0],[re.TextTupletBracketStartLongStem,0],[re.TextTuplet3LongStem,0],[re.TextTupletBracketEndLongStem,0],[re.Tremolo3,12],[re.Tremolo2,12],[re.Tremolo1,12],[re.FlagEighthUp,0],[re.FlagEighthDown,0],[re.FlagSixteenthUp,0],[re.FlagSixteenthDown,0],[re.FlagThirtySecondUp,0],[re.FlagThirtySecondDown,0],[re.FlagSixtyFourthUp,0],[re.FlagSixtyFourthDown,0],[re.FlagOneHundredTwentyEighthUp,0],[re.FlagOneHundredTwentyEighthDown,0],[re.FlagTwoHundredFiftySixthUp,0],[re.FlagTwoHundredFiftySixthDown,0],[re.AccidentalFlat,8],[re.AccidentalNatural,8],[re.AccidentalSharp,8],[re.AccidentalDoubleSharp,8],[re.AccidentalDoubleFlat,18],[re.AccidentalQuarterToneFlatArrowUp,8],[re.AccidentalQuarterToneSharpArrowUp,8],[re.AccidentalQuarterToneNaturalArrowUp,8],[re.Segno,0],[re.Coda,0],[re.ArticAccentAbove,9],[re.ArticAccentBelow,9],[re.ArticStaccatoAbove,9],[re.ArticStaccatoBelow,9],[re.ArticTenutoAbove,9],[re.ArticTenutoBelow,9],[re.ArticMarcatoAbove,9],[re.ArticMarcatoBelow,9],[re.FermataAbove,23],[re.FermataShortAbove,23],[re.FermataLongAbove,23],[re.RestLonga,9],[re.RestDoubleWhole,9],[re.RestWhole,9],[re.RestHalf,9],[re.RestQuarter,9],[re.RestEighth,9],[re.RestSixteenth,9],[re.RestThirtySecond,12],[re.RestSixtyFourth,14],[re.RestOneHundredTwentyEighth,14],[re.RestTwoHundredFiftySixth,14],[re.RestHBarLeft,0],[re.RestHBarMiddle,0],[re.RestHBarRight,0],[re.Repeat1Bar,0],[re.Repeat2Bars,0],[re.Ottava,0],[re.OttavaAlta,32],[re.OttavaBassaVb,29],[re.Quindicesima,23],[re.QuindicesimaAlta,46],[re.DynamicPPPPPP,0],[re.DynamicPPPPP,0],[re.DynamicPPPP,0],[re.DynamicPPP,0],[re.DynamicPP,0],[re.DynamicPiano,0],[re.DynamicMP,0],[re.DynamicMF,0],[re.DynamicPF,0],[re.DynamicForte,0],[re.DynamicFF,0],[re.DynamicFFF,0],[re.DynamicFFFF,0],[re.DynamicFFFFF,0],[re.DynamicFFFFFF,0],[re.DynamicFortePiano,0],[re.DynamicNiente,0],[re.DynamicSforzando1,0],[re.DynamicSforzandoPiano,0],[re.DynamicSforzandoPianissimo,0],[re.DynamicSforzato,0],[re.DynamicSforzatoPiano,0],[re.DynamicSforzatoFF,0],[re.DynamicRinforzando1,0],[re.DynamicRinforzando2,0],[re.DynamicForzando,0],[re.OrnamentTrill,20],[re.OrnamentTurn,26],[re.OrnamentTurnInverted,26],[re.OrnamentShortTrill,0],[re.OrnamentMordent,26],[re.StringsDownBow,9],[re.StringsUpBow,9],[re.KeyboardPedalPed,35],[re.KeyboardPedalUp,16],[re.PictEdgeOfCymbal,44],[re.GuitarString0,20],[re.GuitarString1,20],[re.GuitarString2,20],[re.GuitarString3,20],[re.GuitarString4,20],[re.GuitarString5,20],[re.GuitarString6,20],[re.GuitarString7,20],[re.GuitarString8,20],[re.GuitarString9,20],[re.GuitarOpenPedal,11],[re.GuitarClosePedal,11],[re.GuitarGolpe,13.4],[re.GuitarFadeIn,13],[re.GuitarFadeOut,13],[re.GuitarVolumeSwell,26],[re.FretboardX,0],[re.FretboardO,0],[re.WiggleTrill,9],[re.WiggleVibratoMediumFast,10],[re.OctaveBaselineM,13],[re.OctaveBaselineB,9]]),Nr.Heights=new Map([[re.Brace,34],[re.BracketTop,0],[re.BracketBottom,0],[re.SystemDivider,0],[re.GClef,0],[re.CClef,0],[re.FClef,0],[re.UnpitchedPercussionClef1,0],[re.SixStringTabClef,0],[re.FourStringTabClef,0],[re.TimeSig0,0],[re.TimeSig1,0],[re.TimeSig2,0],[re.TimeSig3,0],[re.TimeSig4,0],[re.TimeSig5,0],[re.TimeSig6,0],[re.TimeSig7,0],[re.TimeSig8,0],[re.TimeSig9,0],[re.TimeSigCommon,0],[re.TimeSigCutCommon,0],[re.NoteheadDoubleWholeSquare,8],[re.NoteheadDoubleWhole,8],[re.NoteheadWhole,8],[re.NoteheadHalf,8],[re.NoteheadBlack,8],[re.NoteheadNull,8],[re.NoteheadXOrnate,8],[re.NoteheadPlusDoubleWhole,8],[re.NoteheadPlusWhole,8],[re.NoteheadPlusHalf,8],[re.NoteheadPlusBlack,8],[re.NoteheadSquareWhite,8],[re.NoteheadSquareBlack,8],[re.NoteheadTriangleUpDoubleWhole,8],[re.NoteheadTriangleUpWhole,8],[re.NoteheadTriangleUpHalf,8],[re.NoteheadTriangleUpBlack,8],[re.NoteheadTriangleRightWhite,8],[re.NoteheadTriangleRightBlack,8],[re.NoteheadTriangleDownDoubleWhole,8],[re.NoteheadTriangleDownWhole,8],[re.NoteheadTriangleDownHalf,8],[re.NoteheadTriangleDownBlack,8],[re.NoteheadDiamondDoubleWhole,8],[re.NoteheadDiamondWhole,8],[re.NoteheadDiamondHalf,8],[re.NoteheadDiamondBlack,8],[re.NoteheadDiamondBlackWide,9],[re.NoteheadDiamondWhite,9],[re.NoteheadDiamondWhiteWide,9],[re.NoteheadCircleXDoubleWhole,8],[re.NoteheadCircleXWhole,8],[re.NoteheadCircleXHalf,8],[re.NoteheadCircleX,8],[re.NoteheadXDoubleWhole,8],[re.NoteheadXWhole,8],[re.NoteheadXHalf,8],[re.NoteheadXBlack,8],[re.NoteheadParenthesis,8],[re.NoteheadSlashedBlack1,8],[re.NoteheadSlashedBlack2,8],[re.NoteheadSlashedHalf1,8],[re.NoteheadSlashedHalf2,8],[re.NoteheadSlashedWhole1,8],[re.NoteheadSlashedWhole2,8],[re.NoteheadSlashedDoubleWhole1,8],[re.NoteheadSlashedDoubleWhole2,8],[re.NoteheadCircledBlack,8],[re.NoteheadCircledHalf,8],[re.NoteheadCircledWhole,8],[re.NoteheadCircledDoubleWhole,8],[re.NoteheadCircleSlash,8],[re.NoteheadHeavyX,8],[re.NoteheadHeavyXHat,8],[re.NoteheadSlashVerticalEnds,17],[re.NoteheadSlashWhiteWhole,17],[re.NoteheadSlashWhiteHalf,17],[re.NoteheadRoundWhiteWithDot,8],[re.NoteheadSquareBlackLarge,8],[re.NoteheadSquareBlackWhite,8],[re.NoteheadClusterDoubleWhole3rd,8],[re.NoteheadClusterWhole3rd,8],[re.NoteheadClusterHalf3rd,8],[re.NoteheadClusterQuarter3rd,8],[re.NoteShapeRoundWhite,8],[re.NoteShapeRoundBlack,8],[re.NoteShapeSquareWhite,8],[re.NoteShapeSquareBlack,8],[re.NoteShapeTriangleRightWhite,8],[re.NoteShapeTriangleRightBlack,8],[re.NoteShapeTriangleLeftWhite,8],[re.NoteShapeTriangleLeftBlack,8],[re.NoteShapeDiamondWhite,8],[re.NoteShapeDiamondBlack,8],[re.NoteShapeTriangleUpWhite,8],[re.NoteShapeTriangleUpBlack,8],[re.NoteShapeMoonWhite,8],[re.NoteShapeMoonBlack,8],[re.NoteShapeTriangleRoundWhite,8],[re.NoteShapeTriangleRoundBlack,8],[re.NoteQuarterUp,8],[re.NoteEighthUp,8],[re.TextBlackNoteLongStem,0],[re.TextBlackNoteFrac8thLongStem,0],[re.TextBlackNoteFrac16thLongStem,0],[re.TextBlackNoteFrac32ndLongStem,0],[re.TextCont8thBeamLongStem,0],[re.TextCont16thBeamLongStem,0],[re.TextCont32ndBeamLongStem,0],[re.TextAugmentationDot,0],[re.TextTupletBracketStartLongStem,0],[re.TextTuplet3LongStem,0],[re.TextTupletBracketEndLongStem,0],[re.Tremolo3,0],[re.Tremolo2,0],[re.Tremolo1,0],[re.FlagEighthUp,0],[re.FlagEighthDown,0],[re.FlagSixteenthUp,0],[re.FlagSixteenthDown,0],[re.FlagThirtySecondUp,0],[re.FlagThirtySecondDown,0],[re.FlagSixtyFourthUp,0],[re.FlagSixtyFourthDown,0],[re.FlagOneHundredTwentyEighthUp,0],[re.FlagOneHundredTwentyEighthDown,0],[re.FlagTwoHundredFiftySixthUp,0],[re.FlagTwoHundredFiftySixthDown,0],[re.AccidentalFlat,0],[re.AccidentalNatural,0],[re.AccidentalSharp,0],[re.AccidentalDoubleSharp,0],[re.AccidentalDoubleFlat,0],[re.AccidentalQuarterToneFlatArrowUp,0],[re.AccidentalQuarterToneSharpArrowUp,0],[re.AccidentalQuarterToneNaturalArrowUp,0],[re.Segno,0],[re.Coda,0],[re.ArticAccentAbove,9],[re.ArticAccentBelow,9],[re.ArticStaccatoAbove,9],[re.ArticStaccatoBelow,9],[re.ArticTenutoAbove,9],[re.ArticTenutoBelow,9],[re.ArticMarcatoAbove,9],[re.ArticMarcatoBelow,9],[re.FermataAbove,12],[re.FermataShortAbove,12],[re.FermataLongAbove,12],[re.RestLonga,0],[re.RestDoubleWhole,0],[re.RestWhole,0],[re.RestHalf,0],[re.RestQuarter,0],[re.RestEighth,0],[re.RestSixteenth,0],[re.RestThirtySecond,0],[re.RestSixtyFourth,0],[re.RestOneHundredTwentyEighth,0],[re.RestTwoHundredFiftySixth,0],[re.RestHBarLeft,0],[re.RestHBarMiddle,0],[re.RestHBarRight,0],[re.Repeat1Bar,0],[re.Repeat2Bars,0],[re.Ottava,13],[re.OttavaAlta,13],[re.OttavaBassaVb,13],[re.Quindicesima,13],[re.QuindicesimaAlta,13],[re.DynamicPPPPPP,28.4],[re.DynamicPPPPP,28.4],[re.DynamicPPPP,28.4],[re.DynamicPPP,28.4],[re.DynamicPP,28.4],[re.DynamicPiano,28.4],[re.DynamicMP,28.4],[re.DynamicMF,28.4],[re.DynamicPF,28.4],[re.DynamicForte,28.4],[re.DynamicFF,28.4],[re.DynamicFFF,28.4],[re.DynamicFFFF,28.4],[re.DynamicFFFFF,28.4],[re.DynamicFFFFFF,28.4],[re.DynamicFortePiano,28.4],[re.DynamicNiente,28.4],[re.DynamicSforzando1,28.4],[re.DynamicSforzandoPiano,28.4],[re.DynamicSforzandoPianissimo,28.4],[re.DynamicSforzato,28.4],[re.DynamicSforzatoPiano,28.4],[re.DynamicSforzatoFF,28.4],[re.DynamicRinforzando1,28.4],[re.DynamicRinforzando2,28.4],[re.DynamicForzando,28.4],[re.OrnamentTrill,24],[re.OrnamentTurn,18],[re.OrnamentTurnInverted,18],[re.OrnamentShortTrill,18],[re.OrnamentMordent,18],[re.StringsDownBow,13/.75],[re.StringsUpBow,13/.75],[re.KeyboardPedalPed,19],[re.KeyboardPedalUp,16],[re.PictEdgeOfCymbal,30],[re.GuitarString0,20],[re.GuitarString1,20],[re.GuitarString2,20],[re.GuitarString3,20],[re.GuitarString4,20],[re.GuitarString5,20],[re.GuitarString6,20],[re.GuitarString7,20],[re.GuitarString8,20],[re.GuitarString9,20],[re.GuitarOpenPedal,11],[re.GuitarClosePedal,11],[re.GuitarGolpe,13.4],[re.GuitarFadeIn,13],[re.GuitarFadeOut,13],[re.GuitarVolumeSwell,13],[re.FretboardX,0],[re.FretboardO,0],[re.WiggleTrill,6],[re.WiggleVibratoMediumFast,10],[re.OctaveBaselineM,0],[re.OctaveBaselineB,0]]);class xr extends Tr{constructor(e,t,s,i){super(e,t),this.glyphScale=0,this.center=!1,this.glyphScale=s,this.symbol=i}doLayout(){this.width=Nr.Widths.has(this.symbol)?Nr.Widths.get(this.symbol)*this.glyphScale:0,this.height=Nr.Heights.has(this.symbol)?Nr.Heights.get(this.symbol)*this.glyphScale:0}paint(e,t,s){const i=s.color;this.colorOverride&&(s.color=this.colorOverride),s.fillMusicFontSymbol(e+this.x,t+this.y,this.glyphScale,this.symbol,this.center),s.color=i}}class vr extends xr{constructor(e,t,s,i){super(e,t,i?vr.GraceScale:1,vr.getSymbol(s)),this.centerOnStem=!1,this._isGrace=i}paint(e,t,s){const i=this._isGrace?1:0;this.centerOnStem&&(this.center=!0),super.paint(e,t+i,s)}static getSymbol(e){switch(e){case _.QuadrupleWhole:return re.NoteheadDoubleWholeSquare;case _.DoubleWhole:return re.NoteheadDoubleWhole;case _.Whole:return re.NoteheadWhole;case _.Half:return re.NoteheadHalf;default:return re.NoteheadBlack}}}vr.GraceScale=.75;class Pr extends xr{constructor(e,t,s,i,a){super(e,t,a?vr.GraceScale:1,Pr.getSymbol(s,i,a))}static getSymbol(e,t,s){if(s&&(e=_.Eighth),t===Te.Up)switch(e){case _.Eighth:return re.FlagEighthUp;case _.Sixteenth:return re.FlagSixteenthUp;case _.ThirtySecond:return re.FlagThirtySecondUp;case _.SixtyFourth:return re.FlagSixtyFourthUp;case _.OneHundredTwentyEighth:return re.FlagOneHundredTwentyEighthUp;case _.TwoHundredFiftySixth:return re.FlagTwoHundredFiftySixthUp;default:return re.FlagEighthUp}switch(e){case _.Eighth:return re.FlagEighthDown;case _.Sixteenth:return re.FlagSixteenthDown;case _.ThirtySecond:return re.FlagThirtySecondDown;case _.SixtyFourth:return re.FlagSixtyFourthDown;case _.OneHundredTwentyEighth:case _.TwoHundredFiftySixth:return re.FlagOneHundredTwentyEighthDown;default:return re.FlagEighthDown}}}Pr.FlagWidth=11;class Fr extends kr{get onTimeX(){return this.onNotes.x+this.onNotes.centerX}constructor(e,t){super(0,0),this.ties=[],this.minWidth=0,this.beat=e,this.ties=[],this.voiceContainer=t}addTie(e){e.renderer=this.renderer,this.ties.push(e)}drawBeamHelperAsFlags(e){return e.hasFlag(!1,void 0)}registerLayoutingInfo(e){const t=this.preNotes.computedWidth+this.onNotes.centerX;let s=this.onNotes.computedWidth-this.onNotes.centerX;const i=this.renderer.helpers.getBeamingHelperForBeat(this.beat);this.beat.graceType!==w.None?1===this.beat.graceGroup.beats.length?s+=Pr.FlagWidth*vr.GraceScale:this.beat.graceIndex<this.beat.graceGroup.beats.length-1?s+=7:s+=Fr.GraceBeatPadding:i&&this.drawBeamHelperAsFlags(i)&&(s+=Pr.FlagWidth);for(const e of this.ties)s+=e.width;e.addBeatSpring(this.beat,t,s)}applyLayoutingInfo(e){this.onNotes.updateBeamingHelper(),this.updateWidth()}doLayout(){this.preNotes.x=0,this.preNotes.renderer=this.renderer,this.preNotes.container=this,this.preNotes.doLayout(),this.onNotes.x=this.preNotes.x+this.preNotes.width,this.onNotes.renderer=this.renderer,this.onNotes.container=this,this.onNotes.doLayout();let e=this.beat.notes.length-1;for(;e>=0;)this.createTies(this.beat.notes[e--]);this.renderer.registerTies(this.ties),this.updateWidth()}updateWidth(){if(this.minWidth=this.preNotes.width+this.onNotes.width,!this.beat.isRest)if(1===this.onNotes.beamingHelper.beats.length)this.beat.duration>=_.Eighth&&(this.minWidth+=20);else switch(this.beat.duration){case _.OneHundredTwentyEighth:case _.TwoHundredFiftySixth:this.minWidth+=10}let e=0;for(const t of this.ties)t.width>e&&(e=t.width);this.minWidth+=e,this.width=this.minWidth}scaleToWidth(e){this.onNotes.updateBeamingHelper(),this.width=e}createTies(e){}static getGroupId(e){return`b${e.id}`}paint(e,t,s){if(this.preNotes.isEmpty&&this.onNotes.isEmpty&&0===this.ties.length)return;s.beginGroup(Fr.getGroupId(this.beat)),this.preNotes.paint(e+this.x,t+this.y,s),this.onNotes.paint(e+this.x,t+this.y,s);const i=e-this.voiceContainer.x-this.renderer.x,a=t-this.voiceContainer.y-this.renderer.y;for(let e=0,t=this.ties.length;e<t;e++){const t=this.ties[e];t.renderer=this.renderer,t.paint(i,a,s)}s.endGroup()}buildBoundingsLookup(e,t,s,i){const a=new tr;if(a.beat=this.beat,this.beat.isEmpty)a.visualBounds=new mt,a.visualBounds.x=t+this.x,a.visualBounds.y=e.visualBounds.y,a.visualBounds.w=this.width,a.visualBounds.h=e.visualBounds.h,a.realBounds=new mt,a.realBounds.x=t+this.x,a.realBounds.y=e.realBounds.y,a.realBounds.w=this.width,a.realBounds.h=e.realBounds.h,a.onNotesX=t+this.x+this.onNotes.centerX;else{a.visualBounds=new mt,a.visualBounds.x=t+this.x,this.preNotes.isEmpty?this.onNotes.isEmpty?a.visualBounds.x=t+this.x:a.visualBounds.x=t+this.x+this.onNotes.x:a.visualBounds.x=t+this.x+this.preNotes.x;let s=0;s=this.onNotes.isEmpty?this.preNotes.isEmpty?t+this.x+this.width:t+this.x+this.preNotes.x+this.preNotes.width:t+this.x+this.onNotes.x+this.onNotes.width,a.visualBounds.w=s-a.visualBounds.x;const i=this.renderer.helpers.getBeamingHelperForBeat(this.beat);(i&&this.drawBeamHelperAsFlags(i)||this.beat.graceType!==w.None)&&(a.visualBounds.w+=Pr.FlagWidth*(this.beat.graceType!==w.None?vr.GraceScale:1)),a.visualBounds.y=e.visualBounds.y,a.visualBounds.h=e.visualBounds.h,a.realBounds=new mt,a.realBounds.x=t+this.x,a.realBounds.y=e.realBounds.y,a.realBounds.w=this.width,a.realBounds.h=e.realBounds.h,a.onNotesX=t+this.x+this.onNotes.x+this.onNotes.centerX}e.addBeat(a),this.renderer.settings.core.includeNoteBounds&&this.onNotes.buildBoundingsLookup(a,t+this.x,s+this.y)}}Fr.GraceBeatPadding=3;class Cr{constructor(){this.oldWidth=0,this.newWidth=0,this.settings=null}core(){return this.settings&&this.causeIssue()?this.settings.core:new nc}causeIssue(){return this.settings=null,!0}}class Dr{constructor(e){this.activeBeats=e}}class Er{constructor(e){this.bounds=null,this.beat=e}}class Lr{get score(){return this._score}get tracks(){return this._tracks}constructor(e,t){this._startTime=0,this._trackIndexes=null,this._trackIndexLookup=null,this._isDestroyed=!1,this._score=null,this._tracks=[],this._tickCache=null,this.player=null,this._cursorWrapper=null,this._barCursor=null,this._beatCursor=null,this._selectionWrapper=null,this._previousTick=0,this._playerState=Ot.Paused,this._currentBeat=null,this._currentBarBounds=null,this._previousStateForCursor=Ot.Paused,this._previousCursorCache=null,this._lastScroll=0,this.playedBeatChanged=new Zi,this.activeBeatsChanged=new Zi,this._beatMouseDown=!1,this._noteMouseDown=!1,this._selectionStart=null,this._selectionEnd=null,this.beatMouseDown=new Zi,this.beatMouseMove=new Zi,this.beatMouseUp=new Zi,this.noteMouseDown=new Zi,this.noteMouseMove=new Zi,this.noteMouseUp=new Zi,this.scoreLoaded=new Zi,this.resize=new Zi,this.renderStarted=new Zi,this.renderFinished=new Zi,this.postRenderFinished=new Qi,this.error=new Zi,this.playerReady=new Qi,this.playerFinished=new Qi,this.soundFontLoaded=new Qi,this.midiLoad=new Zi,this.midiLoaded=new Zi,this.playerStateChanged=new Zi,this.playerPositionChanged=new Zi,this.midiEventsPlayed=new Zi,this.playbackRangeChanged=new Zi,this.settingsUpdated=new Qi,this.uiFacade=e,this.container=e.rootContainer,e.initialize(this,t),q.logLevel=this.settings.core.logLevel,rc.printEnvironmentInfo(!1),this.canvasElement=e.createCanvasElement(),this.container.appendChild(this.canvasElement),this.settings.core.useWorkers&&this.uiFacade.areWorkersSupported&&rc.getRenderEngineFactory(this.settings.core.engine).supportsWorkers?this.renderer=this.uiFacade.createWorkerRenderer():this.renderer=new nr(this.settings),this.container.resize.on(rc.throttle((()=>{this._isDestroyed||this.container.width!==this.renderer.width&&this.triggerResize()}),e.resizeThrottle));const s=new Cr;s.oldWidth=this.renderer.width,s.newWidth=0|this.container.width,s.settings=this.settings,this.onResize(s),this.renderer.preRender.on(this.onRenderStarted.bind(this)),this.renderer.renderFinished.on((e=>{this.onRenderFinished(e)})),this.renderer.postRenderFinished.on((()=>{const e=Date.now()-this._startTime;q.debug("rendering",`Rendering completed in ${e}ms`),this.onPostRenderFinished()})),this.renderer.preRender.on((e=>{this._startTime=Date.now()})),this.renderer.partialLayoutFinished.on(this.appendRenderResult.bind(this)),this.renderer.partialRenderFinished.on(this.updateRenderResult.bind(this)),this.renderer.renderFinished.on((e=>{this.appendRenderResult(e),this.appendRenderResult(null)})),this.renderer.error.on(this.onError.bind(this)),this.settings.player.enablePlayer&&this.setupPlayer(),this.setupClickHandling(),this.uiFacade.beginInvoke((()=>{this.uiFacade.initialRender()}))}destroy(){this._isDestroyed=!0,this.player&&this.player.destroy(),this.uiFacade.destroy(),this.renderer.destroy()}updateSettings(){const e=this.score;e&&ie.applyPitchOffsets(this.settings,e),this.renderer.updateSettings(this.settings),this.settings.player.enablePlayer?(this.setupPlayer(),e&&this.player?.applyTranspositionPitches(wr.buildTranspositionPitches(e,this.settings))):this.destroyPlayer(),this.onSettingsUpdated()}load(e,t){try{return this.uiFacade.load(e,(e=>{this.renderScore(e,t)}),(e=>{this.onError(e)}))}catch(e){return this.onError(e),!1}}renderScore(e,t){const s=[];if(t)if(0===t.length)e.tracks.length>0&&s.push(e.tracks[0]);else if(1===t.length&&-1===t[0])for(const t of e.tracks)s.push(t);else for(const i of t)i>=0&&i<=e.tracks.length&&s.push(e.tracks[i]);else e.tracks.length>0&&s.push(e.tracks[0]);this.internalRenderTracks(e,s)}renderTracks(e){if(e.length>0){const t=e[0].score;for(const s of e)if(s.score!==t)return void this.onError(new $e(Se.General,"All rendered tracks must belong to the same score."));this.internalRenderTracks(t,e)}}internalRenderTracks(e,t){if(ie.applyPitchOffsets(this.settings,e),e!==this.score){this._score=e,this._tracks=t,this._tickCache=null,this._trackIndexes=[];for(const e of t)this._trackIndexes.push(e.index);this._trackIndexLookup=new Set(this._trackIndexes),this.onScoreLoaded(e),this.loadMidiForScore(),this.render()}else{this._tracks=t;const s=ie.computeFirstDisplayedBarIndex(e,this.settings),i=ie.computeLastDisplayedBarIndex(e,this.settings,s);this._tickCache&&(this._tickCache.multiBarRestInfo=ie.buildMultiBarRestInfo(this.tracks,s,i)),this._trackIndexes=[];for(const e of t)this._trackIndexes.push(e.index);this._trackIndexLookup=new Set(this._trackIndexes),this.render()}}triggerResize(){if(this.container.isVisible){const e=new Cr;e.oldWidth=this.renderer.width,e.newWidth=this.container.width,e.settings=this.settings,this.onResize(e),this.renderer.updateSettings(this.settings),this.renderer.width=this.container.width,this.renderer.resizeRender()}else q.warning("Rendering","AlphaTab container was invisible while autosizing, waiting for element to become visible",null),this.uiFacade.rootContainerBecameVisible.on((()=>{q.debug("Rendering","AlphaTab container became visible, doing autosizing",null),this.triggerResize()}))}appendRenderResult(e){e?(this.canvasElement.width=e.totalWidth,this.canvasElement.height=e.totalHeight,this._cursorWrapper&&(this._cursorWrapper.width=e.totalWidth,this._cursorWrapper.height=e.totalHeight),(e.width>0||e.height>0)&&this.uiFacade.beginAppendRenderResults(e)):this.uiFacade.beginAppendRenderResults(e)}updateRenderResult(e){e&&e.renderResult&&this.uiFacade.beginUpdateRenderResults(e)}tex(e,t){try{const s=new dt;s.logErrors=!0,s.initFromString(e,this.settings);const i=s.readScore();this.renderScore(i,t)}catch(e){this.onError(e)}}loadSoundFont(e,t=!1){return!!this.player&&this.uiFacade.loadSoundFont(e,t)}resetSoundFonts(){this.player&&this.player.resetSoundFonts()}render(){this.renderer&&(this.uiFacade.canRender?(this.renderer.width=this.container.width,this.renderer.renderScore(this.score,this._trackIndexes)):this.uiFacade.canRenderChanged.on((()=>this.render())))}get tickCache(){return this._tickCache}get boundsLookup(){return this.renderer.boundsLookup}get isReadyForPlayback(){return!!this.player&&this.player.isReadyForPlayback}get playerState(){return this.player?this.player.state:Ot.Paused}get masterVolume(){return this.player?this.player.masterVolume:0}set masterVolume(e){this.player&&(this.player.masterVolume=e)}get metronomeVolume(){return this.player?this.player.metronomeVolume:0}set metronomeVolume(e){this.player&&(this.player.metronomeVolume=e)}get countInVolume(){return this.player?this.player.countInVolume:0}set countInVolume(e){this.player&&(this.player.countInVolume=e)}get midiEventsPlayedFilter(){return this.player?this.player.midiEventsPlayedFilter:[]}set midiEventsPlayedFilter(e){this.player&&(this.player.midiEventsPlayedFilter=e)}get tickPosition(){return this.player?this.player.tickPosition:0}set tickPosition(e){this.player&&(this.player.tickPosition=e)}get timePosition(){return this.player?this.player.timePosition:0}set timePosition(e){this.player&&(this.player.timePosition=e)}get playbackRange(){return this.player?this.player.playbackRange:null}set playbackRange(e){this.player&&(this.player.playbackRange=e,this.settings.player.enableCursor&&this.updateSelectionCursor(e))}get playbackSpeed(){return this.player?this.player.playbackSpeed:0}set playbackSpeed(e){this.player&&(this.player.playbackSpeed=e)}get isLooping(){return!!this.player&&this.player.isLooping}set isLooping(e){this.player&&(this.player.isLooping=e)}destroyPlayer(){this.player&&(this.player.destroy(),this.player=null,this._previousTick=0,this._playerState=Ot.Paused,this.destroyCursors())}setupPlayer(){this.updateCursors(),this.player||(this.player=this.uiFacade.createWorkerPlayer(),this.player&&(this.player.ready.on((()=>{this.loadMidiForScore()})),this.player.readyForPlayback.on((()=>{if(this.onPlayerReady(),this.tracks)for(const e of this.tracks){const t=e.playbackInfo.volume/16;this.player.setChannelVolume(e.playbackInfo.primaryChannel,t),this.player.setChannelVolume(e.playbackInfo.secondaryChannel,t)}})),this.player.soundFontLoaded.on(this.onSoundFontLoaded.bind(this)),this.player.soundFontLoadFailed.on((e=>{this.onError(e)})),this.player.midiLoaded.on(this.onMidiLoaded.bind(this)),this.player.midiLoadFailed.on((e=>{this.onError(e)})),this.player.stateChanged.on(this.onPlayerStateChanged.bind(this)),this.player.positionChanged.on(this.onPlayerPositionChanged.bind(this)),this.player.midiEventsPlayed.on(this.onMidiEventsPlayed.bind(this)),this.player.playbackRangeChanged.on(this.onPlaybackRangeChanged.bind(this)),this.player.finished.on(this.onPlayerFinished.bind(this)),this.setupPlayerEvents()))}loadMidiForScore(){if(!this.score)return;const e=this.score;q.debug("AlphaTab","Generating Midi");const t=new Ps,s=new lr(t),i=new wr(e,this.settings,s),a=ie.computeFirstDisplayedBarIndex(e,this.settings),r=ie.computeLastDisplayedBarIndex(e,this.settings,a);i.tickLookup.multiBarRestInfo=ie.buildMultiBarRestInfo(this.tracks,a,r),i.applyTranspositionPitches=!1,i.generate(),this._tickCache=i.tickLookup,this.onMidiLoad(t);const n=this.player;n&&(n.loadMidiFile(t),n.applyTranspositionPitches(i.transpositionPitches))}changeTrackVolume(e,t){if(this.player)for(const s of e)this.player.setChannelVolume(s.playbackInfo.primaryChannel,t),this.player.setChannelVolume(s.playbackInfo.secondaryChannel,t)}changeTrackSolo(e,t){if(this.player)for(const s of e)this.player.setChannelSolo(s.playbackInfo.primaryChannel,t),this.player.setChannelSolo(s.playbackInfo.secondaryChannel,t)}changeTrackMute(e,t){if(this.player)for(const s of e)this.player.setChannelMute(s.playbackInfo.primaryChannel,t),this.player.setChannelMute(s.playbackInfo.secondaryChannel,t)}changeTrackTranspositionPitch(e,t){if(this.player)for(const s of e)this.player.setChannelTranspositionPitch(s.playbackInfo.primaryChannel,t),this.player.setChannelTranspositionPitch(s.playbackInfo.secondaryChannel,t)}play(){return!!this.player&&this.player.play()}pause(){this.player&&this.player.pause()}playPause(){this.player&&this.player.playPause()}stop(){this.player&&this.player.stop()}playBeat(e){if(!this.player)return;const t=new Ps,s=new lr(t);new wr(e.voice.bar.staff.track.score,this.settings,s).generateSingleBeat(e),this.player.playOneTimeMidiFile(t)}playNote(e){if(!this.player)return;const t=new Ps,s=new lr(t);new wr(e.beat.voice.bar.staff.track.score,this.settings,s).generateSingleNote(e),this.player.playOneTimeMidiFile(t)}destroyCursors(){this._cursorWrapper&&(this.uiFacade.destroyCursors(),this._cursorWrapper=null,this._barCursor=null,this._beatCursor=null,this._selectionWrapper=null)}updateCursors(){if(this.settings.player.enableCursor&&!this._cursorWrapper){const e=this.uiFacade.createCursors();e&&(this._cursorWrapper=e.cursorWrapper,this._barCursor=e.barCursor,this._beatCursor=e.beatCursor,this._selectionWrapper=e.selectionWrapper),null!==this._currentBeat&&this.cursorUpdateBeat(this._currentBeat,!1,this._previousTick>10,!0)}else!this.settings.player.enableCursor&&this._cursorWrapper&&this.destroyCursors()}setupPlayerEvents(){this._previousTick=0,this._playerState=Ot.Paused,this.renderer.postRenderFinished.on((()=>{this._currentBeat=null,this.cursorUpdateTick(this._previousTick,!1,this._previousTick>10)})),this.player&&(this.player.positionChanged.on((e=>{this._previousTick=e.currentTick,this.uiFacade.beginInvoke((()=>{this.cursorUpdateTick(e.currentTick,!1,!1,e.isSeek)}))})),this.player.stateChanged.on((e=>{if(this._playerState=e.state,!e.stopped&&e.state===Ot.Paused){const e=this._currentBeat,t=this._tickCache;e&&t&&(this.player.tickPosition=t.getBeatStart(e.beat))}})))}cursorUpdateTick(e,t,s=!1,i=!1){const a=this._tickCache;if(a){const r=this._trackIndexLookup;if(null!=r&&r.size>0){const n=a.findBeat(r,e,this._currentBeat);n&&this.cursorUpdateBeat(n,t,s,i||this.playerState===Ot.Paused)}}}cursorUpdateBeat(e,t,s,i=!1){const a=e.beat,r=e.nextBeat?.beat??null,n=e.duration,o=e.beatLookup.highlightedBeats;if(!a)return;const h=this.renderer.boundsLookup;if(!h)return;const l=this._currentBeat,c=this._previousCursorCache,d=this._previousStateForCursor;if(!i&&a===l?.beat&&h===c&&d===this._playerState&&l?.start===e.start)return;const u=h.findBeat(a);u&&(this._currentBeat=e,this._previousCursorCache=h,this._previousStateForCursor=this._playerState,this.uiFacade.beginInvoke((()=>{this.internalCursorUpdateBeat(a,r,n,t,o,h,u,s,e.cursorMode)})))}scrollToCursor(){const e=this._currentBarBounds;e&&this.internalScrollToCursor(e)}internalScrollToCursor(e){const t=this.uiFacade.getScrollContainer(),s=rc.getLayoutEngineFactory(this.settings.display.layoutMode).vertical,i=this.settings.player.scrollMode;if(s){const s=e.realBounds.y+this.settings.player.scrollOffsetY;if(s!==this._lastScroll)switch(this._lastScroll=s,i){case qt.Continuous:const i=this.uiFacade.getOffset(t,this.container);this.uiFacade.scrollToY(t,i.y+s,this.settings.player.scrollSpeed);break;case qt.OffScreen:const a=t.scrollTop+this.uiFacade.getOffset(null,t).h;if(e.visualBounds.y+e.visualBounds.h>=a||e.visualBounds.y<t.scrollTop){const s=e.realBounds.y+this.settings.player.scrollOffsetY;this.uiFacade.scrollToY(t,s,this.settings.player.scrollSpeed)}}}else{const s=e.visualBounds.x;if(s!==this._lastScroll)switch(this._lastScroll=s,i){case qt.Continuous:const s=e.realBounds.x+this.settings.player.scrollOffsetX;this._lastScroll=e.visualBounds.x,this.uiFacade.scrollToX(t,s,this.settings.player.scrollSpeed);break;case qt.OffScreen:const i=t.scrollLeft+this.uiFacade.getOffset(null,t).w;if(e.visualBounds.x+e.visualBounds.w>=i||e.visualBounds.x<t.scrollLeft){const s=e.realBounds.x+this.settings.player.scrollOffsetX;this._lastScroll=e.visualBounds.x,this.uiFacade.scrollToX(t,s,this.settings.player.scrollSpeed)}}}}internalCursorUpdateBeat(e,t,s,i,a,r,n,o,h){const l=this._barCursor,c=this._beatCursor,d=n.barBounds.masterBarBounds,u=d.visualBounds;this._currentBarBounds=d,l&&l.setBounds(u.x,u.y,u.w,u.h),c&&(this.settings.player.enableAnimatedBeatCursor&&c.stopAnimation(),c.setBounds(n.onNotesX,u.y,1,u.h)),this.settings.player.enableElementHighlighting&&this.uiFacade.removeHighlights();let p=!1;const g=this._playerState===Ot.Playing&&!i;if(g){if(this.settings.player.enableElementHighlighting)for(const t of a){const s=Fr.getGroupId(t.beat);this.uiFacade.highlightElements(s,e.voice.bar.index)}o=!i,p=!0}if(this.settings.player.enableAnimatedBeatCursor&&c){let e=d.visualBounds.x+d.visualBounds.w;if(t&&h===Zt.ToNextBext){const s=r.findBeat(t);s&&s.barBounds.masterBarBounds.staffSystemBounds===d.staffSystemBounds&&(e=s.onNotesX)}g&&this.uiFacade.beginInvoke((()=>{c.transitionToX(s/this.playbackSpeed,e)}))}o&&!this._beatMouseDown&&this.settings.player.scrollMode!==qt.Off&&this.internalScrollToCursor(d),p&&(this.onPlayedBeatChanged(e),this.onActiveBeatsChanged(new Dr(a.map((e=>e.beat)))))}onPlayedBeatChanged(e){this._isDestroyed||(this.playedBeatChanged.trigger(e),this.uiFacade.triggerEvent(this.container,"playedBeatChanged",e))}onActiveBeatsChanged(e){this._isDestroyed||(this.activeBeatsChanged.trigger(e),this.uiFacade.triggerEvent(this.container,"activeBeatsChanged",e))}onBeatMouseDown(e,t){this._isDestroyed||(this.settings.player.enablePlayer&&this.settings.player.enableCursor&&this.settings.player.enableUserInteraction&&(this._selectionStart=new Er(t),this._selectionEnd=null),this._beatMouseDown=!0,this.beatMouseDown.trigger(t),this.uiFacade.triggerEvent(this.container,"beatMouseDown",t,e))}onNoteMouseDown(e,t){this._isDestroyed||(this._noteMouseDown=!0,this.noteMouseDown.trigger(t),this.uiFacade.triggerEvent(this.container,"noteMouseDown",t,e))}onBeatMouseMove(e,t){this._isDestroyed||(this.settings.player.enableUserInteraction&&(this._selectionEnd&&this._selectionEnd.beat===t||(this._selectionEnd=new Er(t),this.cursorSelectRange(this._selectionStart,this._selectionEnd))),this.beatMouseMove.trigger(t),this.uiFacade.triggerEvent(this.container,"beatMouseMove",t,e))}onNoteMouseMove(e,t){this._isDestroyed||(this.noteMouseMove.trigger(t),this.uiFacade.triggerEvent(this.container,"noteMouseMove",t,e))}onBeatMouseUp(e,t){if(!this._isDestroyed){if(this.settings.player.enablePlayer&&this.settings.player.enableCursor&&this.settings.player.enableUserInteraction){if(this._selectionEnd){const e=this._tickCache?.getBeatStart(this._selectionStart.beat)??this._selectionStart.beat.absolutePlaybackStart;if((this._tickCache?.getBeatStart(this._selectionEnd.beat)??this._selectionEnd.beat.absolutePlaybackStart)<e){const e=this._selectionStart;this._selectionStart=this._selectionEnd,this._selectionEnd=e}}if(this._selectionStart&&this._tickCache){const e=this._tickCache,t=e.getMasterBarStart(this._selectionStart.beat.voice.bar.masterBar);if(this._currentBeat=null,this._playerState===Ot.Paused&&this.cursorUpdateTick(this._tickCache.getBeatStart(this._selectionStart.beat),!1),this.tickPosition=t+this._selectionStart.beat.playbackStart,this._selectionEnd&&this._selectionStart.beat!==this._selectionEnd.beat){const s=e.getMasterBarStart(this._selectionEnd.beat.voice.bar.masterBar),i=new Br;i.startTick=t+this._selectionStart.beat.playbackStart,i.endTick=s+this._selectionEnd.beat.playbackStart+this._selectionEnd.beat.playbackDuration-50,this.playbackRange=i}else this._selectionStart=null,this.playbackRange=null,this.cursorSelectRange(this._selectionStart,this._selectionEnd)}}this.beatMouseUp.trigger(t),this.uiFacade.triggerEvent(this.container,"beatMouseUp",t,e),this._beatMouseDown=!1}}onNoteMouseUp(e,t){this._isDestroyed||(this.noteMouseUp.trigger(t),this.uiFacade.triggerEvent(this.container,"noteMouseUp",t,e),this._noteMouseDown=!1)}updateSelectionCursor(e){if(this._tickCache)if(e){const t=this._tickCache.findBeat(this._trackIndexLookup,e.startTick),s=this._tickCache.findBeat(this._trackIndexLookup,e.endTick);if(t&&s){const e=new Er(t.beat),i=new Er(s.beat);this.cursorSelectRange(e,i)}}else this.cursorSelectRange(null,null)}setupClickHandling(){this.canvasElement.mouseDown.on((e=>{if(!e.isLeftMouseButton)return;this.settings.player.enableUserInteraction&&e.preventDefault();const t=e.getX(this.canvasElement),s=e.getY(this.canvasElement),i=this.renderer.boundsLookup?.getBeatAtPos(t,s)??null;if(i&&(this.onBeatMouseDown(e,i),this.settings.core.includeNoteBounds)){const a=this.renderer.boundsLookup?.getNoteAtPos(i,t,s);a&&this.onNoteMouseDown(e,a)}})),this.canvasElement.mouseMove.on((e=>{if(!this._beatMouseDown)return;const t=e.getX(this.canvasElement),s=e.getY(this.canvasElement),i=this.renderer.boundsLookup?.getBeatAtPos(t,s)??null;if(i&&(this.onBeatMouseMove(e,i),this._noteMouseDown)){const a=this.renderer.boundsLookup?.getNoteAtPos(i,t,s);a&&this.onNoteMouseMove(e,a)}})),this.canvasElement.mouseUp.on((e=>{if(!this._beatMouseDown)return;this.settings.player.enableUserInteraction&&e.preventDefault();const t=e.getX(this.canvasElement),s=e.getY(this.canvasElement),i=this.renderer.boundsLookup?.getBeatAtPos(t,s)??null;if(this.onBeatMouseUp(e,i),this._noteMouseDown)if(i){const a=this.renderer.boundsLookup?.getNoteAtPos(i,t,s)??null;this.onNoteMouseUp(e,a)}else this.onNoteMouseUp(e,null)})),this.renderer.postRenderFinished.on((()=>{this._selectionStart&&this.settings.player.enablePlayer&&this.settings.player.enableCursor&&this.settings.player.enableUserInteraction&&this.cursorSelectRange(this._selectionStart,this._selectionEnd)}))}cursorSelectRange(e,t){const s=this.renderer.boundsLookup;if(!s)return;const i=this._selectionWrapper;if(!i)return;if(i.clear(),!e||!t||e.beat===t.beat)return;e.bounds||(e.bounds=s.findBeat(e.beat)),t.bounds||(t.bounds=s.findBeat(t.beat));const a=this._tickCache?.getBeatStart(e.beat)??e.beat.absolutePlaybackStart;if((this._tickCache?.getBeatStart(t.beat)??t.beat.absolutePlaybackStart)<a){const s=e;e=t,t=s}const r=e.bounds.realBounds.x;let n=t.bounds.realBounds.x+t.bounds.realBounds.w;if(t.beat.index===t.beat.voice.beats.length-1&&(n=t.bounds.barBounds.masterBarBounds.realBounds.x+t.bounds.barBounds.masterBarBounds.realBounds.w),e.bounds.barBounds.masterBarBounds.staffSystemBounds!==t.bounds.barBounds.masterBarBounds.staffSystemBounds){const a=e.bounds.barBounds.masterBarBounds.staffSystemBounds.visualBounds.x,o=e.bounds.barBounds.masterBarBounds.staffSystemBounds.visualBounds.x+e.bounds.barBounds.masterBarBounds.staffSystemBounds.visualBounds.w,h=this.uiFacade.createSelectionElement();h.setBounds(r,e.bounds.barBounds.masterBarBounds.visualBounds.y,o-r,e.bounds.barBounds.masterBarBounds.visualBounds.h),i.appendChild(h);const l=e.bounds.barBounds.masterBarBounds.staffSystemBounds.index+1,c=t.bounds.barBounds.masterBarBounds.staffSystemBounds.index;for(let e=l;e<c;e++){const t=s.staffSystems[e],r=this.uiFacade.createSelectionElement();r.setBounds(a,t.visualBounds.y,o-a,t.visualBounds.h),i.appendChild(r)}const d=this.uiFacade.createSelectionElement();d.setBounds(a,t.bounds.barBounds.masterBarBounds.visualBounds.y,n-a,t.bounds.barBounds.masterBarBounds.visualBounds.h),i.appendChild(d)}else{const t=this.uiFacade.createSelectionElement();t.setBounds(r,e.bounds.barBounds.masterBarBounds.visualBounds.y,n-r,e.bounds.barBounds.masterBarBounds.visualBounds.h),i.appendChild(t)}}onScoreLoaded(e){this._isDestroyed||(this.scoreLoaded.trigger(e),this.uiFacade.triggerEvent(this.container,"scoreLoaded",e))}onResize(e){this._isDestroyed||(this.resize.trigger(e),this.uiFacade.triggerEvent(this.container,"resize",e))}onRenderStarted(e){this._isDestroyed||(this.renderStarted.trigger(e),this.uiFacade.triggerEvent(this.container,"renderStarted",e))}onRenderFinished(e){this._isDestroyed||(this.renderFinished.trigger(e),this.uiFacade.triggerEvent(this.container,"renderFinished",e))}onPostRenderFinished(){this._isDestroyed||(this.postRenderFinished.trigger(),this.uiFacade.triggerEvent(this.container,"postRenderFinished",null))}onError(e){this._isDestroyed||(q.error("API","An unexpected error occurred",e),this.error.trigger(e),this.uiFacade.triggerEvent(this.container,"error",e))}onPlayerReady(){this._isDestroyed||(this.playerReady.trigger(),this.uiFacade.triggerEvent(this.container,"playerReady",null))}onPlayerFinished(){this._isDestroyed||(this.playerFinished.trigger(),this.uiFacade.triggerEvent(this.container,"playerFinished",null))}onSoundFontLoaded(){this._isDestroyed||(this.soundFontLoaded.trigger(),this.uiFacade.triggerEvent(this.container,"soundFontLoaded",null))}onMidiLoad(e){this._isDestroyed||(this.midiLoad.trigger(e),this.uiFacade.triggerEvent(this.container,"midiLoad",e))}onMidiLoaded(e){this._isDestroyed||(this.midiLoaded.trigger(e),this.uiFacade.triggerEvent(this.container,"midiFileLoaded",e))}onPlayerStateChanged(e){this._isDestroyed||(this.playerStateChanged.trigger(e),this.uiFacade.triggerEvent(this.container,"playerStateChanged",e))}onPlayerPositionChanged(e){this._isDestroyed||null!==this.score&&this.tracks.length>0&&(this.playerPositionChanged.trigger(e),this.uiFacade.triggerEvent(this.container,"playerPositionChanged",e))}onMidiEventsPlayed(e){this._isDestroyed||(this.midiEventsPlayed.trigger(e),this.uiFacade.triggerEvent(this.container,"midiEventsPlayed",e))}onPlaybackRangeChanged(e){this._isDestroyed||(this.playbackRangeChanged.trigger(e),this.uiFacade.triggerEvent(this.container,"playbackRangeChanged",e))}onSettingsUpdated(){this._isDestroyed||(this.settingsUpdated.trigger(),this.uiFacade.triggerEvent(this.container,"settingsUpdated",null))}async enumerateOutputDevices(){return this.player?await this.player.output.enumerateOutputDevices():[]}async setOutputDevice(e){this.player&&await this.player.output.setOutputDevice(e)}async getOutputDevice(){return this.player?await this.player.output.getOutputDevice():null}}class Mr extends $e{constructor(e,t){super(Se.General,e),this.xhr=t,Object.setPrototypeOf(this,Mr.prototype)}}class Ir{static loadScoreAsync(e,t,s,i){const a=new XMLHttpRequest;a.open("GET",e,!0,null,null),a.responseType="arraybuffer",a.onreadystatechange=()=>{if(a.readyState===XMLHttpRequest.DONE){const e=a.response;if(200===a.status||0===a.status&&e)try{const e=a.response,s=new Uint8Array(e),r=Ir.loadScoreFromBytes(s,i);t(r)}catch(e){s(e)}else 0===a.status?s(new Mr("You are offline!!\n Please Check Your Network.",a)):404===a.status?s(new Mr("Requested URL not found.",a)):500===a.status?s(new Mr("Internel Server Error.",a)):"parsererror"===a.statusText?s(new Mr("Error.\nParsing JSON Request failed.",a)):"timeout"===a.statusText?s(new Mr("Request Time out.",a)):s(new Mr(`Unknow Error: ${a.responseText}`,a))}},a.send()}static loadScoreFromBytes(e,t){t||(t=new Ba);const s=rc.buildImporters();q.debug("ScoreLoader",`Loading score from ${e.length} bytes using ${s.length} importers`);let i=null;const a=ht.fromBuffer(e);for(const e of s){a.reset();try{q.debug("ScoreLoader",`Importing using importer ${e.name}`),e.init(a,t),i=e.readScore(),q.debug("ScoreLoader",`Score imported using ${e.name}`);break}catch(t){if(!(t instanceof qe))throw q.error("ScoreLoader","Score import failed due to unexpected error: ",t),t;q.debug("ScoreLoader",`${e.name} does not support the file`)}}if(i)return i;throw new qe("No compatible importer found for file")}}class Ar{get isLeftMouseButton(){return 0===this.mouseEvent.button}getX(e){const t=e.element,s=t.getBoundingClientRect().left+t.ownerDocument.defaultView.pageXOffset;return this.mouseEvent.pageX-s}getY(e){const t=e.element,s=t.getBoundingClientRect().top+t.ownerDocument.defaultView.pageYOffset;return this.mouseEvent.pageY-s}preventDefault(){this.mouseEvent.preventDefault()}constructor(e){this.mouseEvent=e}}class Rr{get width(){return this.element.offsetWidth}set width(e){this.element.style.width=`${e}px`}get scrollLeft(){return this.element.scrollLeft}set scrollLeft(e){this.element.scrollLeft=e}get scrollTop(){return this.element.scrollTop}set scrollTop(e){this.element.scrollTop=e}get height(){return this.element.offsetHeight}set height(e){this.element.style.height=e>=0?`${e}px`:"100%"}get isVisible(){return!!this.element.offsetWidth||!!this.element.offsetHeight||!!this.element.getClientRects().length}constructor(e){this._resizeListeners=0,this.lastBounds=new mt,this.element=e,this.mouseDown={on:e=>{this.element.addEventListener("mousedown",(t=>{e(new Ar(t))}),!0)},off:e=>{}},this.mouseUp={on:e=>{this.element.addEventListener("mouseup",(t=>{e(new Ar(t))}),!0)},off:e=>{}},this.mouseMove={on:e=>{this.element.addEventListener("mousemove",(t=>{e(new Ar(t))}),!0)},off:e=>{}},this.resize={on:e=>{0===this._resizeListeners&&Rr.resizeObserver.value.observe(this.element),this.element.addEventListener("resize",e,!0),this._resizeListeners++},off:e=>{this.element.removeEventListener("resize",e,!0),this._resizeListeners--,this._resizeListeners<=0&&(this._resizeListeners=0,Rr.resizeObserver.value.unobserve(this.element))}}}stopAnimation(){this.element.style.transition="none"}transitionToX(e,t){this.element.style.transition=`transform ${e}ms linear`,this.setBounds(t,Number.NaN,Number.NaN,Number.NaN)}setBounds(e,t,s,i){Number.isNaN(e)&&(e=this.lastBounds.x),Number.isNaN(t)&&(t=this.lastBounds.y),Number.isNaN(s)&&(s=this.lastBounds.w),Number.isNaN(i)&&(i=this.lastBounds.h),this.element.style.transform=`translate(${e}px, ${t}px) scale(${s}, ${i})`,this.element.style.transformOrigin="top left",this.lastBounds.x=e,this.lastBounds.y=t,this.lastBounds.w=s,this.lastBounds.h=i}appendChild(e){this.element.appendChild(e.element)}clear(){this.element.innerHTML=""}}Rr.resizeObserver=new Y((()=>new ResizeObserver((e=>{for(const t of e){const e=new CustomEvent("resize",{detail:t});t.target.dispatchEvent(e)}}))));class Or{constructor(e){this._isStarted=!1,this.isFontLoaded=!1,this.fontLoaded=new Zi,this._originalFamilies=e,this._families=e}checkForFontAvailability(){if(rc.isRunningInWorker)return void(this.isFontLoaded=!1);if(this._isStarted)return;this._isStarted=!0;let e=0;const t=window.setInterval((()=>{q.warning("Rendering",`Could not load font '${this._families[0]}' within ${5*(e+1)} seconds`,null),this._families.length>1?(this._families.shift(),e=0):e++}),5e3);q.debug("Font",`Start checking for font availablility: ${this._families.join(", ")}`);const s=e=>{this._families.length>1?(q.debug("Font",`[${this._families[0]}] Loading Failed, switching to ${this._families[1]}`,e),this._families.shift(),window.setTimeout((()=>{a()}),0)):(q.error("Font",`[${this._originalFamilies.join(",")}] Loading Failed, rendering cannot start`,e),window.clearInterval(t))},i=e=>{q.debug("Font",`[${e}] Font API signaled available`),this.isFontLoaded=!0,window.clearInterval(t),this.fontLoaded.trigger(this._families[0])},a=async()=>{for(const e of this._families)if(await this.isFontAvailable(e,!1))return void i(e);try{await document.fonts.load(`1em ${this._families[0]}`)}catch(e){s(e)}return q.debug("Font",`[${this._families[0]}] Font API signaled loaded`),await this.isFontAvailable(this._families[0],!0)?i(this._families[0]):s("Font not available"),!0};document.fonts.ready.then((()=>{a()}))}isFontAvailable(e,t){return new Promise((s=>{const i=`1em ${e}`;if(document.fonts.check(i))s(!0);else if(t){q.debug("Font",`Font ${e} not available, creating test element to trigger load`);const t=document.createElement("div");t.style.font=i,t.style.opacity="0",t.style.position="absolute",t.style.top="0",t.style.left="0",t.innerText=`Trigger ${e} load`,document.body.appendChild(t),setTimeout((()=>{document.body.removeChild(t),document.fonts.check(i)?s(!0):s(!1)}),200)}else s(!1)}))}}class Hr{constructor(e){this._writePosition=0,this._readPosition=0,this.count=0,this._buffer=new Float32Array(e)}clear(){this._readPosition=0,this._writePosition=0,this.count=0,this._buffer=new Float32Array(this._buffer.length)}write(e,t,s){let i=0;s>this._buffer.length-this.count&&(s=this._buffer.length-this.count);const a=Math.min(this._buffer.length-this._writePosition,s);return this._buffer.set(e.subarray(t,t+a),this._writePosition),this._writePosition+=a,this._writePosition%=this._buffer.length,i+=a,i<s&&(this._buffer.set(e.subarray(t+i,t+i+s-i),this._writePosition),this._writePosition+=s-i,i=s),this.count+=i,i}read(e,t,s){s>this.count&&(s=this.count);let i=0;const a=Math.min(this._buffer.length-this._readPosition,s);return e.set(this._buffer.subarray(this._readPosition,this._readPosition+a),t),i+=a,this._readPosition+=a,this._readPosition%=this._buffer.length,i<s&&(e.set(this._buffer.subarray(this._readPosition,this._readPosition+s-i),t+i),this._readPosition+=s-i,i=s),this.count-=i,i}}class Wr{constructor(e){this.isDefault=!1,this.device=e}get deviceId(){return this.device.deviceId}get label(){return this.device.label}}class Vr{constructor(){this._context=null,this._buffer=null,this._source=null,this.ready=new Qi,this.samplesPlayed=new Zi,this.sampleRequest=new Qi,this._knownDevices=[]}get sampleRate(){return this._context?this._context.sampleRate:Vr.PreferredSampleRate}activate(e){this._context||(this._context=this.createAudioContext()),"suspended"!==this._context.state&&"interrupted"!==this._context.state||(q.debug("WebAudio","Audio Context is suspended, trying resume"),this._context.resume().then((()=>{q.debug("WebAudio",`Audio Context resume success: state=${this._context?.state}, sampleRate:${this._context?.sampleRate}`),e&&e()}),(e=>{q.warning("WebAudio",`Audio Context resume failed: state=${this._context?.state}, sampleRate:${this._context?.sampleRate}, reason=${e}`)})))}patchIosSampleRate(){const e=navigator.userAgent;if(-1!==e.indexOf("iPhone")||-1!==e.indexOf("iPad")){const e=this.createAudioContext(),t=e.createBuffer(1,1,Vr.PreferredSampleRate),s=e.createBufferSource();s.buffer=t,s.connect(e.destination),s.start(0),s.disconnect(0),e.close()}}createAudioContext(){if("AudioContext"in rc.globalThis)return new AudioContext;if("webkitAudioContext"in rc.globalThis)return new webkitAudioContext;throw new $e(Se.General,"AudioContext not found")}open(e){this.patchIosSampleRate(),this._context=this.createAudioContext();"suspended"===this._context.state&&this.registerResumeHandler()}registerResumeHandler(){this._resumeHandler=(()=>{this.activate((()=>{this.unregisterResumeHandler()}))}).bind(this),document.body.addEventListener("touchend",this._resumeHandler,!1),document.body.addEventListener("click",this._resumeHandler,!1)}unregisterResumeHandler(){const e=this._resumeHandler;e&&(document.body.removeEventListener("touchend",e,!1),document.body.removeEventListener("click",e,!1))}play(){const e=this._context;this.activate(),this._buffer=e.createBuffer(2,Vr.BufferSize,e.sampleRate),this._source=e.createBufferSource(),this._source.buffer=this._buffer,this._source.loop=!0}pause(){this._source&&(this._source.stop(0),this._source.disconnect()),this._source=null}destroy(){this.pause(),this._context?.close(),this._context=null,this.unregisterResumeHandler()}onSamplesPlayed(e){this.samplesPlayed.trigger(e)}onSampleRequest(){this.sampleRequest.trigger()}onReady(){this.ready.trigger()}async checkSinkIdSupport(){return"setSinkId"in(this._context??this.createAudioContext())||(q.warning("WebAudio","Browser does not support changing the output device"),!1)}async enumerateOutputDevices(){try{if(!await this.checkSinkIdSupport())return[];try{await navigator.mediaDevices.getUserMedia({audio:!0})}catch(e){q.warning("WebAudio","Output device permission rejected",e)}const e=await navigator.mediaDevices.enumerateDevices();let t="",s="";const i=new Map;for(const a of e)"audiooutput"===a.kind&&(i.set(a.groupId,new Wr(a)),"default"!==a.deviceId&&""!==a.deviceId||(t=a.groupId,s=a.deviceId));const a=Array.from(i.values());let r=a.find((e=>e.deviceId===s));return r||(r=a.find((e=>e.device.groupId===t))),!r&&a.length>0&&(r=a[0]),r&&(r.isDefault=!0),this._knownDevices=a,a}catch(e){return q.error("WebAudio","Failed to enumerate output devices",e),[]}}async setOutputDevice(e){await this.checkSinkIdSupport()&&(e?await this._context.setSinkId(e.deviceId):await this._context.setSinkId(""))}async getOutputDevice(){if(!await this.checkSinkIdSupport())return null;const e=this._context.sinkId;if("string"!=typeof e||""===e||"default"===e)return null;let t=this._knownDevices.find((t=>t.deviceId===e));if(t)return t;const s=await this.enumerateOutputDevices();return t=s.find((t=>t.deviceId===e)),t||(q.warning("WebAudio","Could not find output device in device list",e,s),null)}}Vr.BufferSize=4096,Vr.PreferredSampleRate=44100;class Gr extends Vr{constructor(){super(...arguments),this._audioNode=null,this._bufferCount=0,this._requestedBufferCount=0,this._outputBuffer=new Float32Array(0)}open(e){super.open(e),this._bufferCount=Math.floor(e*this.sampleRate/1e3/Vr.BufferSize),this._circularBuffer=new Hr(Vr.BufferSize*this._bufferCount),this.onReady()}play(){super.play();const e=this._context;this._audioNode=e.createScriptProcessor(4096,0,2),this._audioNode.onaudioprocess=this.generateSound.bind(this),this._circularBuffer.clear(),this.requestBuffers(),this._source=e.createBufferSource(),this._source.buffer=this._buffer,this._source.loop=!0,this._source.connect(this._audioNode,0,0),this._source.start(0),this._audioNode.connect(e.destination,0,0)}pause(){super.pause(),this._audioNode&&this._audioNode.disconnect(0),this._audioNode=null}addSamples(e){this._circularBuffer.write(e,0,e.length),this._requestedBufferCount--}resetSamples(){this._circularBuffer.clear()}requestBuffers(){const e=this._bufferCount/2|0,t=e*Vr.BufferSize;if(this._circularBuffer.count+this._requestedBufferCount*Vr.BufferSize<t){for(let t=0;t<e;t++)this.onSampleRequest();this._requestedBufferCount+=e}}generateSound(e){const t=e.outputBuffer.getChannelData(0),s=e.outputBuffer.getChannelData(1),i=t.length+s.length;let a=this._outputBuffer;a.length!==i&&(a=new Float32Array(i),this._outputBuffer=a);const r=this._circularBuffer.read(a,0,Math.min(a.length,this._circularBuffer.count));let n=0;const o=Math.min(t.length,r);for(let e=0;e<o;e++)t[e]=a[n++],s[e]=a[n++];if(r<t.length)for(let e=r;e<t.length;e++)t[e]=0,s[e]=0;this.onSamplesPlayed(r/K.AudioChannels),this.requestBuffers()}}class zr{constructor(e,t){this.loaded=e,this.total=t}}class Ur{get output(){return this._output}get isReady(){return this._workerIsReady&&this._outputIsReady}get isReadyForPlayback(){return this._workerIsReadyForPlayback}get state(){return this._state}get logLevel(){return q.logLevel}set logLevel(e){q.logLevel=e,this._synth.postMessage({cmd:"alphaSynth.setLogLevel",value:e})}get masterVolume(){return this._masterVolume}set masterVolume(e){e=Math.max(e,K.MinVolume),this._masterVolume=e,this._synth.postMessage({cmd:"alphaSynth.setMasterVolume",value:e})}get metronomeVolume(){return this._metronomeVolume}set metronomeVolume(e){e=Math.max(e,K.MinVolume),this._metronomeVolume=e,this._synth.postMessage({cmd:"alphaSynth.setMetronomeVolume",value:e})}get countInVolume(){return this._countInVolume}set countInVolume(e){e=Math.max(e,K.MinVolume),this._countInVolume=e,this._synth.postMessage({cmd:"alphaSynth.setCountInVolume",value:e})}get midiEventsPlayedFilter(){return this._midiEventsPlayedFilter}set midiEventsPlayedFilter(e){this._midiEventsPlayedFilter=e,this._synth.postMessage({cmd:"alphaSynth.setMidiEventsPlayedFilter",value:e})}get playbackSpeed(){return this._playbackSpeed}set playbackSpeed(e){e=ie.clamp(e,K.MinPlaybackSpeed,K.MaxPlaybackSpeed),this._playbackSpeed=e,this._synth.postMessage({cmd:"alphaSynth.setPlaybackSpeed",value:e})}get tickPosition(){return this._tickPosition}set tickPosition(e){e<0&&(e=0),this._tickPosition=e,this._synth.postMessage({cmd:"alphaSynth.setTickPosition",value:e})}get timePosition(){return this._timePosition}set timePosition(e){e<0&&(e=0),this._timePosition=e,this._synth.postMessage({cmd:"alphaSynth.setTimePosition",value:e})}get isLooping(){return this._isLooping}set isLooping(e){this._isLooping=e,this._synth.postMessage({cmd:"alphaSynth.setIsLooping",value:e})}get playbackRange(){return this._playbackRange}set playbackRange(e){e&&(e.startTick<0&&(e.startTick=0),e.endTick<0&&(e.endTick=0)),this._playbackRange=e,this._synth.postMessage({cmd:"alphaSynth.setPlaybackRange",value:e})}constructor(e,t){this._workerIsReadyForPlayback=!1,this._workerIsReady=!1,this._outputIsReady=!1,this._state=Ot.Paused,this._masterVolume=0,this._metronomeVolume=0,this._countInVolume=0,this._playbackSpeed=0,this._tickPosition=0,this._timePosition=0,this._isLooping=!1,this._playbackRange=null,this._midiEventsPlayedFilter=[],this.ready=new Qi,this.readyForPlayback=new Qi,this.finished=new Qi,this.soundFontLoaded=new Qi,this.soundFontLoadFailed=new Zi,this.midiLoaded=new Zi,this.midiLoadFailed=new Zi,this.stateChanged=new Zi,this.positionChanged=new Zi,this.midiEventsPlayed=new Zi,this.playbackRangeChanged=new Zi,this._workerIsReadyForPlayback=!1,this._workerIsReady=!1,this._outputIsReady=!1,this._state=Ot.Paused,this._masterVolume=0,this._metronomeVolume=0,this._playbackSpeed=0,this._tickPosition=0,this._timePosition=0,this._isLooping=!1,this._playbackRange=null,this._output=e,this._output.ready.on(this.onOutputReady.bind(this)),this._output.samplesPlayed.on(this.onOutputSamplesPlayed.bind(this)),this._output.sampleRequest.on(this.onOutputSampleRequest.bind(this)),this._output.open(t.player.bufferTimeInMilliseconds);try{this._synth=rc.createWebWorker(t)}catch(e){q.error("AlphaSynth",`Failed to create WebWorker: ${e}`)}this._synth.addEventListener("message",this.handleWorkerMessage.bind(this),!1),this._synth.postMessage({cmd:"alphaSynth.initialize",sampleRate:this._output.sampleRate,logLevel:t.core.logLevel,bufferTimeInMilliseconds:t.player.bufferTimeInMilliseconds}),this.masterVolume=1,this.playbackSpeed=1,this.metronomeVolume=0}destroy(){this._synth.postMessage({cmd:"alphaSynth.destroy"})}play(){return this._output.activate(),this._synth.postMessage({cmd:"alphaSynth.play"}),!0}pause(){this._synth.postMessage({cmd:"alphaSynth.pause"})}playPause(){this._output.activate(),this._synth.postMessage({cmd:"alphaSynth.playPause"})}stop(){this._synth.postMessage({cmd:"alphaSynth.stop"})}playOneTimeMidiFile(e){this._synth.postMessage({cmd:"alphaSynth.playOneTimeMidiFile",midi:$a.midiFileToJsObject(e)})}loadSoundFont(e,t){this._synth.postMessage({cmd:"alphaSynth.loadSoundFontBytes",data:e,append:t})}loadSoundFontFromUrl(e,t,s){q.debug("AlphaSynth",`Start loading Soundfont from url ${e}`);const i=new XMLHttpRequest;i.open("GET",e,!0,null,null),i.responseType="arraybuffer",i.onload=e=>{const s=new Uint8Array(i.response);this.loadSoundFont(s,t)},i.onerror=e=>{q.error("AlphaSynth",`Loading failed: ${e.message}`),this.soundFontLoadFailed.trigger(new Mr(e.message,i))},i.onprogress=e=>{q.debug("AlphaSynth",`Soundfont downloading: ${e.loaded}/${e.total} bytes`),s(new zr(e.loaded,e.total))},i.send()}resetSoundFonts(){this._synth.postMessage({cmd:"alphaSynth.resetSoundFonts"})}loadMidiFile(e){this._synth.postMessage({cmd:"alphaSynth.loadMidi",midi:$a.midiFileToJsObject(e)})}applyTranspositionPitches(e){this._synth.postMessage({cmd:"alphaSynth.applyTranspositionPitches",transpositionPitches:JSON.stringify(Array.from(e.entries()))})}setChannelTranspositionPitch(e,t){this._synth.postMessage({cmd:"alphaSynth.setChannelTranspositionPitch",channel:e,semitones:t})}setChannelMute(e,t){this._synth.postMessage({cmd:"alphaSynth.setChannelMute",channel:e,mute:t})}resetChannelStates(){this._synth.postMessage({cmd:"alphaSynth.resetChannelStates"})}setChannelSolo(e,t){this._synth.postMessage({cmd:"alphaSynth.setChannelSolo",channel:e,solo:t})}setChannelVolume(e,t){t=Math.max(t,K.MinVolume),this._synth.postMessage({cmd:"alphaSynth.setChannelVolume",channel:e,volume:t})}handleWorkerMessage(e){const t=e.data;switch(t.cmd){case"alphaSynth.ready":this._workerIsReady=!0,this.checkReady();break;case"alphaSynth.destroyed":this._synth.terminate();break;case"alphaSynth.readyForPlayback":this._workerIsReadyForPlayback=!0,this.checkReadyForPlayback();break;case"alphaSynth.positionChanged":this._timePosition=t.currentTime,this._tickPosition=t.currentTick,this.positionChanged.trigger(new $s(t.currentTime,t.endTime,t.currentTick,t.endTick,t.isSeek));break;case"alphaSynth.midiEventsPlayed":this.midiEventsPlayed.trigger(new ea(t.events.map($a.jsObjectToMidiEvent)));break;case"alphaSynth.playerStateChanged":this._state=t.state,this.stateChanged.trigger(new Ys(t.state,t.stopped));break;case"alphaSynth.playbackRangeChanged":this._playbackRange=t.playbackRange,this.playbackRangeChanged.trigger(new ta(this._playbackRange));break;case"alphaSynth.finished":this.finished.trigger();break;case"alphaSynth.soundFontLoaded":this.soundFontLoaded.trigger();break;case"alphaSynth.soundFontLoadFailed":this.soundFontLoadFailed.trigger(t.error);break;case"alphaSynth.midiLoaded":this.checkReadyForPlayback(),this.midiLoaded.trigger(new $s(t.currentTime,t.endTime,t.currentTick,t.endTick,t.isSeek));break;case"alphaSynth.midiLoadFailed":this.checkReadyForPlayback(),this.midiLoadFailed.trigger(t.error);break;case"alphaSynth.output.addSamples":this._output.addSamples(t.samples);break;case"alphaSynth.output.play":this._output.play();break;case"alphaSynth.output.pause":this._output.pause();break;case"alphaSynth.output.destroy":this._output.destroy();break;case"alphaSynth.output.resetSamples":this._output.resetSamples()}}checkReady(){this.isReady&&this.ready.trigger()}checkReadyForPlayback(){this.isReadyForPlayback&&this.readyForPlayback.trigger()}onOutputSampleRequest(){this._synth.postMessage({cmd:"alphaSynth.output.sampleRequest"})}onOutputSamplesPlayed(e){this._synth.postMessage({cmd:"alphaSynth.output.samplesPlayed",samples:e})}onOutputReady(){this._outputIsReady=!0,this.checkReady()}}class Xr{constructor(e,t){this._width=0,this.boundsLookup=null,this.preRender=new Zi,this.partialRenderFinished=new Zi,this.partialLayoutFinished=new Zi,this.renderFinished=new Zi,this.postRenderFinished=new Qi,this.error=new Zi,this._api=e;try{this._worker=rc.createWebWorker(t)}catch(e){return void q.error("Rendering",`Failed to create WebWorker: ${e}`)}this._worker.postMessage({cmd:"alphaTab.initialize",settings:this.serializeSettingsForWorker(t)}),this._worker.addEventListener("message",this.handleWorkerMessage.bind(this))}destroy(){this._worker.terminate()}updateSettings(e){this._worker.postMessage({cmd:"alphaTab.updateSettings",settings:this.serializeSettingsForWorker(e)})}serializeSettingsForWorker(e){const t=$a.settingsToJsObject(e);return t.delete("player"),t}render(){this._worker.postMessage({cmd:"alphaTab.render"})}resizeRender(){this._worker.postMessage({cmd:"alphaTab.resizeRender"})}renderResult(e){this._worker.postMessage({cmd:"alphaTab.renderResult",resultId:e})}get width(){return this._width}set width(e){this._width=e,this._worker.postMessage({cmd:"alphaTab.setWidth",width:e})}handleWorkerMessage(e){const t=e.data;switch(t.cmd){case"alphaTab.preRender":this.preRender.trigger(t.resize);break;case"alphaTab.partialRenderFinished":this.partialRenderFinished.trigger(t.result);break;case"alphaTab.partialLayoutFinished":this.partialLayoutFinished.trigger(t.result);break;case"alphaTab.renderFinished":this.renderFinished.trigger(t.result);break;case"alphaTab.postRenderFinished":this.boundsLookup=rr.fromJson(t.boundsLookup,this._api.score),this.boundsLookup.finish(),this.postRenderFinished.trigger();break;case"alphaTab.error":this.error.trigger(t.error)}}renderScore(e,t){const s=null==e?null:$a.scoreToJsObject(e);this._worker.postMessage({cmd:"alphaTab.renderScore",score:s,trackIndexes:t,fontSizes:Qa.FontSizeLookupTables})}}class Jr{constructor(e,t,s,i){this.cursorWrapper=e,this.barCursor=t,this.beatCursor=s,this.selectionWrapper=i}}class Yr{static init(){var e;Yr._isRegistered||(Yr._isRegistered=!0,registerProcessor("alphatab",((e=class extends AudioWorkletProcessor{constructor(t){super(t),this._outputBuffer=new Float32Array(0),this._bufferCount=0,this._requestedBufferCount=0,this._isStopped=!1,q.debug("WebAudio","creating processor"),this._bufferCount=Math.floor(t.processorOptions.bufferTimeInMilliseconds*sampleRate/1e3/e.BufferSize),this._circularBuffer=new Hr(e.BufferSize*this._bufferCount),this.port.onmessage=this.handleMessage.bind(this)}handleMessage(e){const t=e.data;switch(t.cmd){case qa.CmdOutputAddSamples:const e=t.samples;this._circularBuffer.write(e,0,e.length),this._requestedBufferCount--;break;case qa.CmdOutputResetSamples:this._circularBuffer.clear();break;case qa.CmdOutputStop:this._isStopped=!0}}process(e,t,s){if(1!==t.length&&2!==t[0].length)return!1;const i=t[0][0],a=t[0][1];if(!i||!a)return!0;const r=i.length+a.length;let n=this._outputBuffer;n.length!==r&&(n=new Float32Array(r),this._outputBuffer=n);const o=this._circularBuffer.read(n,0,Math.min(n.length,this._circularBuffer.count));let h=0;const l=Math.min(i.length,o);for(let e=0;e<l;e++)i[e]=n[h++],a[e]=n[h++];if(o<i.length)for(let e=o;e<i.length;e++)i[e]=0,a[e]=0;return this.port.postMessage({cmd:qa.CmdOutputSamplesPlayed,samples:o/K.AudioChannels}),this.requestBuffers(),this._circularBuffer.count>0||!this._isStopped}requestBuffers(){const t=this._bufferCount/2|0,s=t*e.BufferSize;if(this._circularBuffer.count+this._requestedBufferCount*e.BufferSize<s){for(let e=0;e<t;e++)this.port.postMessage({cmd:qa.CmdOutputSampleRequest});this._requestedBufferCount+=t}}}).BufferSize=4096,e)))}}Yr._isRegistered=!1;class $r extends Vr{constructor(e){super(),this._worklet=null,this._bufferTimeInMilliseconds=0,this._settings=e}open(e){super.open(e),this._bufferTimeInMilliseconds=e,this.onReady()}play(){super.play();const e=this._context;rc.createAudioWorklet(e,this._settings).then((()=>{this._worklet=new AudioWorkletNode(e,"alphatab",{numberOfOutputs:1,outputChannelCount:[2],processorOptions:{bufferTimeInMilliseconds:this._bufferTimeInMilliseconds}}),this._worklet.port.onmessage=this.handleMessage.bind(this),this._source.connect(this._worklet),this._source.start(0),this._worklet.connect(e.destination)}),(e=>{q.error("WebAudio",`Audio Worklet creation failed: reason=${e}`)}))}handleMessage(e){const t=e.data;switch(t.cmd){case qa.CmdOutputSamplesPlayed:this.onSamplesPlayed(t.samples);break;case qa.CmdOutputSampleRequest:this.onSampleRequest()}}pause(){super.pause(),this._worklet&&(this._worklet.port.postMessage({cmd:qa.CmdOutputStop}),this._worklet.port.onmessage=null,this._worklet.disconnect()),this._worklet=null}addSamples(e){this._worklet?.port.postMessage({cmd:qa.CmdOutputAddSamples,samples:e})}resetSamples(){this._worklet?.port.postMessage({cmd:qa.CmdOutputResetSamples})}}class qr extends Rr{constructor(e,t,s){super(e),this._xscale=t,this._yscale=s}get width(){return this.element.offsetWidth/this._xscale}set width(e){this.element.style.width=e*this._xscale+"px"}get height(){return this.element.offsetHeight/this._yscale}set height(e){this.element.style.height=e>=0?e*this._yscale+"px":"100%"}setBounds(e,t,s,i){Number.isNaN(e)&&(e=this.lastBounds.x),Number.isNaN(t)&&(t=this.lastBounds.y),Number.isNaN(s)?s=this.lastBounds.w:s/=this._xscale,Number.isNaN(i)?i=this.lastBounds.h:i/=this._yscale,this.element.style.transform=`translate(${e}px, ${t}px) scale(${s}, ${i})`,this.element.style.transformOrigin="top left",this.lastBounds.x=e,this.lastBounds.y=t,this.lastBounds.w=s,this.lastBounds.h=i}}!function(e){e[e.LayoutDone=0]="LayoutDone",e[e.RenderRequested=1]="RenderRequested",e[e.RenderDone=2]="RenderDone",e[e.Detached=3]="Detached"}(es||(es={}));class jr{get resizeThrottle(){return 10}get canRender(){return this.areAllFontsLoaded()}areAllFontsLoaded(){if(rc.bravuraFontChecker.checkForFontAvailability(),!rc.bravuraFontChecker.isFontLoaded)return!1;let e=!1;for(const t of this._fontCheckers.values())t.isFontLoaded||(e=!0);return!e&&(q.debug("Font",`All fonts loaded: ${this._fontCheckers.size}`),!0)}onFontLoaded(e){Qa.generateFontLookup(e),this.areAllFontsLoaded()&&this.canRenderChanged.trigger()}constructor(e){if(this._fontCheckers=new Map,this._contents=null,this._file=null,this._totalResultCount=0,this._initialTrackIndexes=null,this._barToElementLookup=new Map,this._resultIdToElementLookup=new Map,this.rootContainerBecameVisible=new Qi,this.canRenderChanged=new Qi,this._highlightedElements=[],this._scrollContainer=null,rc.webPlatform!==Kt.Browser&&rc.webPlatform!==Kt.BrowserModule)throw new $e(Se.General,"Usage of AlphaTabApi is only possible in browser environments. For usage in node use the Low Level APIs");e.classList.add("alphaTab"),this.rootContainer=new Rr(e),this.areWorkersSupported="Worker"in window,rc.bravuraFontChecker.fontLoaded.on(this.onFontLoaded.bind(this)),this._intersectionObserver=new IntersectionObserver(this.onElementVisibilityChanged.bind(this),{threshold:[0,.01,1]}),this._intersectionObserver.observe(e)}onElementVisibilityChanged(e){for(const t of e){const e=t.target;if(e===this.rootContainer.element)t.isIntersecting&&(this.rootContainerBecameVisible.trigger(),this._intersectionObserver.unobserve(this.rootContainer.element));else if("layoutResultId"in e&&this._api.settings.core.enableLazyLoading){const s=e;t.isIntersecting?s.renderedResultId!==s.layoutResultId?this._resultIdToElementLookup.has(s.layoutResultId)?s.resultState!==es.RenderRequested&&(s.resultState=es.RenderRequested,this._api.renderer.renderResult(s.layoutResultId)):e.replaceChildren():s.resultState===es.Detached&&(e.replaceChildren(...s.renderedResult),s.resultState=es.RenderDone):s.resultState===es.RenderDone&&(s.resultState=es.Detached,s.replaceChildren())}}}createWorkerRenderer(){return new Xr(this._api,this._api.settings)}initialize(e,t){let s;this._api=e,s=t instanceof Ba?t:$a.jsObjectToSettings(t);const i=this.getDataAttributes();wa.fromJson(s,i),s.notation.notationMode===D.SongBook&&s.setSongBookModeSettings(),e.settings=s,this.setupFontCheckers(s),this._initialTrackIndexes=this.parseTracks(s.core.tracks),this._contents="";const a=e.container;s.core.tex&&(this._contents=a.element.innerHTML,a.element.innerHTML=""),this.createStyleElement(s),this._file=s.core.file}setupFontCheckers(e){this.registerFontChecker(e.display.resources.copyrightFont),this.registerFontChecker(e.display.resources.effectFont),this.registerFontChecker(e.display.resources.fingeringFont),this.registerFontChecker(e.display.resources.graceFont),this.registerFontChecker(e.display.resources.markerFont),this.registerFontChecker(e.display.resources.tablatureFont),this.registerFontChecker(e.display.resources.titleFont),this.registerFontChecker(e.display.resources.wordsFont),this.registerFontChecker(e.display.resources.barNumberFont),this.registerFontChecker(e.display.resources.fretboardNumberFont),this.registerFontChecker(e.display.resources.subTitleFont)}registerFontChecker(e){if(!this._fontCheckers.has(e.families.join(", "))){const t=new Or(e.families);this._fontCheckers.set(e.families.join(", "),t),t.fontLoaded.on(this.onFontLoaded.bind(this)),t.checkForFontAvailability()}}destroy(){this.rootContainer.element.innerHTML=""}createCanvasElement(){const e=document.createElement("div");return e.className="at-surface",e.style.fontSize="0",e.style.overflow="hidden",e.style.lineHeight="0",e.style.position="relative",new Rr(e)}triggerEvent(e,t,s=null,i){const a=e.element;t=`alphaTab.${t}`;const r=document.createEvent("CustomEvent"),n=i?i.mouseEvent:null;if(r.initCustomEvent(t,!1,!1,s),n&&(r.originalEvent=n),a.dispatchEvent(r),window&&"jQuery"in window){const e=window.jQuery,i=[];i.push(s),n&&i.push(n),e(a).trigger(t,i)}}load(e,t,s){if(e instanceof Je)return t(e),!0;if(e instanceof ArrayBuffer){const s=new Uint8Array(e);return t(Ir.loadScoreFromBytes(s,this._api.settings)),!0}return e instanceof Uint8Array?(t(Ir.loadScoreFromBytes(e,this._api.settings)),!0):"string"==typeof e&&(Ir.loadScoreAsync(e,t,s,this._api.settings),!0)}loadSoundFont(e,t){return!!this._api.player&&(e instanceof ArrayBuffer?(this._api.player.loadSoundFont(new Uint8Array(e),t),!0):e instanceof Uint8Array?(this._api.player.loadSoundFont(e,t),!0):"string"==typeof e&&(this._api.loadSoundFontFromUrl(e,t),!0))}initialRender(){this._api.renderer.preRender.on((e=>{this._totalResultCount=0,this._resultIdToElementLookup.clear(),this._barToElementLookup.clear()}));const e=()=>{this._api.renderer.width=0|this.rootContainer.width,this._api.renderer.updateSettings(this._api.settings),this._contents?(this._api.tex(this._contents,this._initialTrackIndexes??void 0),this._initialTrackIndexes=null):this._file&&Ir.loadScoreAsync(this._file,(e=>{this._api.renderScore(e,this._initialTrackIndexes??void 0),this._initialTrackIndexes=null}),(e=>{this._api.onError(e)}),this._api.settings)};this.rootContainer.isVisible?e():this.rootContainerBecameVisible.on(e)}createStyleElement(e){const t=this._api.container.element.ownerDocument;rc.createStyleElement(t,e.core.fontDirectory)}parseTracks(e){if(!e)return[];const t=[];if("string"==typeof e)try{if("all"===e)return[-1];e=JSON.parse(e)}catch(t){e=[0]}if("number"==typeof e)t.push(e);else if("length"in e){const s=e.length,i=e;for(let e=0;e<s;e++){const s=i[e];let a=0;a="number"==typeof s?s:"index"in s?s.index:Number.parseInt(s.toString()),(a>=0||-1===a)&&t.push(a)}}else"index"in e&&t.push(e.index);return t}getDataAttributes(){const e=new Map,t=this._api.container.element;if(t.dataset)for(const s of Object.keys(t.dataset)){let i=t.dataset[s];try{const e=i;i=JSON.parse(e)}catch(e){""===i&&(i=null)}e.set(s,i)}else for(let s=0;s<t.attributes.length;s++){const i=t.attributes.item(s),a=i.nodeName;if(a.startsWith("data-")){const t=a.substr(5).split("-");let s=t[0];for(let e=1;e<t.length;e++)s+=t[e].substr(0,1).toUpperCase()+t[e].substr(1);let r=i.nodeValue;try{r=JSON.parse(r)}catch(e){""===r&&(r=null)}e.set(s,r)}}return e}beginUpdateRenderResults(e){if(!this._resultIdToElementLookup.has(e.id))return;const t=this._resultIdToElementLookup.get(e.id),s=e.renderResult;"string"==typeof s?t.innerHTML=s:"nodeType"in s&&t.replaceChildren(s),t.resultState=es.RenderDone,t.renderedResultId=e.id,t.renderedResult=Array.from(t.children)}beginAppendRenderResults(e){const t=this._api.canvasElement.element;if(e){let s;this._totalResultCount<t.childElementCount?s=t.childNodes.item(this._totalResultCount):(s=document.createElement("div"),t.appendChild(s)),s.style.zIndex="1",s.style.position="absolute",s.style.left=`${e.x}px`,s.style.top=`${e.y}px`,s.style.width=`${e.width}px`,s.style.height=`${e.height}px`,s.style.display="inline-block",s.layoutResultId=e.id,s.resultState=es.LayoutDone,s.renderedResultId=void 0,s.renderedResult=void 0,this._resultIdToElementLookup.set(e.id,s);for(let t=e.firstMasterBarIndex;t<=e.lastMasterBarIndex;t++)t>=0&&this._barToElementLookup.set(t,s);this._api.settings.core.enableLazyLoading&&(this._intersectionObserver.unobserve(s),this._intersectionObserver.observe(s)),this._totalResultCount++}else for(;t.childElementCount>this._totalResultCount;)this._api.settings.core.enableLazyLoading&&this._intersectionObserver.unobserve(t.lastChild),t.removeChild(t.lastElementChild)}createWorkerPlayer(){let e=null;const t="ScriptProcessorNode"in window;return window.isSecureContext&&"AudioWorkletNode"in window&&this._api.settings.player.outputMode===jt.WebAudioAudioWorklets?(q.debug("Player","Will use webworkers for synthesizing and web audio api with worklets for playback"),e=new Ur(new $r(this._api.settings),this._api.settings)):t&&(q.debug("Player","Will use webworkers for synthesizing and web audio api with ScriptProcessor for playback"),e=new Ur(new Gr,this._api.settings)),e?e.ready.on((()=>{this._api.settings.player.soundFont&&this._api.loadSoundFontFromUrl(this._api.settings.player.soundFont,!1)})):q.error("Player","Player requires webworkers and web audio api, browser unsupported",null),e}beginInvoke(e){window.requestAnimationFrame((()=>{e()}))}highlightElements(e,t){const s=this._barToElementLookup.get(t);if(s){const t=s.getElementsByClassName(e);for(let e=0;e<t.length;e++)t.item(e).classList.add("at-highlight"),this._highlightedElements.push(t.item(e))}}removeHighlights(){const e=this._highlightedElements;if(e){for(const t of e)t.classList.remove("at-highlight");this._highlightedElements=[]}}destroyCursors(){const e=this._api.container.element,t=e.querySelector(".at-cursors");e.removeChild(t)}createCursors(){const e=this._api.container.element,t=document.createElement("div");t.classList.add("at-cursors");const s=document.createElement("div");s.classList.add("at-selection");const i=this.createScalingElement(),a=this.createScalingElement(),r=i.element;r.classList.add("at-cursor-bar");const n=a.element;return n.classList.add("at-cursor-beat"),e.style.position="relative",e.style.textAlign="left",t.style.position="absolute",t.style.zIndex="1000",t.style.display="inline",t.style.pointerEvents="none",s.style.position="absolute",r.style.position="absolute",r.style.left="0",r.style.top="0",r.style.willChange="transform",i.width=1,i.height=1,i.setBounds(0,0,1,1),n.style.position="absolute",n.style.transition="all 0s linear",n.style.left="0",n.style.top="0",n.style.willChange="transform",a.width=3,a.height=1,a.setBounds(0,0,1,1),e.insertBefore(t,e.firstChild),t.appendChild(s),t.appendChild(r),t.appendChild(n),new Jr(new Rr(t),i,a,new Rr(s))}getOffset(e,t){const s=t.element,i=s.getBoundingClientRect();let a=i.top+s.ownerDocument.defaultView.pageYOffset,r=i.left+s.ownerDocument.defaultView.pageXOffset;if(e){const t=e.element,s=t.nodeName.toLowerCase();if("html"!==s&&"body"!==s){const s=this.getOffset(null,e);a=a+t.scrollTop-s.y,r=r+t.scrollLeft-s.x}}const n=new mt;return n.x=r,n.y=a,n.w=i.width,n.h=i.height,n}getScrollContainer(){if(this._scrollContainer)return this._scrollContainer;let e="string"==typeof this._api.settings.player.scrollElement?document.querySelector(this._api.settings.player.scrollElement):this._api.settings.player.scrollElement;const t=e.nodeName.toLowerCase();if("html"===t||"body"===t)if("scrollingElement"in document)e=document.scrollingElement;else{e=-1!==navigator.userAgent.indexOf("WebKit")?document.body:document.documentElement}return this._scrollContainer=new Rr(e),this._scrollContainer}createSelectionElement(){return this.createScalingElement()}createScalingElement(){const e=document.createElement("div");e.style.position="absolute";const t=new qr(e,100,100);return t.width=1,t.height=1,t.setBounds(0,0,1,1),t}scrollToY(e,t,s){this.internalScrollToY(e.element,t,s)}scrollToX(e,t,s){this.internalScrollToX(e.element,t,s)}internalScrollToY(e,t,s){if(this._api.settings.player.nativeBrowserSmoothScroll)e.scrollTo({top:t,behavior:"smooth"});else{const i=e.scrollTop,a=t-i;let r=0;const n=t=>{0===r&&(r=t);const o=t-r,h=Math.min(o/s,1);e.scrollTop=i+a*h|0,o<s&&window.requestAnimationFrame(n)};window.requestAnimationFrame(n)}}internalScrollToX(e,t,s){if(this._api.settings.player.nativeBrowserSmoothScroll)e.scrollTo({left:t,behavior:"smooth"});else{const i=e.scrollLeft,a=t-i;let r=0;const n=t=>{0===r&&(r=t);const o=t-r,h=Math.min(o/s,1);e.scrollLeft=i+a*h|0,o<s&&window.requestAnimationFrame(n)};window.requestAnimationFrame(n)}}}class Kr extends Lr{constructor(e,t){super(new jr(e),t),this.soundFontLoad=new Zi}tex(e,t){const s=this.uiFacade;super.tex(e,s.parseTracks(t))}print(t,s=null){const i=window.open("","","width=0,height=0"),a=i.document.createElement("div");t?a.style.width=t:this.settings.display.layoutMode===e.Horizontal?a.style.width="297mm":a.style.width="210mm",i.document.write("\n <!DOCTYPE html>\n <html>\n <head>\n <style>\n .at-surface {\n width: auto !important;\n height: auto !important;\n }\n .at-surface > div {\n position: relative!important;\n left: auto !important;\n top: auto !important;\n break-inside: avoid;\n }\n </style>\n </head>\n <body></body>\n </html>\n ");const r=this.score;r&&(r.artist&&r.title?i.document.title=`${r.title} - ${r.artist}`:r.title&&(i.document.title=`${r.title}`)),i.document.body.appendChild(a);const n=void 0!==window.screenLeft?window.screenLeft:window.left,o=void 0!==window.screenTop?window.screenTop:window.top,h="innerWidth"in window?window.innerWidth:"clientWidth"in document.documentElement?document.documentElement.clientWidth:window.screen.width,l="innerHeight"in window?window.innerHeight:"clientHeight"in document.documentElement?document.documentElement.clientHeight:window.screen.height,c=a.offsetWidth+50,d=window.innerHeight,u=(h/2|0)-(c/2|0)+n,p=(l/2|0)-(d/2|0)+o;i.resizeTo(c,d),i.moveTo(u,p),i.focus();const g=$a.jsObjectToSettings($a.settingsToJsObject(this.settings));g.core.enableLazyLoading=!1,g.core.useWorkers=!0,g.core.file=null,g.core.tracks=null,g.player.enableCursor=!1,g.player.enablePlayer=!1,g.player.enableElementHighlighting=!1,g.player.enableUserInteraction=!1,g.player.soundFont=null,g.display.scale=.8,g.display.stretchForce=.8,wa.fromJson(g,s);const m=new Kr(a,g);i.onunload=()=>{m.destroy()},m.renderer.postRenderFinished.on((()=>{i.print()})),m.renderTracks(this.tracks)}downloadMidi(e=At.SingleTrackMultiChannel){if(!this.score)return;const t=new Ps;t.format=e;const s=new lr(t,!0);new wr(this.score,this.settings,s).generate();const i=t.toBinary(),a=this.score.title?`${this.score.title}.mid`:"File.mid",r=document.createElement("a");r.download=a;const n=new Blob([i],{type:"audio/midi"}),o=URL.createObjectURL(n);r.href=o,r.style.display="none",document.body.appendChild(r),r.click(),document.body.removeChild(r)}changeTrackMute(e,t){const s=this.trackIndexesToTracks(this.uiFacade.parseTracks(e));super.changeTrackMute(s,t)}changeTrackSolo(e,t){const s=this.trackIndexesToTracks(this.uiFacade.parseTracks(e));super.changeTrackSolo(s,t)}changeTrackVolume(e,t){const s=this.trackIndexesToTracks(this.uiFacade.parseTracks(e));super.changeTrackVolume(s,t)}trackIndexesToTracks(e){if(!this.score)return[];const t=[];if(1===e.length&&-1===e[0])for(const e of this.score.tracks)t.push(e);else for(const s of e)s>=0&&s<this.score.tracks.length&&t.push(this.score.tracks[s]);return t}loadSoundFontFromUrl(e,t){this.player&&this.player.loadSoundFontFromUrl(e,t,(e=>{this.soundFontLoad.trigger(e),this.uiFacade.triggerEvent(this.container,"soundFontLoad",e)}))}}class Qr{constructor(){this._initListeners=[]}exec(e,t,s){if("string"!=typeof t&&(s=[t],t="init"),95===t.charCodeAt(0)||"exec"===t)return null;const i=new jQuery(e),a=i.data("alphaTab");if("destroy"===t&&!a)return null;if("init"!==t&&!a)throw new Error("alphaTab not initialized");const r=this[t];if(r){const e=[i,a].concat(s);return r.apply(this,e)}return q.error("Api",`Method '${t}' does not exist on jQuery.alphaTab`),null}init(e,t,s){if(!t){t=new Kr(e[0],s),e.data("alphaTab",t);for(const i of this._initListeners)i(e,t,s)}}destroy(e,t){e.removeData("alphaTab"),t.destroy()}print(e,t,s,i){t.print(s,i)}load(e,t,s,i){return t.load(s,i)}render(e,t){t.render()}renderScore(e,t,s,i){t.renderScore(s,i)}renderTracks(e,t,s){t.renderTracks(s)}invalidate(e,t){t.render()}tex(e,t,s,i){t.tex(s,i)}muteTrack(e,t,s,i){t.changeTrackMute(s,i)}soloTrack(e,t,s,i){t.changeTrackSolo(s,i)}trackVolume(e,t,s,i){t.changeTrackVolume(s,i)}loadSoundFont(e,t,s,i){t.loadSoundFont(s,i)}resetSoundFonts(e,t){t.resetSoundFonts()}pause(e,t){t.pause()}play(e,t){return t.play()}playPause(e,t){t.playPause()}stop(e,t){t.stop()}api(e,t){return t}player(e,t){return t.player}isReadyForPlayback(e,t){return t.isReadyForPlayback}playerState(e,t){return t.playerState}masterVolume(e,t,s){return"number"==typeof s&&(t.masterVolume=s),t.masterVolume}metronomeVolume(e,t,s){return"number"==typeof s&&(t.metronomeVolume=s),t.metronomeVolume}countInVolume(e,t,s){return"number"==typeof s&&(t.countInVolume=s),t.countInVolume}midiEventsPlayedFilter(e,t,s){return Array.isArray(s)&&(t.midiEventsPlayedFilter=s),t.midiEventsPlayedFilter}playbackSpeed(e,t,s){return"number"==typeof s&&(t.playbackSpeed=s),t.playbackSpeed}tickPosition(e,t,s){return"number"==typeof s&&(t.tickPosition=s),t.tickPosition}timePosition(e,t,s){return"number"==typeof s&&(t.timePosition=s),t.timePosition}loop(e,t,s){return"boolean"==typeof s&&(t.isLooping=s),t.isLooping}renderer(e,t){return t.renderer}score(e,t){return t.score}settings(e,t){return t.settings}tracks(e,t){return t.tracks}_oninit(e){this._initListeners.push(e)}static restore(e){new jQuery(e).empty().removeData("alphaTab")}}class Zr{constructor(){this.buffer="",this._currentPath="",this._currentPathIsEmpty=!0,this.scale=1,this.color=new et(255,255,255,255),this.lineWidth=1,this.font=new na("Arial",10,Jt.Plain),this.textAlign=ne.Left,this.textBaseline=oe.Top}destroy(){}beginRender(e,t){this.scale=this.settings.display.scale,this.buffer=`<svg xmlns="http://www.w3.org/2000/svg" version="1.1" width="${0|e}px" height="${0|t}px" class="at-surface-svg">\n`,this._currentPath="",this._currentPathIsEmpty=!0,this.textBaseline=oe.Top}beginGroup(e){this.buffer+=`<g class="${e}">`}endGroup(){this.buffer+="</g>"}endRender(){return this.buffer+="</svg>",this.buffer}fillRect(e,t,s,i){s>0&&(this.buffer+=`<rect x="${e*this.scale|0}" y="${t*this.scale|0}" width="${s*this.scale}" height="${i*this.scale}" fill="${this.color.rgba}" />\n`)}strokeRect(e,t,s,i){const a=this.lineWidth*this.scale%2==0?0:.5;this.buffer+=`<rect x="${(e*this.scale|0)+a}" y="${(t*this.scale|0)+a}" width="${s*this.scale}" height="${i*this.scale}" stroke="${this.color.rgba}"`,1!==this.lineWidth&&(this.buffer+=` stroke-width="${this.lineWidth*this.scale}"`),this.buffer+=' fill="transparent" />\n'}beginPath(){}closePath(){this._currentPath+=" z"}moveTo(e,t){this._currentPath+=` M${e*this.scale},${t*this.scale}`}lineTo(e,t){this._currentPathIsEmpty=!1,this._currentPath+=` L${e*this.scale},${t*this.scale}`}quadraticCurveTo(e,t,s,i){this._currentPathIsEmpty=!1,this._currentPath+=` Q${e*this.scale},${t*this.scale},${s*this.scale},${i*this.scale}`}bezierCurveTo(e,t,s,i,a,r){this._currentPathIsEmpty=!1,this._currentPath+=` C${e*this.scale},${t*this.scale},${s*this.scale},${i*this.scale},${a*this.scale},${r*this.scale}`}fillCircle(e,t,s){this._currentPathIsEmpty=!1,e*=this.scale,t*=this.scale,s*=this.scale,this._currentPath+=` M${e-s},${t} A1,1 0 0,0 ${e+s},${t} A1,1 0 0,0 ${e-s},${t} z`,this.fill()}strokeCircle(e,t,s){this._currentPathIsEmpty=!1,e*=this.scale,t*=this.scale,s*=this.scale,this._currentPath+=` M${e-s},${t} A1,1 0 0,0 ${e+s},${t} A1,1 0 0,0 ${e-s},${t} z`,this.stroke()}fill(){this._currentPathIsEmpty||(this.buffer+=`<path d="${this._currentPath}"`,"#000000"!==this.color.rgba&&(this.buffer+=` fill="${this.color.rgba}"`),this.buffer+=' style="stroke: none"/>'),this._currentPath="",this._currentPathIsEmpty=!0}stroke(){if(!this._currentPathIsEmpty){let e=`<path d="${this._currentPath}" stroke="${this.color.rgba}"`;1===this.lineWidth&&1===this.scale||(e+=` stroke-width="${this.lineWidth*this.scale}"`),e+=' style="fill: none" />',this.buffer+=e}this._currentPath="",this._currentPathIsEmpty=!0}fillText(e,t,s){if(""===e)return;let i=`<text x="${t*this.scale|0}" y="${s*this.scale|0}" style='stroke: none; font:${this.font.toCssString(this.settings.display.scale)}; ${this.getSvgBaseLine()}'`;"#000000"!==this.color.rgba&&(i+=` fill="${this.color.rgba}"`),this.textAlign!==ne.Left&&(i+=` text-anchor="${this.getSvgTextAlignment(this.textAlign)}"`),i+=`>${Zr.escapeText(e)}</text>`,this.buffer+=i}static escapeText(e){return e.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/'/g,"&#39;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}getSvgTextAlignment(e){switch(e){case ne.Left:return"start";case ne.Center:return"middle";case ne.Right:return"end"}return""}getSvgBaseLine(){switch(this.textBaseline){case oe.Top:return"dominant-baseline: hanging";case oe.Bottom:return"dominant-baseline: ideographic";default:return""}}measureText(e){return e?Qa.measureString(e,this.font.families,this.font.size*this.scale,this.font.style,this.font.weight):new De(0,0)}onRenderFinished(){return null}beginRotate(e,t,s){this.buffer+=`<g transform="translate(${e*this.scale} ,${t*this.scale}) rotate( ${s})">`}endRotate(){this.buffer+="</g>"}}class en extends Zr{fillMusicFontSymbol(e,t,s,i,a){i!==re.None&&this.fillMusicFontSymbolText(e,t,s,`&#${i};`,a)}fillMusicFontSymbols(e,t,s,i,a){let r="";for(const e of i)e!==re.None&&(r+=`&#${e};`);this.fillMusicFontSymbolText(e,t,s,r,a)}fillMusicFontSymbolText(e,t,s,i,a){e*=this.scale,t*=this.scale,this.buffer+=`<g transform="translate(${e} ${t})" class="at" ><text`;const r=this.scale*s;this.buffer+=1!==r?` style="font-size: ${100*r}%; stroke:none"`:' style="stroke:none"',"#000000"!==this.color.rgba&&(this.buffer+=` fill="${this.color.rgba}"`),a&&(this.buffer+=` text-anchor="${this.getSvgTextAlignment(ne.Center)}"`),this.buffer+=`>${i}</text></g>`}}class tn{constructor(){this.isInsideBracket=!0,this.isRelevantForBoundsLookup=!0,this.hideOnMultiTrack=!1,this.hideOnPercussionTrack=!1}canCreate(e,t){return!this.hideOnPercussionTrack||!t.isPercussion}}!function(e){e[e.PreNotes=0]="PreNotes",e[e.OnNotes=1]="OnNotes",e[e.MiddleNotes=2]="MiddleNotes",e[e.Stem=3]="Stem",e[e.PostNotes=4]="PostNotes",e[e.EndBeat=5]="EndBeat"}(ts||(ts={}));class sn extends kr{constructor(){super(...arguments),this.glyphs=null}get isEmpty(){return!this.glyphs||0===this.glyphs.length}doLayout(){if(!this.glyphs||0===this.glyphs.length)return void(this.width=0);let e=0;for(let t=0,s=this.glyphs.length;t<s;t++){const s=this.glyphs[t];s.renderer=this.renderer,s.doLayout(),e=Math.max(e,s.width)}this.width=e}addGlyph(e){this.glyphs||(this.glyphs=[]),this.renderer&&(e.renderer=this.renderer),this.glyphs.push(e)}paint(e,t,s){const i=this.glyphs;if(i&&0!==i.length)for(const a of i)a.paint(e+this.x,t+this.y,s)}}class an extends sn{constructor(){super(0,0),this.glyphs=[]}doLayout(){}addGlyph(e){e.x=this.width,e.renderer=this.renderer,e.doLayout(),this.width=e.x+e.width,super.addGlyph(e)}}class rn{static score(e,t,s,i=!1){if(!s.style&&!i)return;const a=rn.scoreDefaultColor(e.settings.display.resources,t);return new nn(e,t,s.style,a)}static scoreColor(e,t,s){const i=rn.scoreDefaultColor(e,t);if(s.style&&s.style.colors.has(t))return s.style.colors.get(t)??i}static scoreDefaultColor(e,t){return e.mainGlyphColor}static bar(e,t,s,i=!1){if(!s.style&&!i)return;let a=e.settings.display.resources.mainGlyphColor;switch(t){case u.StandardNotationRepeats:case u.GuitarTabsRepeats:case u.SlashRepeats:case u.NumberedRepeats:case u.StandardNotationClef:case u.GuitarTabsClef:case u.StandardNotationKeySignature:case u.NumberedKeySignature:case u.StandardNotationTimeSignature:case u.GuitarTabsTimeSignature:case u.SlashTimeSignature:case u.NumberedTimeSignature:break;case u.StandardNotationBarLines:case u.GuitarTabsBarLines:case u.SlashBarLines:case u.NumberedBarLines:a=e.settings.display.resources.barSeparatorColor;break;case u.StandardNotationBarNumber:case u.SlashBarNumber:case u.NumberedBarNumber:case u.GuitarTabsBarNumber:a=e.settings.display.resources.barNumberColor;break;case u.StandardNotationStaffLine:case u.GuitarTabsStaffLine:case u.SlashStaffLine:case u.NumberedStaffLine:a=e.settings.display.resources.staffLineColor}return new nn(e,t,s.style,a)}static voice(e,t,s,i=!1){if(!s.style&&!i)return;const a=0===s.index?e.settings.display.resources.mainGlyphColor:e.settings.display.resources.secondaryGlyphColor;return new nn(e,t,s.style,a)}static trackColor(e,t,s){const i=rn.trackDefaultColor(e,t);if(s.style&&s.style.colors.has(t))return s.style.colors.get(t)??i}static trackDefaultColor(e,t){let s=e.mainGlyphColor;switch(t){case we.TrackName:case we.SystemSeparator:case we.StringTuning:break;case we.BracesAndBrackets:s=e.barSeparatorColor}return s}static track(e,t,s,i=!1){if(!s.style&&!i)return;const a=rn.trackDefaultColor(e.settings.display.resources,t);return new nn(e,t,s.style,a)}static beatColor(e,t,s){const i=rn.beatDefaultColor(e,t,s);if(s.style&&s.style.colors.has(t))return s.style.colors.get(t)??i}static beatDefaultColor(e,t,s){return 0===s.voice.index?e.mainGlyphColor:e.secondaryGlyphColor}static beat(e,t,s,i=!1){if(!s.style&&!i)return;const a=rn.beatDefaultColor(e.settings.display.resources,t,s);return new nn(e,t,s.style,a)}static noteColor(e,t,s){const i=rn.noteDefaultColor(e,t,s);if(s.style&&s.style.colors.has(t))return s.style.colors.get(t)??i}static noteDefaultColor(e,t,s){return 0===s.beat.voice.index?e.mainGlyphColor:e.secondaryGlyphColor}static note(e,t,s,i=!1){if(!s.style&&!i)return;const a=0===s.beat.voice.index?e.settings.display.resources.mainGlyphColor:e.settings.display.resources.secondaryGlyphColor;return new nn(e,t,s.style,a)}}class nn{constructor(e,t,s,i){this._canvas=e,s&&s.colors.has(t)?(this._previousColor=e.color,e.color=s.colors.get(t)??i):s||(this._previousColor=e.color,e.color=i)}[Symbol.dispose](){this._previousColor&&(this._canvas.color=this._previousColor)}}class on extends sn{constructor(e,t,s){super(e,t),this.voice=s,this.beatGlyphs=[],this.tupletGroups=[]}scaleToWidth(e){const t=this.renderer.layoutingInfo.spaceToForce(e);this.scaleToForce(t)}scaleToForce(e){this.width=this.renderer.layoutingInfo.calculateVoiceWidth(e);const t=this.renderer.layoutingInfo.buildOnTimePositions(e),s=this.beatGlyphs;for(let e=0,i=s.length;e<i;e++){const a=s[e];if(a.beat.graceType===w.None)a.x=t.get(a.beat.absoluteDisplayStart)-a.onTimeX;else{const i=a.beat.graceGroup.beats[0].absoluteDisplayStart,r=a.beat.graceGroup.id;if(a.beat.graceGroup.isComplete&&t.has(i)){a.x=t.get(i)-a.onTimeX;const e=this.renderer.layoutingInfo.allGraceRods.get(r),s=a.beat.graceGroup.beats[a.beat.graceGroup.beats.length-1].nextBeat,n=s?this.renderer.layoutingInfo.getPreBeatSize(s)+Fr.GraceBeatPadding:0;a.x-=n,a.x-=e[a.beat.graceIndex].postSpringWidth,a.x+=e[a.beat.graceIndex].graceBeatWidth;const o=e[a.beat.graceGroup.beats.length-1];a.x-=o.graceBeatWidth}else{const t=this.renderer.layoutingInfo.incompleteGraceRods.get(r),i=t[a.beat.graceIndex].postSpringWidth-t[a.beat.graceIndex].preSpringWidth;e>0?0===a.beat.graceIndex?a.x=s[e-1].x+s[e-1].width:a.x=s[e-1].x+t[a.beat.graceIndex-1].postSpringWidth-t[a.beat.graceIndex-1].preSpringWidth-i:a.x=-i}}if(e>0){const t=a.x-s[e-1].x;s[e-1].scaleToWidth(t)}if(e===i-1){const e=this.width-s[s.length-1].x;a.scaleToWidth(e)}}}registerLayoutingInfo(e){const t=this.beatGlyphs;for(const s of t)s.registerLayoutingInfo(e)}applyLayoutingInfo(e){const t=this.beatGlyphs;for(const s of t)s.applyLayoutingInfo(e);this.scaleToForce(Math.max(this.renderer.settings.display.stretchForce,e.minStretchForce))}addGlyph(e){const t=e;e.x=0===this.beatGlyphs.length?0:this.beatGlyphs[this.beatGlyphs.length-1].x+this.beatGlyphs[this.beatGlyphs.length-1].width,e.renderer=this.renderer,e.doLayout(),this.beatGlyphs.push(t),this.width=e.x+e.width,t.beat.hasTuplet&&t.beat.tupletGroup.beats[0].id===t.beat.id&&this.tupletGroups.push(t.beat.tupletGroup)}doLayout(){}paint(e,t,s){const i=rn.voice(s,I.Glyphs,this.voice,!0);try{for(let i=0,a=this.beatGlyphs.length;i<a;i++)this.beatGlyphs[i].paint(e+this.x,t+this.y,s)}finally{i?.[Symbol.dispose]?.()}}}on.KeySizeBeat="Beat";class hn{constructor(){this.staffId="",this.up=0,this.down=0}}class ln{constructor(){this.startBeat=null,this.startX=0,this.startY=0,this.endBeat=null,this.endX=0,this.endY=0}calcY(e){return this.startX===this.endX?this.startY:(this.endY-this.startY)/(this.endX-this.startX)*(e-this.startX)+this.startY}}class cn{get isRestBeamHelper(){return 1===this.beats.length&&this.beats[0].isRest}hasLine(e,t){return e&&this.beatHasLine(t)||!e&&1===this.beats.length&&this.beatHasLine(t)}beatHasLine(e){return e.duration>_.Whole}hasFlag(e,t){return e&&this.beatHasFlag(t)||!e&&1===this.beats.length&&this.beatHasFlag(this.beats[0])}beatHasFlag(e){return!e.deadSlapped&&!e.isRest&&(e.duration>_.Quarter||e.graceType!==w.None)}constructor(e,t){this._beatLineXPositions=new Map,this._firstNonRestBeat=null,this._lastNonRestBeat=null,this.voice=null,this.beats=[],this.shortestDuration=_.QuadrupleWhole,this.hasTuplet=!1,this.slashBeats=[],this._firstBeatLowestNoteCompareValue=-1,this._firstBeatHighestNoteCompareValue=-1,this._lastBeatLowestNoteCompareValue=-1,this._lastBeatHighestNoteCompareValue=-1,this.lowestNoteInHelper=null,this._lowestNoteCompareValueInHelper=-1,this.highestNoteInHelper=null,this._highestNoteCompareValueInHelper=-1,this.invertBeamDirection=!1,this.preferredBeamDirection=null,this.isGrace=!1,this.minRestLine=null,this.beatOfMinRestLine=null,this.maxRestLine=null,this.beatOfMaxRestLine=null,this.direction=Te.Up,this.drawingInfos=new Map,this._staff=e,this._renderer=t,this.beats=[]}getBeatLineX(e,t){return t=t??this.direction,this.hasBeatLineX(e)?t===Te.Up?this._beatLineXPositions.get(e.index).up:this._beatLineXPositions.get(e.index).down:0}hasBeatLineX(e){return this._beatLineXPositions.has(e.index)}registerBeatLineX(e,t,s,i){const a=this.getOrCreateBeatPositions(t);a.staffId=e,a.up=s,a.down=i;for(const e of this.drawingInfos.values())e.startBeat===t?e.startX=this.getBeatLineX(t):e.endBeat===t&&(e.endX=this.getBeatLineX(t))}getOrCreateBeatPositions(e){return this._beatLineXPositions.has(e.index)||this._beatLineXPositions.set(e.index,new hn),this._beatLineXPositions.get(e.index)}finish(){this.direction=this.calculateDirection()}calculateDirection(){let e=null;if(this.voice?null!==this.preferredBeamDirection?e=this.preferredBeamDirection:this.voice.index>0?e=this.invert(Te.Down):(this.voice.bar.isMultiVoice||this.beats[0].graceType!==w.None)&&(e=this.invert(Te.Up)):e=Te.Up,this.highestNoteInHelper&&this.lowestNoteInHelper){const t=this._renderer.getNoteY(this.highestNoteInHelper,is.Center),s=this._renderer.getNoteY(this.lowestNoteInHelper,is.Center);if(null===e){const i=(t+s)/2;e=this.invert(this._renderer.middleYPosition<i?Te.Up:Te.Down)}this._renderer.completeBeamingHelper(this)}else e=this.invert(Te.Up),this._renderer.completeBeamingHelper(this);return e}static computeLineHeightsForRest(e){switch(e){case _.QuadrupleWhole:case _.DoubleWhole:return[2,2];case _.Whole:return[0,1];case _.Half:return[1,0];case _.Quarter:return[3,3];case _.Eighth:return[2,2];case _.Sixteenth:return[2,4];case _.ThirtySecond:return[4,4];case _.SixtyFourth:return[4,6];case _.OneHundredTwentyEighth:return[6,6];case _.TwoHundredFiftySixth:return[6,8]}return[0,0]}applyRest(e,t){if(this._lastNonRestBeat&&e.index>=this._lastNonRestBeat.index||this._firstNonRestBeat&&e.index<=this._firstNonRestBeat.index)return;let s=t,i=t;const a=cn.computeLineHeightsForRest(e.duration);s-=a[0],i+=a[1];const r=this.minRestLine,n=this.maxRestLine;(null===r||r>s)&&(this.minRestLine=s,this.beatOfMinRestLine=e),(null===n||n<i)&&(this.maxRestLine=i,this.beatOfMaxRestLine=e)}invert(e){return this.invertBeamDirection?e===Te.Down?Te.Up:Te.Down:e}checkBeat(e){e.invertBeamDirection&&(this.invertBeamDirection=!0),this.voice||(this.voice=e.voice);let t=!1;if(0===this.beats.length)t=!0;else switch(this.beats[this.beats.length-1].beamingMode){case fe.Auto:case fe.ForceSplitOnSecondaryToNext:t=cn.canJoin(this.beats[this.beats.length-1],e);break;case fe.ForceSplitToNext:t=!1;break;case fe.ForceMergeWithNext:t=!0}return t&&(null==this.preferredBeamDirection&&null!==e.preferredBeamDirection&&(this.preferredBeamDirection=e.preferredBeamDirection),e.hasTuplet&&(this.hasTuplet=!0),e.graceType!==w.None&&(this.isGrace=!0),e.isRest?0===this.beats.length&&this.beats.push(e):(this.isRestBeamHelper&&(this.beats=[]),this.beats.push(e),this.checkNote(e.minNote),this.checkNote(e.maxNote),this.shortestDuration<e.duration&&(this.shortestDuration=e.duration),this._firstNonRestBeat||(this._firstNonRestBeat=e),this._lastNonRestBeat=e),e.slashed&&this.slashBeats.push(e)),t}checkNote(e){if(!e)return;let t,s;this.voice&&e.isPercussion?(t=-Bs.getPercussionLine(this.voice.bar,Bs.getNoteValue(e)),s=t):(t=Bs.getNoteValue(e),s=t,e.harmonicType!==T.None&&e.harmonicType!==T.Natural&&(s=e.realValue-this._staff.displayTranspositionPitch)),1===this.beats.length&&this.beats[0]===e.beat&&((-1===this._firstBeatLowestNoteCompareValue||t<this._firstBeatLowestNoteCompareValue)&&(this._firstBeatLowestNoteCompareValue=t),(-1===this._firstBeatHighestNoteCompareValue||s>this._firstBeatHighestNoteCompareValue)&&(this._firstBeatHighestNoteCompareValue=s)),(-1===this._lastBeatLowestNoteCompareValue||t<this._lastBeatLowestNoteCompareValue)&&(this._lastBeatLowestNoteCompareValue=t),(-1===this._lastBeatHighestNoteCompareValue||s>this._lastBeatHighestNoteCompareValue)&&(this._lastBeatHighestNoteCompareValue=s),(!this.lowestNoteInHelper||t<this._lowestNoteCompareValueInHelper)&&(this.lowestNoteInHelper=e,this._lowestNoteCompareValueInHelper=t),(!this.highestNoteInHelper||s>this._highestNoteCompareValueInHelper)&&(this.highestNoteInHelper=e,this._highestNoteCompareValueInHelper=s)}static canJoin(e,t){if(!e||!t||e.graceType!==t.graceType||e.graceType===w.BendGrace||t.graceType===w.BendGrace||e.deadSlapped||t.deadSlapped)return!1;if(e.graceType!==w.None&&t.graceType!==w.None)return!0;const s=e.voice.bar;if(s!==t.voice.bar)return!1;const i=e.playbackStart,a=t.playbackStart;if(!cn.canJoinDuration(e.duration)||!cn.canJoinDuration(t.duration))return i===a;if(e.tupletGroup!==t.tupletGroup)return!1;if(e.hasTuplet&&t.hasTuplet&&e.tupletGroup===t.tupletGroup&&e.tupletGroup.isFull)return!0;let r=z.QuarterTime;if(8===s.masterBar.timeSignatureDenominator)s.masterBar.timeSignatureNumerator%3==0&&(r+=z.QuarterTime/2|0);return((r+i)/r|0)===((r+a)/r|0)}static canJoinDuration(e){switch(e){case _.Whole:case _.Half:case _.Quarter:return!1;default:return!0}}static isFullBarJoin(e,t,s){return ie.getIndex(e.duration)-2-s>0&&ie.getIndex(t.duration)-2-s>0}get beatOfLowestNote(){return this.lowestNoteInHelper.beat}get beatOfHighestNote(){return this.highestNoteInHelper.beat}isPositionFrom(e,t){return!this._beatLineXPositions.has(t.index)||(this._beatLineXPositions.get(t.index).staffId===e||!this._beatLineXPositions.get(t.index).staffId)}}class dn{constructor(e,t){this.topY=0,this.bottomY=0,this.topY=e,this.bottomY=t}}class un{constructor(e){this.topY=-1e3,this.bottomY=-1e3,this.slots=[],this.beat=e}addSlot(e,t){if(this.slots.push(new dn(e,t)),-1e3===this.topY)this.topY=e,this.bottomY=t;else{const s=Math.min(e,t),i=Math.max(e,t);s<this.topY&&(this.topY=s),i>this.bottomY&&(this.bottomY=i)}}}class pn{constructor(){this.reservedLayoutAreasByDisplayTime=new Map,this.restDurationsByDisplayTime=new Map}getBeatMinMaxY(){let e=-1e3,t=-1e3;for(const s of this.reservedLayoutAreasByDisplayTime.values())-1e3===e?(e=s.topY,t=s.bottomY):(e>s.topY&&(e=s.topY),t<s.bottomY&&(t=s.bottomY));return-1e3===e?[0,0]:[e,t]}reserveBeatSlot(e,t,s){t!==s&&(this.reservedLayoutAreasByDisplayTime.has(e.displayStart)||this.reservedLayoutAreasByDisplayTime.set(e.displayStart,new un(e)),this.reservedLayoutAreasByDisplayTime.get(e.displayStart).addSlot(t,s),e.isRest&&this.registerRest(e))}registerRest(e){this.restDurationsByDisplayTime.has(e.displayStart)||this.restDurationsByDisplayTime.set(e.displayStart,new Map),this.restDurationsByDisplayTime.get(e.displayStart).has(e.playbackDuration)||this.restDurationsByDisplayTime.get(e.displayStart).set(e.playbackDuration,e.id)}applyRestCollisionOffset(e,t,s){if(e.voice.index>0&&this.reservedLayoutAreasByDisplayTime.has(e.playbackStart)){const i=cn.computeLineHeightsForRest(e.duration).map((e=>e*s)),a=t-i[0],r=t+i[1];let n=a;const o=this.reservedLayoutAreasByDisplayTime.get(e.playbackStart);let h=!1;for(const e of o.slots)if(a>=e.topY&&a<=e.bottomY||r>=e.topY&&r<=e.bottomY){h=!0;break}if(h){n=1===e.voice.index?o.topY-i[1]-i[0]:o.bottomY;const t=n+i[0]+i[1],r=2*s,h=Math.ceil(Math.abs(n-a)/r);return o.addSlot(n,t),n<a?h*-r:h*r}}return 0}}class gn{constructor(e){this.beamHelpers=[],this.beamHelperLookup=[],this.preferredBeamDirection=null,this._renderer=e,this.collisionHelper=new pn}initialize(){const e=this._renderer,t=this._renderer.bar;let s=null,i=null;for(let a=0,r=t.voices.length;a<r;a++){const r=t.voices[a];this.beamHelpers.push([]),this.beamHelperLookup.push(new Map);for(let a=0,n=r.beats.length;a<n;a++){const n=r.beats[a];let o;n.graceType!==w.None?o=i:(o=s,i=null),o&&o.checkBeat(n)||(o&&o.finish(),o=new cn(t.staff,e),o.preferredBeamDirection=this.preferredBeamDirection,o.checkBeat(n),n.graceType!==w.None?i=o:s=o,this.beamHelpers[r.index].push(o)),this.beamHelperLookup[r.index].set(n.index,o)}s&&s.finish(),i&&i.finish(),s=null,i=null}}getBeamingHelperForBeat(e){return this.beamHelperLookup[e.voice.index].get(e.index)}}class mn extends Tr{constructor(e,t,s){super(e,t),this._textRow=0,this._fretRow=0,this._firstFretSpacing=0,this._chord=s}doLayout(){super.doLayout();const e=this.renderer.resources;this._textRow=1.5*e.effectFont.size,this._fretRow=1.5*e.effectFont.size,this._chord.firstFret>1?this._firstFretSpacing=mn.FretSpacing:this._firstFretSpacing=0,this.height=this._textRow+this._fretRow+mn.Frets*mn.FretSpacing+2*mn.Padding[1],this.width=this._firstFretSpacing+(this._chord.strings.length-1)*mn.StringSpacing+2*mn.Padding[0]}paint(e,t,s){e+=this.x+mn.Padding[0]+this._firstFretSpacing,t+=this.y;const i=mn.StringSpacing,a=mn.FretSpacing,r=this.renderer.resources,n=mn.CircleRadius,o=this.width-2*mn.Padding[0]-this._firstFretSpacing,h=s.textAlign,l=s.textBaseline;s.font=r.effectFont,s.textAlign=ne.Center,s.textBaseline=oe.Top,this._chord.showName&&s.fillText(this._chord.name,e+o/2,t+r.effectFont.size/2),t+=this._textRow,s.font=r.fretboardNumberFont,s.textBaseline=oe.Middle;for(let a=0;a<this._chord.strings.length;a++){const r=e+a*i,n=t+this._fretRow/2;let o=this._chord.strings[this._chord.strings.length-a-1];o<0?s.fillMusicFontSymbol(r,n,1,re.FretboardX,!0):0===o?s.fillMusicFontSymbol(r,n,1,re.FretboardO,!0):(o-=this._chord.firstFret-1,s.fillText(o.toString(),r,n))}t+=this._fretRow;for(let r=0;r<this._chord.strings.length;r++){const n=e+r*i;s.fillRect(n,t,1,a*mn.Frets+1)}this._chord.firstFret>1&&(s.textAlign=ne.Left,s.fillText(this._chord.firstFret.toString(),e-this._firstFretSpacing,t+a/2)),s.fillRect(e,t-1,o,2);for(let i=0;i<=mn.Frets;i++){const r=t+i*a;s.fillRect(e,r,o,1)}const c=new Map;for(const e of this._chord.barreFrets){const t=[-1,-1];c.set(e-this._chord.firstFret,t)}for(let r=0;r<this._chord.strings.length;r++){let o=this._chord.strings[r];if(o>0){if(o-=this._chord.firstFret,c.has(o)){const e=c.get(o);(-1===e[0]||r<e[0])&&(e[0]=r),(-1===e[1]||r>e[1])&&(e[1]=r)}const h=t+o*a+a/2+.5,l=e+(this._chord.strings.length-r-1)*i;s.fillCircle(l,h,n)}}for(const[r,o]of c){const h=t+r*a+a/2+.5,l=e+(this._chord.strings.length-o[1]-1)*i,c=e+(this._chord.strings.length-o[0]-1)*i;s.fillRect(l,h-n,c-l,2*n)}s.textAlign=h,s.textBaseline=l}}mn.Padding=[5,2],mn.Frets=5,mn.CircleRadius=2.5,mn.StringSpacing=10,mn.FretSpacing=12;class fn extends sn{constructor(e,t,s=ne.Center){super(e,t),this._glyphWidth=0,this.glyphs=[],this._align=s}doLayout(){let e=0;switch(this._align){case ne.Left:e=0;break;case ne.Center:e=(this.width-this._glyphWidth)/2;break;case ne.Right:e=this.width-this._glyphWidth}for(const t of this.glyphs)t.x=e,e+=t.width}addGlyphToRow(e){this.glyphs.push(e),this._glyphWidth+=e.width,e.height>this.height&&(this.height=e.height)}}class yn extends sn{constructor(e,t,s=ne.Center){super(e,t),this._rows=[],this.height=0,this.glyphs=[],this._align=s}doLayout(){let e=0,t=0;const s=yn.Padding;this._rows=[];let i=new fn(e,t,this._align);i.width=this.width;for(const a of this.glyphs)e+a.width<this.width?(i.addGlyphToRow(a),e+=a.width):(i.isEmpty||(i.doLayout(),this._rows.push(i),t+=i.height+s),e=0,i=new fn(e,t,this._align),i.width=this.width,i.addGlyphToRow(a),e+=a.width);i.isEmpty||(i.doLayout(),this._rows.push(i),t+=i.height+s),this.height=t}paint(e,t,s){for(const i of this._rows)i.paint(e+this.x,t+this.y,s)}}yn.Padding=3;class bn extends yn{addChord(e){if(e.strings.length>0){const t=new mn(0,0,e);t.renderer=this.renderer,t.doLayout(),this.glyphs.push(t)}}paint(e,t,s){if(this.glyphs.length>0){const i=rn.score(s,be.ChordDiagramList,this.renderer.scoreRenderer.score);try{super.paint(e,t,s)}finally{i?.[Symbol.dispose]?.()}}}}class Sn extends Tr{constructor(e,t,s,i,a=ne.Left,r=null,n){super(e,t),this._lineHeights=null,this._lines=s.split("\n"),this.font=i,this.textAlign=a,this.textBaseline=r,this.colorOverride=n}doLayout(){super.doLayout(),this._lineHeights=[];const e=this.renderer.scoreRenderer.canvas;for(const t of this._lines){e.font=this.font;const s=e.measureText(t),i=s.height;this._lineHeights.push(i),this.height+=i,this.width=Math.max(this.width,s.width)}}paint(e,t,s){const i=s.color;s.color=this.colorOverride??i,s.font=this.font;const a=s.textAlign,r=s.textBaseline;s.textAlign=this.textAlign,null!==this.textBaseline&&(s.textBaseline=this.textBaseline);let n=t+this.y;for(let t=0;t<this._lines.length;t++)s.fillText(this._lines[t],e+this.x,n),n+=this._lineHeights[t];s.textAlign=a,s.textBaseline=r,s.color=i}}class _n{get staffId(){return this._factory.staffId}get contentTop(){return this.y+this.staveTop+this.topSpacing+this.topOverflow}get contentBottom(){return this.y+this.topSpacing+this.topOverflow+this.staveBottom}constructor(e,t,s){this._sharedLayoutData=new Map,this.barRenderers=[],this.x=0,this.y=0,this.height=0,this.index=0,this.staffIndex=0,this.isFirstInSystem=!1,this.trackIndex=0,this.staveTop=0,this.topSpacing=0,this.bottomSpacing=0,this.staveBottom=0,this._factory=s,this.trackIndex=e,this.modelStaff=t}getSharedLayoutData(e,t){return this._sharedLayoutData.has(e)?this._sharedLayoutData.get(e):t}setSharedLayoutData(e,t){this._sharedLayoutData.set(e,t)}get isInsideBracket(){return this._factory.isInsideBracket}get isRelevantForBoundsLookup(){return this._factory.isRelevantForBoundsLookup}registerStaffTop(e){this.staveTop=e}registerStaffBottom(e){this.staveBottom=e}addBarRenderer(e){e.staff=this,e.index=this.barRenderers.length,e.reLayout(),this.barRenderers.push(e),this.system.layout.registerBarRenderer(this.staffId,e)}addBar(e,t,s){const i=this._factory.create(this.system.layout.renderer,e);i.additionalMultiRestBars=s,i.staff=this,i.index=this.barRenderers.length,i.layoutingInfo=t,i.doLayout(),i.registerLayoutingInfo();const a=i.barDisplayWidth;a>0&&this.system.layout.systemsLayoutMode===ss.FromModelWithWidths&&(i.width=a),this.barRenderers.push(i),e&&this.system.layout.registerBarRenderer(this.staffId,i)}revertLastBar(){const e=this.barRenderers[this.barRenderers.length-1];this.barRenderers.splice(this.barRenderers.length-1,1),this.system.layout.unregisterBarRenderer(this.staffId,e);for(const e of this.barRenderers)e.applyLayoutingInfo();return e}scaleToWidth(e){this._sharedLayoutData=new Map;const t=this.topOverflow;let s=0;switch(this.system.layout.systemsLayoutMode){case ss.Automatic:const i=(e-this.system.computedWidth)/this.barRenderers.length;for(const e of this.barRenderers){e.x=s,e.y=this.topSpacing+t;const a=e.computedWidth+i;e.scaleToWidth(a),s+=e.width}break;case ss.FromModelWithScale:e-=this.system.accoladeWidth;const a=this.system.totalBarDisplayScale;for(const i of this.barRenderers){i.x=s,i.y=this.topSpacing+t;const r=i.barDisplayScale*e/a;i.scaleToWidth(r),s+=i.width}break;case ss.FromModelWithWidths:for(const e of this.barRenderers){e.x=s,e.y=this.topSpacing+t;const i=e.barDisplayWidth;i>0?e.scaleToWidth(i):e.scaleToWidth(e.computedWidth),s+=e.width}}}get topOverflow(){let e=0;for(let t=0,s=this.barRenderers.length;t<s;t++){const s=this.barRenderers[t];s.topOverflow>e&&(e=s.topOverflow)}return e}get bottomOverflow(){let e=0;for(let t=0,s=this.barRenderers.length;t<s;t++){const s=this.barRenderers[t];s.bottomOverflow>e&&(e=s.bottomOverflow)}return e}calculateHeightForAccolade(){this.topSpacing=this._factory.getStaffPaddingTop(this),this.bottomSpacing=this._factory.getStaffPaddingBottom(this),this.height=this.barRenderers.length>0?this.barRenderers[0].height:0,this.height>0&&(this.height+=this.topSpacing+this.topOverflow+this.bottomOverflow+this.bottomSpacing)}finalizeStaff(){this.topSpacing=this._factory.getStaffPaddingTop(this),this.bottomSpacing=this._factory.getStaffPaddingBottom(this),this.height=0;let e=!1,t=this.topOverflow;for(let s=0;s<this.barRenderers.length;s++)this.barRenderers[s].y=this.topSpacing+t,this.height=Math.max(this.height,this.barRenderers[s].height),this.barRenderers[s].finalizeRenderer()&&(e=!0);if(e){t=this.topOverflow;for(let e=0;e<this.barRenderers.length;e++)this.barRenderers[e].y=this.topSpacing+t;for(let e=0;e<this.barRenderers.length;e++)this.barRenderers[e].finalizeRenderer()}this.height>0&&(this.height+=this.topSpacing+t+this.bottomOverflow+this.bottomSpacing)}paint(e,t,s,i,a){if(0!==this.height&&0!==a)for(let r=i,n=Math.min(i+a,this.barRenderers.length);r<n;r++)this.barRenderers[r].paint(e+this.x,t+this.y,s)}}class wn{constructor(){this.timePosition=0,this.longestDuration=0,this.smallestDuration=0,this.force=0,this.springConstant=0,this.preBeatWidth=0,this.graceBeatWidth=0,this.postSpringWidth=0,this.allDurations=new Set}get springWidth(){return this.preSpringWidth+this.postSpringWidth}get preSpringWidth(){return this.preBeatWidth+this.graceBeatWidth}}class Bn{constructor(){this._timeSortedSprings=[],this._minTime=-1,this._onTimePositionsForce=0,this._onTimePositions=new Map,this._incompleteGraceRodsWidth=0,this._minDuration=Bn.MinDuration,this.version=0,this.preBeatSize=0,this.postBeatSize=0,this.minStretchForce=0,this.totalSpringConstant=0,this.incompleteGraceRods=new Map,this.allGraceRods=new Map,this.springs=new Map,this.height=0}updateMinStretchForce(e){this.minStretchForce<e&&(this.minStretchForce=e)}getPreBeatSize(e){if(e.graceType!==w.None){const t=e.graceGroup.id;return this.allGraceRods.get(t)[e.graceIndex].preBeatWidth}const t=e.absoluteDisplayStart;return this.springs.has(t)?this.springs.get(t).preBeatWidth:0}getPostBeatSize(e){if(e.graceType!==w.None){const t=e.graceGroup.id;return this.allGraceRods.get(t)[e.graceIndex].postSpringWidth}const t=e.absoluteDisplayStart;return this.springs.has(t)?this.springs.get(t).postSpringWidth:0}addSpring(e,t,s,i,a){let r;if(this.version++,this.springs.has(e))r=this.springs.get(e),r.postSpringWidth<a&&(r.postSpringWidth=a),r.graceBeatWidth<s&&(r.graceBeatWidth=s),r.preBeatWidth<i&&(r.preBeatWidth=i),t<r.smallestDuration&&(r.smallestDuration=t),t>r.longestDuration&&(r.longestDuration=t),r.allDurations.add(t);else{if(r=new wn,r.timePosition=e,r.allDurations.add(t),this._timeSortedSprings.length>0){const e=this._timeSortedSprings[this._timeSortedSprings.length-1];for(const t of e.allDurations)e.timePosition;t<this._minDuration&&(this._minDuration=t)}r.longestDuration=t,r.postSpringWidth=a,r.graceBeatWidth=s,r.preBeatWidth=i,this.springs.set(e,r);const n=this._timeSortedSprings;let o=n.length-1;for(;o>0&&n[o].timePosition>e;)o--;this._timeSortedSprings.splice(o+1,0,r)}return(-1===this._minTime||this._minTime>e)&&(this._minTime=e),r}addBeatSpring(e,t,s){const i=e.absoluteDisplayStart;if(e.graceType!==w.None){const a=e.graceGroup.id;this.allGraceRods.has(a)||this.allGraceRods.set(a,new Array(e.graceGroup.beats.length)),e.graceGroup.isComplete||this.incompleteGraceRods.has(a)||this.incompleteGraceRods.set(a,new Array(e.graceGroup.beats.length));const r=this.allGraceRods.get(a)[e.graceIndex];if(r)r.postSpringWidth<s&&(r.postSpringWidth=s),r.preBeatWidth<t&&(r.preBeatWidth=t);else{const r=new wn;r.timePosition=i,r.postSpringWidth=s,r.preBeatWidth=t,e.graceGroup.isComplete||(this.incompleteGraceRods.get(a)[e.graceIndex]=r),this.allGraceRods.get(a)[e.graceIndex]=r}}else{let a=0;if(e.graceGroup&&this.allGraceRods.has(e.graceGroup.id))for(const t of this.allGraceRods.get(e.graceGroup.id))a+=t.springWidth;this.addSpring(i,e.displayDuration,a,t,s)}}finish(){for(const[e,t]of this.allGraceRods){let e=0;for(const s of t)e+=s.preBeatWidth,s.graceBeatWidth=e,e+=s.postSpringWidth}this._incompleteGraceRodsWidth=0;for(const e of this.incompleteGraceRods.values())for(const t of e)this._incompleteGraceRodsWidth+=t.preBeatWidth+t.postSpringWidth;this.calculateSpringConstants(),this.version++}calculateSpringConstants(){let e=0;const t=this._timeSortedSprings;if(0===t.length)return this.totalSpringConstant=-1,void(this.minStretchForce=-1);for(let s=0;s<t.length;s++){const i=t[s];let a=0;if(s===t.length-1)a=i.longestDuration;else{const e=t[s+1];a=Math.abs(e.timePosition-i.timePosition)}i.springConstant=this.calculateSpringConstant(i,a),e+=1/i.springConstant}this.totalSpringConstant=1/e,this.minStretchForce=0;for(let e=0;e<t.length;e++){const s=t[e];let i=0;if(e===t.length-1)i=s.postSpringWidth;else{const a=t[e+1];i=s.postSpringWidth+a.preSpringWidth}0===e&&(i+=s.preSpringWidth);const a=i*s.springConstant;this.updateMinStretchForce(a)}}paint(e,t,s){}calculateSpringConstant(e,t){t<=0&&(t=z.toTicks(_.TwoHundredFiftySixth)),0===e.smallestDuration&&(e.smallestDuration=t);const s=e.smallestDuration,i=this._minDuration,a=Bn.MinDurationWidth;return s/t*(1/((1+.85*Math.log2(t/i))*a))}spaceToForce(e){return-1!==this.totalSpringConstant?(this._timeSortedSprings.length>0&&(e-=this._timeSortedSprings[0].preSpringWidth),e-=this._incompleteGraceRodsWidth,Math.max(e,0)*this.totalSpringConstant):-1}calculateVoiceWidth(e){let t=0;return-1!==this.totalSpringConstant&&(t=this.calculateWidth(e,this.totalSpringConstant)),this._timeSortedSprings.length>0&&(t+=this._timeSortedSprings[0].preSpringWidth),t+=this._incompleteGraceRodsWidth,t}calculateWidth(e,t){return e/t}buildOnTimePositions(e){if(-1===this.totalSpringConstant)return new Map;if(ie.isAlmostEqualTo(this._onTimePositionsForce,e)&&this._onTimePositions)return this._onTimePositions;this._onTimePositionsForce=e;const t=new Map;this._onTimePositions=t;const s=this._timeSortedSprings;if(0===s.length)return t;let i=s[0].preSpringWidth;for(let a=0;a<s.length;a++)t.set(s[a].timePosition,i),i+=this.calculateWidth(e,s[a].springConstant);return t}}Bn.MinDuration=30,Bn.MinDurationWidth=7;class kn{constructor(){this.width=0,this.isLinkedToPrevious=!1,this.canWrap=!0,this.additionalMultiBarRestIndexes=null,this.renderers=[]}get lastMasterBarIndex(){return this.additionalMultiBarRestIndexes?this.additionalMultiBarRestIndexes[this.additionalMultiBarRestIndexes.length-1]:this.masterBar.index}}class Tn{constructor(e,t){this.staves=[],this.stavesRelevantForBoundsLookup=[],this.firstStaffInBracket=null,this.lastStaffInBracket=null,this.bracket=null,this.staffSystem=e,this.track=t}addStaff(e){this.staves.push(e),e.isRelevantForBoundsLookup&&this.stavesRelevantForBoundsLookup.push(e)}}class Nn{constructor(){this.firstStaffInBracket=null,this.lastStaffInBracket=null,this.drawAsBrace=!1,this.braceScale=1,this.width=0,this.index=0}finalizeBracket(){if(this.firstStaffInBracket===this.lastStaffInBracket)return void(this.width=0);const e=Nr.Heights.get(re.Brace),t=Nr.Widths.get(re.Brace);if(this.width=t,!this.drawAsBrace||!this.firstStaffInBracket||!this.lastStaffInBracket)return;const s=this.firstStaffInBracket.contentTop,i=(this.lastStaffInBracket.contentBottom-s)/e;this.braceScale=i,this.width=t*this.braceScale}}class xn extends Nn{constructor(e){super(),this.track=e,this.drawAsBrace=xn.isTrackDrawAsBrace(e)}includesStaff(e){return e.modelStaff.track===this.track}static isTrackDrawAsBrace(e){return e.staves.filter((e=>e.showStandardNotation)).length>1}}class vn extends xn{includesStaff(e){return e.modelStaff.track===this.track||!this.drawAsBrace&&this.track.playbackInfo.program===e.modelStaff.track.playbackInfo.program}}class Pn{constructor(e){this._allStaves=[],this._firstStaffInBrackets=null,this._lastStaffInBrackets=null,this._accoladeSpacingCalculated=!1,this._brackets=[],this._hasSystemSeparator=!1,this.x=0,this.y=0,this.index=0,this.accoladeWidth=0,this.isFull=!1,this.width=0,this.computedWidth=0,this.totalBarDisplayScale=0,this.isLast=!1,this.masterBarsRenderers=[],this.staves=[],this.layout=e,this.topPadding=e.renderer.settings.display.systemPaddingTop,this.bottomPadding=e.renderer.settings.display.systemPaddingBottom}get firstBarIndex(){return this.masterBarsRenderers[0].masterBar.index}get lastBarIndex(){return this.masterBarsRenderers[this.masterBarsRenderers.length-1].masterBar.index}addMasterBarRenderers(e,t){if(0===e.length)return null;this.masterBarsRenderers.push(t),t.layoutingInfo.preBeatSize=0;let s=0;for(let e=0,i=this.staves.length;e<i;e++){const i=this.staves[e];for(let e=0,a=i.staves.length;e<a;e++){const a=i.staves[e],r=t.renderers[s++];a.addBarRenderer(r)}}return this.calculateAccoladeSpacing(e),this.updateWidthFromLastBar(),t}addBars(e,t,s){const i=new kn;i.additionalMultiBarRestIndexes=s,i.layoutingInfo=new Bn,i.masterBar=e[0].score.masterBars[t],this.masterBarsRenderers.push(i);const a=i.layoutingInfo;for(const e of this.staves)for(const r of e.staves){const n=e.track.staves[r.modelStaff.index].bars[t],o=null==s?null:s.map((t=>e.track.staves[r.modelStaff.index].bars[t]));r.addBar(n,a,o);const h=r.barRenderers[r.barRenderers.length-1];i.renderers.push(h),h.isLinkedToPrevious&&(i.isLinkedToPrevious=!0),h.canWrap||(i.canWrap=!1)}return this.calculateAccoladeSpacing(e),a.finish(),i.width=this.updateWidthFromLastBar(),i}revertLastBar(){if(this.masterBarsRenderers.length>1){const e=this.masterBarsRenderers[this.masterBarsRenderers.length-1];this.masterBarsRenderers.splice(this.masterBarsRenderers.length-1,1);let t=0,s=0;for(let e=0,i=this._allStaves.length;e<i;e++){const i=this._allStaves[e].revertLastBar(),a=i.computedWidth;a>t&&(t=a);const r=i.barDisplayScale;r>s&&(s=r)}return this.width-=t,this.computedWidth-=t,this.totalBarDisplayScale-=s,e}return null}updateWidthFromLastBar(){let e=0,t=0;for(let s=0,i=this._allStaves.length;s<i;s++){const i=this._allStaves[s],a=i.barRenderers[i.barRenderers.length-1];a.applyLayoutingInfo(),a.computedWidth>e&&(e=a.computedWidth);const r=a.barDisplayScale;r>t&&(t=r)}return this.width+=e,this.computedWidth+=e,this.totalBarDisplayScale+=t,e}calculateAccoladeSpacing(e){const t=this.layout.renderer.settings;if(!this._accoladeSpacingCalculated){this._accoladeSpacingCalculated=!0,this.accoladeWidth=0;const s=this.layout.renderer.score.stylesheet;if(this.layout.renderer.settings.notation.isNotationElementVisible(E.TrackNames)){const n=1===this.layout.renderer.tracks.length?s.singleTrackTrackNamePolicy:s.multiTrackTrackNamePolicy,o=0===this.index?s.firstSystemTrackNameMode:s.otherSystemsTrackNameMode,h=0===this.index?s.firstSystemTrackNameOrientation:s.otherSystemsTrackNameOrientation;let l=!1;switch(n){case i.Hidden:break;case i.FirstSystem:l=0===this.index;break;case i.AllSystems:l=!0}let c=!1;if(l){const s=this.layout.renderer.canvas,i=t.display.resources.effectFont;s.font=i;for(const t of e){let e="";switch(o){case a.FullName:e=t.name;break;case a.ShortName:e=t.shortName}if(e.length>0){c=!0;const t=s.measureText(e);switch(h){case r.Horizontal:this.accoladeWidth=Math.ceil(Math.max(this.accoladeWidth,t.width));break;case r.Vertical:this.accoladeWidth=Math.ceil(Math.max(this.accoladeWidth,t.height))}}}c&&(this.accoladeWidth+=t.display.systemLabelPaddingLeft,this.accoladeWidth+=t.display.systemLabelPaddingRight)}}let n=0;for(const e of this._allStaves)e.y=n,e.calculateHeightForAccolade(),n+=e.height;let o=0;for(const e of this._brackets)e.finalizeBracket(),o=Math.max(o,e.width);this.accoladeWidth+=o,this.width+=this.accoladeWidth,this.computedWidth+=this.accoladeWidth}}getStaffTrackGroup(e){for(let t=0,s=this.staves.length;t<s;t++){const s=this.staves[t];if(s.track===e)return s}return null}addStaff(e,t){let i=this.getStaffTrackGroup(e);if(i||(i=new Tn(this,e),this.staves.push(i)),t.staffTrackGroup=i,t.system=this,t.index=this._allStaves.length,this._allStaves.push(t),i.addStaff(t),t.isInsideBracket){this._firstStaffInBrackets||(this._firstStaffInBrackets=t,t.isFirstInSystem=!0),i.firstStaffInBracket||(i.firstStaffInBracket=t),this._lastStaffInBrackets=t,i.lastStaffInBracket=t;let a=this._brackets.find((e=>e.includesStaff(t)));if(!a)switch(e.score.stylesheet.bracketExtendMode){case s.NoBrackets:break;case s.GroupStaves:a=new xn(e),a.index=this._brackets.length,this._brackets.push(a);break;case s.GroupSimilarInstruments:a=new vn(e),a.index=this._brackets.length,this._brackets.push(a)}a&&(a.firstStaffInBracket||(a.firstStaffInBracket=t),a.lastStaffInBracket=t,i.bracket=a)}}get height(){return 0===this._allStaves.length?0:this._allStaves[this._allStaves.length-1].y+this._allStaves[this._allStaves.length-1].height+this.topPadding+this.bottomPadding}scaleToWidth(e){for(let t=0,s=this._allStaves.length;t<s;t++)this._allStaves[t].scaleToWidth(e);this.width=e}paint(e,t,s){if(t+=this.topPadding,this.paintPartial(e+this.x,t+this.y,s,0,this.masterBarsRenderers.length),this._hasSystemSeparator){const i=rn.track(s,we.SystemSeparator,this._allStaves[0].modelStaff.track);try{s.fillMusicFontSymbol(e+this.x,t+this.y+this.height-10,1,re.SystemDivider,!1),s.fillMusicFontSymbol(e+this.x+this.width-Pn.SystemSignSeparatorWidth,t+this.y+this.height-Pn.SystemSignSeparatorPadding,1,re.SystemDivider,!1)}finally{i?.[Symbol.dispose]?.()}}}paintPartial(e,t,s,n,o){for(let i=0,a=this._allStaves.length;i<a;i++)this._allStaves[i].paint(e,t,s,n,o);const h=this.layout.renderer.settings.display.resources;if(this.staves.length>0&&0===n){s.color=h.barSeparatorColor;const n=this.layout.renderer.settings,o=this.layout.renderer.settings.notation.isNotationElementVisible(E.TrackNames);if(s.font=h.effectFont,o){const o=this.layout.renderer.score.stylesheet,h=1===this.layout.renderer.tracks.length?o.singleTrackTrackNamePolicy:o.multiTrackTrackNamePolicy,l=0===this.index?o.firstSystemTrackNameMode:o.otherSystemsTrackNameMode,c=0===this.index?o.firstSystemTrackNameOrientation:o.otherSystemsTrackNameOrientation;let d=!1;switch(h){case i.Hidden:break;case i.FirstSystem:d=0===this.index;break;case i.AllSystems:d=!0}if(d){const i=s.textBaseline,o=s.textAlign;for(const i of this.staves)if(i.firstStaffInBracket&&i.lastStaffInBracket){const o=t+i.firstStaffInBracket.contentTop,h=t+i.lastStaffInBracket.contentBottom;let d="";switch(l){case a.FullName:d=i.track.name;break;case a.ShortName:d=i.track.shortName}const u=rn.track(s,we.TrackName,i.track);try{if(d.length>0){const t=e+i.firstStaffInBracket.x-n.display.accoladeBarPaddingRight-(i.bracket?.width??0)-n.display.systemLabelPaddingRight;switch(c){case r.Horizontal:s.textBaseline=oe.Middle,s.textAlign=ne.Right,s.fillText(d,t,(o+h)/2);break;case r.Vertical:s.textBaseline=oe.Bottom,s.textAlign=ne.Center;const e=.1;s.beginRotate(t,(o+h)/2,-90-e),s.fillText(d,0,0),s.endRotate()}}}finally{u?.[Symbol.dispose]?.()}}s.textBaseline=i,s.textAlign=o}}if(this._allStaves.length>0){let i=null;for(const a of this._allStaves)if(a.isInsideBracket){if(null!==i){const r=i.contentBottom,n=a.contentTop,o=e+i.x,h=i.barRenderers[0],l=rn.bar(s,h.staffLineBarSubElement,h.bar);try{const e=Math.ceil(n-r);s.fillRect(o,t+r,1,e)}finally{l?.[Symbol.dispose]?.()}}i=a}}for(const i of this._brackets)if(i.firstStaffInBracket&&i.lastStaffInBracket){const a=e+i.firstStaffInBracket.x,r=i.width,o=n.display.accoladeBarPaddingRight;let h=t+i.firstStaffInBracket.contentTop,l=t+i.lastStaffInBracket.contentBottom;if(i.drawAsBrace)s.fillMusicFontSymbol(a-o-r,l,i.braceScale,re.Brace);else if(i.firstStaffInBracket!==i.lastStaffInBracket){const e=r/2;h-=e,l+=2*e,s.fillRect(a-o-r,h,r,Math.ceil(l-h));const t=a-o-r-.5;s.fillMusicFontSymbol(t,h,1,re.BracketTop),s.fillMusicFontSymbol(t,Math.floor(l),1,re.BracketBottom)}}}}finalizeSystem(){const e=this.layout.renderer.settings;0===this.index&&(this.topPadding=e.display.firstSystemPaddingTop),this.isLast?this.bottomPadding=e.display.lastSystemPaddingBottom:this.layout.renderer.score.stylesheet.useSystemSignSeparator&&this.layout.renderer.tracks.length>1&&(this.bottomPadding+=Pn.SystemSignSeparatorHeight,this._hasSystemSeparator=!0);let t=0;for(const e of this._allStaves)e.x=this.accoladeWidth,e.y=t,e.finalizeStaff(),t+=e.height;for(const e of this._brackets)e.finalizeBracket()}buildBoundingsLookup(e,t){if(this.layout.renderer.boundsLookup.isFinished)return;const s=this._firstStaffInBrackets,i=this._lastStaffInBrackets;if(!s||!i)return;t+=this.topPadding;const a=this._allStaves[this._allStaves.length-1],r=t+this.y+s.y,n=t+this.y+i.y+i.height,o=t+this.y+this._allStaves[0].y,h=t+this.y+a.y+a.height,l=t+this.y+s.y+s.topSpacing+s.topOverflow+(s.barRenderers.length>0?s.barRenderers[0].topPadding:0),c=n-r,d=t+this.y+a.y+a.height-a.bottomSpacing-a.bottomOverflow-(a.barRenderers.length>0?a.barRenderers[0].bottomPadding:0)-l,u=h-o,p=this.x+s.x,g=new ar;g.visualBounds=new mt,g.visualBounds.x=e+this.x,g.visualBounds.y=t+this.y,g.visualBounds.w=this.width,g.visualBounds.h=this.height-this.topPadding-this.bottomPadding,g.realBounds=new mt,g.realBounds.x=e+this.x,g.realBounds.y=t+this.y,g.realBounds.w=this.width,g.realBounds.h=this.height,this.layout.renderer.boundsLookup.addStaffSystem(g);const m=new Map;for(let e=0;e<this.staves.length;e++)for(const s of this.staves[e].stavesRelevantForBoundsLookup)for(const e of s.barRenderers){let i;m.has(e.bar.masterBar.index)?i=m.get(e.bar.masterBar.index):(i=new sr,i.index=e.bar.masterBar.index,i.isFirstOfLine=e.isFirstOfLine,i.realBounds=new mt,i.realBounds.x=p+e.x,i.realBounds.y=o,i.realBounds.w=e.width,i.realBounds.h=u,i.visualBounds=new mt,i.visualBounds.x=p+e.x,i.visualBounds.y=r,i.visualBounds.w=e.width,i.visualBounds.h=c,i.lineAlignedBounds=new mt,i.lineAlignedBounds.x=p+e.x,i.lineAlignedBounds.y=l,i.lineAlignedBounds.w=e.width,i.lineAlignedBounds.h=d,this.layout.renderer.boundsLookup.addMasterBar(i),m.set(i.index,i)),e.buildBoundingsLookup(i,p,t+this.y+s.y)}}getBarX(e){if(!this._firstStaffInBrackets||0===this.layout.renderer.tracks.length)return 0;const t=this.layout.renderer.tracks[0].staves[0].bars[e];return this.layout.getRendererForBar(this._firstStaffInBrackets.staffId,t).x}}Pn.SystemSignSeparatorHeight=40,Pn.SystemSignSeparatorPadding=10,Pn.SystemSignSeparatorWidth=36;class Fn extends yn{constructor(e,t){super(e,t,ne.Left)}}class Cn extends sn{constructor(e,t,s,i){super(e,t),this._tuning=s,this._trackLabel=i,this.glyphs=[]}doLayout(){if(!(this.glyphs.length>0)){this.createGlyphs(this._tuning);for(const e of this.glyphs)e.renderer=this.renderer,e.doLayout()}}paint(e,t,s){s.textBaseline=oe.Middle;const i=s.color;this.colorOverride&&(s.color=this.colorOverride),super.paint(e,t,s),s.color=i}createGlyphs(e){const t=this.renderer.resources;this.height=0;if(this._trackLabel.length>0){this.height+=1;const e=new Sn(0,this.height,this._trackLabel,t.effectFont,ne.Left);e.renderer=this.renderer,e.doLayout(),this.height+=e.height+1,e.y+=e.height/2,this.addGlyph(e)}const s=new Sn(0,this.height,e.name,t.effectFont,ne.Left);s.renderer=this.renderer,s.doLayout(),this.height+=s.height,s.y+=s.height/2,this.addGlyph(s);if(this.renderer.scoreRenderer.canvas.font=t.effectFont,this.width=Math.max(this.renderer.scoreRenderer.canvas.measureText(this._trackLabel).width,Math.max(this.renderer.scoreRenderer.canvas.measureText(e.name).width,128)),!e.isStandard){this.height+=15;const s=Cn.CircleNumberScale,i=Nr.Heights.get(re.GuitarString0)*s,a=0|Math.ceil(e.tunings.length/2);let r=0,n=this.height;for(let o=0,h=e.tunings.length;o<h;o++){const h=re.GuitarString0+(o+1);this.addGlyph(new xr(r,n+i/2.5,s,h));const l=`= ${st.getTextForTuning(e.tunings[o],!1)}`;this.addGlyph(new Sn(r+i+1,n,l,t.effectFont,ne.Left)),n+=15,o===a-1&&(n=this.height,r+=64)}this.height+=15*a}this.width+=15}}Cn.CircleNumberScale=.7;class Dn{constructor(e,t){this.args=e,this.renderCallback=t}}!function(e){e[e.Automatic=0]="Automatic",e[e.FromModelWithScale=1]="FromModelWithScale",e[e.FromModelWithWidths=2]="FromModelWithWidths"}(ss||(ss={}));class En{get scaledWidth(){return Math.round(this.width/this.renderer.settings.display.scale)}constructor(e){this._barRendererLookup=new Map,this.pagePadding=null,this.width=0,this.height=0,this.multiBarRestInfo=null,this.headerGlyphs=new Map,this.footerGlyphs=new Map,this.chordDiagrams=null,this.tuningGlyph=null,this.systemsLayoutMode=ss.Automatic,this._lazyPartials=new Map,this.firstBarIndex=0,this.lastBarIndex=0,this.renderer=e}resize(){this._lazyPartials.clear(),this.doResize()}layoutAndRender(){this._lazyPartials.clear();const e=this.renderer.score;this.firstBarIndex=ie.computeFirstDisplayedBarIndex(e,this.renderer.settings),this.lastBarIndex=ie.computeLastDisplayedBarIndex(e,this.renderer.settings,this.firstBarIndex),this.multiBarRestInfo=ie.buildMultiBarRestInfo(this.renderer.tracks,this.firstBarIndex,this.lastBarIndex),this.pagePadding=this.renderer.settings.display.padding.map((e=>e/this.renderer.settings.display.scale)),this.pagePadding||(this.pagePadding=[0,0,0,0]),1===this.pagePadding.length?this.pagePadding=[this.pagePadding[0],this.pagePadding[0],this.pagePadding[0],this.pagePadding[0]]:2===this.pagePadding.length&&(this.pagePadding=[this.pagePadding[0],this.pagePadding[1],this.pagePadding[0],this.pagePadding[1]]),this.createScoreInfoGlyphs(),this.doLayoutAndRender()}registerPartial(e,t){if(0===e.height)return;const s=this.renderer.settings.display.scale;e.x*=s,e.y*=s,e.width*=s,e.height*=s,e.totalWidth*=s,e.totalHeight*=s,this.renderer.settings.core.enableLazyLoading?(this._lazyPartials.set(e.id,new Dn(e,t)),this.renderer.partialLayoutFinished.trigger(e)):(this.renderer.partialLayoutFinished.trigger(e),this.internalRenderLazyPartial(e,t))}internalRenderLazyPartial(e,t){const s=this.renderer.canvas;s.beginRender(e.width,e.height),t(s),e.renderResult=s.endRender(),this.renderer.partialRenderFinished.trigger(e)}renderLazyPartial(e){if(this._lazyPartials.has(e)){const t=this._lazyPartials.get(e);this.internalRenderLazyPartial(t.args,t.renderCallback)}}createHeaderFooterGlyph(e,t,s,i){switch(s){case be.WordsAndMusic:if(t.words!==t.music)return;break;case be.Words:case be.Music:if(t.words===t.music)return;break;case be.CopyrightSecondLine:if(!this.headerGlyphs.has(be.Copyright))return}const a=e.display.resources,r=e.notation,n=t.style&&t.style.headerAndFooter.has(s)?t.style.headerAndFooter.get(s):Xe.defaultHeaderAndFooter.get(s);let o=void 0===n.isVisible||n.isVisible;if(void 0!==i&&(o=r.isNotationElementVisible(i)),!o)return;const h=n.buildText(t);return h?new Sn(0,0,h,a.getFontForElement(s),n.textAlign,void 0,rn.scoreColor(a,s,t)):void 0}createScoreInfoGlyphs(){q.debug("ScoreLayout","Creating score info glyphs");const e=this.renderer.settings,t=this.renderer.score;this.headerGlyphs=new Map,this.footerGlyphs=new Map;const s=new On(this.renderer,this.renderer.tracks[0].staves[0].bars[0]);for(const[i,a]of En.HeaderElements.value){const r=this.createHeaderFooterGlyph(e,t,i,a);r&&(r.renderer=s,r.doLayout(),this.headerGlyphs.set(i,r))}for(const[i,a]of En.FooterElements.value){const r=this.createHeaderFooterGlyph(e,t,i,a);r&&(r.renderer=s,r.doLayout(),this.footerGlyphs.set(i,r))}const i=e.notation,a=e.display.resources;if(i.isNotationElementVisible(E.GuitarTuning)){const e=[];for(const s of this.renderer.tracks)for(const i of s.staves){let a=!i.isPercussion&&i.isStringed&&i.tuning.length>0&&i.showTablature;if(t.stylesheet.perTrackDisplayTuning&&t.stylesheet.perTrackDisplayTuning.has(s.index)&&!1===t.stylesheet.perTrackDisplayTuning.get(s.index)&&(a=!1),a){e.push(i);break}}if(e.length>0&&t.stylesheet.globalDisplayTuning){this.tuningGlyph=new Fn(0,0),this.tuningGlyph.renderer=s;for(const t of e)if(t.stringTuning.tunings.length>0){const i=e.length>1?t.track.name:"",r=new Cn(0,0,t.stringTuning,i);r.colorOverride=rn.trackColor(a,we.StringTuning,t.track),r.renderer=s,r.doLayout(),this.tuningGlyph.addGlyph(r)}}}if(i.isNotationElementVisible(E.ChordDiagrams)){this.chordDiagrams=new bn(0,0),this.chordDiagrams.renderer=s;const e=new Set;for(const s of this.renderer.tracks){if(t.stylesheet.globalDisplayChordDiagramsOnTop&&(null==t.stylesheet.perTrackChordDiagramsOnTop||!t.stylesheet.perTrackChordDiagramsOnTop.has(s.index)||t.stylesheet.perTrackChordDiagramsOnTop.get(s.index)))for(const t of s.staves){const s=t.chords;if(s)for(const[,t]of s)e.has(t.uniqueId)||t.showDiagram&&(e.add(t.uniqueId),this.chordDiagrams.addChord(t))}}}}createEmptyStaffSystem(){const e=new Pn(this);for(let t=0;t<this.renderer.tracks.length;t++){const s=this.renderer.tracks[t];for(let i=0;i<s.staves.length;i++){const a=s.staves[i],r=rc.staveProfiles.get(this.renderer.settings.display.staveProfile);for(const i of r)i.canCreate(s,a)&&e.addStaff(s,new _n(t,a,i))}}return e}registerBarRenderer(e,t){if(this._barRendererLookup.has(e)||this._barRendererLookup.set(e,new Map),this._barRendererLookup.get(e).set(t.bar.id,t),t.additionalMultiRestBars)for(const s of t.additionalMultiRestBars)this._barRendererLookup.get(e).set(s.id,t)}unregisterBarRenderer(e,t){if(this._barRendererLookup.has(e)){const s=this._barRendererLookup.get(e);if(s.delete(t.bar.id),t.additionalMultiRestBars)for(const e of t.additionalMultiRestBars)s.delete(e.id)}}getRendererForBar(e,t){const s=t.id;return this._barRendererLookup.has(e)&&this._barRendererLookup.get(e).has(s)?this._barRendererLookup.get(e).get(s):null}layoutAndRenderBottomScoreInfo(e){e=Math.round(e);const t=new Za;t.x=0,t.y=e;let s=0;const i=this.renderer.settings.display.resources,a=[];let r=0;for(const[e,t]of En.FooterElements.value)if(this.footerGlyphs.has(e)){const t=this.footerGlyphs.get(e);t.y=s,this.alignScoreInfoGlyph(t),s+=1.2*t.font.size,a.push(t),r=Math.max(r,Math.round(t.x+t.width))}return s=Math.round(s),a.length>0&&(t.width=r,t.height=s,t.totalWidth=this.scaledWidth,t.totalHeight=e+t.height,this.registerPartial(t,(e=>{e.color=i.scoreInfoColor,e.textAlign=ne.Left,e.textBaseline=oe.Top;for(const t of a)t.paint(0,0,e)}))),e+s}alignScoreInfoGlyph(e){if(rc.getLayoutEngineFactory(this.renderer.settings.display.layoutMode).vertical)switch(e.textAlign){case ne.Left:e.x=this.pagePadding[0];break;case ne.Center:e.x=this.scaledWidth/2;break;case ne.Right:e.x=this.scaledWidth-this.pagePadding[2]}else e.x=this.firstBarX,e.textAlign=ne.Left}layoutAndRenderAnnotation(e){const t=this.renderer.settings.display.resources,s=na.withFamilyList(t.copyrightFont.families,12,Jt.Plain,Yt.Bold),i=new On(this.renderer,this.renderer.tracks[0].staves[0].bars[0]),a=new Sn(0,0,"rendered by alphaTab",s,ne.Center,void 0,t.mainGlyphColor);a.renderer=i,a.doLayout(),this.alignScoreInfoGlyph(a);const r=new Za;return r.width=a.x+a.width,r.x=0,r.height=12,r.y=e,r.totalWidth=this.scaledWidth,r.totalHeight=e+12,r.firstMasterBarIndex=-1,r.lastMasterBarIndex=-1,this.registerPartial(r,(e=>{e.color=t.mainGlyphColor,e.font=s,e.textAlign=ne.Left,e.textBaseline=oe.Top,a.paint(0,0,e)})),e+12}}En.HeaderElements=new Y((()=>new Map([[be.Title,E.ScoreTitle],[be.SubTitle,E.ScoreSubTitle],[be.Artist,E.ScoreArtist],[be.Album,E.ScoreAlbum],[be.Words,E.ScoreWords],[be.Music,E.ScoreMusic],[be.WordsAndMusic,E.ScoreWordsAndMusic],[be.Transcriber,void 0]]))),En.FooterElements=new Y((()=>new Map([[be.Copyright,E.ScoreCopyright],[be.CopyrightSecondLine,void 0]])));class Ln extends sn{constructor(){super(0,0),this._effectGlyphs=[],this._normalGlyphs=[],this.computedWidth=0}doLayout(){let e=0;if(this.glyphs)for(let t=0,s=this.glyphs.length;t<s;t++){const s=this.glyphs[t];s.x=e,s.renderer=this.renderer,s.doLayout(),e+=s.width}this.width=e,this.computedWidth=e}noteLoop(e){for(let t=this.container.beat.notes.length-1;t>=0;t--)e(this.container.beat.notes[t])}addEffect(e){super.addGlyph(e),this._effectGlyphs.push(e)}addNormal(e){super.addGlyph(e),this._normalGlyphs.push(e)}get effectElement(){}paint(e,t,s){this.paintEffects(e,t,s),this.paintNormal(e,t,s)}paintNormal(e,t,s){for(const i of this._normalGlyphs)i.paint(e+this.x,t+this.y,s)}paintEffects(e,t,s){const i=this.effectElement?rn.beat(s,this.effectElement,this.container.beat):void 0;try{for(const i of this._effectGlyphs)i.paint(e+this.x,t+this.y,s)}finally{i?.[Symbol.dispose]?.()}}}class Mn extends Ln{constructor(){super(...arguments),this.centerX=0}updateBeamingHelper(){}buildBoundingsLookup(e,t,s){}getNoteX(e,t){return 0}getNoteY(e,t){return 0}}class In extends kr{constructor(e,t,s,i=1){super(e,t),this._scale=0,this._symbols=[],this._symbols=In.getSymbols(s),this._scale=i}static getSymbols(e){const t=[];for(;e>0;){const s=e%10;t.unshift(In.getSymbol(s)),e=e/10|0}return t}static getSymbol(e){switch(e){case 0:return re.TimeSig0;case 1:return re.TimeSig1;case 2:return re.TimeSig2;case 3:return re.TimeSig3;case 4:return re.TimeSig4;case 5:return re.TimeSig5;case 6:return re.TimeSig6;case 7:return re.TimeSig7;case 8:return re.TimeSig8;case 9:return re.TimeSig9;default:return re.None}}doLayout(){let e=0;for(const t of this._symbols)e+=Nr.Widths.get(t);this.width=e}paint(e,t,s){s.fillMusicFontSymbols(e+this.x,t+this.y,this._scale,this._symbols)}}In.numberHeight=18;class An extends kr{constructor(){super(0,0),this._numberGlyph=[]}doLayout(){this.width=70,this.renderer.registerOverflowTop(this.renderer.getLineHeight(1));const e=this.renderer.additionalMultiRestBars.length+1;this._numberGlyph=In.getSymbols(e)}paint(e,t,s){s.fillMusicFontSymbols(e+this.x,t+this.y+this.renderer.height/2,1,[re.RestHBarLeft,re.RestHBarMiddle,re.RestHBarMiddle,re.RestHBarMiddle,re.RestHBarRight]);const i=this.renderer.getLineY(-1.5);s.fillMusicFontSymbols(e+this.x+An.BarWidth/2,t+this.y+i|0,1,this._numberGlyph,!0)}}An.BarWidth=60;class Rn extends Fr{constructor(e){super(Rn.getOrCreatePlaceholderBeat(e),e),this.preNotes=new Ln,this.onNotes=new Mn}doLayout(){this.renderer.showMultiBarRest&&this.onNotes.addNormal(new An),super.doLayout()}static getOrCreatePlaceholderBeat(e){if(e.voice.beats.length>1)return e.voice.beats[0];const t=new ze;return t.voice=e.voice,t}}!function(e){e[e.TopWithStem=0]="TopWithStem",e[e.Top=1]="Top",e[e.Center=2]="Center",e[e.Bottom=3]="Bottom",e[e.BottomWithStem=4]="BottomWithStem"}(is||(is={})),function(e){e[e.Left=0]="Left",e[e.Center=1]="Center",e[e.Right=2]="Right"}(as||(as={}));class On{get nextRenderer(){return this.bar&&this.bar.nextBar?this.scoreRenderer.layout.getRendererForBar(this.staff.staffId,this.bar.nextBar):null}get previousRenderer(){return this.bar&&this.bar.previousBar?this.scoreRenderer.layout.getRendererForBar(this.staff.staffId,this.bar.previousBar):null}get lastBar(){return this.additionalMultiRestBars?this.additionalMultiRestBars[this.additionalMultiRestBars.length-1]:this.bar}get showMultiBarRest(){return!1}constructor(e,t){this._preBeatGlyphs=new an,this._voiceContainers=new Map,this._postBeatGlyphs=new an,this._ties=[],this.additionalMultiRestBars=null,this.x=0,this.y=0,this.width=0,this.computedWidth=0,this.height=0,this.index=0,this.topOverflow=0,this.bottomOverflow=0,this.isLinkedToPrevious=!1,this.canWrap=!0,this.wasFirstOfLine=!1,this._appliedLayoutingInfo=0,this.isFinalized=!1,this.topPadding=0,this.bottomPadding=0,this.scoreRenderer=e,this.bar=t,t&&(this.helpers=new gn(this))}registerTies(e){this._ties.push(...e)}get middleYPosition(){return 0}registerOverflowTop(e){return e>this.topOverflow&&(this.topOverflow=e,!0)}registerOverflowBottom(e){return e>this.bottomOverflow&&(this.bottomOverflow=e,!0)}scaleToWidth(e){const t=e-this._preBeatGlyphs.width-this._postBeatGlyphs.width;for(const e of this._voiceContainers.values())e.scaleToWidth(t);this._postBeatGlyphs.x=this._preBeatGlyphs.x+this._preBeatGlyphs.width+t,this.width=e}get resources(){return this.settings.display.resources}get settings(){return this.scoreRenderer.settings}get barDisplayScale(){return this.staff.system.staves.length>1?this.bar.masterBar.displayScale:this.bar.displayScale}get barDisplayWidth(){return this.staff.system.staves.length>1?this.bar.masterBar.displayWidth:this.bar.displayWidth}get isFirstOfLine(){return 0===this.index}get isLast(){return!this.bar||this.bar.index===this.scoreRenderer.layout.lastBarIndex}registerLayoutingInfo(){const e=this.layoutingInfo,t=this._preBeatGlyphs.width;e.preBeatSize<t&&(e.preBeatSize=t);for(const t of this._voiceContainers.values())t.registerLayoutingInfo(e),t.x,t.width;const s=this._postBeatGlyphs.width;e.postBeatSize<s&&(e.postBeatSize=s)}applyLayoutingInfo(){if(this._appliedLayoutingInfo>=this.layoutingInfo.version)return!1;this._appliedLayoutingInfo=this.layoutingInfo.version,this._preBeatGlyphs.width=this.layoutingInfo.preBeatSize;let e=this._preBeatGlyphs.x+this._preBeatGlyphs.width;for(const t of this._voiceContainers.values()){t.x=this._preBeatGlyphs.x+this._preBeatGlyphs.width,t.applyLayoutingInfo(this.layoutingInfo);const s=t.x+t.width;e<s&&(e=s)}this._postBeatGlyphs.x=Math.floor(e),this._postBeatGlyphs.width=this.layoutingInfo.postBeatSize,this.width=Math.ceil(this._postBeatGlyphs.x+this._postBeatGlyphs.width),this.computedWidth=this.width;const t=this.barDisplayWidth;return t>0&&this.scoreRenderer.layout.systemsLayoutMode===ss.FromModelWithWidths&&(this.width=t,this.computedWidth=t),!0}finalizeRenderer(){this.isFinalized=!0;let e=!1;const t=this.y-this.staff.topSpacing,s=this.y+this.height+this.staff.bottomSpacing;for(const i of this._ties)if(i.doLayout(),i.height>0){const a=i.y+i.height-s;a>0&&this.registerOverflowBottom(a)&&(e=!0);const r=i.y-t;r<0&&this.registerOverflowTop(-1*r)&&(e=!0)}return e}doLayout(){if(this.bar){this.helpers.initialize(),this._ties=[],this._preBeatGlyphs=new an,this._preBeatGlyphs.renderer=this,this._voiceContainers.clear(),this._postBeatGlyphs=new an,this._postBeatGlyphs.renderer=this;for(let e=0;e<this.bar.voices.length;e++){const t=this.bar.voices[e];if(this.hasVoiceContainer(t)){const s=new on(0,0,t);s.renderer=this,this._voiceContainers.set(this.bar.voices[e].index,s)}}if(this.bar.simileMark===h.SecondOfDouble&&(this.canWrap=!1),this.createPreBeatGlyphs(),this.additionalMultiRestBars){const e=new Rn(this.getVoiceContainer(this.bar.voices[0]));this.addBeatGlyph(e)}else this.createBeatGlyphs();this.createPostBeatGlyphs(),this.updateSizes();for(const e of this.helpers.beamHelpers)for(const t of e)t.finish();this.computedWidth=this.width}}hasVoiceContainer(e){return!(!this.additionalMultiRestBars&&0!==e.index)||!e.isEmpty}updateSizes(){this.staff.registerStaffTop(this.topPadding),this.staff.registerStaffBottom(this.height-this.bottomPadding);const e=this._voiceContainers,t=this.beatGlyphsStart;let s=t;for(const i of e.values()){i.x=t,i.doLayout();const e=i.x+i.width;s<e&&(s=e)}this._postBeatGlyphs.x=Math.floor(s),this.width=Math.ceil(this._postBeatGlyphs.x+this._postBeatGlyphs.width),this.height+=this.layoutingInfo.height}addPreBeatGlyph(e){e.renderer=this,this._preBeatGlyphs.addGlyph(e)}addBeatGlyph(e){e.renderer=this,e.preNotes.renderer=this,e.onNotes.renderer=this,e.onNotes.beamingHelper=this.helpers.beamHelperLookup[e.beat.voice.index].get(e.beat.index),this.getVoiceContainer(e.beat.voice).addGlyph(e)}getVoiceContainer(e){return this._voiceContainers.has(e.index)?this._voiceContainers.get(e.index):void 0}getBeatContainer(e){return this.getVoiceContainer(e.voice)?.beatGlyphs?.[e.index]}getPreNotesGlyphForBeat(e){return this.getBeatContainer(e)?.preNotes}getOnNotesGlyphForBeat(e){return this.getBeatContainer(e)?.onNotes}paint(e,t,s){this.paintBackground(e,t,s),s.color=this.resources.mainGlyphColor,this._preBeatGlyphs.paint(e+this.x,t+this.y,s);for(const i of this._voiceContainers.values())i.paint(e+this.x,t+this.y,s);s.color=this.resources.mainGlyphColor,this._postBeatGlyphs.paint(e+this.x,t+this.y,s)}paintBackground(e,t,s){this.layoutingInfo.paint(e+this.x+this._preBeatGlyphs.x+this._preBeatGlyphs.width,t+this.y+this.height,s)}buildBoundingsLookup(e,t,s){const i=new er;i.bar=this.bar,i.visualBounds=new mt,i.visualBounds.x=t+this.x,i.visualBounds.y=s+this.y+this.topPadding,i.visualBounds.w=this.width,i.visualBounds.h=this.height-this.topPadding-this.bottomPadding,i.realBounds=new mt,i.realBounds.x=t+this.x,i.realBounds.y=s+this.y,i.realBounds.w=this.width,i.realBounds.h=this.height,e.addBar(i);for(const[e,a]of this._voiceContainers){const r=this.bar.isEmpty&&0===e;if(!a.voice.isEmpty||r)for(let e=0,n=a.beatGlyphs.length;e<n;e++){a.beatGlyphs[e].buildBoundingsLookup(i,t+this.x+a.x,s+this.y+a.y,r)}}}addPostBeatGlyph(e){this._postBeatGlyphs.addGlyph(e)}createPreBeatGlyphs(){this.wasFirstOfLine=this.isFirstOfLine}createBeatGlyphs(){for(const e of this.bar.voices)this.hasVoiceContainer(e)&&this.createVoiceGlyphs(e)}createVoiceGlyphs(e){}createPostBeatGlyphs(){}get beatGlyphsStart(){return this._preBeatGlyphs.x+this._preBeatGlyphs.width}get postBeatGlyphsStart(){return this._postBeatGlyphs.x}getBeatX(e,t=ts.PreNotes){const s=this.getBeatContainer(e);if(s)switch(t){case ts.PreNotes:return s.voiceContainer.x+s.x;case ts.OnNotes:return s.voiceContainer.x+s.x+s.onNotes.x;case ts.MiddleNotes:return s.voiceContainer.x+s.x+s.onTimeX;case ts.Stem:const t=s.onNotes.beamingHelper?s.onNotes.beamingHelper.getBeatLineX(e):s.onNotes.x+s.onNotes.width/2;return s.voiceContainer.x+t;case ts.PostNotes:return s.voiceContainer.x+s.x+s.onNotes.x+s.onNotes.width;case ts.EndBeat:return s.voiceContainer.x+s.x+s.width}return 0}getRatioPositionX(e){const t=this.bar.isEmpty?this.beatGlyphsStart:this.getBeatX(this.bar.voices[0].beats[0],ts.OnNotes);return t+(this.postBeatGlyphsStart-t)*e}getNoteX(e,t){const s=this.getBeatContainer(e.beat);return s?s.voiceContainer.x+s.x+s.onNotes.x+s.onNotes.getNoteX(e,t):0}getNoteY(e,t){const s=this.getOnNotesGlyphForBeat(e.beat);return s?s.getNoteY(e,t):Number.NaN}reLayout(){(this.wasFirstOfLine&&!this.isFirstOfLine||!this.wasFirstOfLine&&this.isFirstOfLine)&&this.recreatePreBeatGlyphs(),this.updateSizes(),this.registerLayoutingInfo()}recreatePreBeatGlyphs(){this._preBeatGlyphs=new an,this._preBeatGlyphs.renderer=this,this.createPreBeatGlyphs()}paintSimileMark(e,t,s){const i=rn.voice(s,I.Glyphs,this.bar.voices[0],!0);try{switch(this.bar.simileMark){case h.Simple:s.beginGroup(Fr.getGroupId(this.bar.voices[0].beats[0])),s.fillMusicFontSymbol(e+this.x+(this.width-20)/2,t+this.y+this.height/2,1,re.Repeat1Bar,!1),s.endGroup();break;case h.SecondOfDouble:s.beginGroup(Fr.getGroupId(this.bar.voices[0].beats[0])),s.beginGroup(Fr.getGroupId(this.bar.previousBar.voices[0].beats[0])),s.fillMusicFontSymbol(e+this.x-14,t+this.y+this.height/2,1,re.Repeat2Bars,!1),s.endGroup(),s.endGroup()}}finally{i?.[Symbol.dispose]?.()}}completeBeamingHelper(e){}getBeatDirection(e){return this.helpers.getBeamingHelperForBeat(e).direction}}On.RawLineSpacing=8,On.StemWidth=.12*On.RawLineSpacing,On.StaffLineThickness=.13*On.RawLineSpacing,On.BeamThickness=.5*On.RawLineSpacing,On.BeamSpacing=.25*On.RawLineSpacing,function(e){e[e.SinglePreBeat=0]="SinglePreBeat",e[e.SingleOnBeat=1]="SingleOnBeat",e[e.SingleOnBeatToEnd=2]="SingleOnBeatToEnd",e[e.GroupedOnBeat=3]="GroupedOnBeat",e[e.GroupedOnBeatToEnd=4]="GroupedOnBeatToEnd",e[e.FullBar=5]="FullBar"}(rs||(rs={}));class Hn extends kr{constructor(e,t){super(0,0),this._uniqueEffectGlyphs=[],this._effectGlyphs=[],this.isEmpty=!0,this.previousBand=null,this.isLinkedToPrevious=!1,this.firstBeat=null,this.lastBeat=null,this.height=0,this.originalHeight=0,this.slot=null,this.voice=e,this.info=t}doLayout(){super.doLayout();for(let e=0;e<this.renderer.bar.voices.length;e++)this._effectGlyphs.push(new Map),this._uniqueEffectGlyphs.push([])}createGlyph(e){if(e.voice===this.voice&&this.info.shouldCreateGlyph(this.renderer.settings,e)&&(!this.info.hideOnMultiTrack||0===this.renderer.staff.trackIndex)){if(this.isEmpty=!1,this.firstBeat&&!e.isBefore(this.firstBeat)||(this.firstBeat=e),!this.lastBeat||e.isAfter(this.lastBeat))switch(this.lastBeat=e,this.info.sizingMode){case rs.SingleOnBeatToEnd:case rs.GroupedOnBeatToEnd:this.lastBeat.nextBeat&&(this.lastBeat=this.lastBeat.nextBeat)}const t=this.createOrResizeGlyph(this.info.sizingMode,e);t.height>this.height&&(this.height=t.height,this.originalHeight=t.height)}}resetHeight(){this.height=this.originalHeight}createOrResizeGlyph(e,t){let s;switch(e){case rs.FullBar:case rs.SinglePreBeat:case rs.SingleOnBeat:case rs.SingleOnBeatToEnd:return s=this.info.createNewGlyph(this.renderer,t),s.renderer=this.renderer,s.beat=t,s.doLayout(),this._effectGlyphs[t.voice.index].set(t.index,s),this._uniqueEffectGlyphs[t.voice.index].push(s),s;case rs.GroupedOnBeat:case rs.GroupedOnBeatToEnd:const i=e===rs.GroupedOnBeat?rs.SingleOnBeat:rs.SingleOnBeatToEnd;if(t.index>0||this.renderer.index>0){const e=t.previousBeat;if(this.info.shouldCreateGlyph(this.renderer.settings,e)){let s=null;if(t.index>0&&this._effectGlyphs[t.voice.index].has(e.index))s=this._effectGlyphs[t.voice.index].get(e.index);else if(this.renderer.index>0){const t=this.renderer.previousRenderer.getBand(e.voice,this.info.effectId);if(t){const i=t._effectGlyphs[e.voice.index];i.has(e.index)&&(s=i.get(e.index))}}const a=this.createOrResizeGlyph(i,t);return s&&this.info.canExpand(e,t)&&(s.nextGlyph=a,a.previousGlyph=s,this.isLinkedToPrevious=!0),a}return this.createOrResizeGlyph(i,t)}return this.createOrResizeGlyph(i,t);default:return this.createOrResizeGlyph(rs.SingleOnBeat,t)}}paint(e,t,s){super.paint(e,t,s);for(let i=0,a=this._uniqueEffectGlyphs.length;i<a;i++){const a=this._uniqueEffectGlyphs[i];for(let i=0,r=a.length;i<r;i++){const r=a[i],n=rn.beat(s,ye.Effects,r.beat,!1);try{r.paint(e+this.x,t+this.y,s)}finally{n?.[Symbol.dispose]?.()}}}}alignGlyphs(){for(let e=0;e<this._effectGlyphs.length;e++)for(const t of this._effectGlyphs[e].keys())this.alignGlyph(this.info.sizingMode,this.renderer.bar.voices[e].beats[t])}alignGlyph(e,t){const s=this._effectGlyphs[t.voice.index].get(t.index),i=this.renderer.getBeatContainer(t);switch(e){case rs.SinglePreBeat:const e=this.renderer.layoutingInfo.getPreBeatSize(t);s.x=this.renderer.beatGlyphsStart+i.x-e;break;case rs.SingleOnBeat:case rs.GroupedOnBeat:s.x=this.renderer.beatGlyphsStart+i.x;break;case rs.SingleOnBeatToEnd:case rs.GroupedOnBeatToEnd:if(s.x=this.renderer.beatGlyphsStart+i.x,i.beat.isLastOfVoice)s.width=this.renderer.width-s.x;else{const e=this.renderer.layoutingInfo.getPostBeatSize(t);s.width=e}break;case rs.FullBar:s.width=this.renderer.width}}}class Wn{constructor(){this.uniqueEffectId=null,this.y=0,this.height=0,this.firstBeat=null,this.lastBeat=null}}class Vn{constructor(){this.bands=[],this.shared=new Wn}update(e){e.info.canShareBand||(this.shared.uniqueEffectId=e.info.effectId),e.slot=this,this.bands.push(e),e.height>this.shared.height&&(this.shared.height=e.height),this.shared.firstBeat&&!e.firstBeat.isBefore(this.shared.firstBeat)||(this.shared.firstBeat=e.firstBeat),this.shared.lastBeat&&!e.lastBeat.isAfter(this.shared.lastBeat)||(this.shared.lastBeat=e.lastBeat)}canBeUsed(e){return(!this.shared.uniqueEffectId&&e.info.canShareBand||e.info.effectId===this.shared.uniqueEffectId)&&(!this.shared.firstBeat||this.shared.lastBeat.isBefore(e.firstBeat)||this.shared.lastBeat.isBefore(this.shared.firstBeat))}}class Gn{constructor(){this.slots=[],this._effectSlot=new Map}getOrCreateSlot(e){if(this._effectSlot.has(e.info.effectId)){const t=this._effectSlot.get(e.info.effectId);if(t.canBeUsed(e))return t}for(const t of this.slots)if(t.canBeUsed(e))return t;const t=new Vn;return this.slots.push(t),t}register(e){const t=this.getOrCreateSlot(e);t.update(e),this._effectSlot.set(e.info.effectId,t)}}class zn extends On{constructor(e,t,s){super(e,t),this._bands=[],this._bandLookup=new Map,this.sizingInfo=null,this._infos=s}updateSizes(){this.topOverflow=0,this.bottomOverflow=0,this.topPadding=0,this.bottomPadding=0,this.updateHeight(),super.updateSizes()}finalizeRenderer(){let e=super.finalizeRenderer();return this.updateHeight()&&(e=!0),e}updateHeight(){if(!this.sizingInfo)return!1;let e=0;for(const t of this.sizingInfo.slots){t.shared.y=e;for(const s of t.bands)s.y=e,s.height=t.shared.height;e+=t.shared.height}return e!==this.height&&(this.height=e,!0)}applyLayoutingInfo(){const e=!super.applyLayoutingInfo();if(this.index>0){const e=this.previousRenderer;this.sizingInfo=e.sizingInfo}else this.sizingInfo=new Gn;for(const e of this._bands)e.resetHeight(),e.alignGlyphs(),e.isEmpty||this.sizingInfo.register(e);return this.updateHeight(),e}scaleToWidth(e){super.scaleToWidth(e);for(const e of this._bands)e.alignGlyphs()}createBeatGlyphs(){this._bands=[],this._bandLookup=new Map;for(const e of this.bar.voices)if(this.hasVoiceContainer(e))for(const t of this._infos){const s=new Hn(e,t);s.renderer=this,s.doLayout(),this._bands.push(s),this._bandLookup.set(`${e.index}.${t.effectId}`,s)}super.createBeatGlyphs();for(const e of this._bands)e.isLinkedToPrevious&&(this.isLinkedToPrevious=!0)}createVoiceGlyphs(e){for(const t of e.beats){const s=new Fr(t,this.getVoiceContainer(e));s.preNotes=new Ln,s.onNotes=new Mn,this.addBeatGlyph(s);for(const e of this._bands)e.createGlyph(t)}}paint(e,t,s){this.paintBackground(e,t,s);for(const i of this._bands)s.color=0===i.voice.index?this.resources.mainGlyphColor:this.resources.secondaryGlyphColor,i.isEmpty||i.paint(e+this.x,t+this.y,s)}getBand(e,t){const s=`${e.index}.${t}`;return this._bandLookup.has(s)?this._bandLookup.get(s):null}}class Un extends tn{get staffId(){return this._staffId}getStaffPaddingTop(e){return e.system.layout.renderer.settings.display.effectStaffPaddingTop}getStaffPaddingBottom(e){return e.system.layout.renderer.settings.display.effectStaffPaddingBottom}constructor(e,t,s=null){super(),this.infos=t,this._staffId=e,this.isInsideBracket=!1,this.isRelevantForBoundsLookup=!1,this.shouldShow=s}canCreate(e,t){const s=this.shouldShow;return super.canCreate(e,t)&&(!s||s(e,t))}create(e,t){return new zn(e,t,this.infos.filter((t=>e.settings.notation.isNotationElementVisible(t.notationElement))))}}class Xn extends Tr{constructor(e,t,s,i,a){super(e,t),this._endingsString="",this._endings=ie.getAlternateEndingsList(s),this._openLine=i,this._closeLine=a}doLayout(){super.doLayout(),this.height=this.renderer.resources.wordsFont.size+(Xn.Padding+2);let e="";for(let t=0,s=this._endings.length;t<s;t++)e+=this._endings[t]+1,e+=". ";this._endingsString=e}paint(e,t,s){const i=this._closeLine?this.width-4:this.width;if(e=.5+(0|e),t=.5+(0|t),this._openLine?(s.moveTo(e+this.x,t+this.y+this.height),s.lineTo(e+this.x,t+this.y)):s.moveTo(e+this.x,t+this.y),s.lineTo(e+this.x+i,t+this.y),this._closeLine&&s.lineTo(e+this.x+i,t+this.y+this.height),s.stroke(),this._openLine){const i=s.textBaseline;s.textBaseline=oe.Top;const a=this.renderer.resources;s.font=a.wordsFont,s.fillText(this._endingsString,e+this.x+Xn.Padding,t+this.y),s.textBaseline=i}}}Xn.Padding=3;class Jn{get effectId(){return this.notationElement.toString()}}class Yn extends Jn{get notationElement(){return E.EffectAlternateEndings}get hideOnMultiTrack(){return!0}get canShareBand(){return!1}get sizingMode(){return rs.FullBar}shouldCreateGlyph(e,t){return 0===t.voice.index&&0===t.index&&0!==t.voice.bar.masterBar.alternateEndings}createNewGlyph(e,t){const s=t.voice.bar.masterBar,i=null===s.previousMasterBar||s.alternateEndings!==s.previousMasterBar.alternateEndings;let a=s.isRepeatEnd||null===s.nextMasterBar||s.alternateEndings!==s.nextMasterBar.alternateEndings;return s.repeatGroup.closings.some((e=>e.index>=s.index))||(a=!1),new Xn(0,0,s.alternateEndings,i,a)}canExpand(e,t){return!0}}class $n extends Jn{get notationElement(){return E.EffectCapo}get hideOnMultiTrack(){return!1}get canShareBand(){return!1}get sizingMode(){return rs.SingleOnBeat}shouldCreateGlyph(e,t){return 0===t.index&&0===t.voice.bar.index&&0!==t.voice.bar.staff.capo}createNewGlyph(e,t){return new Sn(0,0,`Capo. fret ${t.voice.bar.staff.capo}`,e.resources.effectFont,ne.Left)}canExpand(e,t){return!1}}class qn extends Jn{get notationElement(){return E.EffectChordNames}get hideOnMultiTrack(){return!1}get canShareBand(){return!0}get sizingMode(){return rs.SingleOnBeat}shouldCreateGlyph(e,t){return t.hasChord}createNewGlyph(e,t){return new Sn(0,0,t.chord.name,e.resources.effectFont,ne.Center)}canExpand(e,t){return!1}}class jn extends Tr{constructor(e){super(),this.forceGroupedRendering=!1,this.endOnBarLine=!1,this.endPosition=e}get isLinkedWithPrevious(){return!!this.previousGlyph&&this.previousGlyph.renderer.staff.system===this.renderer.staff.system}get isLinkedWithNext(){return!!this.nextGlyph&&this.nextGlyph.renderer.isFinalized&&this.nextGlyph.renderer.staff.system===this.renderer.staff.system}paint(e,t,s){if(this.isLinkedWithPrevious)return;if(!this.isLinkedWithNext&&!this.forceGroupedRendering)return void this.paintNonGrouped(e,t,s);let i;if(!this.isLinkedWithNext&&this.forceGroupedRendering)i=this;else for(i=this.nextGlyph;i.isLinkedWithNext;)i=i.nextGlyph;const a=i.renderer,r=i.beat,n=this.endPosition,o=e-this.renderer.x,h=this.calculateEndX(a,r,o,n);this.paintGrouped(e,t,h,s)}calculateEndX(e,t,s,i){return t?s+e.x+e.getBeatX(t,i):s+e.x+this.x+this.width}paintNonGrouped(e,t,s){const i=e-this.renderer.x,a=this.calculateEndX(this.renderer,this.beat,i,this.endPosition);this.paintGrouped(e,t,a,s)}}class Kn extends jn{constructor(e,t,s){super(ts.EndBeat),this._crescendo=S.None,this._crescendo=s,this.x=e,this.y=t}doLayout(){super.doLayout(),this.height=17}paintGrouped(e,t,s,i){const a=e+this.x,r=this.height,n=Nr.Widths.get(re.NoteheadBlack)/2;i.beginPath(),this._crescendo===S.Crescendo?(s-=n,i.moveTo(s,t+this.y),i.lineTo(a,t+this.y+r/2),i.lineTo(s,t+this.y+r)):(s-=n,i.moveTo(a,t+this.y),i.lineTo(s,t+this.y+r/2),i.lineTo(a,t+this.y+r)),i.stroke()}}class Qn extends Jn{get notationElement(){return E.EffectCrescendo}get hideOnMultiTrack(){return!1}get canShareBand(){return!0}get sizingMode(){return rs.GroupedOnBeatToEnd}shouldCreateGlyph(e,t){return t.crescendo!==S.None}createNewGlyph(e,t){return new Kn(0,0,t.crescendo)}canExpand(e,t){return e.crescendo===t.crescendo}}class Zn extends xr{constructor(e,t,s){super(e,t,.6,Zn.getSymbol(s)),this.center=!0}doLayout(){super.doLayout(),this.y+=this.height/2}static getSymbol(e){switch(e){case g.PPP:return re.DynamicPPP;case g.PP:return re.DynamicPP;case g.P:return re.DynamicPiano;case g.MP:return re.DynamicMP;case g.MF:return re.DynamicMF;case g.F:return re.DynamicForte;case g.FF:return re.DynamicFF;case g.FFF:return re.DynamicFFF;case g.PPPP:return re.DynamicPPPP;case g.PPPPP:case g.PPPPPP:return re.DynamicPPPPP;case g.FFFF:return re.DynamicFFFF;case g.FFFFF:return re.DynamicFFFFF;case g.FFFFFF:return re.DynamicFFFFFF;case g.SF:return re.DynamicSforzando1;case g.SFP:return re.DynamicSforzandoPiano;case g.SFPP:return re.DynamicSforzandoPianissimo;case g.FP:return re.DynamicFortePiano;case g.RF:return re.DynamicRinforzando1;case g.RFZ:return re.DynamicRinforzando2;case g.SFZ:return re.DynamicSforzato;case g.SFFZ:return re.DynamicSforzatoFF;case g.FZ:return re.DynamicForzando;case g.N:return re.DynamicNiente;case g.PF:return re.DynamicPF;case g.SFZP:return re.DynamicSforzatoPiano;default:return re.None}}}class eo extends Jn{get notationElement(){return E.EffectDynamics}get hideOnMultiTrack(){return!1}get canShareBand(){return!1}get sizingMode(){return rs.SingleOnBeat}shouldCreateGlyph(e,t){return this.internalShouldCreateGlyph(t)}internalShouldCreateGlyph(e){if(e.voice.bar.staff.track.score.stylesheet.hideDynamics||e.isEmpty||e.voice.isEmpty||e.isRest)return!1;const t=this.getPreviousDynamicsBeat(e);let s=0===e.voice.index&&!t||e.dynamics!==t?.dynamics;if(s&&e.voice.index>0)for(const t of e.voice.bar.voices)if(t.index<e.voice.index){const i=t.getBeatAtPlaybackStart(e.playbackStart);i&&e.dynamics===i.dynamics&&this.internalShouldCreateGlyph(i)&&(s=!1)}return s}getPreviousDynamicsBeat(e){let t=e.previousBeat;for(;null!=t;){if(!t.isRest)return t;t=t.previousBeat}return null}createNewGlyph(e,t){return new Zn(0,0,t.dynamics)}canExpand(e,t){return!0}}class to extends xr{constructor(e){super(0,0,1,to.getSymbol(e)),this.center=!0}static getSymbol(e){switch(e){case ue.FadeIn:return re.GuitarFadeIn;case ue.FadeOut:return re.GuitarFadeOut;case ue.VolumeSwell:return re.GuitarVolumeSwell}return re.None}paint(e,t,s){super.paint(e,t+this.height,s)}}class so extends Jn{get notationElement(){return E.EffectFadeIn}get hideOnMultiTrack(){return!1}get canShareBand(){return!0}get sizingMode(){return rs.SingleOnBeat}shouldCreateGlyph(e,t){return t.fade!==ue.None}createNewGlyph(e,t){return new to(t.fade)}canExpand(e,t){return!0}}class io extends xr{constructor(e,t,s){super(e,t,1,io.getSymbol(s))}static getSymbol(e){switch(e){case ke.Short:return re.FermataShortAbove;case ke.Medium:return re.FermataAbove;case ke.Long:return re.FermataLongAbove;default:return re.None}}paint(e,t,s){super.paint(e-this.width/2,t+this.height,s)}}class ao extends Jn{get notationElement(){return E.EffectFermata}get hideOnMultiTrack(){return!1}get canShareBand(){return!1}get sizingMode(){return rs.SingleOnBeat}shouldCreateGlyph(e,t){return 0===t.voice.index&&!!t.fermata}createNewGlyph(e,t){return new io(0,0,t.fermata.type)}canExpand(e,t){return!0}}class ro extends Jn{get notationElement(){return E.EffectFingering}get hideOnMultiTrack(){return!1}get canShareBand(){return!0}get sizingMode(){return rs.SingleOnBeat}shouldCreateGlyph(e,t){return!(0!==t.voice.index||t.isRest||e.notation.fingeringMode!==C.SingleNoteEffectBand&&e.notation.fingeringMode!==C.SingleNoteEffectBandForcePiano)&&(1===t.notes.length&&t.notes[0].isFingering)}createNewGlyph(e,t){let s=k.Unknown,i=!1;const a=t.notes[0];a.leftHandFinger!==k.Unknown?(s=a.leftHandFinger,i=!0):a.rightHandFinger!==k.Unknown&&(s=a.rightHandFinger);const r=ie.fingerToString(e.settings,t,s,i)??"";return new Sn(0,0,r,e.resources.fingeringFont,ne.Left)}canExpand(e,t){return!0}}class no extends Jn{constructor(){super(...arguments),this.lastCreateInfo=null}shouldCreateGlyph(e,t){this.lastCreateInfo=[];for(let e=0,s=t.notes.length;e<s;e++){const s=t.notes[e];this.shouldCreateGlyphForNote(s)&&this.lastCreateInfo.push(s)}return this.lastCreateInfo.length>0}get hideOnMultiTrack(){return!1}get canShareBand(){return!0}canExpand(e,t){return!0}}class oo extends jn{constructor(e,t=!0){super(ts.OnNotes),this._label=e,this._dashed=t}doLayout(){this.renderer.settings.notation.extendLineEffectsToBeatEnd&&(this.endPosition=ts.EndBeat,this.forceGroupedRendering=!0),super.doLayout(),this.height=this.renderer.resources.effectFont.size}paintNonGrouped(e,t,s){const i=this.renderer.resources;s.font=i.effectFont;const a=s.textAlign;s.textAlign=ne.Center,s.fillText(this._label,e+this.x,t+this.y),s.textAlign=a}paintGrouped(e,t,s,i){this.paintNonGrouped(e,t,i);const a=i.measureText(this._label).width,r=e+this.x+a/2+3,n=t+this.y+4;if(this._dashed){if(s>r){let e=r;for(;e<s;)i.beginPath(),i.moveTo(e,0|n),i.lineTo(Math.min(e+8,s),0|n),e+=11,i.stroke();i.beginPath(),i.moveTo(s,n-5|0),i.lineTo(s,n+5|0),i.stroke()}}else i.beginPath(),i.moveTo(r,0|n),i.lineTo(s,0|n),i.lineTo(s,n+5|0),i.stroke()}}oo.LineSpacing=3,oo.LineTopPadding=4,oo.LineTopOffset=5,oo.LineSize=8;class ho extends no{get effectId(){return this._effectId}get notationElement(){return E.EffectHarmonics}constructor(e){switch(super(),this._beat=null,this._harmonicType=e,e){case T.None:this._effectId="harmonics-none";break;case T.Natural:this._effectId="harmonics-natural";break;case T.Artificial:this._effectId="harmonics-artificial";break;case T.Pinch:this._effectId="harmonics-pinch";break;case T.Tap:this._effectId="harmonics-tap";break;case T.Semi:this._effectId="harmonics-semi";break;case T.Feedback:this._effectId="harmonics-feedback";break;default:this._effectId=""}}shouldCreateGlyphForNote(e){return!(!e.isHarmonic||e.harmonicType!==this._harmonicType)&&(e.beat!==this._beat&&(this._beat=e.beat),!0)}get sizingMode(){return rs.GroupedOnBeat}createNewGlyph(e,t){return new oo(ho.harmonicToString(this._harmonicType))}static harmonicToString(e){switch(e){case T.Natural:return"N.H.";case T.Artificial:return"A.H.";case T.Pinch:return"P.H.";case T.Tap:return"T.H.";case T.Semi:return"S.H.";case T.Feedback:return"Fdbk."}return""}}class lo extends Jn{get notationElement(){return E.EffectLetRing}get canShareBand(){return!1}get hideOnMultiTrack(){return!1}shouldCreateGlyph(e,t){return t.isLetRing}get sizingMode(){return rs.GroupedOnBeat}createNewGlyph(e,t){return new oo("LetRing")}canExpand(e,t){return!0}}class co extends Tr{constructor(e,t,s,i,a=ne.Center){super(e,t),this._lines=s,this.font=i,this.textAlign=a}doLayout(){super.doLayout(),this.height=this.font.size*this._lines.length}paint(e,t,s){s.font=this.font;const i=s.textAlign;s.textAlign=this.textAlign;for(let i=0;i<this._lines.length;i++)this._lines[i]&&s.fillText(this._lines[i],e+this.x,t+this.y+i*this.font.size);s.textAlign=i}}class uo extends Jn{get notationElement(){return E.EffectLyrics}get hideOnMultiTrack(){return!1}get canShareBand(){return!1}get sizingMode(){return rs.SingleOnBeat}shouldCreateGlyph(e,t){return!!t.lyrics}createNewGlyph(e,t){return new co(0,0,t.lyrics,e.resources.effectFont,ne.Center)}canExpand(e,t){return!0}}class po extends Jn{get notationElement(){return E.EffectMarker}get hideOnMultiTrack(){return!0}get canShareBand(){return!0}get sizingMode(){return rs.SinglePreBeat}shouldCreateGlyph(e,t){return 0===t.voice.bar.staff.index&&0===t.voice.index&&0===t.index&&t.voice.bar.masterBar.isSectionStart}createNewGlyph(e,t){return new Sn(0,0,t.voice.bar.masterBar.section.marker?`[${t.voice.bar.masterBar.section.marker}] ${t.voice.bar.masterBar.section.text}`:t.voice.bar.masterBar.section.text,e.resources.markerFont,ne.Left)}canExpand(e,t){return!0}}class go extends jn{constructor(e,t){super(ts.PostNotes),this._ottava=e,this._aboveStaff=t}doLayout(){super.doLayout(),this.height=Nr.Heights.get(re.QuindicesimaAlta)}paintNonGrouped(e,t,s){this.paintOttava(e,t,s)}paintOttava(e,t,s){let i=0;switch(this._ottava){case o._15ma:i=.8*Nr.Widths.get(re.QuindicesimaAlta),s.fillMusicFontSymbol(e+this.x-i/2,t+this.y+this.height,.8,re.QuindicesimaAlta,!1);break;case o._8va:i=.8*Nr.Widths.get(re.OttavaAlta),s.fillMusicFontSymbol(e+this.x-i/2,t+this.y+this.height,.8,re.OttavaAlta,!1);break;case o._8vb:i=.8*Nr.Widths.get(re.OttavaBassaVb),s.fillMusicFontSymbol(e+this.x-i/2,t+this.y+this.height,.8,re.OttavaBassaVb,!1);break;case o._15mb:i=.8*(Nr.Widths.get(re.Quindicesima)+Nr.Widths.get(re.OctaveBaselineM)+Nr.Widths.get(re.OctaveBaselineB)),s.fillMusicFontSymbols(e+this.x-i/2,t+this.y+this.height,.8,[re.Quindicesima,re.OctaveBaselineM,re.OctaveBaselineB],!1)}return i/2}paintGrouped(e,t,s,i){const a=this.paintOttava(e,t,i),r=e+this.x+a+3;let n=t+this.y;n+=this._aboveStaff?2:this.height-2;if(s>r){let e=r;for(;e<s;)i.beginPath(),i.moveTo(e,0|n),i.lineTo(Math.min(e+8,s),0|n),e+=11,i.stroke();i.beginPath(),this._aboveStaff?(i.moveTo(s,n),i.lineTo(s,t+this.y+this.height)):(i.moveTo(s,n),i.lineTo(s,t+this.y)),i.stroke()}}}class mo extends Jn{get effectId(){return"ottavia-"+(this._aboveStaff?"above":"below")}get notationElement(){return E.EffectOttavia}get hideOnMultiTrack(){return!1}get canShareBand(){return!0}get sizingMode(){return rs.GroupedOnBeat}constructor(e){super(),this._aboveStaff=e}shouldCreateGlyph(e,t){switch(t.ottava){case o._15ma:case o._8va:return this._aboveStaff;case o._8vb:case o._15mb:return!this._aboveStaff}return!1}createNewGlyph(e,t){return new go(t.ottava,this._aboveStaff)}canExpand(e,t){return e.ottava===t.ottava}}class fo extends no{get notationElement(){return E.EffectPalmMute}shouldCreateGlyphForNote(e){return e.isPalmMute}get sizingMode(){return rs.GroupedOnBeat}createNewGlyph(e,t){return new oo("P.M.")}}class yo extends no{get notationElement(){return E.EffectPickSlide}shouldCreateGlyphForNote(e){return e.slideOutType===v.PickSlideDown||e.slideOutType===v.PickSlideUp}get sizingMode(){return rs.GroupedOnBeat}createNewGlyph(e,t){return new oo("P.S.")}}class bo extends xr{constructor(e,t,s){super(e,t,vr.GraceScale,bo.getSymbol(s))}paint(e,t,s){super.paint(e,t+this.height,s)}static getSymbol(e){switch(e){case ae.Up:return re.StringsUpBow;case ae.Down:return re.StringsDownBow;default:return re.None}}}class So extends Jn{get notationElement(){return E.EffectPickStroke}get hideOnMultiTrack(){return!1}get canShareBand(){return!0}get sizingMode(){return rs.SingleOnBeat}shouldCreateGlyph(e,t){return t.pickStroke!==ae.None}createNewGlyph(e,t){return new bo(0,0,t.pickStroke)}canExpand(e,t){return!0}}class _o extends jn{constructor(e){super(ts.EndBeat),this._stepSize=0,this._type=e}doLayout(){switch(super.doLayout(),this._type){case P.Slight:this._stepSize=12;break;case P.Wide:this._stepSize=23}this.height=18}paintGrouped(e,t,s,i){let a=e+this.x;const r=s-a,n=Math.max(1,r/this._stepSize);i.beginPath(),i.moveTo(a,t+this.y);for(let e=0;e<n;e++)i.lineTo(a+this._stepSize/2,t+this.y+this.height),i.lineTo(a+this._stepSize,t+this.y),a+=this._stepSize;i.stroke()}}class wo extends Jn{get notationElement(){return E.EffectSlightBeatVibrato}get hideOnMultiTrack(){return!1}get canShareBand(){return!0}get sizingMode(){return rs.GroupedOnBeatToEnd}shouldCreateGlyph(e,t){return t.vibrato===P.Slight}createNewGlyph(e,t){return new _o(P.Slight)}canExpand(e,t){return!0}}class Bo extends jn{constructor(e,t,s,i=1.2,a=!1){super(ts.EndBeat),this._scale=0,this._symbol=re.None,this._symbolSize=0,this._type=s,this._scale=i,this.x=e,this.y=t,this._partialWaves=a}doLayout(){switch(super.doLayout(),this._type){case P.Slight:this._symbol=re.WiggleTrill;break;case P.Wide:this._symbol=re.WiggleVibratoMediumFast}this._symbolSize=Nr.Widths.get(this._symbol)*this._scale,this.height=Nr.Heights.get(this._symbol)*this._scale}paintGrouped(e,t,s,i){const a=s-(e+this.x),r=this._symbolSize;let n=a/r;this._partialWaves||(n=Math.floor(n)),n<1&&(n=1);let o=0;for(let s=0;s<n;s++)i.fillMusicFontSymbol(e+this.x+o,t+this.y+2*this.height,this._scale,this._symbol,!1),o+=r}}class ko extends no{get notationElement(){return E.EffectSlightNoteVibrato}shouldCreateGlyphForNote(e){let t=e.vibrato===P.Slight||e.isTieDestination&&e.tieOrigin.vibrato===P.Slight;return this._hideOnTiedBend&&t&&e.isTieDestination&&e.tieOrigin.hasBend&&(t=!1),t}get sizingMode(){return rs.GroupedOnBeatToEnd}createNewGlyph(e,t){return new Bo(0,0,P.Slight,1.2)}constructor(e){super(),this._hideOnTiedBend=e}}class To extends Jn{get notationElement(){return E.EffectTap}get hideOnMultiTrack(){return!1}get canShareBand(){return!0}get sizingMode(){return rs.SingleOnBeat}shouldCreateGlyph(e,t){return t.slap||t.pop||t.tap}createNewGlyph(e,t){const s=e.resources;return t.slap?new Sn(0,0,"S",s.effectFont,ne.Left):t.pop?new Sn(0,0,"P",s.effectFont,ne.Left):new Sn(0,0,"T",s.effectFont,ne.Left)}canExpand(e,t){return!0}}class No extends Tr{constructor(e){super(0,0),this.tempoAutomations=e}doLayout(){super.doLayout(),this.height=25}paint(e,t,s){for(const i of this.tempoAutomations){let a=e+this.renderer.getRatioPositionX(i.ratioPosition);const r=this.renderer.resources;if(s.font=r.markerFont,s.textBaseline=oe.Top,i.text){const e=s.measureText(i.text);s.fillText(i.text,a,t+this.y+s.font.size/2),a+=e.width+.7*s.font.size}s.fillMusicFontSymbol(a,t+this.y+.8*this.height,.5,re.NoteQuarterUp,!0),s.fillText(`= ${i.value.toString()}`,a+.5*Nr.Widths.get(re.NoteQuarterUp)+3,t+this.y+s.font.size/2)}}}class xo extends Jn{get notationElement(){return E.EffectTempo}get hideOnMultiTrack(){return!0}get canShareBand(){return!1}get sizingMode(){return rs.SinglePreBeat}shouldCreateGlyph(e,t){return 0===t.voice.bar.staff.index&&0===t.voice.index&&0===t.index&&t.voice.bar.masterBar.tempoAutomations.length>0}createNewGlyph(e,t){return new No(t.voice.bar.masterBar.tempoAutomations)}canExpand(e,t){return!0}}class vo extends Jn{get notationElement(){return E.EffectText}get hideOnMultiTrack(){return!1}get canShareBand(){return!1}get sizingMode(){return rs.SingleOnBeat}shouldCreateGlyph(e,t){return!!t.text}createNewGlyph(e,t){return new Sn(0,0,t.text,e.resources.effectFont,ne.Left)}canExpand(e,t){return!0}}class Po extends jn{constructor(e,t){super(ts.EndBeat),this.x=e,this.y=t}doLayout(){super.doLayout(),this.height=Nr.Heights.get(re.OrnamentTrill)/2}paintGrouped(e,t,s,i){let a=e+this.x;i.fillMusicFontSymbol(a,t+this.y+this.height,1,re.OrnamentTrill,!0),a+=Nr.Widths.get(re.OrnamentTrill)/2;const r=1.2*Nr.Widths.get(re.WiggleTrill),n=Math.floor((s-a)/r),o=t+this.y+1.37*this.height;let h=a;for(let e=0;e<n;e++)i.fillMusicFontSymbol(h,o,1.2,re.WiggleTrill,!1),h+=r}}class Fo extends no{get notationElement(){return E.EffectTrill}shouldCreateGlyphForNote(e){return e.isTrill}get sizingMode(){return rs.GroupedOnBeatToEnd}createNewGlyph(e,t){return new Po(0,0)}}!function(e){e[e.Full=0]="Full",e[e.PartialLeft=1]="PartialLeft",e[e.PartialRight=2]="PartialRight"}(ns||(ns={}));class Co extends Tr{constructor(e){super(0,0),this._tripletFeel=e}doLayout(){super.doLayout(),this.height=25}paint(e,t,s){e+=this.x;const i=(t+=this.y)+this.height*vr.GraceScale,a=i+8;s.font=this.renderer.resources.effectFont,s.fillText("(",e,t+.3*this.height);const r=e+10,n=e+40;let o=[],h=[],l=[],c=[];switch(this._tripletFeel){case M.NoTripletFeel:o=[re.TextBlackNoteLongStem,re.TextCont8thBeamLongStem,re.TextBlackNoteFrac8thLongStem],l=[re.TextBlackNoteLongStem,re.TextCont8thBeamLongStem,re.TextBlackNoteFrac8thLongStem];break;case M.Triplet8th:o=[re.TextBlackNoteLongStem,re.TextCont8thBeamLongStem,re.TextBlackNoteFrac8thLongStem],l=[re.TextBlackNoteLongStem,re.Space,re.NoteEighthUp],c=[re.TextTupletBracketStartLongStem,re.TextTuplet3LongStem,re.TextTupletBracketEndLongStem];break;case M.Triplet16th:o=[re.TextBlackNoteLongStem,re.TextCont8thBeamLongStem,re.TextBlackNoteFrac8thLongStem],l=[re.TextBlackNoteLongStem,re.TextCont8thBeamLongStem,re.TextBlackNoteFrac16thLongStem],c=[re.TextTupletBracketStartLongStem,re.TextTuplet3LongStem,re.TextTupletBracketEndLongStem];break;case M.Dotted8th:o=[re.TextBlackNoteLongStem,re.TextCont8thBeamLongStem,re.TextBlackNoteFrac8thLongStem],h=[re.TextAugmentationDot],l=[re.TextBlackNoteLongStem,re.TextCont8thBeamLongStem,re.TextBlackNoteFrac16thLongStem];break;case M.Dotted16th:o=[re.TextBlackNoteLongStem,re.TextCont16thBeamLongStem,re.TextBlackNoteFrac16thLongStem],h=[re.TextAugmentationDot],l=[re.TextBlackNoteLongStem,re.TextCont16thBeamLongStem,re.TextBlackNoteFrac32ndLongStem],s.fillCircle(n+9,i,1);break;case M.Scottish8th:o=[re.TextBlackNoteLongStem,re.TextCont8thBeamLongStem,re.TextBlackNoteFrac8thLongStem],l=[re.TextBlackNoteLongStem,re.TextCont16thBeamLongStem,re.TextBlackNoteFrac8thLongStem,re.TextAugmentationDot];break;case M.Scottish16th:o=[re.TextBlackNoteLongStem,re.TextCont16thBeamLongStem,re.TextBlackNoteFrac16thLongStem],l=[re.TextBlackNoteLongStem,re.TextCont32ndBeamLongStem,re.TextBlackNoteFrac16thLongStem,re.TextAugmentationDot]}s.fillMusicFontSymbols(r,i,Co.NoteScale,o,!1),s.fillText("=",e+32,t+5),s.fillMusicFontSymbols(n,i,Co.NoteScale,l,!1),h.length>0&&s.fillMusicFontSymbols(n+7,i,Co.NoteScale,h,!1),c.length>0&&s.fillMusicFontSymbols(n,a,Co.TupletScale,c,!1),s.fillText(")",e+65,t+.3*this.height)}}Co.NoteScale=.5,Co.TupletScale=.7;class Do extends Jn{get notationElement(){return E.EffectTripletFeel}get hideOnMultiTrack(){return!0}get canShareBand(){return!1}get sizingMode(){return rs.SinglePreBeat}shouldCreateGlyph(e,t){return 0===t.index&&(0===t.voice.bar.masterBar.index&&t.voice.bar.masterBar.tripletFeel!==M.NoTripletFeel||t.voice.bar.masterBar.index>0&&t.voice.bar.masterBar.tripletFeel!==t.voice.bar.masterBar.previousMasterBar.tripletFeel)}createNewGlyph(e,t){return new Co(t.voice.bar.masterBar.tripletFeel)}canExpand(e,t){return!0}}class Eo extends Jn{get notationElement(){return E.EffectWhammyBar}get hideOnMultiTrack(){return!1}get canShareBand(){return!1}get sizingMode(){return rs.GroupedOnBeat}shouldCreateGlyph(e,t){return t.hasWhammyBar}createNewGlyph(e,t){return new oo("w/bar")}canExpand(e,t){return!0}}class Lo extends Jn{get notationElement(){return E.EffectWideBeatVibrato}get hideOnMultiTrack(){return!1}get canShareBand(){return!0}get sizingMode(){return rs.GroupedOnBeatToEnd}shouldCreateGlyph(e,t){return t.vibrato===P.Wide}createNewGlyph(e,t){return new _o(P.Wide)}canExpand(e,t){return!0}}class Mo extends no{get notationElement(){return E.EffectWideNoteVibrato}shouldCreateGlyphForNote(e){return e.vibrato===P.Wide||e.isTieDestination&&e.tieOrigin.vibrato===P.Wide}get sizingMode(){return rs.GroupedOnBeatToEnd}createNewGlyph(e,t){return new Bo(0,0,P.Wide,1.2)}}class Io{constructor(){this.x=0,this.width=0,this.masterBars=[]}}class Ao extends En{constructor(){super(...arguments),this._system=null}get name(){return"HorizontalScreen"}get supportsResize(){return!1}get firstBarX(){let e=this.pagePadding[0];return this._system&&(e+=this._system.accoladeWidth),e}doResize(){}doLayoutAndRender(){switch(this.renderer.settings.display.systemsLayoutMode){case $t.Automatic:this.systemsLayoutMode=ss.Automatic;break;case $t.UseModelLayout:this.systemsLayoutMode=ss.FromModelWithWidths}const e=this.renderer.score;let t=this.renderer.settings.display.startBar;t--,t=Math.min(e.masterBars.length-1,Math.max(0,t));let s=t,i=this.renderer.settings.display.barCount;i<=0&&(i=e.masterBars.length),i=t+i-1,i=Math.min(e.masterBars.length-1,Math.max(0,i)),this._system=this.createEmptyStaffSystem(),this._system.isLast=!0,this._system.x=this.pagePadding[0],this._system.y=this.pagePadding[1];const a=this.renderer.settings.display.barCountPerPartial,r=[];let n=new Io,o=0;for(;s<=i;){const t=this.multiBarRestInfo,i=null!==t&&t.has(s)?t.get(s):null,h=this._system.addBars(this.renderer.tracks,s,i);if(0===n.masterBars.length&&h.isLinkedToPrevious&&r.length>0){const t=r[r.length-1];t.masterBars.push(e.masterBars[s]),t.width+=h.width,o+=h.width,n.x+=o}else n.masterBars.push(e.masterBars[s]),n.width+=h.width,n.masterBars.length>=a&&(0===r.length&&(n.width+=this._system.accoladeWidth+this.pagePadding[0]),o+=n.width,r.push(n),q.debug(this.name,`Finished partial from bar ${n.masterBars[0].index} to ${n.masterBars[n.masterBars.length-1].index}`,null),n=new Io,n.x=o);s++}n.masterBars.length>0&&(0===r.length&&(n.width+=this._system.accoladeWidth+this.pagePadding[0]),r.push(n),q.debug(this.name,`Finished partial from bar ${n.masterBars[0].index} to ${n.masterBars[n.masterBars.length-1].index}`,null)),this.finalizeStaffSystem();const h=this.renderer.settings.display.scale;this.height=Math.floor(this._system.y+this._system.height)*h,this.width=(this._system.x+this._system.width+this.pagePadding[2])*h,s=0;let l=0;for(let e=0;e<r.length;e++){const t=r[e],i=new Za;i.x=l,i.y=0,i.totalWidth=this.width/h,i.totalHeight=this.height/h,i.width=t.width,i.height=this.height/h,i.firstMasterBarIndex=t.masterBars[0].index,i.lastMasterBarIndex=t.masterBars[t.masterBars.length-1].index,l+=t.width;const a=s,n=e;this._system.buildBoundingsLookup(0,0),this.registerPartial(i,(e=>{let s=this._system.getBarX(t.masterBars[0].index)+this._system.accoladeWidth;0===n&&(s-=this._system.x+this._system.accoladeWidth),e.color=this.renderer.settings.display.resources.mainGlyphColor,e.textAlign=ne.Left,q.debug(this.name,`Rendering partial from bar ${t.masterBars[0].index} to ${t.masterBars[t.masterBars.length-1].index}`,null),this._system.paintPartial(-s,this._system.y,e,a,t.masterBars.length)})),s+=t.masterBars.length}this.height=this.layoutAndRenderBottomScoreInfo(this.height),this.height=this.layoutAndRenderAnnotation(this.height),this.height+=this.pagePadding[3]}finalizeStaffSystem(){this._system.scaleToWidth(this._system.width),this._system.finalizeSystem()}}class Ro extends En{constructor(){super(...arguments),this._systems=[],this._allMasterBarRenderers=[],this._barsFromPreviousSystem=[]}get name(){return"PageView"}doLayoutAndRender(){switch(this.renderer.settings.display.systemsLayoutMode){case $t.Automatic:this.systemsLayoutMode=ss.Automatic;break;case $t.UseModelLayout:this.systemsLayoutMode=ss.FromModelWithScale}let e=this.pagePadding[1];this.width=this.renderer.width,this._allMasterBarRenderers=[],e=this.layoutAndRenderScoreInfo(e,-1),e=this.layoutAndRenderTunings(e,-1),e=this.layoutAndRenderChordDiagrams(e,-1),e=this.layoutAndRenderScore(e),e=this.layoutAndRenderBottomScoreInfo(e),e=this.layoutAndRenderAnnotation(e),this.height=(e+this.pagePadding[3])*this.renderer.settings.display.scale}get supportsResize(){return!0}get firstBarX(){let e=this.pagePadding[0];return this._systems.length>0&&(e+=this._systems[0].accoladeWidth),e}doResize(){let e=this.pagePadding[1];this.width=this.renderer.width;const t=this.height;e=this.layoutAndRenderScoreInfo(e,t),e=this.layoutAndRenderTunings(e,t),e=this.layoutAndRenderChordDiagrams(e,t),e=this.resizeAndRenderScore(e,t),e=this.layoutAndRenderBottomScoreInfo(e),e=this.layoutAndRenderAnnotation(e),this.height=(e+this.pagePadding[3])*this.renderer.settings.display.scale}layoutAndRenderTunings(e,t=-1){if(!this.tuningGlyph)return e;const s=this.renderer.settings.display.resources;this.tuningGlyph.x=this.pagePadding[0],this.tuningGlyph.width=this.scaledWidth,this.tuningGlyph.doLayout();const i=Math.round(this.tuningGlyph.height),a=new Za;return a.x=0,a.y=e,a.width=this.scaledWidth,a.height=i,a.totalWidth=this.scaledWidth,a.totalHeight=t<0?e+a.height:t,this.registerPartial(a,(e=>{e.color=s.scoreInfoColor,e.textAlign=ne.Center,this.tuningGlyph.paint(0,0,e)})),e+i}layoutAndRenderChordDiagrams(e,t=-1){if(!this.chordDiagrams)return e;const s=this.renderer.settings.display.resources;this.chordDiagrams.width=this.scaledWidth,this.chordDiagrams.doLayout();const i=Math.round(this.chordDiagrams.height),a=new Za;return a.x=0,a.y=e,a.width=this.scaledWidth,a.height=i,a.totalWidth=this.scaledWidth,a.totalHeight=t<0?e+i:t,this.registerPartial(a,(e=>{e.color=s.scoreInfoColor,e.textAlign=ne.Center,this.chordDiagrams.paint(0,0,e)})),e+i}layoutAndRenderScoreInfo(e,t=-1){q.debug(this.name,"Layouting score info");const s=new Za;s.x=0,s.y=e;let i=0;const a=this.renderer.settings.display.resources,r=[];for(const[e,t]of En.HeaderElements.value)if(this.headerGlyphs.has(e)){const t=this.headerGlyphs.get(e);t.y=i,this.alignScoreInfoGlyph(t);let s=t.font.size;if(e===be.Words&&this.headerGlyphs.has(be.Music)){this.headerGlyphs.get(be.Music).textAlign!==t.textAlign&&(s=0)}i+=s,r.push(t)}return r.length>0&&(i=Math.floor(i+17),s.width=this.scaledWidth,s.height=i,s.totalWidth=this.scaledWidth,s.totalHeight=t<0?e+s.height:t,this.registerPartial(s,(e=>{e.color=a.scoreInfoColor,e.textAlign=ne.Center;for(const t of r)t.paint(0,0,e)}))),e+i}resizeAndRenderScore(e,t){if(this.renderer.settings.display.barsPerRow>0||this.systemsLayoutMode===ss.FromModelWithScale)for(let s=0;s<this._systems.length;s++){const i=this._systems[s];this.fitSystem(i),e+=this.paintSystem(i,t)}else{this._systems=[];let s=0;const i=this.maxWidth;let a=this.createEmptyStaffSystem();for(a.index=this._systems.length,a.x=this.pagePadding[0],a.y=e;s<this._allMasterBarRenderers.length;){let r=this._allMasterBarRenderers[s];if(a.width+r.width<=i||0===a.masterBarsRenderers.length)a.addMasterBarRenderers(this.renderer.tracks,r),s++;else{for(;r&&!r.canWrap&&a.masterBarsRenderers.length>1;)r=a.revertLastBar(),s--;a.isFull=!0,a.isLast=this.lastBarIndex===a.lastBarIndex,this._systems.push(a),this.fitSystem(a),e+=this.paintSystem(a,t),a=this.createEmptyStaffSystem(),a.index=this._systems.length,a.x=this.pagePadding[0],a.y=e}}a.isLast=this.lastBarIndex===a.lastBarIndex,this.fitSystem(a),e+=this.paintSystem(a,t)}return e}layoutAndRenderScore(e){let t=this.firstBarIndex;const s=this.lastBarIndex;for(this._systems=[];t<=s;){const i=this.createStaffSystem(t,s);this._systems.push(i),i.x=this.pagePadding[0],i.y=e,t=i.lastBarIndex+1,this.fitSystem(i),q.debug(this.name,`Rendering partial from bar ${i.firstBarIndex} to ${i.lastBarIndex}`,null),e+=this.paintSystem(i,e)}return e}paintSystem(e,t){const s=Math.floor(e.height),i=new Za;return i.x=0,i.y=e.y,i.totalWidth=this.scaledWidth,i.totalHeight=t,i.width=this.scaledWidth,i.height=s,i.firstMasterBarIndex=e.firstBarIndex,i.lastMasterBarIndex=e.lastBarIndex,e.buildBoundingsLookup(0,0),this.registerPartial(i,(t=>{this.renderer.canvas.color=this.renderer.settings.display.resources.mainGlyphColor,this.renderer.canvas.textAlign=ne.Left,e.paint(0,-i.y/this.renderer.settings.display.scale,t)})),s}fitSystem(e){e.isFull||e.width>this.maxWidth||this.renderer.settings.display.justifyLastSystem?e.scaleToWidth(this.maxWidth):e.scaleToWidth(e.width),e.finalizeSystem()}getBarsPerSystem(e){let t=this.renderer.settings.display.barsPerRow;if(this.systemsLayoutMode===ss.FromModelWithScale){let s,i;this.renderer.tracks.length>1?(s=this.renderer.score.defaultSystemsLayout,i=this.renderer.score.systemsLayout):(s=this.renderer.tracks[0].defaultSystemsLayout,i=this.renderer.tracks[0].systemsLayout),t=e<i.length?i[e]:s}return t}createStaffSystem(e,t){const s=this.createEmptyStaffSystem();s.index=this._systems.length;const i=this.getBarsPerSystem(s.index),a=this.maxWidth,r=t+1;let n=e;for(;n<r;){if(this._barsFromPreviousSystem.length>0)for(const e of this._barsFromPreviousSystem)s.addMasterBarRenderers(this.renderer.tracks,e),n=e.lastMasterBarIndex;else{const e=this.multiBarRestInfo,t=null!==e&&e.has(n)?e.get(n):null,i=s.addBars(this.renderer.tracks,n,t);this._allMasterBarRenderers.push(i),n=i.lastMasterBarIndex}this._barsFromPreviousSystem=[];let e=!1;if((-1===i&&s.width>=a&&0!==s.masterBarsRenderers.length||s.masterBarsRenderers.length===i+1)&&(e=!0),e){let e=s.revertLastBar();if(e)for(this._barsFromPreviousSystem.push(e);e&&!e.canWrap&&s.masterBarsRenderers.length>1;)e=s.revertLastBar(),e&&this._barsFromPreviousSystem.push(e);return s.isFull=!0,s.isLast=!1,this._barsFromPreviousSystem.reverse(),s}let t=!1,r=!0;for(const e of this.renderer.tracks)e.lineBreaks&&e.lineBreaks.has(n+1)?t=!0:r=!1;if(t&&r)return s.isFull=!0,s.isLast=!1,s;s.x=0,n++}return s.isLast=t===s.lastBarIndex,s}get maxWidth(){return this.scaledWidth-this.pagePadding[0]-this.pagePadding[2]}}class Oo extends xr{constructor(e,t,s,i){super(e,t,i,Oo.getMusicSymbol(s))}static getMusicSymbol(e){switch(e){case It.Natural:return re.AccidentalNatural;case It.Sharp:return re.AccidentalSharp;case It.Flat:return re.AccidentalFlat;case It.NaturalQuarterNoteUp:return re.AccidentalQuarterToneNaturalArrowUp;case It.SharpQuarterNoteUp:return re.AccidentalQuarterToneSharpArrowUp;case It.FlatQuarterNoteUp:return re.AccidentalQuarterToneFlatArrowUp;case It.DoubleSharp:return re.AccidentalDoubleSharp;case It.DoubleFlat:return re.AccidentalDoubleFlat}return re.None}}class Ho extends xr{constructor(e,t,s,i){super(e,t,1,Ho.getSymbol(s)),this._clef=s,this._clefOttava=i}static getSymbol(e){switch(e){case n.Neutral:return re.UnpitchedPercussionClef1;case n.C3:case n.C4:return re.CClef;case n.F4:return re.FClef;case n.G2:return re.GClef;default:return re.None}}paint(e,t,s){const i=rn.bar(s,u.StandardNotationClef,this.renderer.bar);try{let i;super.paint(e,t,s);let a=!1;switch(this._clefOttava){case o._15ma:i=new xr(-4,0,.5,re.Quindicesima),a=!0;break;case o._8va:i=new xr(-2,0,.5,re.Ottava),a=!0;break;case o._8vb:i=new xr(-6,0,.5,re.Ottava);break;case o._15mb:i=new xr(-8,0,.5,re.Quindicesima);break;default:return}let r=0,h=0;switch(this._clef){case n.Neutral:r=a?-12:15,h=0;break;case n.C3:case n.C4:r=a?-19:27,h=0;break;case n.F4:r=a?-9:27,h=-4;break;case n.G2:r=a?-37:30,h=0;break;default:return}i.renderer=this.renderer,i.doLayout();const l=this.width/2;i.paint(e+this.x+l+h,t+this.y+r,s)}finally{i?.[Symbol.dispose]?.()}}}class Wo extends Tr{constructor(e,t,s){super(e,t),this._note=s}static getSymbol(e,t){switch(e){case B.None:return re.None;case B.Normal:return t?re.ArticAccentAbove:re.ArticAccentBelow;case B.Heavy:return t?re.ArticMarcatoAbove:re.ArticMarcatoBelow;case B.Tenuto:return t?re.ArticTenutoAbove:re.ArticTenutoBelow;default:return re.None}}doLayout(){this.width=Nr.Widths.get(re.ArticAccentAbove),this.height=Nr.Heights.get(re.ArticAccentAbove)}paint(e,t,s){const i=this.renderer.getBeatDirection(this._note.beat),a=Wo.getSymbol(this._note.accentuated,i===Te.Down),r=i===Te.Up?t+this.y:t+this.y+this.height-2;s.fillMusicFontSymbol(e+this.x-2,r,1,a,!1)}}class Vo extends kr{constructor(e,t,s){super(e,t),this._size=0,this._size=s}doLayout(){this.width=this._size+3}paint(e,t,s){const i=s.color;this.colorOverride&&(s.color=this.colorOverride),s.fillCircle(e+this.x,t+this.y,this._size),s.color=i}}class Go extends xr{constructor(e,t,s){super(e,t,s?vr.GraceScale:1,re.NoteheadXOrnate)}}class zo extends xr{constructor(e,t,s,i){super(e,t,i?vr.GraceScale:1,zo.getSymbol(s))}static getSymbol(e){switch(e){case _.QuadrupleWhole:case _.DoubleWhole:case _.Whole:case _.Half:return re.NoteheadDiamondWhiteWide;default:return re.NoteheadDiamondBlackWide}}}class Uo extends kr{constructor(e,t,s){super(0,0),this.yOffset=0,this.startNoteRenderer=null,this.endNoteRenderer=null,this.tieDirection=Te.Up,this._startX=0,this._startY=0,this._endX=0,this._endY=0,this._tieHeight=0,this._shouldDraw=!1,this.startBeat=e,this.endBeat=t,this.forEnd=s}doLayout(){if(this.width=0,!this.endBeat)return void(this._shouldDraw=!1);const e=this.renderer.scoreRenderer.layout.getRendererForBar(this.renderer.staff.staffId,this.startBeat.voice.bar);this.startNoteRenderer=e;const t=this.renderer.scoreRenderer.layout.getRendererForBar(this.renderer.staff.staffId,this.endBeat.voice.bar);if(this.endNoteRenderer=t,this._startX=0,this._endX=0,this._startY=0,this._endY=0,this.height=0,this._shouldDraw=!1,this.tieDirection=e?this.getBeamDirection(this.startBeat,e):this.getBeamDirection(this.endBeat,t),!this.forEnd&&e?(e!==t?(this._startX=e.x+this.getStartX(),this._startY=e.y+this.getStartY()+this.yOffset,t&&e.staff===t.staff?(this._endX=t.x+this.getEndX(),this._endY=t.y+this.getEndY()+this.yOffset):(this._endX=e.x+e.width,this._endY=this._startY)):(this._startX=e.x+this.getStartX(),this._endX=t.x+this.getEndX(),this._startY=e.y+this.getStartY()+this.yOffset,this._endY=t.y+this.getEndY()+this.yOffset),this._shouldDraw=!0):e&&e.staff===t.staff||(this._startX=t.x,this._endX=t.x+this.getEndX(),this._startY=t.y+this.getEndY()+this.yOffset,this._endY=this._startY,this._shouldDraw=!0),this._shouldDraw)if(this.y=Math.min(this._startY,this._endY),this.shouldDrawBendSlur())this._tieHeight=0;else{this._tieHeight=this.getTieHeight(this._startX,this._startY,this._endX,this._endY);const e=Uo.calculateActualTieHeight(1,this._startX,this._startY,this._endX,this._endY,this.tieDirection===Te.Down,this._tieHeight,4);if(this.height=e.h,this.tieDirection===Te.Up){const t=this.y-e.y;t>0&&(this.y-=t)}}}paint(e,t,s){this._shouldDraw&&(this.shouldDrawBendSlur()?Uo.drawBendSlur(s,e+this._startX,t+this._startY,e+this._endX,t+this._endY,this.tieDirection===Te.Down,1):Uo.paintTie(s,1,e+this._startX,t+this._startY,e+this._endX,t+this._endY,this.tieDirection===Te.Down,this._tieHeight,4))}shouldDrawBendSlur(){return!1}getTieHeight(e,t,s,i){return 22}getBeamDirection(e,t){return Te.Down}getStartY(){return 0}getEndY(){return 0}getStartX(){return 0}getEndX(){return 0}static calculateActualTieHeight(e,t,s,i,a,r,n,o){const h=Uo.computeBezierControlPoints(e,t,s,i,a,r,n,o);t=h[0],s=h[1];const l=h[2],c=h[3];i=h[6],a=h[7];const d=(t-l)/(t-2*l+i),u=Uo.calculateExtrema(t,s,l,c,i,a,d),p=u.length>0?Math.min(t,i,u[0]):Math.min(t,i),g=u.length>0?Math.max(t,i,u[0]):Math.max(t,i),m=(s-c)/(s-2*c+a),f=Uo.calculateExtrema(t,s,l,c,i,a,m),y=f.length>0?Math.min(s,a,f[1]):Math.min(s,a),b=f.length>0?Math.max(s,a,f[1]):Math.max(s,a),S=new mt;return S.x=p,S.y=y,S.w=g-p,S.h=b-y,S}static calculateExtrema(e,t,s,i,a,r,n){if(n<=0||1<=n)return[];const o=e+(s-e)*n,h=t+(i-t)*n;return[o+(s+(a-s)*n-o)*n,h+(i+(r-i)*n-h)*n]}static computeBezierControlPoints(e,t,s,i,a,r,n,o){if(t===i&&s===a)return[];if(i<t){let e=t;t=i,i=e,e=s,s=a,a=e}n*=e,o*=e;let h=a-s,l=i-t;const c=Math.sqrt(h*h+l*l);r?h*=-1:l*=-1,h/=c,l/=c;const d=(i+t)/2,u=(a+s)/2;return[t,s,d+n*h,u+n*l,d+(n-o)*h,u+(n-o)*l,i,a]}static paintTie(e,t,s,i,a,r,n=!1,o=22,h=4){const l=Uo.computeBezierControlPoints(t,s,i,a,r,n,o,h);e.beginPath(),e.moveTo(l[0],l[1]),e.quadraticCurveTo(l[2],l[3],l[6],l[7]),e.quadraticCurveTo(l[4],l[5],l[0],l[1]),e.closePath(),e.fill()}static drawBendSlur(e,t,s,i,a,r,n,o){let h=a-s,l=i-t;const c=Math.sqrt(h*h+l*l);r?h*=-1:l*=-1,h/=c,l/=c;const d=(i+t)/2,u=(a+s)/2;let p=Uo.BendSlurHeight*n;i-t<20&&(p/=2);const g=d+p*h,m=u+p*l;if(e.beginPath(),e.moveTo(t,s),e.lineTo(g,m),e.lineTo(i,a),e.stroke(),o){const t=e.measureText(o).width,s=r?0:-e.font.size;e.fillText(o,g-t/2,m+s)}}}Uo.BendSlurHeight=11;class Xo extends kr{constructor(e){super(0,0),this._isOpen=e}doLayout(){super.doLayout(),this.width=Xo.Size}paint(e,t,s){const i=s.color;this.colorOverride&&(s.color=this.colorOverride),this._isOpen?Uo.paintTie(s,1,e+this.x+this.width,t+this.y+this.height,e+this.x+this.width,t+this.y,!1,6,3):Uo.paintTie(s,1,e+this.x,t+this.y,e+this.x,t+this.y+this.height,!1,6,3),s.color=i}}Xo.Size=6;class Jo{constructor(e,t,s){this.line=0,this.line=e,this.isGhost=t,this.color=s}}class Yo extends kr{constructor(e){super(0,0),this._infos=[],this._glyphs=[],this.isEmpty=!0,this._isOpen=e}addParenthesis(e){const t=this.renderer,s=t.getNoteLine(e),i=e.isGhost||this.isTiedBend(e)&&t.settings.notation.isNotationElementVisible(E.ParenthesisOnTiedBends),a=rn.noteColor(t.resources,le.Effects,e);this.add(new Jo(s,i,a))}addParenthesisOnLine(e,t){const s=new Jo(e,t,void 0);this.add(s)}add(e){this._infos.push(e),e.isGhost&&(this.isEmpty=!1)}isTiedBend(e){return!!e.isTieDestination&&(!!e.tieOrigin.hasBend||this.isTiedBend(e.tieOrigin))}doLayout(){const e=this.renderer;this._infos.sort(((e,t)=>e.line-t.line));let t=null;const s=e.getScoreHeight(1);for(let i=0,a=this._infos.length;i<a;i++){let a;if(this._infos[i].isGhost)if(t){const a=e.getScoreY(this._infos[i].line)+s;t.height=a-t.y}else a=new Xo(this._isOpen),a.colorOverride=this._infos[i].color,a.renderer=this.renderer,a.y=e.getScoreY(this._infos[i].line)-s,a.height=2*s,a.doLayout(),this._glyphs.push(a),t=a;else t=null}this.width=this._glyphs.length>0?this._glyphs[0].width:0}paint(e,t,s){super.paint(e,t,s);for(const i of this._glyphs)i.paint(e+this.x,t+this.y,s)}}class $o{constructor(e,t){this.steps=0,this.glyph=e,this.steps=t}}class qo extends kr{constructor(){super(0,0),this._infos=[],this._noteHeadPadding=0,this.minNote=null,this.maxNote=null,this.spacingChanged=new Qi,this.upLineX=0,this.downLineX=0,this.displacedX=0,this.noteStartX=0}add(e,t){const s=new $o(e,t);this._infos.push(s),(!this.minNote||this.minNote.steps>s.steps)&&(this.minNote=s),(!this.maxNote||this.maxNote.steps<s.steps)&&(this.maxNote=s)}doLayout(){this._infos.sort(((e,t)=>t.steps-e.steps));let e=0,t=!1,s=0,i=!1;const a=this.direction;let r=0;for(let n=0,o=this._infos.length;n<o;n++){const o=this._infos[n].glyph;o.renderer=this.renderer,o.doLayout();let h=!1;0===n?e=o.width:Math.abs(s-this._infos[n].steps)<=1?t?t=!1:(h=!0,o.x=e,i=!0,t=!0):t=!1,a===Te.Down?o.x=h?0:e:o.x=h?e:0,o.x+=this.noteStartX,s=this._infos[n].steps,r=Math.max(r,o.x+o.width),o instanceof vr&&o.centerOnStem&&(o.x=e)}i?(this._noteHeadPadding=0,this.upLineX=e,this.downLineX=e):(this._noteHeadPadding=a===Te.Down?-e:0,r+=this._noteHeadPadding,this.upLineX=r,this.downLineX=0),this.displacedX=e,this.width=r}paint(e,t,s){e+=this.x,t+=this.y,this.paintLedgerLines(e,t,s);const i=this._infos,a=e+this._noteHeadPadding;for(const e of i)e.glyph.renderer=this.renderer,e.glyph.paint(a,t,s)}paintLedgerLines(e,t,s){if(!this.minNote)return;const i=this.renderer,a=rn.bar(s,u.StandardNotationStaffLine,i.bar,!0);try{const a=3,r=this.width-this.noteStartX+2*a,n=i.getLineHeight(1),o=i.getLineY(-1),h=i.getLineY(i.drawnLineCount),l=i.getLineY(this.minNote.steps/2),c=i.getLineY(this.maxNote.steps/2);let d=o;for(;d>=l;)s.fillRect(e-a+this.noteStartX,t+d|0,r,On.StaffLineThickness),d-=n;for(d=h;d<=c;)s.fillRect(e-a+this.noteStartX,t+d|0,r,On.StaffLineThickness),d+=n}finally{a?.[Symbol.dispose]?.()}}}class jo extends xr{constructor(e,t,s){super(e,t,1,jo.getSymbol(s))}static getSymbol(e){switch(e){case _.ThirtySecond:return re.Tremolo3;case _.Sixteenth:return re.Tremolo2;case _.Eighth:return re.Tremolo1;default:return re.None}}}class Ko extends kr{constructor(){super(0,0)}doLayout(){this.width=26}paint(e,t,s){const i=this.renderer,a=i.getLineHeight(i.heightLineCount-1),r=i.getLineY(0)+i.getLineHeight(i.drawnLineCount-1)/2-a/2,n=s.lineWidth;s.lineWidth=2,s.moveTo(e+this.x,t+r),s.lineTo(e+this.x+this.width,t+r+a),s.moveTo(e+this.x,t+r+a),s.lineTo(e+this.x+this.width,t+r),s.stroke(),s.lineWidth=n}}class Qo extends qo{constructor(){super(...arguments),this._noteGlyphLookup=new Map,this._notes=[],this._deadSlapped=null,this._tremoloPicking=null,this.aboveBeatEffects=new Map,this.belowBeatEffects=new Map}get direction(){return this.beamingHelper.direction}getNoteX(e,t){if(this._noteGlyphLookup.has(e.id)){const s=this._noteGlyphLookup.get(e.id);let i=this.x+s.x+this._noteHeadPadding;switch(t){case as.Left:break;case as.Center:i+=s.width/2;break;case as.Right:i+=s.width}return i}return 0}getNoteY(e,t){if(this._noteGlyphLookup.has(e.id)){const s=this._noteGlyphLookup.get(e.id);let i=this.y+s.y;switch(t){case is.TopWithStem:i-=this.renderer.getStemSize(this.beamingHelper);break;case is.Top:i-=s.height/2;break;case is.Center:break;case is.Bottom:i+=s.height/2;break;case is.BottomWithStem:i+=this.renderer.getStemSize(this.beamingHelper)}return i}return 0}addNoteGlyph(e,t,s){super.add(e,s),this._noteGlyphLookup.set(t.id,e),this._notes.push(t)}updateBeamingHelper(e){this.beamingHelper&&this.beamingHelper.registerBeatLineX("score",this.beat,e+this.x+this.upLineX,e+this.x+this.downLineX)}doLayout(){super.doLayout();const e=this.renderer;this.beat.deadSlapped&&(this._deadSlapped=new Ko,this._deadSlapped.renderer=this.renderer,this._deadSlapped.doLayout(),this.width=this._deadSlapped.width);const t=this.direction;let s=0,i=0,a=1,r=-a,n=!1,o=!1;this.beat.deadSlapped?(i=e.getScoreY(0),s=e.getScoreY(e.heightLineCount)):this.direction===Te.Up?(n=!1,o=!0,i=e.getScoreY(this.maxNote.steps+2),s=e.getScoreY(this.minNote.steps)-e.getStemSize(this.beamingHelper,!0)):(n=!0,o=!1,i=e.getScoreY(this.minNote.steps-1),a*=-1,r*=-1,s=e.getScoreY(this.maxNote.steps)+e.getStemSize(this.beamingHelper,!0));let h=null,l=null;for(const e of this.aboveBeatEffects.values())e.renderer=this.renderer,e.doLayout(),o&&(s+=r*e.height),e.y=s,(null===h||h>s)&&(h=s),(null===l||l<s)&&(l=s),o||(s+=r*e.height);for(const e of this.belowBeatEffects.values())e.renderer=this.renderer,e.doLayout(),n&&(i+=a*e.height),e.y=i,(null===h||h>i)&&(h=i),(null===l||l<i)&&(l=i),n||(i+=a*e.height);if(null!==h&&e.registerBeatEffectOverflows(h,l??0),this.beat.isTremolo&&!this.beat.deadSlapped){let e=0;const s=t===Te.Up?this.minNote:this.maxNote;let i=t===Te.Up?this.upLineX:this.downLineX;const a=this.beat.tremoloSpeed;switch(a){case _.ThirtySecond:e=t===Te.Up?-15:15;break;case _.Sixteenth:e=t===Te.Up?-12:15;break;case _.Eighth:e=t===Te.Up?-10:10;break;default:e=t===Te.Up?-10:15}this.beat.duration<_.Half&&(i=this.width/2),this._tremoloPicking=new jo(i,s.glyph.y+e,a),this._tremoloPicking.renderer=this.renderer,this._tremoloPicking.doLayout()}}buildBoundingsLookup(e,t,s){for(const i of this._notes)if(this._noteGlyphLookup.has(i.id)){const a=this._noteGlyphLookup.get(i.id),r=new ir;r.note=i,r.noteHeadBounds=new mt,r.noteHeadBounds.x=t+this.x+this._noteHeadPadding+a.x,r.noteHeadBounds.y=s+this.y+a.y-a.height/2,r.noteHeadBounds.w=a.width,r.noteHeadBounds.h=a.height,e.addNote(r)}}paint(e,t,s){this.paintEffects(e,t,s),super.paint(e,t,s)}paintEffects(e,t,s){const i=rn.beat(s,ye.StandardNotationEffects,this.beat);try{for(const i of this.aboveBeatEffects.values())i.paint(e+this.x+2,t+this.y,s);for(const i of this.belowBeatEffects.values())i.paint(e+this.x+2,t+this.y,s);this._tremoloPicking&&this._tremoloPicking.paint(e,t,s),this._deadSlapped&&this._deadSlapped.paint(e,t,s)}finally{i?.[Symbol.dispose]?.()}}}class Zo extends xr{constructor(e,t,s){super(e,t,1,Zo.getSymbol(s))}static getSymbol(e){switch(e){case _.QuadrupleWhole:return re.RestLonga;case _.DoubleWhole:return re.RestDoubleWhole;case _.Whole:return re.RestWhole;case _.Half:return re.RestHalf;case _.Quarter:return re.RestQuarter;case _.Eighth:return re.RestEighth;case _.Sixteenth:return re.RestSixteenth;case _.ThirtySecond:return re.RestThirtySecond;case _.SixtyFourth:return re.RestSixtyFourth;case _.OneHundredTwentyEighth:return re.RestOneHundredTwentyEighth;case _.TwoHundredFiftySixth:return re.RestTwoHundredFiftySixth;default:return re.None}}updateBeamingHelper(e){this.beamingHelper&&this.beamingHelper.registerBeatLineX("score",this.beat,e+this.x+this.width/2,e+this.x+this.width/2)}paint(e,t,s){this.internalPaint(e,t,s,ye.StandardNotationRests)}internalPaint(e,t,s,i){const a=rn.beat(s,i,this.beat);try{super.paint(e,t,s)}finally{a?.[Symbol.dispose]?.()}}}class eh{constructor(){this.x=0,this.y=-3e3,this.width=0}}class th extends sn{constructor(){super(0,0)}doLayout(){if(!this.glyphs||0===this.glyphs.length)return void(this.width=0);this.glyphs.sort(((e,t)=>e.y<t.y?-1:e.y>t.y?1:0));const e=[];e.push(new eh);for(let t=0,s=this.glyphs.length;t<s;t++){const s=this.glyphs[t];s.renderer=this.renderer,s.doLayout();let i=0;for(;e[i].y>s.y;)i++,i===e.length&&e.push(new eh);s.x=i,e[i].y=s.y+21,e[i].width<s.width&&(e[i].width=s.width)}this.width=0;for(const t of e)this.width+=t.width,t.x=this.width;for(let t=0,s=this.glyphs.length;t<s;t++){const s=this.glyphs[t],i=e[s.x];s.x=this.width-i.x}}}class sh extends qo{get direction(){return Te.Up}constructor(e,t=!1){super(),this._showParenthesis=!1,this._noteValueLookup=new Map,this._accidentals=new th,this._preNoteParenthesis=null,this._postNoteParenthesis=null,this.isEmpty=!0,this.noteHeadOffset=0,this._beat=e,this._showParenthesis=t,t&&(this._preNoteParenthesis=new Yo(!0),this._postNoteParenthesis=new Yo(!1))}containsNoteValue(e){return this._noteValueLookup.has(e)}getNoteValueY(e){return this._noteValueLookup.has(e)?this.y+this._noteValueLookup.get(e).y:0}addGlyph(e,t,s){const i=this.renderer,a=new vr(0,0,_.Quarter,!0),r=i.accidentalHelper.applyAccidentalForValue(this._beat,e,t,!0),n=i.accidentalHelper.getNoteLineForValue(e,!1);if(a.y=i.getScoreY(n),this._showParenthesis&&(this._preNoteParenthesis.renderer=this.renderer,this._postNoteParenthesis.renderer=this.renderer,this._preNoteParenthesis.addParenthesisOnLine(n,!0),this._postNoteParenthesis.addParenthesisOnLine(n,!0)),r!==It.None){const e=new Oo(0,a.y,r,vr.GraceScale);e.renderer=this.renderer,this._accidentals.renderer=this.renderer,this._accidentals.addGlyph(e)}this._noteValueLookup.set(e,a),this.add(a,n),this.isEmpty=!1}doLayout(){let e=0;this._showParenthesis&&(this._preNoteParenthesis.x=e,this._preNoteParenthesis.renderer=this.renderer,this._preNoteParenthesis.doLayout(),e+=this._preNoteParenthesis.width+sh.ElementPadding),this._accidentals.isEmpty||(e+=this._accidentals.width+sh.ElementPadding,this._accidentals.x=e,this._accidentals.renderer=this.renderer,this._accidentals.doLayout(),e+=this._accidentals.width+sh.ElementPadding),this.noteStartX=e,super.doLayout(),this.noteHeadOffset=this.noteStartX+(this.width-this.noteStartX)/2,this._showParenthesis&&(this._postNoteParenthesis.x=this.width+sh.ElementPadding,this._postNoteParenthesis.renderer=this.renderer,this._postNoteParenthesis.doLayout(),this.width+=this._postNoteParenthesis.width+sh.ElementPadding)}paint(e,t,s){this._accidentals.isEmpty||this._accidentals.paint(e+this.x,t+this.y,s),this._showParenthesis&&(this._preNoteParenthesis.paint(e+this.x,t+this.y,s),this._postNoteParenthesis.paint(e+this.x,t+this.y,s)),super.paint(e,t,s)}}sh.ElementPadding=2;class ih extends kr{constructor(){super(...arguments),this.BendNoteHeads=[]}drawBendSlur(e,t,s,i,a,r,n,o){Uo.drawBendSlur(e,t,s,i,a,r,n,o)}doLayout(){super.doLayout(),this.width=0;for(const e of this.BendNoteHeads)e.doLayout(),this.width+=e.width+10}getTieDirection(e,t){return t.getBeatDirection(e)===Te.Up?Te.Down:Te.Up}}ih.EndPadding=8;class ah extends X{constructor(e=0,t=0){super(e,t),this.lineValue=0,this.lineValue=t}}class rh extends kr{constructor(){super(0,0),this._notes=[],this._renderPoints=new Map,this._preBendMinValue=-1,this._bendMiddleMinValue=-1,this._bendEndMinValue=-1,this._bendEndContinuedMinValue=-1,this._releaseMinValue=-1,this._releaseContinuedMinValue=-1,this._maxBendValue=-1}addBends(e){this._notes.push(e);const t=this.createRenderingPoints(e);this._renderPoints.set(e.id,t),(-1===this._maxBendValue||this._maxBendValue<e.maxBendPoint.value)&&(this._maxBendValue=e.maxBendPoint.value);let s=0;switch(e.bendType){case y.Bend:s=t[1].value,e.isTieOrigin?(-1===this._bendEndContinuedMinValue||s<this._bendEndContinuedMinValue)&&(this._bendEndContinuedMinValue=s):(-1===this._bendEndMinValue||s<this._bendEndMinValue)&&(this._bendEndMinValue=s);break;case y.Release:s=t[1].value,e.isTieOrigin?(-1===this._releaseContinuedMinValue||s<this._releaseContinuedMinValue)&&(this._releaseContinuedMinValue=s):s>0&&(-1===this._releaseMinValue||s<this._releaseMinValue)&&(this._releaseMinValue=s);break;case y.BendRelease:s=t[1].value,(-1===this._bendMiddleMinValue||s<this._bendMiddleMinValue)&&(this._bendMiddleMinValue=s),s=t[2].value,e.isTieOrigin?(-1===this._releaseContinuedMinValue||s<this._releaseContinuedMinValue)&&(this._releaseContinuedMinValue=s):s>0&&(-1===this._releaseMinValue||s<this._releaseMinValue)&&(this._releaseMinValue=s);break;case y.Prebend:s=t[0].value,(-1===this._preBendMinValue||s<this._preBendMinValue)&&(this._preBendMinValue=s);break;case y.PrebendBend:s=t[0].value,(-1===this._preBendMinValue||s<this._preBendMinValue)&&(this._preBendMinValue=s),s=t[1].value,e.isTieOrigin?(-1===this._bendEndContinuedMinValue||s<this._bendEndContinuedMinValue)&&(this._bendEndContinuedMinValue=s):(-1===this._bendEndMinValue||s<this._bendEndMinValue)&&(this._bendEndMinValue=s);break;case y.PrebendRelease:s=t[0].value,(-1===this._preBendMinValue||s<this._preBendMinValue)&&(this._preBendMinValue=s),s=t[1].value,e.isTieOrigin?(-1===this._releaseContinuedMinValue||s<this._releaseContinuedMinValue)&&(this._releaseContinuedMinValue=s):s>0&&(-1===this._releaseMinValue||s<this._releaseMinValue)&&(this._releaseMinValue=s)}}doLayout(){super.doLayout();const e=this._maxBendValue*rh.BendValueHeight;this.renderer.registerOverflowTop(e);let t=0;for(const e of this._notes){const s=this._renderPoints.get(e.id);switch(e.bendType){case y.Bend:s[1].lineValue=e.isTieOrigin?this._bendEndContinuedMinValue:this._bendEndMinValue;break;case y.Release:t=e.isTieOrigin?this._releaseContinuedMinValue:this._releaseMinValue,t>=0&&(s[1].lineValue=t);break;case y.BendRelease:s[1].lineValue=this._bendMiddleMinValue,t=e.isTieOrigin?this._releaseContinuedMinValue:this._releaseMinValue,t>=0&&(s[2].lineValue=t);break;case y.Prebend:s[0].lineValue=this._preBendMinValue;break;case y.PrebendBend:s[0].lineValue=this._preBendMinValue,s[1].lineValue=e.isTieOrigin?this._bendEndContinuedMinValue:this._bendEndMinValue;break;case y.PrebendRelease:s[0].lineValue=this._preBendMinValue,t=e.isTieOrigin?this._releaseContinuedMinValue:this._releaseMinValue,t>=0&&(s[1].lineValue=t)}}this.width=0,this._notes.sort(((e,t)=>e.isStringed?e.string-t.string:e.realValue-t.realValue))}createRenderingPoints(e){const t=[];switch(e.bendType){case y.Custom:for(const s of e.bendPoints)t.push(new ah(s.offset,s.value));break;case y.BendRelease:t.push(new ah(0,e.bendPoints[0].value)),t.push(new ah(X.MaxPosition/2|0,e.bendPoints[1].value)),t.push(new ah(X.MaxPosition,e.bendPoints[3].value));break;case y.Bend:case y.Hold:case y.Prebend:case y.PrebendBend:case y.PrebendRelease:case y.Release:t.push(new ah(0,e.bendPoints[0].value)),t.push(new ah(X.MaxPosition,e.bendPoints[1].value))}return t}paint(e,t,s){const i=s.color;this._notes.length>1&&(s.color=this.renderer.resources.secondaryGlyphColor);for(const a of this._notes){const r=this._renderPoints.get(a.id),n=this.renderer;let o=a,h=!1,l=null,c=!1;const d=a.bendStyle===f.Gradual?"grad.":"";let u=null;for(;o.isTieOrigin;){const e=o.tieDestination;if(l=this.renderer.scoreRenderer.layout.getRendererForBar(this.renderer.staff.staffId,e.beat.voice.bar),!l||n.staff!==l.staff)break;if(o=e,h=!0,o.hasBend||!this.renderer.settings.notation.extendBendArrowsOnTiedNotes||o.vibrato!==P.None){c=!0;break}}u=o.beat,l=this.renderer.scoreRenderer.layout.getRendererForBar(this.renderer.staff.staffId,u.voice.bar),u.isLastOfVoice&&!o.hasBend&&this.renderer.settings.notation.extendBendArrowsOnTiedNotes&&(u=null);let p=0,g=0;const m=t+n.y;p=e+n.x,r[0].value>0||a.isContinuedBend?p+=n.getBeatX(a.beat,ts.MiddleNotes):p+=n.getNoteX(a,as.Right),g=!u||u.isLastOfVoice&&!c?e+l.x+l.postBeatGlyphsStart:c||!u.nextBeat?e+l.x+l.getBeatX(u,ts.MiddleNotes):a.bendType===y.Hold?e+l.x+l.getBeatX(u.nextBeat,ts.OnNotes):e+l.x+l.getBeatX(u.nextBeat,ts.PreNotes),h||(g-=rh.ArrowSize);const b=(g-p)/X.MaxPosition;s.beginPath();for(let e=0,t=r.length-1;e<t;e++){const t=r[e];let i=r[e+1];0!==e||0===t.value||a.isTieDestination||this.paintBend(a,new ah(0,0),t,p,m,b,d,s),a.bendType!==y.Prebend?(0===e&&(p+=2),this.paintBend(a,t,i,p,m,b,d,s)):a.isTieOrigin&&a.tieDestination.hasBend&&(i=new ah(X.MaxPosition,t.value),i.lineValue=t.lineValue,this.paintBend(a,t,i,p,m,b,d,s))}if(o.vibrato!==P.None){const i=g-e+rh.ArrowSize-l.x,a=m-t-rh.BendValueHeight*r[r.length-1].lineValue,n=new Bo(i,a,o.vibrato,1.2);n.beat=o.beat,n.renderer=l,n.doLayout(),n.paint(e+l.x,t,s)}s.color=i}}paintBend(e,t,s,i,a,r,n,o){const h=this.renderer,l=this.renderer.resources,c=h.lineOffset/2,d=i+r*t.offset,u=rh.BendValueHeight;let p=a-u*t.lineValue;0===t.value?s.offset===t.offset?p+=h.getNoteY(e.beat.maxStringNote,is.Top):p+=h.getNoteY(e,is.Center):p+=c;const g=i+r*s.offset;let m=a-u*s.lineValue;0===s.lineValue?m+=h.getNoteY(e,is.Center):m+=c;let f=0;const y=rh.ArrowSize;if(s.value>t.value?(m+y>p&&(m=p-y),o.beginPath(),o.moveTo(g,m),o.lineTo(g-.5*y,m+y),o.lineTo(g+.5*y,m+y),o.closePath(),o.fill(),f=y):s.value!==t.value&&(m<p&&(m=p+y),o.beginPath(),o.moveTo(g,m),o.lineTo(g-.5*y,m-y),o.lineTo(g+.5*y,m-y),o.closePath(),o.fill(),f=-y),o.beginPath(),t.value===s.value){if(t.lineValue>0){let e=g;const t=rh.DashSize,s=d+t;if((e-d)/(2*t)<1)o.moveTo(e,p),o.lineTo(d,p);else for(;e>s;)o.moveTo(e,p),o.lineTo(e-t,p),e-=2*t;o.stroke()}}else g>d?(o.moveTo(d,p),o.bezierCurveTo((d+g)/2,p,g,p,g,m+f),o.stroke()):(o.moveTo(d,p),o.lineTo(g,m),o.stroke());if(n&&t.offset<s.offset){o.font=l.graceFont;const e=o.measureText(n).width;let t=0,s=0;if(p>m){const i=Math.abs(p-m);t=i>1.3*o.font.size?p-i/2:p,s=(d+g-e)/2}else t=p,s=g-e;o.fillText(n,s,t)}if(0!==s.value&&t.value!==s.value){let e=s.value;const i=s.value>t.value;e=Math.abs(e);let r="";if(4===e)r="full",e-=4;else if(e>=4||e<=-4){const t=e/4|0;r+=t,e-=4*t}if(e>0&&(r+=rh.getFractionSign(e)),""!==r){m=a-u*s.value;let e=m;i||(e=p+1*Math.abs(m-p)/3),o.font=l.tablatureFont;const t=o.measureText(r).width,n=e-.5*l.tablatureFont.size-2,h=g-t/2;o.fillText(r,h,n)}}}static getFractionSign(e){switch(e){case 1:return"¼";case 2:return"½";case 3:return"¾";default:return`${e}/ 4`}}}rh.ArrowSize=6,rh.DashSize=3,rh.BendValueHeight=6;class nh extends kr{constructor(e){super(0,0),this._isSimpleDip=!1,this._beat=e,this._renderPoints=this.createRenderingPoints(e)}createRenderingPoints(e){if(e.whammyBarType===ce.Custom)return e.whammyBarPoints;const t=[];switch(e.whammyBarType){case ce.Dive:case ce.Hold:case ce.PrediveDive:case ce.Predive:t.push(new X(0,e.whammyBarPoints[0].value)),t.push(new X(X.MaxPosition,e.whammyBarPoints[1].value));break;case ce.Dip:t.push(new X(0,e.whammyBarPoints[0].value)),t.push(new X(X.MaxPosition/2|0,e.whammyBarPoints[1].value)),t.push(new X(X.MaxPosition,e.whammyBarPoints[e.whammyBarPoints.length-1].value))}return t}doLayout(){super.doLayout(),this._isSimpleDip=this.renderer.settings.notation.notationMode===D.SongBook&&this._beat.whammyBarType===ce.Dip;let e=null,t=null,s=this._beat;for(;s&&s.hasWhammyBar;)(!e||e.value>s.minWhammyPoint.value)&&(e=s.minWhammyPoint),(!t||t.value<s.maxWhammyPoint.value)&&(t=s.maxWhammyPoint),s=s.nextBeat;let i=t.value>0?Math.abs(this.getOffset(t.value)):0;(i>0||0!==this._beat.whammyBarPoints[0].value||this.renderer.settings.notation.isNotationElementVisible(E.ZerosOnDiveWhammys))&&(i+=2*this.renderer.resources.tablatureFont.size);const a=e.value<0?Math.abs(this.getOffset(e.value)):0;this.renderer.registerOverflowTop(i+a);i>this.renderer.staff.getSharedLayoutData(nh.TopOffsetSharedDataKey,-1)&&this.renderer.staff.setSharedLayoutData(nh.TopOffsetSharedDataKey,i)}getOffset(e){if(0===e)return 0;let t=nh.PerHalfSize+Math.log2(Math.abs(e)/2)*nh.PerHalfSize;return e<0&&(t=-t),t}paint(e,t,s){const i=rn.beat(s,ye.StandardNotationEffects,this._beat);try{const i=this.renderer;let a=this._beat.nextBeat,r=null,n=ts.PreNotes;a&&(r=this.renderer.scoreRenderer.layout.getRendererForBar(this.renderer.staff.staffId,a.voice.bar),r&&r.staff===i.staff&&(r===i||a.hasWhammyBar)?n=!a.hasWhammyBar||i.settings.notation.notationMode===D.SongBook&&a.whammyBarType===ce.Dip?ts.PreNotes:ts.MiddleNotes:(a=null,r=null));let o=0,h=0;this._isSimpleDip?(o=e+i.x+i.getBeatX(this._beat,ts.OnNotes)-2,h=e+i.x+i.getBeatX(this._beat,ts.PostNotes)+2):(o=e+i.x+i.getBeatX(this._beat,ts.MiddleNotes),h=r?e+r.x+r.getBeatX(a,n):e+i.x+i.width-2);const l=s.textAlign;if(s.textAlign=ne.Center,this._renderPoints.length>=2){const e=(h-o)/X.MaxPosition;s.beginPath();const i=t+this.renderer.staff.getSharedLayoutData(nh.TopOffsetSharedDataKey,0);let a=this._beat.whammyStyle===f.Gradual?"grad.":"";for(let t=0,r=this._renderPoints.length-1;t<r;t++){const n=this._renderPoints[t],h=this._renderPoints[t+1],l=t<r-2?this._renderPoints[t+2]:null;let c=0===t;0!==t||0===n.value||this._beat.isContinuedWhammy||(this.paintWhammy(!1,new X(0,0),n,h,o,i,e,s),c=!1),this.paintWhammy(c,n,h,l,o,i,e,s,a),a=""}s.stroke()}s.textAlign=l}finally{i?.[Symbol.dispose]?.()}}paintWhammy(e,t,s,i,a,r,n,o,h){const l=a+n*t.offset,c=a+n*s.offset,d=r-this.getOffset(t.value),u=r-this.getOffset(s.value);if(t.offset===s.offset){const e=nh.DashSize;if(Math.abs(u-d)/(2*e)<1)o.moveTo(l,d),o.lineTo(c,u);else{const t=Math.max(d,u);let s=Math.min(d,u);for(;t>s;)o.moveTo(l,s),o.lineTo(l,s+e),s+=2*e}o.stroke()}else if(t.value===s.value){const e=nh.DashSize;if(Math.abs(c-l)/(2*e)<1)o.moveTo(l,d),o.lineTo(c,u);else{let t=Math.max(l,c);const s=Math.min(l,c);for(;t>s;)o.moveTo(t,d),o.lineTo(t-e,d),t-=2*e}o.stroke()}else o.moveTo(l,d),o.lineTo(c,u);const p=this.renderer.resources;if(e&&!this._beat.isContinuedWhammy&&!this._isSimpleDip){let e=d;e-=p.tablatureFont.size+2,this.renderer.settings.notation.isNotationElementVisible(E.ZerosOnDiveWhammys)&&o.fillText("0",l,e),h&&(e-=p.tablatureFont.size+2,o.fillText(h,l,e))}let g=Math.abs(s.value);if((0!==g||this.renderer.settings.notation.isNotationElementVisible(E.ZerosOnDiveWhammys)&&!this._isSimpleDip)&&t.value!==s.value){let e="";if(s.value<0&&(e+="-"),g>=4){const t=g/4|0;e+=t,g-=4*t}else 0===g&&(e+="0");g>0&&(e+=rh.getFractionSign(g));let a=0;this._isSimpleDip?a=Math.min(d,u)-p.tablatureFont.size-2:(a=t.offset===s.offset?Math.min(d,u):u,a-=p.tablatureFont.size+2,i&&i.value>s.value&&(a-=2));const r=c;o.fillText(e,r,a)}}}nh.TopOffsetSharedDataKey="tab.whammy.topoffset",nh.PerHalfSize=6,nh.DashSize=3;class oh extends ih{constructor(e){super(0,0),this._beat=e}doLayout(){const e=this.renderer.settings.notation.notationMode;switch(this._beat.whammyBarType){case ce.None:case ce.Custom:case ce.Hold:return;case ce.Dive:case ce.PrediveDive:{const e=new sh(this._beat,!1);e.renderer=this.renderer;const t=this._beat.whammyBarPoints[this._beat.whammyBarPoints.length-1];for(const s of this._beat.notes)s.isTieOrigin||e.addGlyph(this.getBendNoteValue(s,t),t.value%2!=0,void 0);e.doLayout(),this.BendNoteHeads.push(e)}break;case ce.Dip:if(e===D.SongBook){const e=this.renderer.resources;this.renderer.simpleWhammyOverflow=1.5*e.tablatureFont.size+oh.SimpleDipHeight+oh.SimpleDipPadding}else{const e=new sh(this._beat,!1);if(e.renderer=this.renderer,this.renderer.settings.notation.notationMode===D.GuitarPro){const t=this._beat.whammyBarPoints[1];for(const s of this._beat.notes)e.addGlyph(this.getBendNoteValue(s,this._beat.whammyBarPoints[1]),t.value%2!=0,void 0)}e.doLayout(),this.BendNoteHeads.push(e);const t=new sh(this._beat,!1);if(t.renderer=this.renderer,this.renderer.settings.notation.notationMode===D.GuitarPro){const e=this._beat.whammyBarPoints[this._beat.whammyBarPoints.length-1];for(const s of this._beat.notes)t.addGlyph(this.getBendNoteValue(s,e),e.value%2!=0,void 0)}t.doLayout(),this.BendNoteHeads.push(t)}case ce.Predive:}super.doLayout()}paint(e,t,s){const i=this._beat;switch(i.whammyBarType){case ce.None:case ce.Custom:return}const a=this.renderer.settings.notation.notationMode,r=this.renderer.scoreRenderer.layout.getRendererForBar(this.renderer.staff.staffId,i.voice.bar),n=rn.beat(s,ye.StandardNotationEffects,i);try{const n=e+r.x+r.getBeatX(i,ts.MiddleNotes),o=this.getTieDirection(i,r);let h=1===this._beat.notes.length?o:Te.Up;const l=s.textAlign,c=Nr.Heights.get(re.NoteheadBlack);for(let l=0;l<i.notes.length;l++){const d=i.notes[l],u=rn.note(s,le.StandardNotationEffects,d);try{let u=t+r.y;l>0&&l>=(this._beat.notes.length/2|0)&&(h=Te.Down),h===Te.Down?u+=r.getNoteY(d,is.Bottom):u+=r.getNoteY(d,is.Top);let p=e+r.x;i.isLastOfVoice?p+=r.width:p+=r.getBeatX(i,ts.EndBeat),p-=8;const g=i.whammyStyle===f.Gradual&&0===l?"grad.":"";let m=null;d.isTieOrigin&&(m=this.renderer.scoreRenderer.layout.getRendererForBar(this.renderer.staff.staffId,d.tieDestination.beat.voice.bar),m&&m.staff===r.staff?p=e+m.x+m.getBeatX(d.tieDestination.beat,ts.MiddleNotes):m=null);let y=c*vr.GraceScale*.5;h===Te.Up&&(y=-y);const b=i.whammyBarPoints.length>0?this.getBendNoteValue(d,i.whammyBarPoints[i.whammyBarPoints.length-1]):0;let S=0,_=!1;switch(this.BendNoteHeads.length>0&&this.BendNoteHeads[0].containsNoteValue(b)?(S=this.BendNoteHeads[0].getNoteValueY(b)+y,_=!0):m&&(d.isTieOrigin&&d.tieDestination.beat.hasWhammyBar||d.beat.isContinuedWhammy)?(S=t+m.y+m.getNoteY(d.tieDestination,is.Top),_=!0,h===Te.Down&&(S+=c)):d.isTieOrigin&&(S=m?t+m.y+m.getNoteY(d.tieDestination,is.Top):u,h===Te.Down&&(S+=c)),i.whammyBarType){case ce.Hold:d.isTieOrigin&&Uo.paintTie(s,1,n,u,p,S,o===Te.Down,22,4);break;case ce.Dive:if(0===l){this.BendNoteHeads[0].x=p-this.BendNoteHeads[0].noteHeadOffset;const e=this.BendNoteHeads[0].y;this.BendNoteHeads[0].y=t+r.y,this.BendNoteHeads[0].paint(0,0,s),this.BendNoteHeads[0].containsNoteValue(b)&&(S-=e,S+=this.BendNoteHeads[0].y)}_?this.drawBendSlur(s,n,u,p,S,h===Te.Down,1,g):d.isTieOrigin&&Uo.paintTie(s,1,n,u,p,S,o===Te.Down,22,4);break;case ce.Dip:if(a===D.SongBook){if(0===l){const i=e+r.x+r.getBeatX(this._beat,ts.OnNotes)-2,a=e+r.x+r.getBeatX(this._beat,ts.PostNotes)+2,n=(i+a)/2,o=((this._beat.whammyBarPoints[1].value-this._beat.whammyBarPoints[0].value)/4|0).toString();s.font=this.renderer.resources.tablatureFont,s.fillText(o,n,t+this.y);const h=t+this.y+s.font.size+2,l=h+oh.SimpleDipHeight;this._beat.whammyBarPoints[1].value>this._beat.whammyBarPoints[0].value?(s.moveTo(i,l),s.lineTo(n,h),s.lineTo(a,l)):(s.moveTo(i,h),s.lineTo(n,l),s.lineTo(a,h)),s.stroke()}d.isTieOrigin&&Uo.paintTie(s,1,n,u,p,S,o===Te.Down,22,4)}else{const e=(n+p)/2;this.BendNoteHeads[0].x=e-this.BendNoteHeads[0].noteHeadOffset,this.BendNoteHeads[0].y=t+r.y,this.BendNoteHeads[0].paint(0,0,s);const a=this.getBendNoteValue(d,i.whammyBarPoints[1]),o=this.BendNoteHeads[0].getNoteValueY(a)+y;this.drawBendSlur(s,n,u,e,o,h===Te.Down,1,g),this.BendNoteHeads[1].x=p-this.BendNoteHeads[1].noteHeadOffset,this.BendNoteHeads[1].y=t+r.y,this.BendNoteHeads[1].paint(0,0,s),S=this.BendNoteHeads[1].getNoteValueY(b)+y,this.drawBendSlur(s,e,o,p,S,h===Te.Down,1,g)}break;case ce.PrediveDive:case ce.Predive:let c=e+r.x+r.getBeatX(d.beat,ts.PreNotes);c+=r.getPreNotesGlyphForBeat(d.beat).prebendNoteHeadOffset;const m=t+r.y+r.getScoreY(r.accidentalHelper.getNoteLineForValue(d.displayValue-(d.beat.whammyBarPoints[0].value/2|0),!1))+y;this.drawBendSlur(s,c,m,n,u,h===Te.Down,1,g),this.BendNoteHeads.length>0&&(this.BendNoteHeads[0].x=p-this.BendNoteHeads[0].noteHeadOffset,this.BendNoteHeads[0].y=t+r.y,this.BendNoteHeads[0].paint(0,0,s),this.drawBendSlur(s,n,u,p,S,h===Te.Down,1,g))}}finally{u?.[Symbol.dispose]?.()}}s.textAlign=l}finally{n?.[Symbol.dispose]?.()}}getBendNoteValue(e,t){return e.displayValueWithoutBend+(t.value/2|0)}}oh.SimpleDipHeight=2*nh.PerHalfSize,oh.SimpleDipPadding=2;class hh extends kr{constructor(e,t,s){super(e,t),this.width=s}}class lh extends xr{constructor(e,t,s,i,a){super(e,t,a?vr.GraceScale:1,s.getSymbol(i)),this._isGrace=a,this._articulation=s}paint(e,t,s){const i=s.color;this.colorOverride&&(s.color=this.colorOverride);const a=this._isGrace?1:0;s.fillMusicFontSymbol(e+this.x,t+this.y+a,this.glyphScale,this.symbol,!1),this._articulation.techniqueSymbol!==re.None&&this._articulation.techniqueSymbolPlacement===oe.Middle&&s.fillMusicFontSymbol(e+this.x,t+this.y+a,this.glyphScale,this._articulation.techniqueSymbol,!1),s.color=i}doLayout(){super.doLayout(),0===this.width&&(this.height=Nr.Widths.get(re.NoteheadBlack)),0===this.height&&(this.height=Nr.Heights.get(re.NoteheadBlack))}}class ch extends xr{constructor(e,t){super(e,t,vr.GraceScale,re.ArticStaccatoAbove)}paint(e,t,s){super.paint(e+3,t+5,s)}}class dh extends xr{constructor(e,t){super(e,t,.5,re.PictEdgeOfCymbal)}paint(e,t,s){super.paint(e-3,t+this.height,s)}}class uh extends xr{constructor(e,t,s=!1){super(e,t,vr.GraceScale,re.GuitarGolpe),this.center=s}paint(e,t,s){super.paint(e,t+this.height,s)}}class ph extends Tr{constructor(){super(...arguments),this._strings=new Set}addString(e){this._strings.add(e)}doLayout(){const e=Nr.Widths.get(re.GuitarString0)*Cn.CircleNumberScale;this.height=(e+3)*this._strings.size,this.width=e}paint(e,t,s){const i=this.renderer.bar.staff.tuning.length;let a=0;const r=Nr.Widths.get(re.GuitarString0)*Cn.CircleNumberScale,n=Nr.Heights.get(re.NoteheadBlack);for(const o of this._strings){const h=i-o,l=re.GuitarString1+h;s.fillMusicFontSymbol(e+this.x+n/2,t+this.y+r+a,Cn.CircleNumberScale,l,!0),a+=r+3}}}class gh extends Tr{constructor(e,t,s,i,a){super(e,t),this.beatEffects=new Map,this.noteHeadElement=le.SlashNoteHead,this.effectElement=ye.SlashEffects,this._isGrace=i,this._symbol=gh.getSymbol(s),this.beat=a}paint(e,t,s){const i=0===this.beat.notes.length?void 0:rn.note(s,this.noteHeadElement,this.beat.notes[0]);try{const i=this._isGrace?1:0,a=this._isGrace?vr.GraceScale:1;s.fillMusicFontSymbol(e+this.x,t+this.y+i,a,this._symbol,!1),this.paintEffects(e,t,s)}finally{i?.[Symbol.dispose]?.()}}paintEffects(e,t,s){const i=rn.beat(s,this.effectElement,this.beat);try{for(const i of this.beatEffects.values())i.paint(e+this.x,t+this.y,s)}finally{i?.[Symbol.dispose]?.()}}doLayout(){const e=this._isGrace?vr.GraceScale:1;this.width=Nr.Widths.get(this._symbol)*e,this.height=Nr.Heights.get(this._symbol)*e;let t=Nr.Heights.get(this._symbol);for(const e of this.beatEffects.values())e.y+=t,e.x+=this.width/2,e.renderer=this.renderer,t+=7,e.doLayout()}static getSymbol(e){switch(e){case _.QuadrupleWhole:case _.DoubleWhole:case _.Whole:return re.NoteheadSlashWhiteWhole;case _.Half:return re.NoteheadSlashWhiteHalf;default:return re.NoteheadSlashVerticalEnds}}updateBeamingHelper(e){this.beamingHelper&&this.beamingHelper.registerBeatLineX("slash",this.beat,e+this.x+this.width,e+this.x)}}class mh extends Mn{constructor(){super(...arguments),this._collisionOffset=-1e3,this._skipPaint=!1,this.slash=null,this.noteHeads=null,this.restGlyph=null}get effectElement(){return ye.StandardNotationEffects}getNoteX(e,t){return this.noteHeads?this.noteHeads.getNoteX(e,t):0}buildBoundingsLookup(e,t,s){this.noteHeads&&this.noteHeads.buildBoundingsLookup(e,t+this.x,s+this.y)}getNoteY(e,t){return this.noteHeads?this.noteHeads.getNoteY(e,t):0}updateBeamingHelper(){if(this.noteHeads)this.noteHeads.updateBeamingHelper(this.container.x+this.x);else if(this.restGlyph){if(this.restGlyph.updateBeamingHelper(this.container.x+this.x),this.renderer.bar.isMultiVoice&&-1e3===this._collisionOffset){this._collisionOffset=this.renderer.helpers.collisionHelper.applyRestCollisionOffset(this.container.beat,this.restGlyph.y,this.renderer.getScoreHeight(1)),this.y+=this._collisionOffset;const e=this.renderer.helpers.collisionHelper.restDurationsByDisplayTime;e.has(this.container.beat.playbackStart)&&e.get(this.container.beat.playbackStart).has(this.container.beat.playbackDuration)&&e.get(this.container.beat.playbackStart).get(this.container.beat.playbackDuration)!==this.container.beat.id&&(this._skipPaint=!0)}}else this.slash&&this.slash.updateBeamingHelper(this.container.x+this.x)}paint(e,t,s){this._skipPaint||super.paint(e,t,s)}doLayout(){const e=this.renderer;if(!this.container.beat.isEmpty)if(this.container.beat.isRest){let t=2*Math.ceil((this.renderer.bar.staff.standardNotationLineCount-1)/2);this.container.beat.duration===_.Whole&&1!==this.renderer.bar.staff.standardNotationLineCount&&3!==this.renderer.bar.staff.standardNotationLineCount&&(t-=2);const s=new Zo(0,e.getScoreY(t),this.container.beat.duration);if(this.restGlyph=s,s.beat=this.container.beat,s.beamingHelper=this.beamingHelper,this.addNormal(s),this.renderer.bar.isMultiVoice)if(0===this.container.beat.voice.index){const t=cn.computeLineHeightsForRest(this.container.beat.duration),i=s.y-e.getScoreHeight(t[0]),a=s.y+e.getScoreHeight(t[1]);this.renderer.helpers.collisionHelper.reserveBeatSlot(this.container.beat,i,a)}else this.renderer.helpers.collisionHelper.registerRest(this.container.beat);if(this.beamingHelper&&this.beamingHelper.applyRest(this.container.beat,t),this.container.beat.dots>0){this.addNormal(new hh(0,0,5));for(let e=0;e<this.container.beat.dots;e++){const e=new sn(0,0);e.renderer=this.renderer,this.createBeatDot(t,e),this.addEffect(e)}}}else{if(this.container.beat.slashed){const t=this.container.beat.graceType!==w.None,s=(e.heightLineCount-1)/2,i=e.getLineY(s),a=new gh(0,i,this.container.beat.duration,t,this.container.beat);a.noteHeadElement=le.StandardNotationNoteHead,a.effectElement=ye.StandardNotationEffects,this.slash=a,a.beat=this.container.beat,a.beamingHelper=this.beamingHelper,this.addNormal(a)}else{const e=new Qo;this.noteHeads=e,e.beat=this.container.beat,e.beamingHelper=this.beamingHelper;const t=new Yo(!1);t.renderer=this.renderer;for(const e of this.container.beat.notes)e.isVisible&&(this.createNoteGlyph(e),t.addParenthesis(e));this.addNormal(e),t.isEmpty||(this.addNormal(new hh(0,0,4*(this.container.beat.graceType!==w.None?vr.GraceScale:1))),this.addEffect(t))}if(this.container.beat.hasWhammyBar){const e=new oh(this.container.beat);e.renderer=this.renderer,e.doLayout(),this.container.ties.push(e)}if(this.container.beat.dots>0){this.addNormal(new hh(0,0,5));for(let t=0;t<this.container.beat.dots;t++){const t=new sn(0,0);t.renderer=this.renderer;for(const s of this.container.beat.notes){this.createBeatDot(e.getNoteLine(s),t).colorOverride=rn.noteColor(e.resources,le.StandardNotationEffects,s)}this.addEffect(t)}}}super.doLayout(),this.container.beat.isEmpty?this.centerX=this.width/2:this.restGlyph?this.centerX=this.restGlyph.x+this.restGlyph.width/2:this.noteHeads?this.centerX=this.noteHeads.x+this.noteHeads.width/2:this.slash&&(this.centerX=this.slash.x+this.slash.width/2)}createBeatDot(e,t){const s=this.renderer,i=new Vo(0,s.getScoreY(e),1.5);return t.addGlyph(i),i}createNoteHeadGlyph(e){const t=this.container.beat.graceType!==w.None,s=e.style;if(void 0!==s?.noteHead){const i=new vr(0,0,e.beat.duration,t);return i.symbol=s.noteHead,s.noteHeadCenterOnStem&&(i.centerOnStem=!0),i}if(e.beat.voice.bar.staff.isPercussion){const s=Le.getArticulation(e);if(s)return new lh(0,0,s,e.beat.duration,t);q.warning("Rendering",`No articulation found for percussion instrument ${e.percussionArticulation}`)}return e.isDead?new Go(0,0,t):e.beat.graceType===w.BendGrace?new vr(0,0,_.Quarter,!0):e.harmonicType===T.Natural?new zo(0,0,e.beat.duration,t):new vr(0,0,e.beat.duration,t)}createNoteGlyph(e){if(e.beat.graceType===w.BendGrace&&!e.hasBend)return;const t=this.renderer,s=this.createNoteHeadGlyph(e);s.colorOverride=rn.noteColor(t.resources,le.StandardNotationNoteHead,e);let i=t.getNoteLine(e);if(s.y=t.getScoreY(i),this.noteHeads.addNoteGlyph(s,e,i),e.harmonicType!==T.None&&e.harmonicType!==T.Natural){const a=e.displayValue+e.harmonicPitch,r=new zo(0,0,e.beat.duration,this.container.beat.graceType!==w.None);r.colorOverride=s.colorOverride,i=t.accidentalHelper.getNoteLineForValue(a,!1),r.y=t.getScoreY(i),this.noteHeads.addNoteGlyph(r,e,i)}const a=this.noteHeads.belowBeatEffects,r=this.noteHeads.aboveBeatEffects;if(e.isStaccato&&!a.has("Staccato")&&a.set("Staccato",new ch(0,0)),e.accentuated!==B.Normal||a.has("Accent")||a.set("Accent",new Wo(0,0,e)),e.accentuated!==B.Heavy||a.has("HAccent")||a.set("HAccent",new Wo(0,0,e)),e.accentuated!==B.Tenuto||a.has("Tenuto")||a.set("Tenuto",new Wo(0,0,e)),e.showStringNumber&&e.isStringed){let t;r.has("StringNumber")?t=r.get("StringNumber"):(t=new ph(0,0),r.set("StringNumber",t)),t.addString(e.string)}if(e.isPercussion){const t=Le.getArticulation(e);if(t&&t.techniqueSymbolPlacement!==oe.Middle){const e=t.techniqueSymbolPlacement===oe.Top?this.noteHeads.aboveBeatEffects:this.noteHeads.belowBeatEffects;switch(t.techniqueSymbol){case re.PictEdgeOfCymbal:e.set("PictEdgeOfCymbal",new dh(0,0));break;case re.ArticStaccatoAbove:e.set("ArticStaccatoAbove",new ch(0,0));break;case re.StringsUpBow:e.set("StringsUpBow",new bo(0,0,ae.Up));break;case re.StringsDownBow:e.set("StringsDownBow",new bo(0,0,ae.Down));break;case re.GuitarGolpe:e.set("GuitarGolpe",new uh(0,0))}}}}}class fh extends kr{constructor(e){super(0,0),this._beat=e}doLayout(){this.width=this._beat.brushType===b.ArpeggioUp||this._beat.brushType===b.ArpeggioDown?10:0}paint(e,t,s){if(this._beat.brushType===b.ArpeggioUp||this._beat.brushType===b.ArpeggioDown){const i=this.renderer,a=i.lineOffset,r=t+this.y+(i.getNoteY(this._beat.maxNote,is.Bottom)-a),n=t+this.y+i.getNoteY(this._beat.minNote,is.Top)+a,o=e+this.x+this.width/2,h=8,l=new Bo(0,0,P.Slight,1.2,!0);l.renderer=this.renderer,l.doLayout();const c=-l.height/2;if(this._beat.brushType===b.ArpeggioUp){const t=r+h,i=n-h;l.width=Math.abs(i-t),s.beginRotate(e+this.x+5,i,-90),l.paint(0,c,s),s.endRotate(),s.beginPath(),s.moveTo(o,n),s.lineTo(o+h/2,n-h),s.lineTo(o-h/2,n-h),s.closePath(),s.fill()}else if(this._beat.brushType===b.ArpeggioDown){const t=r+h,i=n;l.width=Math.abs(i-t),s.beginRotate(e+this.x+5,t,90),l.paint(0,c,s),s.endRotate(),s.beginPath(),s.moveTo(o,r),s.lineTo(o+h/2,r+h),s.lineTo(o-h/2,r+h),s.closePath(),s.fill()}}}}class yh{constructor(e,t){this.line=0,this.line=e,this.text=t}}class bh extends sn{constructor(){super(0,0),this._infos=new Map}get isEmpty(){return 0===this._infos.size}addFingers(e){const t=this.renderer.settings;if(t.notation.fingeringMode!==C.ScoreDefault&&t.notation.fingeringMode!==C.ScoreForcePiano)return;const s=ie.fingerToString(this.renderer.settings,e.beat,e.leftHandFinger,!0);s&&this.addFinger(e,s);const i=ie.fingerToString(this.renderer.settings,e.beat,e.rightHandFinger,!1);i&&this.addFinger(e,i)}addFinger(e,t){const s=this.renderer,i=s.getNoteLine(e);if(this._infos.has(i)){this._infos.get(i).text+=t}else{const a=new yh(i,t);a.color=rn.noteColor(s.resources,le.StandardNotationEffects,e),this._infos.set(i,a)}}doLayout(){const e=this.renderer;for(const[t,s]of this._infos){const t=new Sn(0,0,s.text,e.resources.inlineFingeringFont,ne.Left,oe.Middle);t.colorOverride=s.color,t.renderer=e,t.y=e.getScoreY(s.line),t.doLayout(),this.addGlyph(t),this.width=Math.max(this.width,t.width)}}}class Sh extends Ln{constructor(){super(...arguments),this._prebends=null,this.accidentals=null}get prebendNoteHeadOffset(){return this._prebends?this._prebends.x+this._prebends.noteHeadOffset:0}get effectElement(){return ye.StandardNotationEffects}doLayout(){if(!this.container.beat.isRest){const e=new th;e.renderer=this.renderer;const t=new bh;t.renderer=this.renderer;const s=new Yo(!0);s.renderer=this.renderer;const i=new sh(this.container.beat,!0);this._prebends=i,i.renderer=this.renderer;for(const a of this.container.beat.notes){const r=rn.noteColor(this.renderer.resources,le.StandardNotationEffects,a);if(a.isVisible){if(a.hasBend)switch(a.bendType){case y.PrebendBend:case y.Prebend:case y.PrebendRelease:i.addGlyph(a.displayValue-(a.bendPoints[0].value/2|0),!1,r)}else if(a.beat.hasWhammyBar)switch(a.beat.whammyBarType){case ce.PrediveDive:case ce.Predive:this._prebends.addGlyph(a.displayValue-(a.beat.whammyBarPoints[0].value/2|0),!1,r)}this.createAccidentalGlyph(a,e),s.addParenthesis(a),t.addFingers(a)}}i.isEmpty||(this.addEffect(i),this.addNormal(new hh(0,0,4*(this.container.beat.graceType!==w.None?vr.GraceScale:1)))),this.container.beat.brushType!==b.None&&(this.addEffect(new fh(this.container.beat)),this.addNormal(new hh(0,0,4))),t.isEmpty||(this.isEmpty||this.addNormal(new hh(0,0,2*(this.container.beat.graceType!==w.None?vr.GraceScale:1))),this.addEffect(t),this.addNormal(new hh(0,0,2*(this.container.beat.graceType!==w.None?vr.GraceScale:1)))),s.isEmpty||(this.addEffect(s),this.addNormal(new hh(0,0,4*(this.container.beat.graceType!==w.None?vr.GraceScale:1)))),e.isEmpty||(this.accidentals=e,this.isEmpty||this.addNormal(new hh(0,0,2*(this.container.beat.graceType!==w.None?vr.GraceScale:1))),this.addNormal(e),this.addNormal(new hh(0,0,2*(this.container.beat.graceType!==w.None?vr.GraceScale:1))))}super.doLayout()}createAccidentalGlyph(e,t){const s=this.renderer;let i=s.accidentalHelper.applyAccidental(e),a=s.getNoteLine(e);const r=this.container.beat.graceType!==w.None,n=rn.noteColor(s.resources,le.StandardNotationAccidentals,e),o=r?vr.GraceScale:1;if(i!==It.None){const e=new Oo(0,s.getScoreY(a),i,o);e.colorOverride=n,e.renderer=this.renderer,t.addGlyph(e)}if(e.harmonicType!==T.None&&e.harmonicType!==T.Natural){const h=e.displayValue+e.harmonicPitch;i=s.accidentalHelper.applyAccidentalForValue(e.beat,h,r,!1),a=s.accidentalHelper.getNoteLineForValue(h,!1);const l=new Oo(0,s.getScoreY(a),i,o);l.colorOverride=n,l.renderer=this.renderer,t.addGlyph(l)}}}class _h extends sn{constructor(e,t,s,i,a,r){super(e,t),this._numerator=0,this._denominator=0,this.barSubElement=u.StandardNotationTimeSignature,this._numerator=s,this._denominator=i,this._isCommon=a,this._isFreeTime=r}paint(e,t,s){const i=rn.bar(s,this.barSubElement,this.renderer.bar);try{super.paint(e,t,s)}finally{i?.[Symbol.dispose]?.()}}doLayout(){let e=0;const t=In.numberHeight;if(this._isFreeTime){const s=new Xo(!0);s.renderer=this.renderer,s.y=-t,s.height=2*t,s.doLayout(),this.addGlyph(s),e+=s.width+10}if(this._isCommon&&2===this._numerator&&2===this._denominator){const t=new xr(e,0,this.commonScale,re.TimeSigCutCommon);this.addGlyph(t),super.doLayout()}else if(this._isCommon&&4===this._numerator&&4===this._denominator){const t=new xr(e,0,this.commonScale,re.TimeSigCommon);this.addGlyph(t),super.doLayout()}else{const s=new In(e,-t/2,this._numerator,this.numberScale),i=new In(e,t/2,this._denominator,this.numberScale);this.addGlyph(s),this.addGlyph(i),super.doLayout();const a=this.width-e;s.x=e+(a-s.width)/2,i.x=e+(a-i.width)/2}if(this._isFreeTime){const e=new Xo(!1);e.renderer=this.renderer,e.x=this.width+13,e.y=-t,e.height=2*t,e.doLayout(),this.addGlyph(e),this.width=e.x+e.width}}}class wh extends _h{get commonScale(){return 1}get numberScale(){return 1}}class Bh extends ih{constructor(e){super(0,0),this._notes=[],this._endNoteGlyph=null,this._middleNoteGlyph=null,this._beat=e}addBends(e){if(this._notes.push(e),e.isTieOrigin)return;const t=rn.noteColor(this.renderer.resources,le.StandardNotationEffects,e);switch(e.bendType){case y.Bend:case y.PrebendRelease:case y.PrebendBend:{let s=this._endNoteGlyph;s||(s=new sh(e.beat,!1),s.renderer=this.renderer,this._endNoteGlyph=s,this.BendNoteHeads.push(s));const i=e.bendPoints[e.bendPoints.length-1];s.addGlyph(this.getBendNoteValue(e,i),i.value%2!=0,t)}break;case y.Release:if(!e.isTieOrigin){let s=this._endNoteGlyph;s||(s=new sh(e.beat,!1),s.renderer=this.renderer,this._endNoteGlyph=s,this.BendNoteHeads.push(s));const i=e.bendPoints[e.bendPoints.length-1];s.addGlyph(this.getBendNoteValue(e,i),i.value%2!=0,t)}break;case y.BendRelease:{let s=this._middleNoteGlyph;s||(s=new sh(e.beat,!1),this._middleNoteGlyph=s,s.renderer=this.renderer,this.BendNoteHeads.push(s));const i=e.bendPoints[1];s.addGlyph(this.getBendNoteValue(e,e.bendPoints[1]),i.value%2!=0,t);let a=this._endNoteGlyph;a||(a=new sh(e.beat,!1),a.renderer=this.renderer,this._endNoteGlyph=a,this.BendNoteHeads.push(a));const r=e.bendPoints[e.bendPoints.length-1];a.addGlyph(this.getBendNoteValue(e,r),r.value%2!=0,t)}}}paint(e,t,s){const i=this.renderer.scoreRenderer.layout.getRendererForBar(this.renderer.staff.staffId,this._beat.voice.bar),a=e+i.x+i.getBeatX(this._beat,ts.MiddleNotes);let r=e+i.x;this._beat.isLastOfVoice?r+=i.postBeatGlyphsStart:r+=i.getBeatX(this._beat.nextBeat,ts.PreNotes),r-=8;const n=(a+r)/2;this._middleNoteGlyph&&(this._middleNoteGlyph.x=n-this._middleNoteGlyph.noteHeadOffset,this._middleNoteGlyph.y=t+i.y,this._middleNoteGlyph.paint(0,0,s)),this._endNoteGlyph&&(this._endNoteGlyph.x=r-this._endNoteGlyph.noteHeadOffset,this._endNoteGlyph.y=t+i.y,this._endNoteGlyph.paint(0,0,s)),this._notes.sort(((e,t)=>t.displayValue-e.displayValue));const o=this._beat.graceType===w.BendGrace?this._beat.nextBeat:this._beat;let h=1===this._notes.length?this.getTieDirection(o,i):Te.Up;const l=Nr.Heights.get(re.NoteheadBlack);for(let o=0;o<this._notes.length;o++){const c=this._notes[o],d=rn.note(s,le.StandardNotationEffects,c);try{o>0&&o>=(this._notes.length/2|0)&&(h=Te.Down);let d=t+i.y+i.getNoteY(c,is.Top),u=l*vr.GraceScale*.5;h===Te.Down&&(d+=l);const p=c.bendStyle===f.Gradual?"grad.":"";if(c.isTieOrigin){const r=c.tieDestination,n=r?this.renderer.scoreRenderer.layout.getRendererForBar(this.renderer.staff.staffId,r.beat.voice.bar):null;if(n&&n.staff===i.staff){const i=e+n.x+n.getBeatX(r.beat,ts.MiddleNotes);let o=t+n.y+n.getNoteY(r,is.Top);h===Te.Down&&(o+=l),c.bendType===y.Hold||c.bendType===y.Prebend?Uo.paintTie(s,1,a,d,i,o,h===Te.Down,22,4):this.drawBendSlur(s,a,d,i,o,h===Te.Down,1,p)}else{const r=e+i.x+i.width,n=c.tieDestination.realValue;i.accidentalHelper.applyAccidentalForValue(c.beat,n,!1,!0);const o=t+i.y+i.getScoreY(i.accidentalHelper.getNoteLineForValue(n,!1));c.bendType===y.Hold||c.bendType===y.Prebend?Uo.paintTie(s,1,a,d,r,o,h===Te.Down,22,4):this.drawBendSlur(s,a,d,r,o,h===Te.Down,1,p)}switch(c.bendType){case y.Prebend:case y.PrebendBend:case y.PrebendRelease:let r=e+i.x+i.getBeatX(c.beat,ts.PreNotes);r+=i.getPreNotesGlyphForBeat(c.beat).prebendNoteHeadOffset;const n=t+i.y+i.getScoreY(i.accidentalHelper.getNoteLineForValue(c.displayValue-(c.bendPoints[0].value/2|0),!1))+u;this.drawBendSlur(s,r,n,a,d,h===Te.Down,1)}}else{h===Te.Up&&(u=-u);let o=0,l=0;switch(c.bendType){case y.Bend:o=this.getBendNoteValue(c,c.bendPoints[c.bendPoints.length-1]),l=this._endNoteGlyph.getNoteValueY(o)+u,this.drawBendSlur(s,a,d,r,l,h===Te.Down,1,p);break;case y.BendRelease:const g=this.getBendNoteValue(c,c.bendPoints[1]),m=this._middleNoteGlyph.getNoteValueY(g)+u;this.drawBendSlur(s,a,d,n,m,h===Te.Down,1,p),o=this.getBendNoteValue(c,c.bendPoints[c.bendPoints.length-1]),l=this._endNoteGlyph.getNoteValueY(o)+u,this.drawBendSlur(s,n,m,r,l,h===Te.Down,1,p);break;case y.Release:this.BendNoteHeads.length>0&&(o=this.getBendNoteValue(c,c.bendPoints[c.bendPoints.length-1]),l=this.BendNoteHeads[0].getNoteValueY(o)+u,this.drawBendSlur(s,a,d,r,l,h===Te.Down,1,p));break;case y.Prebend:case y.PrebendBend:case y.PrebendRelease:let f=e+i.x+i.getBeatX(c.beat,ts.PreNotes);f+=i.getPreNotesGlyphForBeat(c.beat).prebendNoteHeadOffset;const b=t+i.y+i.getScoreY(i.accidentalHelper.getNoteLineForValue(c.displayValue-(c.bendPoints[0].value/2|0),!1))+u;this.drawBendSlur(s,f,b,a,d,h===Te.Down,1),this.BendNoteHeads.length>0&&(o=this.getBendNoteValue(c,c.bendPoints[c.bendPoints.length-1]),l=this.BendNoteHeads[0].getNoteValueY(o)+u,this.drawBendSlur(s,a,d,r,l,h===Te.Down,1,p))}}}finally{d?.[Symbol.dispose]?.()}}}getBendNoteValue(e,t){return e.displayValueWithoutBend+(t.value/2|0)}}class kh extends Uo{constructor(e,t,s=!1){super(e,t,s)}doLayout(){super.doLayout()}getBeamDirection(e,t){return e.isRest?Te.Up:t.getBeatDirection(e)===Te.Up?Te.Down:Te.Up}getStartY(){return this.startBeat.isRest?this.startNoteRenderer.getScoreY(9):this.tieDirection===Te.Up?this.startNoteRenderer.getNoteY(this.startBeat.maxNote,is.Top):this.startNoteRenderer.getNoteY(this.startBeat.minNote,is.Bottom)}getEndY(){const e=this.endNoteRenderer;if(this.endBeat.isRest)return this.tieDirection===Te.Up?e.getScoreY(9):e.getScoreY(0);const t=this.startNoteRenderer.getBeatDirection(this.startBeat),s=e.getBeatDirection(this.endBeat);return t!==s&&this.startBeat.graceType===w.None?s===this.tieDirection?this.tieDirection===Te.Up?e.getNoteY(this.endBeat.maxNote,is.TopWithStem):e.getNoteY(this.endBeat.minNote,is.BottomWithStem):this.tieDirection===Te.Up?e.getNoteY(this.endBeat.maxNote,is.BottomWithStem):e.getNoteY(this.endBeat.minNote,is.TopWithStem):this.tieDirection===Te.Up?e.getNoteY(this.endBeat.maxNote,is.Top):e.getNoteY(this.endBeat.minNote,is.Bottom)}getStartX(){return this.startNoteRenderer.getBeatX(this.startBeat,ts.MiddleNotes)}getEndX(){const e=this.endNoteRenderer.getBeatDirection(this.endBeat);return this.endNoteRenderer.getBeatX(this.endBeat,this.endBeat.duration>_.Whole&&e===this.tieDirection?ts.Stem:ts.MiddleNotes)}}class Th extends kr{constructor(e,t,s,i){super(0,0),this._outType=t,this._inType=e,this._startNote=s,this._parent=i}doLayout(){this.width=0}paint(e,t,s){this.paintSlideIn(e,t,s),this.drawSlideOut(e,t,s)}paintSlideIn(e,t,s){const i=this.renderer;let a=e+i.x+i.getNoteX(this._startNote,as.Left)-2;const r=t+i.y+i.getNoteY(this._startNote,is.Center);let n=a-12,o=t+i.y;switch(this._inType){case x.IntoFromBelow:o+=i.getNoteY(this._startNote,is.Bottom);break;case x.IntoFromAbove:o+=i.getNoteY(this._startNote,is.Top);break;default:return}const h=this.getAccidentalsWidth(i,this._startNote.beat);n-=h,a-=h,this.paintSlideLine(s,!1,n,a,o,r)}getAccidentalsWidth(e,t){const s=e.getPreNotesGlyphForBeat(t);return s&&s.accidentals?s.accidentals.width:0}drawSlideOut(e,t,s){const i=this.renderer;let a=0,r=0,n=0,o=0,h=!1;switch(this._outType){case v.Shift:case v.Legato:if(a=e+i.x+i.getBeatX(this._startNote.beat,ts.PostNotes)+2,r=t+i.y+i.getNoteY(this._startNote,is.Center),this._startNote.slideTarget){const s=this.renderer.scoreRenderer.layout.getRendererForBar(this.renderer.staff.staffId,this._startNote.slideTarget.beat.voice.bar);s&&s.staff===i.staff?(n=e+s.x+s.getBeatX(this._startNote.slideTarget.beat,ts.PreNotes)-2,o=t+s.y+s.getNoteY(this._startNote.slideTarget,is.Center)):(n=e+i.x+i.width,o=r),this._startNote.slideTarget.realValue>this._startNote.realValue?(r+=2,o-=2):(r-=2,o+=2)}else n=e+i.x+this._parent.x,o=r;break;case v.OutUp:a=e+i.x+i.getNoteX(this._startNote,as.Right)+2,r=t+i.y+i.getNoteY(this._startNote,is.Center),n=a+12,o=t+i.y+i.getNoteY(this._startNote,is.Top);break;case v.OutDown:a=e+i.x+i.getNoteX(this._startNote,as.Right)+2,r=t+i.y+i.getNoteY(this._startNote,is.Center),n=a+12,o=t+i.y+i.getNoteY(this._startNote,is.Bottom);break;case v.PickSlideUp:a=e+i.x+i.getNoteX(this._startNote,as.Right)+4,r=t+i.y+i.getNoteY(this._startNote,is.Center),o=t+i.y+i.getNoteY(this._startNote,is.Top),n=e+i.x+i.width,this._startNote.beat.nextBeat&&this._startNote.beat.nextBeat.voice===this._startNote.beat.voice&&(n=e+i.x+i.getBeatX(this._startNote.beat.nextBeat,ts.PreNotes)),h=!0;break;case v.PickSlideDown:a=e+i.x+i.getNoteX(this._startNote,as.Right)+4,r=t+i.y+i.getNoteY(this._startNote,is.Center),o=t+i.y+i.getNoteY(this._startNote,is.Bottom),n=e+i.x+i.width,this._startNote.beat.nextBeat&&this._startNote.beat.nextBeat.voice===this._startNote.beat.voice&&(n=e+i.x+i.getBeatX(this._startNote.beat.nextBeat,ts.PreNotes)),h=!0;break;default:return}this.paintSlideLine(s,h,a,n,r,o)}paintSlideLine(e,t,s,i,a,r){if(t){const t=new Bo(0,0,P.Slight,1.2);t.renderer=this.renderer,t.doLayout(),a-=t.height/2;const n=i-s,o=(r-=t.height/2)-a,h=Math.sqrt(Math.pow(o,2)+Math.pow(n,2));t.width=n;const l=Math.asin(o/h)*(180/Math.PI);e.beginRotate(s,a,l),t.paint(0,0,e),e.endRotate()}else e.beginPath(),e.moveTo(s,a),e.lineTo(i,r),e.stroke()}}class Nh extends kh{constructor(e,t,s=!1){super(e.beat,t.beat,s),this._startNote=e,this._endNote=t}getTieHeight(e,t,s,i){return Math.log2(s-e+1)*this.renderer.settings.notation.slurHeight}getStartY(){return this.isStartCentered()?this.tieDirection===Te.Up?this.startNoteRenderer.getNoteY(this._startNote,is.Top):this.startNoteRenderer.getNoteY(this._startNote,is.Bottom):this.startNoteRenderer.getNoteY(this._startNote,is.Center)}getEndY(){return this.isEndCentered()?this.isEndOnStem()?this.tieDirection===Te.Up?this.endNoteRenderer.getNoteY(this._endNote,is.TopWithStem):this.endNoteRenderer.getNoteY(this._endNote,is.BottomWithStem):this.tieDirection===Te.Up?this.endNoteRenderer.getNoteY(this._endNote,is.Top):this.endNoteRenderer.getNoteY(this._endNote,is.Bottom):this.endNoteRenderer.getNoteY(this._endNote,is.Center)}isStartCentered(){return this._startNote===this._startNote.beat.maxNote&&this.tieDirection===Te.Up||this._startNote===this._startNote.beat.minNote&&this.tieDirection===Te.Down}isEndCentered(){return this._startNote.beat.graceType===w.None&&(this._endNote===this._endNote.beat.maxNote&&this.tieDirection===Te.Up||this._endNote===this._endNote.beat.minNote&&this.tieDirection===Te.Down)}isEndOnStem(){const e=this.endNoteRenderer;return this.startNoteRenderer.getBeatDirection(this.startBeat)!==e.getBeatDirection(this.endBeat)&&this.startBeat.graceType===w.None}getStartX(){return this.isStartCentered()?this.startNoteRenderer.getBeatX(this._startNote.beat,ts.MiddleNotes):this.startNoteRenderer.getNoteX(this._startNote,as.Right)}getEndX(){return this.isEndCentered()?this.isEndOnStem()?this.endNoteRenderer.getBeatX(this._endNote.beat,ts.Stem):this.endNoteRenderer.getNoteX(this._endNote,as.Center):this.endNoteRenderer.getBeatX(this._endNote.beat,ts.PreNotes)}}class xh extends Uo{constructor(e,t,s=!1){super(e?e.beat:null,t?t.beat:null,s),this.startNote=e,this.endNote=t}shouldDrawBendSlur(){return this.renderer.settings.notation.extendBendArrowsOnTiedNotes&&!!this.startNote.bendOrigin&&this.startNote.isTieOrigin}doLayout(){super.doLayout()}getBeamDirection(e,t){return t.getBeatDirection(e)===Te.Up?Te.Down:Te.Up}getStartY(){return this.startBeat.isRest?this.startNoteRenderer.getScoreY(9):this.tieDirection===Te.Up?this.startNoteRenderer.getNoteY(this.startNote,is.Top):this.startNoteRenderer.getNoteY(this.startNote,is.Bottom)}getEndY(){const e=this.endNoteRenderer;return this.endBeat.isRest?this.tieDirection===Te.Up?e.getScoreY(9):e.getScoreY(0):this.tieDirection===Te.Up?e.getNoteY(this.endNote,is.Top):e.getNoteY(this.endNote,is.Bottom)}getStartX(){return this.startNoteRenderer.getBeatX(this.startNote.beat,ts.PostNotes)}getEndX(){return this.endNoteRenderer.getBeatX(this.endNote.beat,ts.PreNotes)}}class vh extends Fr{constructor(){super(...arguments),this._bend=null,this._effectSlur=null,this._effectEndSlur=null}doLayout(){this._effectSlur=null,this._effectEndSlur=null,super.doLayout(),this._bend&&(this._bend.renderer=this.renderer,this._bend.doLayout(),this.updateWidth())}createTies(e){if(e.isVisible){if(e.isTieOrigin&&!e.hasBend&&!e.beat.hasWhammyBar&&e.beat.graceType!==w.BendGrace&&e.tieDestination&&e.tieDestination.isVisible){const t=new xh(e,e.tieDestination,!1);this.addTie(t)}if(e.isTieDestination&&!e.tieOrigin.hasBend&&!e.beat.hasWhammyBar){const t=new xh(e.tieOrigin,e,!0);this.addTie(t)}if(e.slideInType!==x.None||e.slideOutType!==v.None){const t=new Th(e.slideInType,e.slideOutType,e,this);this.addTie(t)}if(e.isSlurOrigin&&e.slurDestination&&e.slurDestination.isVisible){const t=new Nh(e,e.slurDestination,!1);this.addTie(t)}if(e.isSlurDestination){const t=new Nh(e.slurOrigin,e,!0);this.addTie(t)}if(!this._effectSlur&&e.isEffectSlurOrigin&&e.effectSlurDestination){const t=new Nh(e,e.effectSlurDestination,!1);this._effectSlur=t,this.addTie(t)}if(!this._effectEndSlur&&e.beat.isEffectSlurDestination&&e.beat.effectSlurOrigin){const t=this.onNotes.beamingHelper.direction,s=t===Te.Up?e.beat.effectSlurOrigin.minNote:e.beat.effectSlurOrigin.maxNote,i=t===Te.Up?e.beat.minNote:e.beat.maxNote,a=new Nh(s,i,!0);this._effectEndSlur=a,this.addTie(a)}if(e.hasBend){if(!this._bend){const t=new Bh(e.beat);this._bend=t,t.renderer=this.renderer,this.addTie(t)}this._bend.addBends(e)}if(this.beat.isLegatoOrigin){if(!this.beat.previousBeat||!this.beat.previousBeat.isLegatoOrigin){let e=this.beat.nextBeat;for(;e.nextBeat&&e.nextBeat.isLegatoDestination;)e=e.nextBeat;this.addTie(new kh(this.beat,e,!1))}}else if(this.beat.isLegatoDestination&&!this.beat.isLegatoOrigin){let e=this.beat.previousBeat;for(;e.previousBeat&&e.previousBeat.isLegatoOrigin;)e=e.previousBeat;this.addTie(new kh(e,this.beat,!0))}}}}class Ph extends kr{doLayout(){this.width=1}paint(e,t,s){const i=e+this.x,a=t+this.y+this.renderer.topPadding,r=t+this.y+this.renderer.height-this.renderer.bottomPadding-a;this.paintInternal(i,a,r,s)}}class Fh extends Ph{paintInternal(e,t,s,i){i.fillRect(e,t,1,s)}}class Ch extends Ph{paintInternal(e,t,s,i){const a=e,r=this.renderer.getLineHeight(1);let n=t+.5*r+1;const o=t+s;for(;n<o;)i.fillCircle(a,n,1),n+=r}}class Dh extends Ph{paintInternal(e,t,s,i){const a=Dh.DashSize,r=e+.5,n=Math.ceil(s/2/a),o=t+s;if(i.beginPath(),n<1)i.moveTo(r,t),i.lineTo(r,o);else{let e=t;const h=(s-n*a)/(n-1);for(;e<o;)i.moveTo(r,e),i.lineTo(r,e+a),e+=a+h}i.stroke()}}Dh.DashSize=4;class Eh extends Ph{doLayout(){this.width=4}paintInternal(e,t,s,i){i.fillRect(e,t,this.width,s)}}class Lh extends Ph{paintInternal(e,t,s,i){const a=1.5,r=(t+(t+s))/2;i.fillCircle(e,r-4.5,a),i.fillCircle(e,r+4.5,a)}}class Mh extends Ph{paintInternal(e,t,s,i){const a=this.renderer,r=a.drawnLineCount-1;if(r<=2)return;const n=a.getLineHeight(1),o=2*n,h=r/2*n-o/2;i.fillRect(e,t+h,1,o)}}class Ih extends Ph{paintInternal(e,t,s,i){const a=this.renderer.getLineHeight(1),r=-a/2+1;i.fillRect(e,t+r,1,a)}}class Ah extends an{constructor(e){super(),this._isRight=e}doLayout(){const e=this.renderer.bar,t=e.masterBar,s=this._isRight?e.getActualBarLineRight():e.getActualBarLineLeft(0===this.renderer.index);let i=p.Automatic;if(!this._isRight){const e=this.renderer.previousRenderer;if(e&&e.staff===this.renderer.staff&&(i=e.bar.getActualBarLineRight(),s===i))return}switch(this._isRight&&t.isRepeatEnd&&(this.addGlyph(new Lh(0,0)),this.width+=3),s){case p.Dashed:this.addGlyph(new Dh(0,0));break;case p.Dotted:this.addGlyph(new Ch(0,0));break;case p.Heavy:i!==p.LightHeavy&&i!==p.HeavyHeavy&&this.addGlyph(new Eh(0,0));break;case p.HeavyHeavy:i!==p.LightHeavy&&i!==p.Heavy&&this.addGlyph(new Eh(0,0)),this.width+=3,this.addGlyph(new Eh(0,0));break;case p.HeavyLight:i!==p.LightHeavy&&i!==p.Heavy&&i!==p.HeavyHeavy&&this.addGlyph(new Eh(0,0)),this.width+=3,this.addGlyph(new Fh(0,0));break;case p.LightHeavy:i!==p.HeavyLight&&i!==p.Regular&&i!==p.LightLight&&this.addGlyph(new Fh(0,0)),this.width+=3,this.addGlyph(new Eh(0,0));break;case p.LightLight:i!==p.HeavyLight&&i!==p.Regular&&this.addGlyph(new Fh(0,0)),this.width+=3,this.addGlyph(new Fh(0,0));break;case p.None:break;case p.Regular:i!==p.HeavyLight&&i!==p.LightLight&&this.addGlyph(new Fh(0,0));break;case p.Short:this.addGlyph(new Mh(0,0));break;case p.Tick:this.addGlyph(new Ih(0,0))}this._isRight||t.isRepeatStart&&(this.width+=3,this.addGlyph(new Lh(0,0)))}paint(e,t,s){const i=this.renderer,a=rn.bar(s,i.barLineBarSubElement,this.renderer.bar,!0);try{super.paint(e,t,s)}finally{a?.[Symbol.dispose]?.()}}}class Rh extends kr{constructor(e,t,s){super(e,t),this._count=0,this._count=0,this._count=s}doLayout(){this.width=0}paint(e,t,s){const i=rn.bar(s,this.renderer.repeatsBarSubElement,this.renderer.bar);try{const i=this.renderer.resources,a=s.textAlign;s.font=i.barNumberFont,s.textAlign=ne.Right;const r=`x${this._count}`,n=s.measureText(r).width/1.5;s.fillText(r,e+this.x-n,t+this.y),s.textAlign=a}finally{i?.[Symbol.dispose]?.()}}}class Oh extends kr{constructor(e,t,s){super(e,t),this._number=0,this._number=s}doLayout(){this.renderer.scoreRenderer.canvas.font=this.renderer.resources.barNumberFont,this.width=this.renderer.scoreRenderer.canvas.measureText(this._number.toString()).width+5}paint(e,t,s){if(!this.renderer.staff.isFirstInSystem)return;const i=rn.bar(s,this.renderer.barNumberBarSubElement,this.renderer.bar,!0);try{const i=this.renderer.resources,a=s.textBaseline;s.textBaseline=oe.Top,s.font=i.barNumberFont,s.fillText(this._number.toString(),e+this.x,t+this.y),s.textBaseline=a}finally{i?.[Symbol.dispose]?.()}}}class Hh extends On{constructor(){super(...arguments),this.firstLineY=0,this._startSpacing=!1,this.tupletSize=0}get lineOffset(){return this.lineSpacing+1}get tupletOffset(){return 10}get topGlyphOverflow(){const e=this.resources;return e.tablatureFont.size/2+.2*e.tablatureFont.size}get bottomGlyphOverflow(){const e=this.resources;return e.tablatureFont.size/2+.2*e.tablatureFont.size}initLineBasedSizes(){this.topPadding=this.topGlyphOverflow,this.bottomPadding=this.bottomGlyphOverflow,this.height=this.lineOffset*(this.heightLineCount-1)+this.topPadding+this.bottomPadding}updateSizes(){this.initLineBasedSizes(),this.adjustSizes(),this.updateFirstLineY(),super.updateSizes()}adjustSizes(){}updateFirstLineY(){const e=this.lineOffset*(this.heightLineCount-1),t=(this.drawnLineCount-1)*this.lineOffset;this.firstLineY=this.topPadding+(e-t)/2}doLayout(){this.initLineBasedSizes(),this.updateFirstLineY(),this.tupletSize=15+.3*this.resources.effectFont.size,super.doLayout()}getLineY(e){return this.firstLineY+this.getLineHeight(e)}getLineHeight(e){return this.lineOffset*e}paintBackground(e,t,s){super.paintBackground(e,t,s),this.paintStaffLines(e,t,s),this.paintSimileMark(e,t,s)}paintStaffLines(e,t,s){const i=rn.bar(s,this.staffLineBarSubElement,this.bar,!0);try{const i=[];for(let e=0,t=this.drawnLineCount;e<t;e++)i.push([]);this.additionalMultiRestBars||this.collectSpaces(i);for(const e of i)e.sort(((e,t)=>e[0]>t[0]?1:e[0]<t[0]?-1:0));const a=Math.ceil(this.width);for(let r=0;r<this.drawnLineCount;r++){const n=this.getLineY(r);let o=0;for(const a of i[r])s.fillRect(e+this.x+o,t+this.y+n|0,a[0]-o,On.StaffLineThickness),o=a[0]+a[1];s.fillRect(e+this.x+o,t+this.y+n|0,a-o,On.StaffLineThickness)}}finally{i?.[Symbol.dispose]?.()}}collectSpaces(e){}createStartSpacing(){if(this._startSpacing)return;const e=0===this.index?this.settings.display.firstStaffPaddingLeft:this.settings.display.staffPaddingLeft;this.addPreBeatGlyph(new hh(0,0,e)),this._startSpacing=!0}paintTuplets(e,t,s,i,a=!1){for(const r of this.bar.voices)if(this.hasVoiceContainer(r)){const n=this.getVoiceContainer(r);for(const r of n.tupletGroups)this.paintTupletHelper(e+this.beatGlyphsStart,t,s,r,i,a)}}getTupletBeamDirection(e){return this.getBeamDirection(e)}paintTupletHelper(e,t,s,i,a,r){const n=this.resources,o=s.textAlign,h=s.textBaseline;let l;s.color=0===i.voice.index?this.resources.mainGlyphColor:this.resources.secondaryGlyphColor,s.textAlign=ne.Center,s.textBaseline=oe.Middle;const c=i.beats[0].tupletNumerator,d=i.beats[0].tupletDenominator;l=2===c&&3===d?"2":3===c&&2===d?"3":4===c&&6===d?"4":5===c&&4===d?"5":6===c&&4===d?"6":7===c&&4===d?"7":9===c&&8===d?"9":10===c&&8===d?"10":11===c&&8===d?"11":12===c&&8===d?"12":13===c&&8===d?"13":`${c}:${d}`;let u=this.tupletOffset,p=5;const g=rn.beat(s,a,i.beats[0]);try{if(1!==i.beats.length&&i.isFull){const a=i.beats[0],o=i.beats[i.beats.length-1];let h=null,c=null;for(let e=0;e<i.beats.length;e++)if(!i.beats[e].isRest){h=i.beats[e];break}for(let e=i.beats.length-1;e>=0;e--)if(!i.beats[e].isRest){c=i.beats[e];break}let d=!1;h||(h=a,d=!0),c||(c=o);const g=this.helpers.beamHelperLookup[i.voice.index].get(a.index),m=this.helpers.beamHelperLookup[i.voice.index].get(o.index),f=g.getBeatLineX(a),y=m.getBeatLineX(o),b=this.helpers.beamHelperLookup[i.voice.index].get(h.index),S=this.helpers.beamHelperLookup[i.voice.index].get(c.index),_=this.getTupletBeamDirection(g);let w=this.calculateBeamYWithDirection(b,f,_),B=this.calculateBeamYWithDirection(S,y,_);d&&(w=Math.max(w,B),B=w),s.font=n.effectFont;const k=s.measureText(l).width,T=3,N=(f+y)/2,x=N-k/2-T,v=N+k/2+T,P=(B-w)/(y-f),F=w-P*f,C=P*x+F,D=P*N+F,E=P*v+F;_===Te.Down&&(u*=-1,p*=-1),s.beginPath(),s.moveTo(e+this.x+f,t+this.y+w-u|0),r?s.quadraticCurveTo(e+this.x+(x+f)/2,t+this.y+C-u-p|0,e+this.x+x,t+this.y+C-u-p|0):(s.lineTo(e+this.x+f,t+this.y+w-u-p|0),s.lineTo(e+this.x+x,t+this.y+C-u-p|0)),s.stroke(),s.beginPath(),s.moveTo(e+this.x+v,t+this.y+E-u-p|0),r?s.quadraticCurveTo(e+this.x+(y+v)/2,t+this.y+E-u-p|0,e+this.x+y,t+this.y+B-u|0):(s.lineTo(e+this.x+y,t+this.y+B-u-p|0),s.lineTo(e+this.x+y,t+this.y+B-u|0)),s.stroke(),s.fillText(l,e+this.x+N,t+this.y+D-u-p)}else for(const a of i.beats){const r=this.helpers.beamHelperLookup[i.voice.index].get(a.index);if(!r)continue;const o=this.getTupletBeamDirection(r),h=r.getBeatLineX(a);let c=this.calculateBeamYWithDirection(r,h,o);o===Te.Down?c+=u+p:c-=u+p,s.font=n.effectFont,s.fillText(l,e+this.x+h,t+this.y+c)}s.textAlign=o,s.textBaseline=h}finally{g?.[Symbol.dispose]?.()}}paintBeams(e,t,s,i,a){for(const r of this.helpers.beamHelpers)for(const n of r)this.paintBeamHelper(e+this.beatGlyphsStart,t,s,n,i,a)}drawBeamHelperAsFlags(e){return 1===e.beats.length}paintBeamHelper(e,t,s,i,a,r){s.color=0===i.voice.index?this.resources.mainGlyphColor:this.resources.secondaryGlyphColor,i.isRestBeamHelper||(this.drawBeamHelperAsFlags(i)?this.paintFlag(e,t,s,i,a):this.paintBar(e,t,s,i,r))}shouldPaintFlag(e,t){return e.graceType!==w.BendGrace&&(!e.deadSlapped&&(!!t.hasBeatLineX(e)&&((e.graceType===w.None||this.settings.notation.notationMode!==D.SongBook)&&(e.duration!==_.Whole&&e.duration!==_.DoubleWhole&&e.duration!==_.QuadrupleWhole))))}paintFlag(e,t,s,i,a){for(const r of i.beats){if(!this.shouldPaintFlag(r,i))continue;const n=r.graceType!==w.None,o=n?vr.GraceScale:1,h=this.getFlagStemSize(i.shortestDuration),l=i.getBeatLineX(r),c=this.getBeamDirection(i);let d=this.getFlagTopY(r,c),u=this.getFlagBottomY(r,c),p=0;if(c===Te.Down?(u+=h*o,p=u):(d-=h*o,p=d),!i.hasLine(!0,r))continue;this.paintBeamingStem(r,t+this.y,e+this.x+l,t+this.y+d,t+this.y+u,s);const g=rn.beat(s,a,r);try{if(r.graceType===w.BeforeBeat){const i=15,a=12;s.beginPath(),c===Te.Down?(s.moveTo(e+this.x+l-a/2,t+this.y+u-i),s.lineTo(e+this.x+l+a/2,t+this.y+u)):(s.moveTo(e+this.x+l-a/2,t+this.y+d+i),s.lineTo(e+this.x+l+a/2,t+this.y+d)),s.stroke()}if(i.hasFlag(!0,r)){const i=new Pr(l-.5,p,r.duration,c,n);i.renderer=this,i.doLayout(),i.paint(e+this.x,t+this.y,s)}}finally{g?.[Symbol.dispose]?.()}}}getFlagStemSize(e,t=!1){let s=0;switch(e){case _.QuadrupleWhole:case _.Half:case _.Quarter:case _.Eighth:case _.Sixteenth:case _.ThirtySecond:case _.SixtyFourth:case _.OneHundredTwentyEighth:case _.TwoHundredFiftySixth:s=3;break;default:s=t?3:0}return this.getLineHeight(s)}recreatePreBeatGlyphs(){this._startSpacing=!1,super.recreatePreBeatGlyphs()}calculateBeamY(e,t){return this.calculateBeamYWithDirection(e,t,this.getBeamDirection(e))}createPreBeatGlyphs(){super.createPreBeatGlyphs(),this.addPreBeatGlyph(new Ah(!1)),this.createLinePreBeatGlyphs(),this.addPreBeatGlyph(new Oh(0,this.getLineHeight(-.25),this.bar.index+1))}createPostBeatGlyphs(){super.createPostBeatGlyphs();const e=this.lastBar;this.addPostBeatGlyph(new Ah(!0)),e.masterBar.isRepeatEnd&&e.masterBar.repeatCount>2&&this.addPostBeatGlyph(new Rh(0,this.getLineHeight(-.25),this.bar.masterBar.repeatCount))}paintBar(e,t,s,i,a){for(let r=0,n=i.beats.length;r<n;r++){const n=i.beats[r];if(!i.hasBeatLineX(n)||n.deadSlapped)continue;const o=n.graceType!==w.None?vr.GraceScale:1,h=i.getBeatLineX(n),l=this.getBeamDirection(i),c=t+this.y+this.getBarLineStart(n,l),d=t+this.y+this.calculateBeamY(i,h);this.paintBeamingStem(n,t+this.y,e+this.x+h,c,d,s);const u=rn.beat(s,a,n);try{let a=d;l===Te.Down?a+=2*s.font.size:0!==r&&(a-=1.5*s.font.size);const c=6*o;let u=(On.BeamSpacing+On.BeamThickness)*o,p=On.BeamThickness*o;const g=ie.getIndex(n.duration)-2,m=t+this.y;l===Te.Down&&(u=-u,p=-p);for(let t=0;t<g;t++){let a=0,o=0,l=0,d=0;const f=m+t*u;if(r<i.beats.length-1){const u=cn.isFullBarJoin(n,i.beats[r+1],t);if(t===g-1&&u&&n.beamingMode===fe.ForceSplitOnSecondaryToNext)a=h,o=a+c,l=f+this.calculateBeamY(i,a),d=f+this.calculateBeamY(i,o),Hh.paintSingleBar(s,e+this.x+a,l,e+this.x+o,d,p),o=i.getBeatLineX(i.beats[r+1]),a=o-c,l=f+this.calculateBeamY(i,a),d=f+this.calculateBeamY(i,o),Hh.paintSingleBar(s,e+this.x+a,l,e+this.x+o,d,p);else{if(u)a=h,o=i.getBeatLineX(i.beats[r+1]);else{if(0!==r&&cn.isFullBarJoin(i.beats[r-1],n,t))continue;a=h,o=a+c}l=f+this.calculateBeamY(i,a),d=f+this.calculateBeamY(i,o),Hh.paintSingleBar(s,e+this.x+a,l,e+this.x+o,d,p)}}else r>0&&!cn.isFullBarJoin(n,i.beats[r-1],t)&&(a=h-c,o=h,l=f+this.calculateBeamY(i,a),d=f+this.calculateBeamY(i,o),Hh.paintSingleBar(s,e+this.x+a,l,e+this.x+o,d,p))}}finally{u?.[Symbol.dispose]?.()}}}static paintSingleBar(e,t,s,i,a,r){e.beginPath(),e.moveTo(t,s),e.lineTo(i,a),e.lineTo(i,a+r),e.lineTo(t,s+r),e.closePath(),e.fill()}}class Wh extends an{paint(e,t,s){const i=rn.bar(s,u.StandardNotationKeySignature,this.renderer.bar);try{super.paint(e,t,s)}finally{i?.[Symbol.dispose]?.()}}}class Vh extends Hh{constructor(e,t){super(e,t),this.simpleWhammyOverflow=0,this.beatEffectsMinY=null,this.beatEffectsMaxY=null,this.accidentalHelper=new Bs(this)}get repeatsBarSubElement(){return u.StandardNotationRepeats}get barNumberBarSubElement(){return u.StandardNotationBarNumber}get barLineBarSubElement(){return u.StandardNotationBarLines}get staffLineBarSubElement(){return u.StandardNotationStaffLine}get showMultiBarRest(){return!0}get lineSpacing(){return On.RawLineSpacing}get heightLineCount(){return 5}get drawnLineCount(){return this.bar.staff.standardNotationLineCount}registerBeatEffectOverflows(e,t){const s=this.beatEffectsMinY;(null==s||e<s)&&(this.beatEffectsMinY=e);const i=this.beatEffectsMaxY;(null==i||t>i)&&(this.beatEffectsMaxY=t)}getScoreY(e){return super.getLineY(e/2)}getScoreHeight(e){return super.getLineHeight(e/2)}doLayout(){if(super.doLayout(),!this.bar.isEmpty&&this.accidentalHelper.maxLineBeat){const e=this.getScoreY(-2),t=this.getScoreY(10),s=this.simpleWhammyOverflow,i=this.beatEffectsMinY;if(null!==i){const t=e-i;t>0&&this.registerOverflowTop(t)}const a=this.beatEffectsMaxY;if(null!==a){const e=a-t;e>0&&this.registerOverflowBottom(e)}this.registerOverflowTop(s);let r=this.getScoreY(this.accidentalHelper.maxLine);const n=this.helpers.getBeamingHelperForBeat(this.accidentalHelper.maxLineBeat);n.direction===Te.Up&&(r-=this.getStemSize(n),n.hasTuplet&&(r-=this.tupletSize)),r<e&&this.registerOverflowTop(Math.abs(r)+s);let o=this.getScoreY(this.accidentalHelper.minLine);const h=this.helpers.getBeamingHelperForBeat(this.accidentalHelper.minLineBeat);h.direction===Te.Down&&(o+=this.getStemSize(h),h.hasTuplet&&(o+=this.tupletSize)),o>t&&this.registerOverflowBottom(Math.abs(o)-t)}}paint(e,t,s){super.paint(e,t,s),this.paintBeams(e,t,s,ye.StandardNotationFlags,ye.StandardNotationBeams),this.paintTuplets(e,t,s,ye.StandardNotationTuplet)}getSlashFlagY(e,t){let s=(this.heightLineCount-1)/2,i=0;switch(e){case _.QuadrupleWhole:case _.DoubleWhole:case _.Whole:i+=2;break;default:i+=1}t===Te.Down?s+=i:s-=i;return this.getLineY(s)}getFlagTopY(e,t){return e.slashed?this.getSlashFlagY(e.duration,t):this.getScoreY(this.accidentalHelper.getMinLine(e))}getFlagBottomY(e,t){return e.slashed?this.getSlashFlagY(e.duration,t):this.getScoreY(this.accidentalHelper.getMaxLine(e))}getBeamDirection(e){return e.direction}getStemSize(e,t=!1){let s=1===e.beats.length?this.getFlagStemSize(e.shortestDuration,t):this.getBarStemSize(e.shortestDuration);return e.isGrace&&(s*=vr.GraceScale),s}getBarStemSize(e){let t=0;switch(e){case _.QuadrupleWhole:case _.Half:case _.Quarter:case _.Eighth:case _.Sixteenth:t=6;break;case _.ThirtySecond:t=8;break;case _.SixtyFourth:case _.OneHundredTwentyEighth:t=9;break;case _.TwoHundredFiftySixth:t=10;break;default:t=0}return this.getScoreHeight(t)}get middleYPosition(){return this.getScoreY(this.bar.staff.standardNotationLineCount-1)}getNoteY(e,t){if(e.beat.slashed){const e=(this.heightLineCount-1)/2;return this.getLineY(e)}let s=super.getNoteY(e,t);if(Number.isNaN(s)){const t=Bs.computeLineWithoutAccidentals(this.bar,e);s=this.getScoreY(t)}return s}applyLayoutingInfo(){const e=super.applyLayoutingInfo();if(e&&this.bar.isMultiVoice){const e=this.getScoreY(-2),t=this.getScoreY(10),s=this.helpers.collisionHelper.getBeatMinMaxY();s[0]<e&&this.registerOverflowTop(Math.abs(s[0])),s[1]>t&&this.registerOverflowBottom(Math.abs(s[1])-t)}return e}calculateBeamYWithDirection(e,t,s){const i=this.getStemSize(e);if(!e.drawingInfos.has(s)){const t=new ln;e.drawingInfos.set(s,t);const a=e.beats[0],r=e.beats[e.beats.length-1],n=e.isRestBeamHelper;t.startBeat=a,t.startX=e.getBeatLineX(a),t.startY=n?s===Te.Up?this.getScoreY(e.minRestLine):this.getScoreY(e.maxRestLine):s===Te.Up?this.getFlagTopY(a,s)-i:this.getFlagBottomY(a,s)+i,t.endBeat=r,t.endX=e.getBeatLineX(r),t.endY=n?s===Te.Up?this.getScoreY(e.minRestLine):this.getScoreY(e.maxRestLine):s===Te.Up?this.getFlagTopY(r,s)-i:this.getFlagBottomY(r,s)+i;const o=10;if(s===Te.Down&&t.startY>t.endY&&t.startY-t.endY>o&&(t.endY=t.startY-o),s===Te.Down&&t.endY>t.startY&&t.endY-t.startY>o&&(t.startY=t.endY-o),s===Te.Up&&t.startY<t.endY&&t.endY-t.startY>o&&(t.endY=t.startY+o),s===Te.Up&&t.endY<t.startY&&t.startY-t.endY>o&&(t.startY=t.endY+o),e.beats.length>1){if(s===Te.Up){const s=this.getScoreY(this.accidentalHelper.getMinLine(e.beatOfHighestNote))-i,a=t.calcY(e.getBeatLineX(e.beatOfHighestNote))-s;a>0&&(t.startY-=a,t.endY-=a)}else{const s=this.getScoreY(this.accidentalHelper.getMaxLine(e.beatOfLowestNote))+i-t.calcY(e.getBeatLineX(e.beatOfLowestNote));s>0&&(t.startY+=s,t.endY+=s)}if(null!==e.minRestLine||null!==e.maxRestLine){const i=ie.getIndex(e.shortestDuration)-2,a=e.isGrace?vr.GraceScale:1;let r=i*(On.BeamSpacing+On.BeamThickness)*a;if(r+=On.BeamSpacing,s===Te.Up&&null!==e.minRestLine){const s=this.getScoreY(e.minRestLine)-r,i=t.calcY(e.getBeatLineX(e.beatOfMinRestLine))-s;i>0&&(t.startY-=i,t.endY-=i)}else if(s===Te.Down&&null!==e.maxRestLine){const s=this.getScoreY(e.maxRestLine)+r-t.calcY(e.getBeatLineX(e.beatOfMaxRestLine));s>0&&(t.startY+=s,t.endY+=s)}}if(e.slashBeats.length>0)for(const a of e.slashBeats){const r=t.calcY(e.getBeatLineX(a));let n=this.getSlashFlagY(a.duration,s);s===Te.Up?n-=i:s===Te.Down&&(n+=i);const o=n-r;o>0&&(t.startY+=o,t.endY+=o)}}}return e.drawingInfos.get(s).calcY(t)}getBarLineStart(e,t){return e.slashed?this.getSlashFlagY(e.duration,t):t===Te.Up?this.getScoreY(this.accidentalHelper.getMaxLine(e)):this.getScoreY(this.accidentalHelper.getMinLine(e))}createLinePreBeatGlyphs(){let e=!1;if(this.isFirstOfLine||this.bar.clef!==this.bar.previousBar.clef||this.bar.clefOttava!==this.bar.previousBar.clefOttava){let t=0;switch(this.bar.clef){case n.Neutral:t=this.bar.staff.standardNotationLineCount-1;break;case n.F4:t=2;break;case n.C3:t=4;break;case n.C4:t=2;break;case n.G2:t=6}this.createStartSpacing(),this.addPreBeatGlyph(new Ho(0,this.getScoreY(t)+.5*On.StaffLineThickness,this.bar.clef,this.bar.clefOttava)),e=!0}(e||0===this.index&&this.bar.keySignature!==l.C||this.bar.previousBar&&this.bar.keySignature!==this.bar.previousBar.keySignature)&&(this.createStartSpacing(),this.createKeySignatureGlyphs()),(!this.bar.previousBar||this.bar.previousBar&&this.bar.masterBar.timeSignatureNumerator!==this.bar.previousBar.masterBar.timeSignatureNumerator||this.bar.previousBar&&this.bar.masterBar.timeSignatureDenominator!==this.bar.previousBar.masterBar.timeSignatureDenominator||this.bar.previousBar&&this.bar.masterBar.isFreeTime&&this.bar.masterBar.isFreeTime!==this.bar.previousBar.masterBar.isFreeTime)&&(this.createStartSpacing(),this.createTimeSignatureGlyphs())}createKeySignatureGlyphs(){let e=0;const t=this.bar.keySignature,s=this.bar.previousBar?this.bar.previousBar.keySignature:0;switch(this.bar.clef){case n.Neutral:e=0;break;case n.G2:e=1;break;case n.F4:e=3;break;case n.C3:e=2;break;case n.C4:e=0}const i=new Wh;i.renderer=this;const a=new Map,r=[];if(ie.keySignatureIsSharp(t))for(let s=0;s<Math.abs(t);s++){const t=Vh.SharpKsSteps[s]+e;r.push(new Oo(0,this.getScoreY(t),It.Sharp,1)),a.set(t,!0)}else for(let s=0;s<Math.abs(t);s++){const t=Vh.FlatKsSteps[s]+e;r.push(new Oo(0,this.getScoreY(t),It.Flat,1)),a.set(t,!0)}if(this.bar.keySignature===l.C){const t=Math.abs(s),r=ie.keySignatureIsSharp(s)?Vh.SharpKsSteps:Vh.FlatKsSteps;for(let s=0;s<t;s++){const t=r[s]+e;a.has(t)||i.addGlyph(new Oo(0,this.getScoreY(r[s]+e),It.Natural,1))}}for(const e of r)i.addGlyph(e);this.addPreBeatGlyph(i)}createTimeSignatureGlyphs(){this.addPreBeatGlyph(new hh(0,0,5));const e=this.bar.staff.standardNotationLineCount-1;this.addPreBeatGlyph(new wh(0,this.getScoreY(e),this.bar.masterBar.timeSignatureNumerator,this.bar.masterBar.timeSignatureDenominator,this.bar.masterBar.timeSignatureCommon,this.bar.masterBar.isFreeTime))}createVoiceGlyphs(e){for(const t of e.beats){const s=new vh(t,this.getVoiceContainer(e));s.preNotes=new Sh,s.onNotes=new mh,this.addBeatGlyph(s)}}getNoteLine(e){return this.accidentalHelper.getNoteLine(e)}completeBeamingHelper(e){if(this.bar.isMultiVoice&&e.highestNoteInHelper&&e.lowestNoteInHelper){let t=this.getNoteY(e.highestNoteInHelper,is.Center),s=this.getNoteY(e.lowestNoteInHelper,is.Center),i=this.getStemSize(e);e.hasTuplet&&(i+=2*this.resources.effectFont.size),e.direction===Te.Up?t-=i:s+=i;for(const i of e.beats)this.helpers.collisionHelper.reserveBeatSlot(i,t,s)}}paintBeamingStem(e,t,s,i,a,r){const n=rn.beat(r,ye.StandardNotationStem,e);try{r.lineWidth=On.StemWidth,r.beginPath(),r.moveTo(s,i),r.lineTo(s,a),r.stroke(),r.lineWidth=1}finally{n?.[Symbol.dispose]?.()}}}Vh.StaffId="score",Vh.SharpKsSteps=[-1,2,-2,1,4,0,3],Vh.FlatKsSteps=[3,0,4,1,5,2,6];class Gh extends tn{get staffId(){return Vh.StaffId}getStaffPaddingTop(e){return e.system.layout.renderer.settings.display.notationStaffPaddingTop}getStaffPaddingBottom(e){return e.system.layout.renderer.settings.display.notationStaffPaddingBottom}create(e,t){return new Vh(e,t)}canCreate(e,t){return super.canCreate(e,t)&&t.showStandardNotation}}class zh extends kr{constructor(e,t,s,i){super(0,0),this._inType=e,this._outType=t,this._startNote=s,this._parent=i}doLayout(){this.width=0}paint(e,t,s){this.paintSlideIn(e,t,s),this.paintSlideOut(e,t,s)}paintSlideIn(e,t,s){const i=this.renderer;let a=0,r=0,n=0,o=0;switch(this._inType){case x.IntoFromBelow:n=e+i.x+i.getNoteX(this._startNote,as.Left)-2,o=t+i.y+i.getNoteY(this._startNote,is.Center),a=n-12,r=t+i.y+i.getNoteY(this._startNote,is.Center)+3;break;case x.IntoFromAbove:n=e+i.x+i.getNoteX(this._startNote,as.Left)-2,o=t+i.y+i.getNoteY(this._startNote,is.Center),a=n-12,r=t+i.y+i.getNoteY(this._startNote,is.Center)-3;break;default:return}this.paintSlideLine(s,!1,a,n,r,o)}paintSlideOut(e,t,s){const i=this.renderer;let a=0,r=0,n=0,o=0,h=!1;switch(this._outType){case v.Shift:case v.Legato:if(a=e+i.x+i.getBeatX(this._startNote.beat,ts.PostNotes)+2,r=t+i.y+i.getNoteY(this._startNote,is.Center),this._startNote.slideTarget){const s=this.renderer.scoreRenderer.layout.getRendererForBar(this.renderer.staff.staffId,this._startNote.slideTarget.beat.voice.bar);s&&s.staff===i.staff?(n=e+s.x+s.getBeatX(this._startNote.slideTarget.beat,ts.OnNotes)-2,o=t+s.y+s.getNoteY(this._startNote.slideTarget,is.Center)):(n=e+i.x+i.width,o=r),this._startNote.slideTarget.fret>this._startNote.fret?(r+=3,o-=3):(r-=3,o+=3)}else n=e+i.x+this._parent.x,o=r;break;case v.OutUp:a=e+i.x+i.getNoteX(this._startNote,as.Right)+2,r=t+i.y+i.getNoteY(this._startNote,is.Center),n=a+12,o=t+i.y+i.getNoteY(this._startNote,is.Center)-3;break;case v.OutDown:a=e+i.x+i.getNoteX(this._startNote,as.Right)+2,r=t+i.y+i.getNoteY(this._startNote,is.Center),n=a+12,o=t+i.y+i.getNoteY(this._startNote,is.Center)+3;break;case v.PickSlideDown:a=e+i.x+i.getNoteX(this._startNote,as.Right)+4,r=t+i.y+i.getNoteY(this._startNote,is.Center),n=e+i.x+i.width,o=r+9,this._startNote.beat.nextBeat&&this._startNote.beat.nextBeat.voice===this._startNote.beat.voice&&(n=e+i.x+i.getBeatX(this._startNote.beat.nextBeat,ts.PreNotes)),h=!0;break;case v.PickSlideUp:a=e+i.x+i.getNoteX(this._startNote,as.Right)+4,r=t+i.y+i.getNoteY(this._startNote,is.Center),n=e+i.x+i.width,o=r-9,this._startNote.beat.nextBeat&&this._startNote.beat.nextBeat.voice===this._startNote.beat.voice&&(n=e+i.x+i.getBeatX(this._startNote.beat.nextBeat,ts.PreNotes)),h=!0;break;default:return}this.paintSlideLine(s,h,a,n,r,o)}paintSlideLine(e,t,s,i,a,r){if(t){const t=new Bo(0,0,P.Slight,1.2);t.renderer=this.renderer,t.doLayout(),a-=t.height/2;const n=i-s,o=(r-=t.height/2)-a,h=Math.sqrt(Math.pow(o,2)+Math.pow(n,2));t.width=n;const l=Math.asin(o/h)*(180/Math.PI);e.beginRotate(s,a,l),t.paint(0,0,e),e.endRotate()}else e.beginPath(),e.moveTo(s,a),e.lineTo(i,r),e.stroke()}}class Uh extends Uo{constructor(e,t,s=!1){super(e.beat,t.beat,s),this.startNote=e,this.endNote=t}getTieHeight(e,t,s,i){return this.startNote===this.endNote?15:super.getTieHeight(e,t,s,i)}getBeamDirection(e,t){return this.startNote===this.endNote?Te.Up:Uh.getBeamDirectionForNote(this.startNote)}static getBeamDirectionForNote(e){return e.string>3?Te.Up:Te.Down}getStartY(){return this.startNote===this.endNote?this.startNoteRenderer.getNoteY(this.startNote,is.Center):this.tieDirection===Te.Up?this.startNoteRenderer.getNoteY(this.startNote,is.Top):this.startNoteRenderer.getNoteY(this.startNote,is.Bottom)}getEndY(){return this.getStartY()}getStartX(){return this.startNote===this.endNote?this.getEndX()-20:this.startNoteRenderer.getNoteX(this.startNote,as.Center)}getEndX(){return this.startNote===this.endNote?this.endNoteRenderer.getNoteX(this.endNote,as.Left):this.endNoteRenderer.getNoteX(this.endNote,as.Center)}}class Xh extends Uh{constructor(e,t,s,i=!1){super(e,t,i),this._direction=Uh.getBeamDirectionForNote(e),this._forSlide=s}getTieHeight(e,t,s,i){return Math.log(s-e+1)*this.renderer.settings.notation.slurHeight}tryExpand(e,t,s,i){if(this._forSlide!==s)return!1;if(this.forEnd!==i)return!1;if(this.startNote.beat.id!==e.beat.id)return!1;if(this.endNote.beat.id!==t.beat.id)return!1;if(this._direction!==Uh.getBeamDirectionForNote(e))return!1;switch(this._direction){case Te.Up:e.realValue>this.startNote.realValue&&(this.startNote=e,this.startBeat=e.beat),t.realValue>this.endNote.realValue&&(this.endNote=t,this.endBeat=t.beat);break;case Te.Down:e.realValue<this.startNote.realValue&&(this.startNote=e,this.startBeat=e.beat),t.realValue<this.endNote.realValue&&(this.endNote=t,this.endBeat=t.beat)}return!0}paint(e,t,s){const i=this.renderer.scoreRenderer.layout.getRendererForBar(this.renderer.staff.staffId,this.startBeat.voice.bar),a=this.getBeamDirection(this.startBeat,i),r=`tab.slur.${this.startNote.beat.id}.${this.endNote.beat.id}.${a}`,n=this.renderer;n.staff.getSharedLayoutData(r,!1)||(n.staff.setSharedLayoutData(r,!0),super.paint(e,t,s))}}class Jh extends Fr{constructor(){super(...arguments),this._bend=null,this._effectSlurs=[]}drawBeamHelperAsFlags(e){return e.hasFlag(this.renderer.drawBeamHelperAsFlags(e),this.beat)}doLayout(){this._effectSlurs=[],super.doLayout(),this._bend&&(this._bend.renderer=this.renderer,this._bend.doLayout(),this.updateWidth())}createTies(e){if(!e.isVisible)return;const t=this.renderer;if(e.isTieOrigin&&t.showTiedNotes&&e.tieDestination.isVisible){const t=new Uh(e,e.tieDestination,!1);this.addTie(t)}if(e.isTieDestination&&t.showTiedNotes){const t=new Uh(e.tieOrigin,e,!0);this.addTie(t)}if(e.isLeftHandTapped&&!e.isHammerPullDestination){const t=new Uh(e,e,!1);this.addTie(t)}if(e.isEffectSlurOrigin&&e.effectSlurDestination){let t=!1;for(const s of this._effectSlurs)if(s.tryExpand(e,e.effectSlurDestination,!1,!1)){t=!0;break}if(!t){const t=new Xh(e,e.effectSlurDestination,!1,!1);this._effectSlurs.push(t),this.addTie(t)}}if(e.isEffectSlurDestination&&e.effectSlurOrigin){let t=!1;for(const s of this._effectSlurs)if(s.tryExpand(e.effectSlurOrigin,e,!1,!0)){t=!0;break}if(!t){const t=new Xh(e.effectSlurOrigin,e,!1,!0);this._effectSlurs.push(t),this.addTie(t)}}if(e.slideInType!==x.None||e.slideOutType!==v.None){const t=new zh(e.slideInType,e.slideOutType,e,this);this.addTie(t)}if(e.hasBend){if(!this._bend){const e=new rh;this._bend=e,e.renderer=this.renderer,this.addTie(e)}this._bend.addBends(e)}}}class Yh extends kr{constructor(e,t,s){super(e,t),this._noteString=null,this._trillNoteString=null,this._trillNoteStringWidth=0,this.isEmpty=!1,this.noteStringWidth=0,this._note=s}doLayout(){const e=this._note;let t=e.fret-e.beat.voice.bar.staff.transpositionPitch;if(e.harmonicType===T.Natural&&0!==e.harmonicValue&&(t=e.harmonicValue-e.beat.voice.bar.staff.transpositionPitch),e.isTieDestination)0===e.beat.index&&this.renderer.settings.notation.notationMode===D.GuitarPro||(e.bendType===y.Bend||e.bendType===y.BendRelease)&&this.renderer.settings.notation.isNotationElementVisible(E.TabNotesOnTiedBends)?this._noteString=`(${(e.tieOrigin.fret-e.beat.voice.bar.staff.transpositionPitch).toString()})`:this._noteString="";else if(this._noteString=e.isDead?"x":t.toString(),e.isGhost)this._noteString=`(${this._noteString})`;else if(e.harmonicType===T.Natural){const e=this._noteString.indexOf(String.fromCharCode(46));e>=0&&(this._noteString=this._noteString.substr(0,e+2)),this._noteString=`<${this._noteString}>`}if(e.isTrill)this._trillNoteString=`(${(e.trillFret-e.beat.voice.bar.staff.transpositionPitch).toString()})`;else if(ie.isAlmostEqualTo(e.harmonicValue,0))this._trillNoteString="";else switch(e.harmonicType){case T.Artificial:case T.Pinch:case T.Tap:case T.Semi:case T.Feedback:let s=(t+e.harmonicValue).toString();const i=s.indexOf(String.fromCharCode(46));i>=0&&(s=s.substr(0,i+2)),this._trillNoteString=`<${s}>`;break;default:this._trillNoteString=""}if(this.isEmpty=!this._noteString,!this.isEmpty){this.renderer.scoreRenderer.canvas.font=this.renderer.resources.tablatureFont,this.noteStringWidth=this.renderer.scoreRenderer.canvas.measureText(this._noteString).width,this.width=this.noteStringWidth,this.height=this.renderer.scoreRenderer.canvas.font.size;!!this._trillNoteString&&(this.renderer.scoreRenderer.canvas.font=this.renderer.resources.graceFont,this._trillNoteStringWidth=3+this.renderer.scoreRenderer.canvas.measureText(this._trillNoteString).width,this.width+=this._trillNoteStringWidth)}}paint(e,t,s){if(this.isEmpty)return;const i=this.noteStringWidth+this._trillNoteStringWidth,a=e+this.x+(this.width-i)/2;this.paintTrill(a,t,s);const r=rn.note(s,le.GuitarTabFretNumber,this._note);try{s.fillText(this._noteString,a,t+this.y)}finally{r?.[Symbol.dispose]?.()}}paintTrill(e,t,s){const i=rn.note(s,le.GuitarTabFretNumber,this._note);try{const i=this.renderer.scoreRenderer.canvas.font;this.renderer.scoreRenderer.canvas.font=this.renderer.resources.graceFont,s.fillText(this._trillNoteString,e+this.noteStringWidth+3,t+this.y),this.renderer.scoreRenderer.canvas.font=i}finally{i?.[Symbol.dispose]?.()}}buildBoundingsLookup(e,t,s){const i=new ir;i.note=this._note,i.noteHeadBounds=new mt,i.noteHeadBounds.x=t+this.x,i.noteHeadBounds.y=s+this.y-this.height/2,i.noteHeadBounds.w=this.width,i.noteHeadBounds.h=this.height,e.addNote(i)}}class $h extends kr{constructor(e,t,s){super(e,t),this._notes=[],this._deadSlapped=null,this.minStringNote=null,this.beatEffects=new Map,this.notesPerString=new Map,this.noteStringWidth=0,this._isGrace=s}buildBoundingsLookup(e,t,s){for(const i of this._notes)i.buildBoundingsLookup(e,t+this.x,s+this.y)}getNoteX(e,t){if(this.notesPerString.has(e.string)){const s=this.notesPerString.get(e.string);let i=this.x+s.x;switch(t){case as.Left:break;case as.Center:i+=s.noteStringWidth/2;break;case as.Right:i+=s.width}return i}return 0}getNoteY(e,t){if(this.notesPerString.has(e.string)){const s=this.notesPerString.get(e.string);let i=this.y+s.y;switch(t){case is.Top:case is.TopWithStem:i-=s.height/2+2;break;case is.Center:break;case is.Bottom:case is.BottomWithStem:i+=s.height/2}return i}return 0}doLayout(){let e=0;if(this.beat.deadSlapped)this._deadSlapped=new Ko,this._deadSlapped.renderer=this.renderer,this._deadSlapped.doLayout(),e=this._deadSlapped.width,this.noteStringWidth=e;else{let t=0;for(let s=0,i=this._notes.length;s<i;s++){const i=this._notes[s];i.renderer=this.renderer,i.doLayout(),i.width>e&&(e=i.width),i.noteStringWidth>t&&(t=i.noteStringWidth)}this.noteStringWidth=t;const s=this.renderer.resources.tablatureFont.size;let i=this.getNoteY(this.minStringNote,is.Center)+s/2;const a=7;for(const e of this.beatEffects.values())e.y+=i,e.x+=this.width/2,e.renderer=this.renderer,i+=a,e.doLayout()}this.width=e}addNoteGlyph(e,t){this._notes.push(e),this.notesPerString.set(t.string,e),(!this.minStringNote||t.string<this.minStringNote.string)&&(this.minStringNote=t)}paint(e,t,s){if(e+=this.x,t+=this.y,this.beat.deadSlapped)this._deadSlapped?.paint(e,t,s);else{const i=this.renderer.resources,a=s.textBaseline;s.textBaseline=oe.Middle,s.font=this._isGrace?i.graceFont:i.tablatureFont;const r=this._notes,n=this.width;for(const i of r)i.renderer=this.renderer,i.width=n,i.paint(e,t,s);s.textBaseline=a;const o=rn.beat(s,ye.GuitarTabEffects,this.beat);try{for(const i of this.beatEffects.values())i.paint(e,t,s)}finally{o?.[Symbol.dispose]?.()}}}updateBeamingHelper(e){this.beamingHelper&&this.beamingHelper.isPositionFrom("tab",this.beat)&&this.beamingHelper.registerBeatLineX("tab",this.beat,e+this.x+this.width/2,e+this.x+this.width/2)}}class qh extends xr{constructor(e,t,s,i){super(e,t,1,Zo.getSymbol(i)),this._isVisibleRest=s}doLayout(){super.doLayout(),this._isVisibleRest||(this.width=10)}updateBeamingHelper(e){this.beamingHelper&&this.beamingHelper.isPositionFrom("tab",this.beat)&&this.beamingHelper.registerBeatLineX("tab",this.beat,e+this.x+this.width/2,e+this.x+this.width/2)}paint(e,t,s){if(this._isVisibleRest){const i=rn.beat(s,ye.GuitarTabRests,this.beat);try{super.paint(e,t,s)}finally{i?.[Symbol.dispose]?.()}}}}class jh extends Mn{constructor(){super(...arguments),this.slash=null,this.noteNumbers=null,this.restGlyph=null}get effectElement(){return ye.GuitarTabEffects}getNoteX(e,t){return this.noteNumbers?this.noteNumbers.getNoteX(e,t):0}getNoteY(e,t){return this.noteNumbers?this.noteNumbers.getNoteY(e,t):0}buildBoundingsLookup(e,t,s){this.noteNumbers&&this.noteNumbers.buildBoundingsLookup(e,t+this.x,s+this.y)}doLayout(){const e=this.renderer;if(this.container.beat.isRest){const t=Math.floor((this.renderer.bar.staff.tuning.length-1)/2),s=e.getTabY(t),i=new qh(0,s,e.showRests,this.container.beat.duration);if(this.restGlyph=i,i.beat=this.container.beat,i.beamingHelper=this.beamingHelper,this.addNormal(i),this.container.beat.dots>0&&e.showRests){this.addNormal(new hh(0,0,5));for(let e=0;e<this.container.beat.dots;e++)this.addEffect(new Vo(0,s,1.5))}}else{const t=this.renderer.settings.notation.smallGraceTabNotes&&this.container.beat.graceType!==w.None;let s;if(this.container.beat.slashed&&!this.container.beat.notes.some((e=>e.isTieDestination))){const i=Math.floor((this.renderer.bar.staff.tuning.length-1)/2),a=e.getLineY(i),r=new gh(0,a,this.container.beat.duration,t,this.container.beat);r.noteHeadElement=le.GuitarTabFretNumber,r.effectElement=ye.GuitarTabEffects,this.slash=r,r.beat=this.container.beat,r.beamingHelper=this.beamingHelper,this.addNormal(r),s=r.beatEffects}else{const e=new $h(0,0,t);this.noteNumbers=e,e.beat=this.container.beat,e.beamingHelper=this.beamingHelper;for(const e of this.container.beat.notes)e.isVisible&&this.createNoteGlyph(e);this.addNormal(e),s=e.beatEffects}if(this.container.beat.hasWhammyBar){const e=new nh(this.container.beat);e.renderer=this.renderer,e.doLayout(),this.container.ties.push(e)}if(this.container.beat.isTremolo&&!s.has("tremolo")){let e=0;const t=this.container.beat.tremoloSpeed;let i=5;switch(t){case _.ThirtySecond:e=10;break;case _.Sixteenth:e=5;break;case _.Eighth:e=0}this.container.beat.duration<_.Half&&(i=0),s.set("tremolo",new jo(i,e,t))}if(this.container.beat.dots>0&&e.rhythmMode!==F.Hidden){this.addNormal(new hh(0,0,5));for(let t=0;t<this.container.beat.dots;t++)this.addEffect(new Vo(0,e.lineOffset*e.bar.staff.tuning.length+e.settings.notation.rhythmHeight,1.5))}}if(this.isEmpty)return;let t=0;for(let e=0,s=this.glyphs.length;e<s;e++){const s=this.glyphs[e];s.x=t,s.renderer=this.renderer,s.doLayout(),t+=s.width}this.width=t,this.computedWidth=t,this.container.beat.isEmpty?this.centerX=this.width/2:this.restGlyph?this.centerX=this.restGlyph.x+this.restGlyph.width/2:this.noteNumbers?this.centerX=this.noteNumbers.x+this.noteNumbers.noteStringWidth/2:this.slash&&(this.centerX=this.slash.x+this.slash.width/2)}updateBeamingHelper(){this.noteNumbers?this.noteNumbers.updateBeamingHelper(this.container.x+this.x):this.restGlyph?this.restGlyph.updateBeamingHelper(this.container.x+this.x):this.slash&&this.slash.updateBeamingHelper(this.container.x+this.x)}createNoteGlyph(e){const t=this.renderer,s=new Yh(0,0,e),i=e.beat.voice.bar.staff.tuning.length-e.string;s.y=t.getTabY(i),s.renderer=this.renderer,s.doLayout(),this.noteNumbers.addNoteGlyph(s,e);const a=s.y-s.height/2,r=a+s.height;this.renderer.helpers.collisionHelper.reserveBeatSlot(this.container.beat,a,r)}}class Kh extends kr{constructor(e){super(0,0),this._beat=e}doLayout(){this.width=10}paint(e,t,s){const i=this.renderer,a=t+this.x+i.getNoteY(this._beat.maxStringNote,is.Top),r=t+this.y+i.getNoteY(this._beat.minStringNote,is.Bottom),n=e+this.x+this.width/2|0;if(this._beat.brushType!==b.None){if(this._beat.brushType===b.BrushUp||this._beat.brushType===b.BrushDown)s.beginPath(),s.moveTo(n,a),s.lineTo(n,r),s.stroke();else if(this._beat.brushType===b.ArpeggioUp){const t=new Bo(0,0,P.Slight,1.2,!0);t.renderer=this.renderer,t.doLayout();const i=a,n=r-8;t.width=Math.abs(n-i),s.beginRotate(e+this.x+4,n,-90),t.paint(0,-t.height/2,s),s.endRotate()}else if(this._beat.brushType===b.ArpeggioDown){const t=new Bo(0,0,P.Slight,1.2,!0);t.renderer=this.renderer,t.doLayout();const i=a+8,n=r;t.width=Math.abs(n-i),s.beginRotate(e+this.x+4,i,90),t.paint(0,-t.height/2,s),s.endRotate()}this._beat.brushType===b.BrushUp||this._beat.brushType===b.ArpeggioUp?(s.beginPath(),s.moveTo(n,r),s.lineTo(n+4,r-8),s.lineTo(n-4,r-8),s.closePath(),s.fill()):(s.beginPath(),s.moveTo(n,a),s.lineTo(n+4,a+8),s.lineTo(n-4,a+8),s.closePath(),s.fill())}}}class Qh extends Ln{doLayout(){this.container.beat.brushType===b.None||this.container.beat.isRest||(this.addEffect(new Kh(this.container.beat)),this.addNormal(new hh(0,0,4))),super.doLayout()}get effectElement(){return ye.GuitarTabEffects}}class Zh extends kr{doLayout(){this.width=Nr.Widths.get(re.SixStringTabClef)}paint(e,t,s){const i=rn.bar(s,u.GuitarTabsClef,this.renderer.bar);try{const i=this.renderer.bar.staff.tuning.length,a=i<=4?re.FourStringTabClef:re.SixStringTabClef,r=i<=4?i/4.5:i/6.5;s.fillMusicFontSymbol(e+this.x+5,t+this.y,r,a,!1)}finally{i?.[Symbol.dispose]?.()}}}class el extends _h{doLayout(){this.barSubElement=u.GuitarTabsTimeSignature,super.doLayout()}get commonScale(){return 1}get numberScale(){return this.renderer.bar.staff.tuning.length<=4?vr.GraceScale:1}}class tl extends Hh{get showMultiBarRest(){return this._showMultiBarRest}get repeatsBarSubElement(){return u.GuitarTabsRepeats}get barNumberBarSubElement(){return u.GuitarTabsBarNumber}get barLineBarSubElement(){return u.GuitarTabsBarLines}get staffLineBarSubElement(){return u.GuitarTabsStaffLine}constructor(e,t){super(e,t),this._hasTuplets=!1,this.showTimeSignature=!1,this.showRests=!1,this.showTiedNotes=!1,this._showMultiBarRest=!1,t.staff.showStandardNotation||(this.showTimeSignature=!0,this.showRests=!0,this.showTiedNotes=!0,this._showMultiBarRest=!0)}get lineSpacing(){return tl.TabLineSpacing}get heightLineCount(){return this.bar.staff.tuning.length}get drawnLineCount(){return this.bar.staff.tuning.length}get rhythmMode(){let e=this.settings.notation.rhythmMode;return e===F.Automatic&&(e=this.bar.staff.showStandardNotation?F.Hidden:F.ShowWithBars),e}getTabY(e){return super.getLineY(e)}getTabHeight(e){return super.getLineHeight(e)}collectSpaces(e){for(const t of this.bar.voices)if(this.hasVoiceContainer(t)){const s=this.getVoiceContainer(t);for(const t of s.beatGlyphs){const i=t.onNotes,a=i.noteNumbers;if(a)for(const[r,n]of a.notesPerString)n.isEmpty||e[this.bar.staff.tuning.length-r].push(new Float32Array([s.x+t.x+i.x+a.x,a.width+1]))}}}adjustSizes(){this.rhythmMode!==F.Hidden&&(this.height+=this.settings.notation.rhythmHeight,this.bottomPadding+=this.settings.notation.rhythmHeight)}doLayout(){if(super.doLayout(),this.rhythmMode!==F.Hidden){this._hasTuplets=!1;for(const e of this.bar.voices)if(this.hasVoiceContainer(e)){if(this.getVoiceContainer(e).tupletGroups.length>0){this._hasTuplets=!0;break}}this._hasTuplets&&this.registerOverflowBottom(this.tupletSize)}}createLinePreBeatGlyphs(){if(this.isFirstOfLine){const e=(this.bar.staff.tuning.length-1)/2;this.addPreBeatGlyph(new Zh(5,this.getTabY(e)))}this.showTimeSignature&&(!this.bar.previousBar||this.bar.previousBar&&this.bar.masterBar.timeSignatureNumerator!==this.bar.previousBar.masterBar.timeSignatureNumerator||this.bar.previousBar&&this.bar.masterBar.timeSignatureDenominator!==this.bar.previousBar.masterBar.timeSignatureDenominator||this.bar.previousBar&&this.bar.masterBar.isFreeTime&&this.bar.masterBar.isFreeTime!==this.bar.previousBar.masterBar.isFreeTime)&&(this.createStartSpacing(),this.createTimeSignatureGlyphs())}createTimeSignatureGlyphs(){this.addPreBeatGlyph(new hh(0,0,5));const e=(this.bar.staff.tuning.length+1)/2-1;this.addPreBeatGlyph(new el(0,this.getTabY(e),this.bar.masterBar.timeSignatureNumerator,this.bar.masterBar.timeSignatureDenominator,this.bar.masterBar.timeSignatureCommon,this.bar.masterBar.isFreeTime))}createVoiceGlyphs(e){if(this.additionalMultiRestBars){const t=new Rn(this.getVoiceContainer(e));this.addBeatGlyph(t)}else for(const t of e.beats){const s=new Jh(t,this.getVoiceContainer(e));s.preNotes=new Qh,s.onNotes=new jh,this.addBeatGlyph(s)}}paint(e,t,s){super.paint(e,t,s),this.rhythmMode!==F.Hidden&&(this.paintBeams(e,t,s,ye.GuitarTabFlags,ye.GuitarTabBeams),this.paintTuplets(e,t,s,ye.GuitarTabTuplet))}drawBeamHelperAsFlags(e){return super.drawBeamHelperAsFlags(e)||this.rhythmMode===F.ShowWithBeams}getFlagTopY(e,t){const s=this.getOnNotesGlyphForBeat(e);return s.noteNumbers&&e.duration!==_.Half?s.noteNumbers.getNoteY(s.noteNumbers.minStringNote,is.Bottom):this.height-this.settings.notation.rhythmHeight-this.tupletSize}getFlagBottomY(e,t){return this.getFlagAndBarPos()}getFlagStemSize(e,t=!1){return 0}getBarLineStart(e,t){const s=this.getOnNotesGlyphForBeat(e);return s.noteNumbers&&e.duration!==_.Half?s.noteNumbers.getNoteY(s.noteNumbers.minStringNote,is.Bottom)+this.lineOffset/2:this.height-this.settings.notation.rhythmHeight-this.tupletSize}getBeamDirection(e){return Te.Down}getFlagAndBarPos(){return this.height-(this._hasTuplets?this.tupletSize/2:0)}calculateBeamYWithDirection(e,t,s){return this.getFlagAndBarPos()}shouldPaintFlag(e,t){return!!super.shouldPaintFlag(e,t)&&(e.graceType===w.None&&this.drawBeamHelperAsFlags(t))}paintBeamingStem(e,t,s,i,a,r){if(a<i){const e=a;a=i,i=e}const n=rn.beat(r,ye.GuitarTabStem,e);try{r.lineWidth=On.StemWidth,r.beginPath();let n=[];this.helpers.collisionHelper.reservedLayoutAreasByDisplayTime.has(e.displayStart)&&(n=this.helpers.collisionHelper.reservedLayoutAreasByDisplayTime.get(e.displayStart).slots.slice(),n.sort(((e,t)=>e.topY-t.topY)));let o=a;for(;o>i;){r.moveTo(s,o);let e=i;if(!(n.length>0&&n[n.length-1].bottomY>e)){r.lineTo(s,e);break}{const i=n.pop();e=t+i.bottomY,r.lineTo(s,e),o=t+i.topY}}r.stroke(),r.lineWidth=1}finally{n?.[Symbol.dispose]?.()}}}tl.StaffId="tab",tl.TabLineSpacing=10;class sl extends tn{get staffId(){return tl.StaffId}getStaffPaddingTop(e){return e.system.layout.renderer.settings.display.notationStaffPaddingTop}getStaffPaddingBottom(e){return e.system.layout.renderer.settings.display.notationStaffPaddingBottom}constructor(){super(),this.showTimeSignature=null,this.showRests=null,this.showTiedNotes=null,this.hideOnPercussionTrack=!0}canCreate(e,t){return t.showTablature&&t.tuning.length>0&&super.canCreate(e,t)}create(e,t){const s=new tl(e,t);return null!==this.showRests&&(s.showRests=this.showRests),null!==this.showTimeSignature&&(s.showTimeSignature=this.showTimeSignature),null!==this.showTiedNotes&&(s.showTiedNotes=this.showTiedNotes),s}}class il extends Tr{constructor(){super(0,0)}doLayout(){super.doLayout();const e=this.renderer.resources.effectFont;this.height=e.size+il.Padding}paint(e,t,s){const i=this.renderer.resources;s.font=i.effectFont;const a=s.textAlign;s.textAlign=ne.Center,s.fillText("T",e+this.x,t+this.y+s.font.size/2),s.textAlign=a,s.strokeCircle(e+this.x,t+this.y+s.font.size/2+(il.Padding-1),s.font.size/1.6)}}il.Padding=4;class al extends no{get notationElement(){return E.EffectTap}get sizingMode(){return rs.SingleOnBeat}shouldCreateGlyphForNote(e){return e.isLeftHandTapped}createNewGlyph(e,t){return new il}}class rl{constructor(){this.noteRange=1,this.x=0,this.y=0}}!function(e){e[e.None=0]="None",e[e.Rectangle=1]="Rectangle",e[e.Ellipse=2]="Ellipse",e[e.Circle=3]="Circle"}(os||(os={}));class nl extends rl{constructor(){super(...arguments),this.align=ne.Left,this.frame=os.None,this.text="",this.fontFace="",this.weight=0,this.height=0}}class ol extends rl{constructor(){super(...arguments),this.chord=new je}}class hl extends rl{}class ll extends rl{}class cl extends rl{constructor(){super(...arguments),this.number=0}}class dl extends rl{constructor(){super(...arguments),this.decrescendo=!1}}class ul extends rl{constructor(){super(...arguments),this.allNumbers=!1,this.firstNumber=0,this.lastNumber=0}}class pl extends rl{constructor(){super(...arguments),this.octave=1}}class gl extends rl{}class ml{constructor(){this.defaultClef=n.G2,this.description="",this.percussion=!1,this.instrument=0,this.volume=0,this.transpose=0,this.index=0}}class fl{constructor(){this.from=0,this.to=0,this.curly=!1}}class yl{constructor(){this.currentBarIndex=-1,this.currentBarComplete=!0,this.currentBarDuration=0,this.currentPosition=0,this.voiceStemDir=null,this.repeatCount=0,this.repeatEnd=null}}class bl{constructor(){this._trackChannel=0,this._beamingMode=fe.Auto,this._isFirstSystem=!0,this._staffLookup=new Map,this._brackets=[],this._staffLayoutLookup=new Map,this._staffLayouts=[],this._timeSignature=new j,this._voiceStates=new Map}parseXml(e,t){this._galleryObjects=new Map,this._tieStarts=[],this._tieStartIds=new Map,this._voiceCounts=new Map,this._slurs=new Map,this._crescendo=new Map,this._isFirstSystem=!0;const s=new wt;try{s.parse(e)}catch(e){throw new qe("Could not parse XML",e)}this.parseDom(s),this.consolidate(),this.score.finish(t)}consolidate(){ie.consolidate(this.score),bl.applyEffectRange(this._slurs,((e,t)=>{t.isLegatoOrigin=!0})),bl.applyEffectRange(this._crescendo,((e,t)=>{t.crescendo=e.decrescendo?S.Decrescendo:S.Crescendo}))}static applyEffectRange(e,t){for(const[s,i]of e){const e=i.noteRange;let a=s;for(let s=0;s<e;s++)if(t(i,a),a.index+1<a.voice.beats.length)a=a.voice.beats[a.index+1];else{if(!(a.voice.bar.index+1<a.voice.bar.staff.bars.length))break;a=a.voice.bar.staff.bars[a.voice.bar.index+1].voices[a.voice.index].beats[0]}}}parseDom(e){const t=e.firstElement;if(!t)throw new qe("No valid XML");if("score"!==t.localName)throw new qe('Root node of XML was not "score"');this.score=new Je,this.score.tempo=120;for(const e of t.childElements())switch(e.localName){case"info":this.parseInfo(e);break;case"layout":this.parseLayout(e);break;case"gallery":this.parseGallery(e);break;case"pageObjects":this.parsePageObjects(e);break;case"systems":this.parseSystems(e)}}parseLayout(e){for(const t of e.childElements())switch(t.localName){case"staves":this.parseLayoutStaves(t);break;case"brackets":this.parseBrackets(t)}const t=this._brackets.filter((e=>!!e.curly));t.sort(((e,t)=>e.from-t.from));let s=0,i=null;for(let e=0;e<this._staffLayouts.length;e++){const a=this._staffLayouts[e];for(;s<t.length&&e>t[s].to;)s++;i&&s<t.length&&e>t[s].from&&e<=t[s].to?i.ensureStaveCount(i.staves.length+1):(i=new rt,i.ensureStaveCount(1),i.name=a.description,i.playbackInfo.volume=Math.floor(a.volume/128*16),i.playbackInfo.program=a.instrument,a.percussion?(i.playbackInfo.primaryChannel=9,i.playbackInfo.secondaryChannel=9):(i.playbackInfo.primaryChannel=this._trackChannel++,i.playbackInfo.secondaryChannel=this._trackChannel++),this.score.addTrack(i));const r=i.staves[i.staves.length-1];r.isPercussion=a.percussion,r.transpositionPitch=a.transpose,r.displayTranspositionPitch=0,r.showTablature=!1,this._staffLookup.set(a.index,r)}}parseBrackets(e){for(const t of e.childElements())if("bracket"===t.localName)this.parseBracket(t)}parseBracket(e){const t=new fl;t.from=Number.parseInt(e.getAttribute("from")),t.to=Number.parseInt(e.getAttribute("to")),e.attributes.has("curly")&&(t.curly="true"===e.attributes.get("curly")),this._brackets.push(t)}parseLayoutStaves(e){for(const t of e.childElements())if("staffLayout"===t.localName)this.parseStaffLayout(t)}parseStaffLayout(e){const t=new ml;t.description=e.getAttribute("description");for(const s of e.childElements())switch(s.localName){case"notation":s.attributes.has("defaultClef")&&(t.defaultClef=this.parseClef(s.attributes.get("defaultClef")));break;case"sound":s.attributes.has("percussion")&&(t.percussion="true"===s.attributes.get("percussion")),s.attributes.has("instr")&&(t.instrument=Number.parseInt(s.attributes.get("instr"))),s.attributes.has("volume")&&(t.volume=Number.parseInt(s.attributes.get("volume"))),s.attributes.has("transpose")&&(t.transpose=Number.parseInt(s.attributes.get("transpose")))}this._staffLayoutLookup.set(t.description,t),t.index=this._staffLayouts.length,this._staffLayouts.push(t)}parseClef(e){switch(e){case"treble":return n.G2;case"bass":return n.F4;case"alto":case"tenor":return n.C4}return n.G2}parseClefOttava(e){return e.endsWith("-")?o._8vb:e.endsWith("+")?o._8va:o.Regular}parseSystems(e){for(const t of e.childElements())if("system"===t.localName)this.parseSystem(t)}parseSystem(e){e.attributes.has("tempo")&&0===this.score.masterBars.length&&(this.score.tempo=Number.parseInt(e.attributes.get("tempo"))),"0"===e.getAttribute("beamGrouping")&&(this._beamingMode=fe.ForceSplitToNext);for(const t of e.childElements())if("staves"===t.localName)this.parseStaves(e,t);this._isFirstSystem=!1}parseStaves(e,t){const s=this.score.masterBars.length;for(const i of t.childElements())if("staff"===i.localName)this.parseStaff(e,s,i)}parseStaff(e,t,s){const i=s.getAttribute("layout");this._currentStaffLayout=this._staffLayoutLookup.get(i),this._timeSignature.timeSignatureNumerator=4,this._timeSignature.timeSignatureDenominator=4,this._timeSignature.timeSignatureCommon=!1,this.parseTime(s.getAttribute("defaultTime"));const a=this._staffLookup.get(this._currentStaffLayout.index);for(;a.bars.length<t;)this.addNewBar(a);for(const r of s.childElements())if("voices"===r.localName)this.parseVoices(i,a,e,t,r)}parseTime(e){switch(e){case"allaBreve":case"C":this._timeSignature.timeSignatureNumerator=2,this._timeSignature.timeSignatureDenominator=2,this._timeSignature.timeSignatureCommon=!0;break;case"longAllaBreve":this._timeSignature.timeSignatureNumerator=4,this._timeSignature.timeSignatureDenominator=4,this._timeSignature.timeSignatureCommon=!0;break;default:if(e.indexOf("/")>0){const t=e.split("/");this._timeSignature.timeSignatureNumerator=Number.parseInt(t[0]),this._timeSignature.timeSignatureDenominator=Number.parseInt(t[1]),this._timeSignature.timeSignatureCommon=!1}}}parseVoices(e,t,s,i,a){let r=0;for(const n of a.childElements())if("voice"===n.localName)this.parseVoice(e,t,s,r,i,n),r++}getOrCreateBar(e,t){return t<e.bars.length?e.bars[t]:this.addNewBar(e)}addNewBar(e){const t=new G;if(e.bars.length>0?(t.clef=e.bars[e.bars.length-1].clef,t.clefOttava=e.bars[e.bars.length-1].clefOttava,t.keySignature=e.bars[e.bars.length-1].keySignature,t.keySignatureType=e.bars[e.bars.length-1].keySignatureType):t.clef=this._currentStaffLayout.defaultClef,e.addBar(t),e.bars.length>this.score.masterBars.length){const e=new j;this.score.addMasterBar(e),e.index>0&&(e.tripletFeel=e.previousMasterBar.tripletFeel),e.timeSignatureDenominator=this._timeSignature.timeSignatureDenominator,e.timeSignatureNumerator=this._timeSignature.timeSignatureNumerator,e.timeSignatureCommon=this._timeSignature.timeSignatureCommon}return t}newBar(e,t){this._currentVoiceState.currentBarIndex++,this._currentBar=this.getOrCreateBar(e,this._currentVoiceState.currentBarIndex),this._currentVoiceState.currentBarDuration=this._currentBar.masterBar.calculateDuration(!1),this._currentVoiceState.currentBarComplete=!1,this._currentVoiceState.currentPosition=0,this.ensureVoice(e,t)}parseVoice(e,t,s,i,a,r){const n=`${e}_${i}`;if(this._currentVoiceState&&!this._currentVoiceState.currentBarComplete&&(this._currentBar.masterBar.isAnacrusis=!0),this._voiceStates.has(n)?(this._currentVoiceState=this._voiceStates.get(n),this._currentBar=this.getOrCreateBar(t,this._currentVoiceState.currentBarIndex),this.ensureVoice(t,i)):(this._currentVoiceState=new yl,this._currentVoiceState.currentBarIndex=a-1,this._voiceStates.set(n,this._currentVoiceState),this.newBar(t,i)),r.attributes.has("stemDir"))switch(r.attributes.get("stemDir")){case"up":this._currentVoiceState.voiceStemDir=Te.Up;break;case"down":this._currentVoiceState.voiceStemDir=Te.Down;break;default:this._currentVoiceState.voiceStemDir=null}else this._currentVoiceState.voiceStemDir=null;const o=r.findChildElement("noteObjects");if(s.attributes.has("tempo")){const e=new U;e.isLinear=!0,e.type=m.Tempo,e.value=Number.parseInt(s.attributes.get("tempo")),e.ratioPosition=this._currentVoiceState.currentPosition/this._currentVoiceState.currentBarDuration,this._currentBar.masterBar.tempoAutomations.push(e)}if(o)for(const e of o.childElements())switch(this._currentVoiceState.currentBarComplete&&"barline"!==e.localName&&this.newBar(t,i),e.localName){case"clefSign":this._currentBar.clef=this.parseClef(e.getAttribute("clef")),this._currentBar.clefOttava=this.parseClefOttava(e.getAttribute("clef"));break;case"keySign":this._currentBar.keySignature=Number.parseInt(e.getAttribute("fifths"));break;case"timeSign":this.parseTime(e.getAttribute("time")),this._currentBar.masterBar.timeSignatureDenominator=this._timeSignature.timeSignatureDenominator,this._currentBar.masterBar.timeSignatureNumerator=this._timeSignature.timeSignatureNumerator,this._currentBar.masterBar.timeSignatureCommon=this._timeSignature.timeSignatureCommon,this._currentVoiceState.currentPosition=0,this._currentVoiceState.currentBarDuration=this._currentBar.masterBar.calculateDuration(!1);break;case"barline":switch(e.getAttribute("type")){case"double":this._currentBar.barLineRight=p.LightLight,this._currentVoiceState.currentBarComplete||(this._currentBar.masterBar.isAnacrusis=!0),this._currentVoiceState.currentBarComplete=!0;break;case"end":this._currentVoiceState.currentBarComplete||(this._currentBar.masterBar.isAnacrusis=!0);break;case"repEnd":this._currentVoiceState.repeatEnd=this._currentBar.masterBar,this._currentBar.masterBar.repeatCount<this._currentVoiceState.repeatCount&&(this._currentBar.masterBar.repeatCount=this._currentVoiceState.repeatCount),this.parseBarDrawObject(e),this._currentVoiceState.currentBarComplete||(this._currentBar.masterBar.isAnacrusis=!0),this._currentVoiceState.currentBarComplete=!0;break;case"repBegin":this.newBar(t,i),this._currentBar.masterBar.isRepeatStart=!0,this._currentVoiceState.repeatEnd=null,this._currentVoiceState.repeatCount=0;break;case"repEndBegin":this._currentVoiceState.repeatEnd=this._currentBar.masterBar,this._currentBar.masterBar.repeatCount<this._currentVoiceState.repeatCount&&(this._currentBar.masterBar.repeatCount=this._currentVoiceState.repeatCount),this.parseBarDrawObject(e),this.newBar(t,i),this._currentBar.masterBar.isRepeatStart=!0;break;default:this._currentVoiceState.currentBarComplete||(this._currentBar.masterBar.isAnacrusis=!0),this._currentVoiceState.currentBarComplete=!0}break;case"chord":const s=new ze;this.initFromPreviousBeat(s,this._currentVoice),s.beamingMode=this._beamingMode,this._currentVoiceState.voiceStemDir&&(s.preferredBeamDirection=this._currentVoiceState.voiceStemDir),this.parseDuration(this._currentBar,s,e.findChildElement("duration")),s.updateDurations(),this._currentVoiceState.currentPosition+=s.playbackDuration,this._currentVoice.addBeat(s),this.parseChord(s,e),this._currentVoiceState.currentPosition>=this._currentVoiceState.currentBarDuration&&(this._currentVoiceState.currentBarComplete=!0);break;case"rest":const a=this.parseRestDurations(this._currentBar,e.findChildElement("duration"));a&&(this.initFromPreviousBeat(a,this._currentVoice),a.updateDurations(),this._currentVoiceState.currentPosition+=a.playbackDuration,this._currentVoice.addBeat(a),this._currentVoiceState.currentPosition>=this._currentVoiceState.currentBarDuration&&(this._currentVoiceState.currentBarComplete=!0))}}initFromPreviousBeat(e,t){const s=this.getLastBeat(t);s&&(e.dynamics=s.dynamics)}getLastBeat(e){if(e.beats.length>0)return e.beats[e.beats.length-1];if(e.bar.index>0){const t=e.bar.staff.bars[e.bar.index-1];if(e.index<t.voices.length){const s=t.voices[e.index];return this.getLastBeat(s)}}return null}ensureVoice(e,t){for(;this._currentBar.voices.length<t+1;)this._currentBar.addVoice(new ee);(!this._voiceCounts.has(e.track.index)||this._voiceCounts.get(e.track.index)<this._currentBar.voices.length)&&this._voiceCounts.set(e.track.index,this._currentBar.voices.length),this._currentVoice=this._currentBar.voices[t]}parseChord(e,t){const s=new Ae;for(const i of t.childElements())switch(i.localName){case"stem":switch(i.getAttribute("dir")){case"up":e.preferredBeamDirection=Te.Up;break;case"down":e.preferredBeamDirection=Te.Down}break;case"articulation":switch(i.getAttribute("type")){case"staccato":s.isStaccato=!0;break;case"normalAccent":s.accentuated=B.Normal;break;case"strongAccent":s.accentuated=B.Heavy}break;case"lyric":this.parseLyric(e,i);break;case"drawObjects":this.parseBeatDrawObject(e,i);break;case"heads":this.parseHeads(e,s,i);break;case"beam":switch(i.getAttribute("group")){case"force":e.beamingMode=fe.ForceMergeWithNext;break;case"divide":e.beamingMode=fe.ForceSplitToNext}}}parseHeads(e,t,s){for(const i of s.childElements())if("head"===i.localName)this.parseHead(e,t,i)}parseHead(e,t,s){const i=new Ae,a=ie.parseTuning(s.getAttribute("pitch"));i.octave=a.octave-1,i.tone=a.tone.noteValue,i.isStaccato=t.isStaccato,i.accentuated=t.accentuated,e.addNote(i);for(const e of s.childElements())switch(e.localName){case"alter":e.attributes.has("step")&&(i.tone+=Number.parseInt(e.attributes.get("step")));break;case"tie":e.attributes.has("begin")?this._tieStartIds.has(i.id)||(this._tieStartIds.set(i.id,!0),this._tieStarts.push(i)):e.attributes.has("end")&&this._tieStarts.length>0&&!i.isTieDestination&&(i.isTieDestination=!0,i.tieOrigin=this._tieStarts[0],this._tieStarts.splice(0,1),this._tieStartIds.delete(i.id))}}parseBeatDrawObject(e,t){for(const s of t.childElements())if("drawObj"===s.localName){const t=this.parseDrawObj(s);if(t)if(t instanceof nl)t.fontFace.startsWith("capella")?"u"===t.text?(e.fermata=new lt,e.fermata.type=ke.Medium):"f"===t.text?e.dynamics=g.F:"j"===t.text&&(e.dynamics=g.MF):this._isFirstSystem&&""===this.score.title&&t.align===ne.Center&&t.height>16&&t.weight>400?this.score.title=t.text:this._isFirstSystem&&""===this.score.artist&&t.align===ne.Center&&t.y<0?this.score.artist=t.text:this._isFirstSystem&&""===this.score.music&&t.align===ne.Right&&t.y<0?this.score.music=t.text:t.text.startsWith("by capella")||(e.text=t.text);else if(t instanceof ol);else if(t instanceof ll)e.vibrato=P.Slight;else if(t instanceof dl)e.crescendo=t.decrescendo?S.Decrescendo:S.Crescendo,t.noteRange++,this._crescendo.set(e,t);else if(t instanceof hl){const s=t;this._slurs.set(e,s)}else t instanceof ul&&this.applyVolta(t)}}parseBarDrawObject(e){for(const t of e.childElements())if("drawObj"===t.localName){const e=this.parseDrawObj(t);e&&e instanceof ul&&this.applyVolta(e)}}applyVolta(e){if(e.lastNumber>0?(this._currentVoiceState.repeatCount=e.lastNumber,this._currentVoiceState.repeatEnd&&this._currentVoiceState.repeatEnd.repeatCount<this._currentVoiceState.repeatCount&&(this._currentVoiceState.repeatEnd.repeatCount=this._currentVoiceState.repeatCount)):e.firstNumber>0&&(this._currentVoiceState.repeatCount=e.firstNumber,this._currentVoiceState.repeatEnd&&this._currentVoiceState.repeatEnd.repeatCount<this._currentVoiceState.repeatCount&&(this._currentVoiceState.repeatEnd.repeatCount=this._currentVoiceState.repeatCount)),e.lastNumber>0&&e.firstNumber>0){let t=0;for(let s=e.firstNumber;s<=e.lastNumber;s++)t|=1<<s-1;this._currentBar.masterBar.alternateEndings=t}else e.lastNumber>0?this._currentBar.masterBar.alternateEndings=1<<e.lastNumber-1:e.firstNumber>0&&(this._currentBar.masterBar.alternateEndings=1<<e.firstNumber-1)}parseLyric(e,t){for(const s of t.childElements())if("verse"===s.localName){e.lyrics||(e.lyrics=[]);let t=s.innerText;"true"===s.getAttribute("hyphen")&&(t+="-"),e.lyrics.push(t)}}parseRestDurations(e,t){const s=t.getAttribute("base");if(-1!==s.indexOf("/")){const s=new ze;return s.beamingMode=this._beamingMode,this.parseDuration(e,s,t),s}if(1===Number.parseInt(s)){const e=new ze;return e.beamingMode=this._beamingMode,e.duration=_.Whole,e}return q.warning("Importer","Multi-Bar rests are not supported"),null}parseDurationValue(e){switch(e){case"2/1":return _.DoubleWhole;case"1/1":return _.Whole;case"1/2":return _.Half;case"1/4":return _.Quarter;case"1/8":return _.Eighth;case"1/16":return _.Sixteenth;case"1/32":return _.ThirtySecond;case"1/64":return _.SixtyFourth;case"1/128":return _.OneHundredTwentyEighth;default:return q.warning("Importer","Unsupported duration"),_.Quarter}}parseDuration(e,t,s){const i=s.getAttribute("base");t.duration=this.parseDurationValue(i),s.attributes.has("dots")&&(t.dots=Number.parseInt(s.attributes.get("dots")));const a=s.findChildElement("tuplet");if(a){t.tupletNumerator=Number.parseInt(a.getAttribute("count"));const e="true"===a.getAttribute("tripartite")?3:1,s="true"===a.getAttribute("prolong")?0:1;let i=0;for(;e*Math.pow(2,i+s)<t.tupletNumerator;)i++;t.tupletDenominator=e*Math.pow(2,i)}}parsePageObjects(e){for(const t of e.childElements())if("drawObj"===t.localName){const e=this.parseDrawObj(t);if(e&&e instanceof nl)switch(e.align){case ne.Center:this.score.title?this.score.subTitle||(this.score.subTitle=t.innerText):this.score.title=t.innerText;break;case ne.Right:this.score.artist||(this.score.artist=t.innerText)}}}parseGallery(e){for(const t of e.childElements())if("drawObj"===t.localName){const e=this.parseDrawObj(t);e&&this._galleryObjects.set(t.getAttribute("name"),e)}}parseDrawObj(e){let t=null,s=1;for(const i of e.childElements())switch(i.localName){case"text":t=this.parseText(i);break;case"guitar":t=this.parseGuitar(i);break;case"slur":t=this.parseSlur(i);break;case"wavyLine":t=this.parseWavyLine(i);break;case"bracket":t=this.parseTupletBracket(i);break;case"wedge":t=this.parseWedge(i);break;case"volta":t=this.parseVolta(i);break;case"octaveClef":t=this.parseOctaveClef(i);break;case"trill":t=this.parseTrill(i);break;case"basic":i.attributes.has("noteRange")&&(s=Number.parseInt(i.attributes.get("noteRange")))}return t&&(t.noteRange=s),t}parseTrill(e){return new gl}parseOctaveClef(e){const t=new pl;return e.attributes.has("octave")&&(t.octave=Number.parseInt(e.attributes.get("octave"))),t}parseVolta(e){const t=new ul;return t.allNumbers="true"===e.attributes.get("allNumbers"),e.attributes.has("firstNumber")&&(t.firstNumber=Number.parseInt(e.attributes.get("firstNumber"))),e.attributes.has("lastNumber")&&(t.lastNumber=Number.parseInt(e.attributes.get("lastNumber"))),t}parseWedge(e){const t=new dl;return t.decrescendo="true"===e.attributes.get("decrescendo"),t}parseTupletBracket(e){const t=new cl;return e.attributes.has("number")&&(t.number=Number.parseInt(e.attributes.get("number"))),t}parseWavyLine(e){return new ll}parseSlur(e){return new hl}parseGuitar(e){const t=new ol,s=e.innerText.trim();for(let e=0;e<s.length;e++)"/"===s.charAt(e)?t.chord.strings.push(0):t.chord.strings.push(Number.parseInt(s.charAt(e)));return t}parseText(e){const t=new nl;switch(e.attributes.has("x")&&(t.x=Number.parseFloat(e.attributes.get("x"))),e.attributes.has("x")&&(t.y=Number.parseFloat(e.attributes.get("y"))),e.getAttribute("align")){case"left":t.align=ne.Left;break;case"center":t.align=ne.Center;break;case"right":t.align=ne.Right}switch(e.getAttribute("frame")){case"rectangle":t.frame=os.Rectangle;break;case"ellipse":t.frame=os.Ellipse;break;case"circle":t.frame=os.Circle;break;case"none":t.frame=os.None}if(e.firstElement)for(const s of e.childElements())switch(s.localName){case"font":t.fontFace=s.getAttribute("face"),s.attributes.has("weight")&&(t.weight=Number.parseInt(s.attributes.get("weight"))),s.attributes.has("height")&&(t.height=Number.parseInt(s.attributes.get("height")));break;case"content":t.text=s.innerText}else t.text=e.innerText;return t}parseInfo(e){for(const t of e.childElements())switch(t.localName){case"author":this.score.tab=t.firstChild.innerText;break;case"comment":this.score.notices=t.firstChild.innerText}}}class Sl extends Ye{get name(){return"Capella"}readScore(){q.debug(this.name,"Loading ZIP entries");let e,t=null;if(e=new ds(this.data).read(),q.debug(this.name,"Zip entries loaded"),e.length>0){for(const s of e)if("score.xml"===s.fileName)t=ot.toString(s.data,this.settings.importer.encoding)}else this.data.reset(),t=ot.toString(this.data.readAll(),this.settings.importer.encoding);if(!t)throw new qe("No valid capella file");q.debug(this.name,"Start Parsing score.xml");try{const e=new bl;e.parseXml(t,this.settings),q.debug(this.name,"score.xml parsed");return e.score}catch(e){throw new qe("Failed to parse CapXML",e)}}}class _l{constructor(e){this._targets=new Set,this._callback=e,window.addEventListener("resize",this.onWindowResize.bind(this),!1)}observe(e){this._targets.add(e)}unobserve(e){this._targets.delete(e)}disconnect(){this._targets.clear()}onWindowResize(){const e=[];for(const t of this._targets)e.push({target:t,contentRect:void 0,borderBoxSize:void 0,contentBoxSize:[],devicePixelContentBoxSize:[]});this._callback(e,this)}}class wl{constructor(e){this._elements=[];let t=null;const s=this.check.bind(this);this.check=()=>{t||(t=setTimeout((()=>{s(),t=null}),100))},this._callback=e,window.addEventListener("resize",this.check,!0),document.addEventListener("scroll",this.check,!0)}observe(e){this._elements.indexOf(e)>=0||(this._elements.push(e),this.check())}unobserve(e){this._elements=this._elements.filter((t=>t!==e))}check(){const e=[];for(const t of this._elements){const s=t.getBoundingClientRect();s.top+s.height>=0&&s.top<=window.innerHeight&&s.left+s.width>=0&&s.left<=window.innerWidth&&e.push({target:t,isIntersecting:!0})}e.length&&this._callback(e,this)}}var Bl="function"==typeof SuppressedError?SuppressedError:function(e,t,s){var i=new Error(s);return i.name="SuppressedError",i.error=e,i.suppressed=t,i};class kl{static enable(e,t){kl.alphaSkia=t,kl.initializeMusicFont(kl.alphaSkia.AlphaSkiaTypeface.register(e))}static initializeMusicFont(e){kl.musicTextStyle=new kl.alphaSkia.AlphaSkiaTextStyle([e.familyName],e.weight,e.isItalic)}static registerFont(e,t){const s=kl.alphaSkia.AlphaSkiaTypeface.register(e.buffer);return t||(t=na.withFamilyList([s.familyName],12,s.isItalic?Jt.Italic:Jt.Plain,s.weight>400?Yt.Bold:Yt.Regular)),t}get font(){return this._font}set font(e){if(this._font===e)return;this._font=e;const t=this.textStyleKey(e);if(this._textStyles.has(t))this._textStyle=this._textStyles.get(t);else{const s=new kl.alphaSkia.AlphaSkiaTextStyle(e.families,e.weight===Yt.Bold?700:400,e.isItalic);this._textStyles.set(t,s),this._textStyle=s}}textStyleKey(e){return[...e.families,e.weight.toString(),e.isItalic?"italic":"upright"].join("_")}constructor(){this._color=new et(0,0,0,0),this._lineWidth=0,this._textStyle=null,this._scale=1,this._textStyles=new Map,this._font=new na("Arial",10,Jt.Plain),this.textAlign=ne.Left,this.textBaseline=oe.Top,this._canvas=new kl.alphaSkia.AlphaSkiaCanvas,this.color=new et(0,0,0,255)}destroy(){this._canvas[Symbol.dispose]();for(const e of this._textStyles.values())e[Symbol.dispose]()}onRenderFinished(){return null}beginRender(e,t){this._scale=this.settings.display.scale,this._canvas.beginRender(e,t,rc.HighDpiFactor)}endRender(){return this._canvas.endRender()}get color(){return this._color}set color(e){this._color.rgba!==e.rgba&&(this._color=e,this._canvas.color=kl.alphaSkia.AlphaSkiaCanvas.rgbaToColor(e.r,e.g,e.b,e.a))}get lineWidth(){return this._lineWidth}set lineWidth(e){this._lineWidth=e,this._canvas.lineWidth=e}fillRect(e,t,s,i){s>0&&this._canvas.fillRect(e*this._scale|0,t*this._scale|0,s*this._scale,i*this._scale)}strokeRect(e,t,s,i){const a=this.lineWidth%2==0?0:.5;this._canvas.strokeRect((e*this._scale|0)+a,(t*this._scale|0)+a,s*this._scale,i*this._scale)}beginPath(){this._canvas.beginPath()}closePath(){this._canvas.closePath()}moveTo(e,t){this._canvas.moveTo(e*this._scale,t*this._scale)}lineTo(e,t){this._canvas.lineTo(e*this._scale,t*this._scale)}quadraticCurveTo(e,t,s,i){this._canvas.quadraticCurveTo(e*this._scale,t*this._scale,s*this._scale,i*this._scale)}bezierCurveTo(e,t,s,i,a,r){this._canvas.bezierCurveTo(e*this._scale,t*this._scale,s*this._scale,i*this._scale,a*this._scale,r*this._scale)}fillCircle(e,t,s){this._canvas.fillCircle(e*this._scale,t*this._scale,s*this._scale)}strokeCircle(e,t,s){this._canvas.strokeCircle(e*this._scale,t*this._scale,s*this._scale)}fill(){this._canvas.fill()}stroke(){this._canvas.stroke()}beginGroup(e){}endGroup(){}fillText(e,t,s){if(0===e.length)return;let i=kl.alphaSkia.AlphaSkiaTextAlign.Left;switch(this.textAlign){case ne.Left:i=kl.alphaSkia.AlphaSkiaTextAlign.Left;break;case ne.Center:i=kl.alphaSkia.AlphaSkiaTextAlign.Center;break;case ne.Right:i=kl.alphaSkia.AlphaSkiaTextAlign.Right}let a=kl.alphaSkia.AlphaSkiaTextBaseline.Top;switch(this.textBaseline){case oe.Top:a=kl.alphaSkia.AlphaSkiaTextBaseline.Top;break;case oe.Middle:a=kl.alphaSkia.AlphaSkiaTextBaseline.Middle;break;case oe.Bottom:a=kl.alphaSkia.AlphaSkiaTextBaseline.Bottom}this._canvas.fillText(e,this._textStyle,this._font.size*this._scale,t*this._scale|0,s*this._scale|0,i,a)}measureText(e){const t={stack:[],error:void 0,hasError:!1};try{const s=function(e,t,s){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var i,a;if(s){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");i=t[Symbol.asyncDispose]}if(void 0===i){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");i=t[Symbol.dispose],s&&(a=i)}if("function"!=typeof i)throw new TypeError("Object not disposable.");a&&(i=function(){try{a.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:i,async:s})}else s&&e.stack.push({async:!0});return t}(t,this._canvas.measureText(e,this._textStyle,this._font.size,kl.alphaSkia.AlphaSkiaTextAlign.Left,kl.alphaSkia.AlphaSkiaTextBaseline.Alphabetic),!1);return new De(s.width,s.actualBoundingBoxAscent+s.actualBoundingBoxDescent)}catch(e){t.error=e,t.hasError=!0}finally{!function(e){function t(t){e.error=e.hasError?new Bl(t,e.error,"An error was suppressed during disposal."):t,e.hasError=!0}var s,i=0;(function a(){for(;s=e.stack.pop();)try{if(!s.async&&1===i)return i=0,e.stack.push(s),Promise.resolve().then(a);if(s.dispose){var r=s.dispose.call(s.value);if(s.async)return i|=2,Promise.resolve(r).then(a,(function(e){return t(e),a()}))}else i|=1}catch(e){t(e)}if(1===i)return e.hasError?Promise.reject(e.error):Promise.resolve();if(e.hasError)throw e.error})()}(t)}}fillMusicFontSymbol(e,t,s,i,a){i!==re.None&&this.fillMusicFontSymbolText(e,t,s,String.fromCharCode(i),a)}fillMusicFontSymbols(e,t,s,i,a){let r="";for(const e of i)e!==re.None&&(r+=String.fromCharCode(e));this.fillMusicFontSymbolText(e,t,s,r,a)}fillMusicFontSymbolText(e,t,s,i,a){this._canvas.fillText(i,kl.musicTextStyle,rc.MusicFontSize*this._scale*s,e*this._scale,t*this._scale,a?kl.alphaSkia.AlphaSkiaTextAlign.Center:kl.alphaSkia.AlphaSkiaTextAlign.Left,kl.alphaSkia.AlphaSkiaTextBaseline.Alphabetic)}beginRotate(e,t,s){this._canvas.beginRotate(e*this._scale,t*this._scale,s)}endRotate(){this._canvas.endRotate()}}kl.musicTextStyle=null;class Tl extends Uo{constructor(e,t,s=!1){super(e.beat,t.beat,s),this.startNote=e,this.endNote=t}getTieHeight(e,t,s,i){return this.startNote===this.endNote?15:super.getTieHeight(e,t,s,i)}getBeamDirection(e,t){return Te.Down}static getBeamDirectionForNote(e){return Te.Down}getStartY(){return this.startNoteRenderer.getNoteY(this.startNote,is.Center)}getEndY(){return this.getStartY()}getStartX(){return this.startNote===this.endNote?this.getEndX()-20:this.startNoteRenderer.getNoteX(this.startNote,as.Right)}getEndX(){return this.endNoteRenderer.getNoteX(this.endNote,as.Left)}}class Nl extends Fr{constructor(){super(...arguments),this._tiedNoteTie=null}createTies(e){if(e.isVisible){if(!this._tiedNoteTie&&e.isTieOrigin&&e.tieDestination.isVisible){const t=new Tl(e,e.tieDestination,!1);this._tiedNoteTie=t,this.addTie(t)}if(!this._tiedNoteTie&&e.isTieDestination){const t=new Tl(e.tieOrigin,e,!0);this._tiedNoteTie=t,this.addTie(t)}}}}class xl extends Zo{updateBeamingHelper(e){this.beamingHelper&&this.beamingHelper.registerBeatLineX("slash",this.beat,e+this.x+this.width/2,e+this.x+this.width/2)}paint(e,t,s){super.internalPaint(e,t,s,ye.SlashRests)}}class vl extends Mn{constructor(){super(...arguments),this.noteHeads=null,this.deadSlapped=null,this.restGlyph=null}get effectElement(){return ye.SlashEffects}getNoteX(e,t){let s=null;if(this.noteHeads?s=this.noteHeads:this.deadSlapped&&(s=this.deadSlapped),s){let e=s.x;switch(t){case as.Left:break;case as.Center:e+=s.width/2;break;case as.Right:e+=s.width}return e}return 0}buildBoundingsLookup(e,t,s){if(this.noteHeads&&this.container.beat.notes.length>0){const i=new ir;i.note=this.container.beat.notes[0],i.noteHeadBounds=new mt,i.noteHeadBounds.x=t+this.x+this.noteHeads.x,i.noteHeadBounds.y=s+this.y+this.noteHeads.y-this.noteHeads.height/2,i.noteHeadBounds.w=this.width,i.noteHeadBounds.h=this.height,e.addNote(i)}}getNoteY(e,t){let s=null;if(this.noteHeads?s=this.noteHeads:this.deadSlapped&&(s=this.deadSlapped),s){let e=this.y+s.y;switch(t){case is.Top:case is.TopWithStem:e-=s.height/2+2;break;case is.Center:break;case is.Bottom:case is.BottomWithStem:e+=s.height/2}return e}return 0}updateBeamingHelper(){this.noteHeads?this.noteHeads.updateBeamingHelper(this.container.x+this.x):this.deadSlapped?this.beamingHelper&&this.beamingHelper.registerBeatLineX("slash",this.container.beat,this.container.x+this.x+this.deadSlapped.x+this.width,this.container.x+this.x+this.deadSlapped.x):this.restGlyph&&this.restGlyph.updateBeamingHelper(this.container.x+this.x)}doLayout(){const e=this.renderer,t=e.getNoteLine(),s=e.getLineY(t);if(this.container.beat.deadSlapped){const e=new Ko;e.renderer=this.renderer,e.doLayout(),this.deadSlapped=e,this.addEffect(e)}else if(!this.container.beat.isEmpty)if(this.container.beat.isRest){const e=new xl(0,s,this.container.beat.duration);this.restGlyph=e,e.beat=this.container.beat,e.beamingHelper=this.beamingHelper,this.addNormal(e),this.beamingHelper&&this.beamingHelper.applyRest(this.container.beat,0)}else{const e=this.container.beat.graceType!==w.None,t=new gh(0,s,this.container.beat.duration,e,this.container.beat);this.noteHeads=t,t.beat=this.container.beat,t.beamingHelper=this.beamingHelper,this.addNormal(t)}if(this.container.beat.dots>0){this.addNormal(new hh(0,0,5));for(let t=0;t<this.container.beat.dots;t++)this.addEffect(new Vo(0,e.getLineY(e.getNoteLine())-e.getLineHeight(.5),1.5))}super.doLayout(),this.container.beat.isEmpty?this.centerX=this.width/2:this.restGlyph?this.centerX=this.restGlyph.x+this.restGlyph.width/2:this.noteHeads?this.centerX=this.noteHeads.x+this.noteHeads.width/2:this.deadSlapped&&(this.centerX=this.deadSlapped.x+this.deadSlapped.width/2)}}class Pl extends Hh{constructor(e,t){super(e,t),this.simpleWhammyOverflow=0,this._isOnlySlash=!t.staff.showTablature&&!t.staff.showStandardNotation,this.helpers.preferredBeamDirection=Te.Up}get repeatsBarSubElement(){return u.SlashRepeats}get barNumberBarSubElement(){return u.SlashBarNumber}get barLineBarSubElement(){return u.SlashBarLines}get staffLineBarSubElement(){return u.SlashStaffLine}get lineSpacing(){return On.RawLineSpacing}get heightLineCount(){return 5}get drawnLineCount(){return 1}get bottomGlyphOverflow(){return 0}paint(e,t,s){super.paint(e,t,s),this.paintBeams(e,t,s,ye.SlashFlags,ye.SlashBeams),this.paintTuplets(e,t,s,ye.SlashTuplet)}doLayout(){super.doLayout();let e=!1;for(const t of this.bar.voices)if(this.hasVoiceContainer(t)){if(this.getVoiceContainer(t).tupletGroups.length>0){e=!0;break}}e&&this.registerOverflowTop(this.tupletSize)}getNoteLine(){return 0}getFlagTopY(e,t){const s=Nr.Heights.get(re.NoteheadSlashWhiteHalf);return this.getLineY(0)-s/2}getFlagBottomY(e,t){const s=Nr.Heights.get(re.NoteheadSlashWhiteHalf);return this.getLineY(0)-s/2}getBeamDirection(e){return Te.Up}getNoteY(e,t){let s=super.getNoteY(e,t);return Number.isNaN(s)&&(s=this.getLineY(0)),s}calculateBeamYWithDirection(e,t,s){return this.getLineY(0)-this.getFlagStemSize(e.shortestDuration)}getBarLineStart(e,t){const s=Nr.Heights.get(re.NoteheadSlashWhiteHalf);return this.getLineY(0)-s/2}createLinePreBeatGlyphs(){this._isOnlySlash&&(!this.bar.previousBar||this.bar.previousBar&&this.bar.masterBar.timeSignatureNumerator!==this.bar.previousBar.masterBar.timeSignatureNumerator||this.bar.previousBar&&this.bar.masterBar.timeSignatureDenominator!==this.bar.previousBar.masterBar.timeSignatureDenominator||this.bar.previousBar&&this.bar.masterBar.isFreeTime&&this.bar.masterBar.isFreeTime!==this.bar.previousBar.masterBar.isFreeTime)&&(this.createStartSpacing(),this.createTimeSignatureGlyphs())}createTimeSignatureGlyphs(){this.addPreBeatGlyph(new hh(0,0,5));const e=this.bar.masterBar,t=new wh(0,this.getLineY(0),e.timeSignatureNumerator,e.timeSignatureDenominator,e.timeSignatureCommon,e.isFreeTime&&(null==e.previousMasterBar||e.isFreeTime!==e.previousMasterBar.isFreeTime));t.barSubElement=u.SlashTimeSignature,this.addPreBeatGlyph(t)}createVoiceGlyphs(e){for(const t of e.beats){const s=new Nl(t,this.getVoiceContainer(e));s.preNotes=new Ln,s.onNotes=0===e.index?new vl:new Mn,this.addBeatGlyph(s)}}paintBeamingStem(e,t,s,i,a,r){const n=rn.beat(r,ye.SlashStem,e);try{r.lineWidth=On.StemWidth,r.beginPath(),r.moveTo(s,i),r.lineTo(s,a),r.stroke(),r.lineWidth=1}finally{n?.[Symbol.dispose]?.()}}}Pl.StaffId="slash";class Fl extends tn{get staffId(){return Pl.StaffId}getStaffPaddingTop(e){return e.system.layout.renderer.settings.display.notationStaffPaddingTop}getStaffPaddingBottom(e){return e.system.layout.renderer.settings.display.notationStaffPaddingBottom}create(e,t){return new Pl(e,t)}canCreate(e,t){return super.canCreate(e,t)&&t.showSlash}}class Cl extends Uo{constructor(e,t,s=!1){super(e?e.beat:null,t?t.beat:null,s),this.startNote=e,this.endNote=t}shouldDrawBendSlur(){return this.renderer.settings.notation.extendBendArrowsOnTiedNotes&&!!this.startNote.bendOrigin&&this.startNote.isTieOrigin}doLayout(){super.doLayout()}getBeamDirection(e,t){return Te.Up}getStartY(){return this.startNoteRenderer.getNoteY(this.startNote,is.Top)}getEndY(){return this.getStartY()}getStartX(){return this.startNote===this.endNote?this.getEndX()-20:this.startNoteRenderer.getNoteX(this.startNote,as.Center)}getEndX(){return this.startNote===this.endNote?this.endNoteRenderer.getNoteX(this.endNote,as.Left):this.endNoteRenderer.getNoteX(this.endNote,as.Center)}}class Dl extends Uh{constructor(e,t,s,i=!1){super(e,t,i),this._direction=Te.Up,this._forSlide=s}getTieHeight(e,t,s,i){return Math.log(s-e+1)*this.renderer.settings.notation.slurHeight}tryExpand(e,t,s,i){if(this._forSlide!==s)return!1;if(this.forEnd!==i)return!1;if(this.startNote.beat.id!==e.beat.id)return!1;if(this.endNote.beat.id!==t.beat.id)return!1;switch(this._direction){case Te.Up:e.realValue>this.startNote.realValue&&(this.startNote=e,this.startBeat=e.beat),t.realValue>this.endNote.realValue&&(this.endNote=t,this.endBeat=t.beat);break;case Te.Down:e.realValue<this.startNote.realValue&&(this.startNote=e,this.startBeat=e.beat),t.realValue<this.endNote.realValue&&(this.endNote=t,this.endBeat=t.beat)}return!0}paint(e,t,s){const i=this.renderer.scoreRenderer.layout.getRendererForBar(this.renderer.staff.staffId,this.startBeat.voice.bar),a=this.getBeamDirection(this.startBeat,i),r=`numbered.slur.${this.startNote.beat.id}.${this.endNote.beat.id}.${a}`,n=this.renderer;n.staff.getSharedLayoutData(r,!1)||(n.staff.setSharedLayoutData(r,!0),super.paint(e,t,s))}}class El extends Fr{constructor(){super(...arguments),this._effectSlurs=[]}createTies(e){if(e.isVisible){if(e.isTieOrigin&&e.tieDestination.isVisible){const t=new Cl(e,e.tieDestination,!1);this.addTie(t)}if(e.isTieDestination){const t=new Cl(e.tieOrigin,e,!0);this.addTie(t)}if(e.isLeftHandTapped&&!e.isHammerPullDestination){const t=new Cl(e,e,!1);this.addTie(t)}if(e.isEffectSlurOrigin&&e.effectSlurDestination){let t=!1;for(const s of this._effectSlurs)if(s.tryExpand(e,e.effectSlurDestination,!1,!1)){t=!0;break}if(!t){const t=new Dl(e,e.effectSlurDestination,!1,!1);this._effectSlurs.push(t),this.addTie(t)}}if(e.isEffectSlurDestination&&e.effectSlurOrigin){let t=!1;for(const s of this._effectSlurs)if(s.tryExpand(e.effectSlurOrigin,e,!1,!0)){t=!0;break}if(!t){const t=new Dl(e.effectSlurOrigin,e,!1,!0);this._effectSlurs.push(t),this.addTie(t)}}}}}class Ll extends kr{constructor(e,t,s,i,a){super(e,t),this._isGrace=i,this._number=s,this._beat=a}paint(e,t,s){const i=this._beat.isRest?rn.beat(s,ye.NumberedRests,this._beat):this._beat.notes.length>0?rn.note(s,le.NumberedNumber,this._beat.notes[0]):void 0;try{const i=this.renderer.resources;s.font=this._isGrace?i.numberedNotationGraceFont:i.numberedNotationFont,s.textBaseline=oe.Middle,s.textAlign=ne.Left,s.fillText(this._number.toString(),e+this.x,t+this.y)}finally{i?.[Symbol.dispose]?.()}}doLayout(){const e=this._isGrace?vr.GraceScale:1;this.width=Ll.NoteHeadWidth*e,this.height=Ll.NoteHeadHeight*e}}Ll.NoteHeadHeight=17,Ll.NoteHeadWidth=12;class Ml extends kr{constructor(e,t,s){super(e,t),this._beat=s}doLayout(){this.width=14+Ml.Padding,this.height=Ol.BarSize}paint(e,t,s){const i=rn.beat(s,ye.NumberedDuration,this._beat);try{const i=Ml.Padding;s.fillRect(e+this.x,t+this.y,this.width-i,this.height)}finally{i?.[Symbol.dispose]?.()}}}Ml.Padding=3;class Il extends Ln{constructor(){super(...arguments),this.isNaturalizeAccidental=!1,this.accidental=It.None}get effectElement(){return ye.NumberedEffects}doLayout(){if(!this.container.beat.isRest&&!this.container.beat.isEmpty){const e=new th;if(e.renderer=this.renderer,this.container.beat.notes.length>0){const t=this.container.beat.notes[0],s=t?t.accidentalMode:N.Default,i=Bs.getNoteValue(t);let a=Bs.computeAccidental(this.renderer.bar.keySignature,s,i,t.hasQuarterToneOffset);if(a===It.Natural){a=this.renderer.bar.keySignature+7<7?It.Sharp:It.Flat,this.isNaturalizeAccidental=!0}if(a!==It.None){this.accidental=a;const s=this.renderer,i=rn.noteColor(s.resources,le.NumberedAccidentals,t),r=new Oo(0,s.getLineY(0),a,t.beat.graceType!==w.None?vr.GraceScale*vr.GraceScale:vr.GraceScale);r.colorOverride=i,r.renderer=this.renderer,e.addGlyph(r),this.addNormal(e),this.addNormal(new hh(0,0,4))}}}super.doLayout()}}class Al extends Mn{constructor(){super(...arguments),this.noteHeads=null,this.deadSlapped=null,this.octaveDots=0}get effectElement(){return ye.NumberedEffects}getNoteX(e,t){let s=null;if(this.noteHeads?s=this.noteHeads:this.deadSlapped&&(s=this.deadSlapped),s){let e=s.x;switch(t){case as.Left:break;case as.Center:e+=s.width/2;break;case as.Right:e+=s.width}return e}return 0}buildBoundingsLookup(e,t,s){if(this.noteHeads&&this.container.beat.notes.length>0){const i=new ir;i.note=this.container.beat.notes[0],i.noteHeadBounds=new mt,i.noteHeadBounds.x=t+this.x+this.noteHeads.x,i.noteHeadBounds.y=s+this.y+this.noteHeads.y-this.noteHeads.height/2,i.noteHeadBounds.w=this.width,i.noteHeadBounds.h=this.height,e.addNote(i)}}getNoteY(e,t){let s=null;if(this.noteHeads?s=this.noteHeads:this.deadSlapped&&(s=this.deadSlapped),s){let e=this.y+s.y;switch(t){case is.Top:case is.TopWithStem:e-=s.height/2+2;break;case is.Center:break;case is.Bottom:case is.BottomWithStem:e+=s.height/2}return e}return 0}updateBeamingHelper(){if(this.beamingHelper){let e=null;this.noteHeads?e=this.noteHeads:this.deadSlapped&&(e=this.deadSlapped),e&&this.beamingHelper.registerBeatLineX("numbered",this.container.beat,this.container.x+this.x+e.x,this.container.x+this.x+e.x+e.width)}}doLayout(){const e=this.renderer;e.shortestDuration<this.container.beat.duration&&(e.shortestDuration=this.container.beat.duration);const t=e.getLineY(e.getNoteLine());if(!this.container.beat.isEmpty){let s="0";if(this.container.beat.notes.length>0){const t=this.renderer.bar.keySignatureType,i=this.renderer.bar.keySignature,a=i+7,r=(t===c.Minor?Al.MinorKeySignatureOneValues:Al.MajorKeySignatureOneValues)[a],n=this.container.beat.notes[0];if(n.isDead)s="X";else{const t=n.displayValue-r,o=t<0?(t%12+12)%12:t%12;let h=t<0?(Math.abs(t)+12)/12|0:t/12|0;t<0&&(h*=-1),this.octaveDots=h,e.registerOctave(h);let l=(ie.keySignatureIsSharp(i)||ie.keySignatureIsNatural(i)?Bs.FlatNoteSteps:Bs.SharpNoteSteps)[o]+1;Bs.AccidentalNotes[o]&&!this.container.preNotes.isNaturalizeAccidental&&(a<7?l++:l--),s=l.toString()}}if(this.container.beat.deadSlapped){const e=new Ko;e.renderer=this.renderer,e.doLayout(),this.deadSlapped=e,this.addEffect(e)}else{const e=this.container.beat.graceType!==w.None,i=new Ll(0,t,s,e,this.container.beat);this.noteHeads=i,this.addNormal(i)}if(this.container.beat.dots>0&&this.container.beat.duration>=_.Quarter){this.addNormal(new hh(0,0,5));for(let t=0;t<this.container.beat.dots;t++){const t=new Vo(0,e.getLineY(0),1.5);t.renderer=this.renderer,this.addEffect(t)}}let i=0;switch(this.container.beat.duration){case _.QuadrupleWhole:i=16;break;case _.DoubleWhole:i=8;break;case _.Whole:i=4;break;case _.Half:i=2}let a=i;for(let e=0;e<this.container.beat.dots;e++)a=a/2|0,i+=a;for(let t=0;t<i-1;t++){const t=new Ml(0,e.getLineY(0),this.container.beat);t.renderer=this.renderer,this.addNormal(t)}}super.doLayout(),this.container.beat.isEmpty?this.centerX=this.width/2:this.noteHeads?this.centerX=this.noteHeads.x+this.noteHeads.width/2:this.deadSlapped&&(this.centerX=this.deadSlapped.x+this.deadSlapped.width/2)}}Al.MajorKeySignatureOneValues=[59,66,61,68,63,58,65,60,67,62,69,64,71,66,61],Al.MinorKeySignatureOneValues=[71,66,73,68,63,70,65,72,67,74,69,64,71,66,73];class Rl extends kr{constructor(e,t,s,i){super(e,t),this._text="",this._accidental=It.None,this._accidentalOffset=0,this._keySignature=s,this._keySignatureType=i}doLayout(){super.doLayout();const e="1 = ";let t="",s=It.None;switch(this._keySignatureType){case c.Major:switch(this._keySignature){case l.Cb:t=" C",s=It.Flat;break;case l.Gb:t=" G",s=It.Flat;break;case l.Db:t=" D",s=It.Flat;break;case l.Ab:t=" A",s=It.Flat;break;case l.Eb:t=" E",s=It.Flat;break;case l.Bb:t=" B",s=It.Flat;break;case l.F:t="F";break;case l.C:t="C",s=It.None;break;case l.G:t="G",s=It.None;break;case l.D:t="D",s=It.None;break;case l.A:t="A",s=It.None;break;case l.E:t="E",s=It.None;break;case l.B:t="B",s=It.None;break;case l.FSharp:t=" F",s=It.Sharp;break;case l.CSharp:t=" C",s=It.Sharp}break;case c.Minor:switch(this._keySignature){case l.Cb:t=" a",s=It.Flat;break;case l.Gb:t=" e",s=It.Flat;break;case l.Db:t=" b",s=It.Flat;break;case l.Ab:t="f",s=It.None;break;case l.Eb:t="c",s=It.None;break;case l.Bb:t="g",s=It.None;break;case l.F:t="d";break;case l.C:t="a",s=It.None;break;case l.G:t="e",s=It.None;break;case l.D:t="b",s=It.None;break;case l.A:t=" f",s=It.Sharp;break;case l.E:t=" c",s=It.Sharp;break;case l.B:t=" g",s=It.Sharp;break;case l.FSharp:t=" d",s=It.Sharp;break;case l.CSharp:t=" a",s=It.Sharp}}this._text=e+t,this._accidental=s;const i=this.renderer.scoreRenderer.canvas,a=this.renderer.resources;i.font=a.numberedNotationFont,this._accidentalOffset=i.measureText(e).width,this.width=i.measureText(e+t).width}paint(e,t,s){const i=rn.bar(s,u.NumberedKeySignature,this.renderer.bar);try{const i=this.renderer.resources;s.font=i.numberedNotationFont,s.textBaseline=oe.Middle,s.fillText(this._text,e+this.x,t+this.y),this._accidental!==It.None&&s.fillMusicFontSymbol(e+this.x+this._accidentalOffset,t+this.y,.7,Oo.getMusicSymbol(this._accidental),!1)}finally{i?.[Symbol.dispose]?.()}}}class Ol extends Hh{registerOctave(e){null===this.lowestOctave?(this.lowestOctave=e,this.highestOctave=e):(e<this.lowestOctave&&(this.lowestOctave=e),e>this.highestOctave&&(this.highestOctave=e))}get repeatsBarSubElement(){return u.NumberedRepeats}get barNumberBarSubElement(){return u.NumberedBarNumber}get barLineBarSubElement(){return u.NumberedBarLines}get staffLineBarSubElement(){return u.NumberedStaffLine}constructor(e,t){super(e,t),this.simpleWhammyOverflow=0,this.shortestDuration=_.QuadrupleWhole,this.lowestOctave=null,this.highestOctave=null,this._isOnlyNumbered=!t.staff.showSlash&&!t.staff.showTablature&&!t.staff.showStandardNotation}get lineSpacing(){return On.RawLineSpacing}get heightLineCount(){return 5}get drawnLineCount(){return 0}get bottomGlyphOverflow(){return 0}paint(e,t,s){super.paint(e,t,s),this.paintBeams(e,t,s,ye.NumberedDuration,ye.NumberedDuration),this.paintTuplets(e,t,s,ye.NumberedTuplet,!0)}doLayout(){super.doLayout();let e=!1;for(const t of this.bar.voices)if(this.hasVoiceContainer(t)){if(this.getVoiceContainer(t).tupletGroups.length>0){e=!0;break}}if(e&&this.registerOverflowTop(this.tupletSize),!this.bar.isEmpty){const e=ie.getIndex(this.shortestDuration)-2;if(e>0){const t=(e-1)*Ol.BarSpacing+Ol.BarSize;let s=0;const i=this.lowestOctave;null!==i&&(s=Math.abs(i)*Ol.DotSpacing+Ol.DotSize),this.registerOverflowBottom(t+s)}const t=this.highestOctave;if(null!==t){const e=Math.abs(t)*Ol.DotSpacing+Ol.DotSize;this.registerOverflowTop(e)}}}paintFlag(e,t,s,i,a){this.paintBar(e,t,s,i,a)}paintBar(e,t,s,i,a){if(0===i.beats.length)return;const r=this.resources;for(let n=0,o=i.beats.length;n<o;n++){const o=i.beats[n],h=rn.beat(s,a,o);try{const a=Ol.BarSpacing,h=Ol.BarSize,l=ie.getIndex(o.duration)-2,c=t+this.y,d=this.getBeatX(o,ts.PreNotes)-this.beatGlyphsStart,u=this.calculateBeamY(i,d);for(let t=0;t<l;t++){let r=0,l=0,p=0;const g=c+t*a;n===i.beats.length-1?(r=d,l=this.getBeatX(o,ts.PostNotes)-this.beatGlyphsStart):(r=d,l=this.getBeatX(i.beats[n+1],ts.PreNotes)-this.beatGlyphsStart),p=g+u|0,Hh.paintSingleBar(s,e+this.x+r,p,e+this.x+l,p,h)}const p=this.getBeatContainer(o).onNotes;let g=p instanceof Al?p.octaveDots:0,m=0,f=0;g>0?(m=c+this.getLineY(0)-r.numberedNotationFont.size/1.5,f=-1*Ol.DotSpacing):g<0&&(m=c+u+l*a,f=Ol.DotSpacing);const y=this.getBeatX(o,ts.OnNotes)+4-this.beatGlyphsStart;g=Math.abs(g);for(let t=0;t<g;t++)s.fillCircle(e+this.x+y,m,Ol.DotSize),m+=f}finally{h?.[Symbol.dispose]?.()}}}getNoteLine(){return 0}get tupletOffset(){return super.tupletOffset+this.resources.numberedNotationFont.size}getFlagTopY(e,t){const s=Nr.Heights.get(re.NoteheadBlack);return this.getLineY(0)-s/2}getFlagBottomY(e,t){const s=Nr.Heights.get(re.NoteheadBlack);return this.getLineY(0)-s/2}getBeamDirection(e){return Te.Down}getTupletBeamDirection(e){return Te.Up}getNoteY(e,t){let s=super.getNoteY(e,t);return Number.isNaN(s)&&(s=this.getLineY(0)),s}calculateBeamYWithDirection(e,t,s){const i=this.resources.numberedNotationFont;return this.getLineY(0)+i.size}getBarLineStart(e,t){const s=Nr.Heights.get(re.NoteheadBlack);return this.getLineY(0)-s/2}createPreBeatGlyphs(){this.wasFirstOfLine=this.isFirstOfLine,(0===this.index||this.bar.masterBar.isRepeatStart&&this._isOnlyNumbered)&&this.addPreBeatGlyph(new Ah(!1)),this.createLinePreBeatGlyphs(),this.addPreBeatGlyph(new Oh(0,this.getLineHeight(-.25),this.bar.index+1))}createLinePreBeatGlyphs(){this.bar.previousBar&&this.bar.keySignature===this.bar.previousBar.keySignature||(this.createStartSpacing(),this.createKeySignatureGlyphs()),this._isOnlyNumbered&&(!this.bar.previousBar||this.bar.previousBar&&this.bar.masterBar.timeSignatureNumerator!==this.bar.previousBar.masterBar.timeSignatureNumerator||this.bar.previousBar&&this.bar.masterBar.timeSignatureDenominator!==this.bar.previousBar.masterBar.timeSignatureDenominator||this.bar.previousBar&&this.bar.masterBar.isFreeTime&&this.bar.masterBar.isFreeTime!==this.bar.previousBar.masterBar.isFreeTime)&&(this.createStartSpacing(),this.createTimeSignatureGlyphs())}createKeySignatureGlyphs(){this.addPreBeatGlyph(new Rl(0,this.getLineY(0),this.bar.keySignature,this.bar.keySignatureType))}createTimeSignatureGlyphs(){this.addPreBeatGlyph(new hh(0,0,5));const e=this.bar.masterBar,t=new wh(0,this.getLineY(0),e.timeSignatureNumerator,e.timeSignatureDenominator,e.timeSignatureCommon,e.isFreeTime&&(null==e.previousMasterBar||e.isFreeTime!==e.previousMasterBar.isFreeTime));t.barSubElement=u.NumberedTimeSignature,this.addPreBeatGlyph(t)}createPostBeatGlyphs(){this._isOnlyNumbered&&super.createPostBeatGlyphs()}createVoiceGlyphs(e){for(const t of e.beats){const s=new El(t,this.getVoiceContainer(e));s.preNotes=0===e.index?new Il:new Ln,s.onNotes=0===e.index?new Al:new Mn,this.addBeatGlyph(s)}}paintBeamingStem(e,t,s,i,a,r){}}Ol.StaffId="numbered",Ol.BarSpacing=On.BeamSpacing+On.BeamThickness,Ol.BarSize=2,Ol.DotSpacing=5,Ol.DotSize=2;class Hl extends tn{get staffId(){return Ol.StaffId}getStaffPaddingTop(e){return e.system.layout.renderer.settings.display.notationStaffPaddingTop}getStaffPaddingBottom(e){return e.system.layout.renderer.settings.display.notationStaffPaddingBottom}create(e,t){return new Ol(e,t)}canCreate(e,t){return super.canCreate(e,t)&&t.showNumbered}}class Wl extends Jn{get notationElement(){return E.EffectText}get hideOnMultiTrack(){return!1}get canShareBand(){return!0}get sizingMode(){return rs.SinglePreBeat}shouldCreateGlyph(e,t){const s=t.voice.bar.masterBar;return 0===t.voice.bar.staff.index&&0===t.voice.index&&0===t.index&&s.isFreeTime&&(0===s.index||s.isFreeTime!==s.previousMasterBar.isFreeTime)}createNewGlyph(e,t){return new Sn(0,0,"Free time",e.resources.effectFont,ne.Left)}canExpand(e,t){return!0}}class Vl extends Tr{constructor(){super(0,0)}doLayout(){super.doLayout(),this.height=Nr.Heights.get(re.KeyboardPedalPed)}paint(e,t,s){const i=this.renderer,a=t+this.y,r=this.height,n=i.bar.sustainPedals,o=Nr.Widths.get(re.KeyboardPedalPed),h=Nr.Widths.get(re.KeyboardPedalUp);let l=0;for(;l<n.length;){let t=n[l];for(;null!=t;){const i=e+this.renderer.getRatioPositionX(t.ratioPosition);let c=0;if(t.pedalType===d.Down?(s.fillMusicFontSymbol(i,a+r,1,re.KeyboardPedalPed,!0),c=o/2+Vl.TextLinePadding):t.pedalType===d.Up&&(s.fillMusicFontSymbol(i,a+r,1,re.KeyboardPedalUp,!0),c=h/2+Vl.StarLinePadding),t.nextPedalMarker)if(t.nextPedalMarker.bar===t.bar){let n=e+this.renderer.getRatioPositionX(t.nextPedalMarker.ratioPosition);switch(t.nextPedalMarker.pedalType){case d.Down:n-=o/2;break;case d.Hold:break;case d.Up:n-=h/2}const l=i+c;n>l&&s.fillRect(l,a+r-1,n-l,1)}else{const t=e+this.x+this.width,n=i+c;s.fillRect(n,a+r-1,t-n,1)}if(0===l&&t.previousPedalMarker){const t=e+this.x,n=i-c;s.fillRect(t,a+r-1,n-t,1)}l++,null!=t.nextPedalMarker&&t.nextPedalMarker.bar!==t.bar?(t=null,l=n.length):t=t.nextPedalMarker}}}}Vl.TextLinePadding=3,Vl.StarLinePadding=3;class Gl extends Jn{get notationElement(){return E.EffectSustainPedal}get hideOnMultiTrack(){return!1}get canShareBand(){return!1}get sizingMode(){return rs.FullBar}shouldCreateGlyph(e,t){return 0===t.voice.index&&0===t.index&&t.voice.bar.sustainPedals.length>0}createNewGlyph(e,t){return new Vl}canExpand(e,t){return!0}}class zl extends Jn{constructor(e,t){super(),this._type=e,this._shouldCreate=t}get notationElement(){return E.EffectGolpe}get hideOnMultiTrack(){return!1}get canShareBand(){return!0}get sizingMode(){return rs.SingleOnBeat}shouldCreateGlyph(e,t){const s=this._shouldCreate;return t.golpe===this._type&&(!s||s(e,t))}createNewGlyph(e,t){return new uh(0,0,!0)}canExpand(e,t){return!1}}class Ul extends xr{constructor(e){super(0,0,1,Ul.getSymbol(e)),this.center=!0}static getSymbol(e){switch(e){case pe.Open:return re.GuitarOpenPedal;case pe.Closed:return re.GuitarClosePedal}return re.None}paint(e,t,s){super.paint(e,t+this.height,s)}}class Xl extends Jn{get notationElement(){return E.EffectWahPedal}get hideOnMultiTrack(){return!1}get canShareBand(){return!0}get sizingMode(){return rs.SingleOnBeat}shouldCreateGlyph(e,t){return t.wahPedal!==pe.None}createNewGlyph(e,t){return new Ul(t.wahPedal)}canExpand(e,t){return!1}}class Jl extends Jn{get notationElement(){return E.EffectLetRing}get canShareBand(){return!1}get hideOnMultiTrack(){return!1}shouldCreateGlyph(e,t){return t.isBarre}get sizingMode(){return rs.GroupedOnBeat}createNewGlyph(e,t){let s="";switch(t.barreShape){case ge.None:case ge.Full:break;case ge.Half:s+="1/2"}return s+=`B ${Jl.toRoman(t.barreFret)}`,new oo(s,!1)}static toRoman(e){let t="";if(e>0)for(const[s,i]of Jl.RomanLetters){const a=Math.floor(e/i);e-=a*i,t+=s.repeat(a)}return t}canExpand(e,t){return e.barreFret===t.barreFret&&e.barreShape===t.barreShape}}Jl.RomanLetters=new Map([["L",50],["XL",40],["X",10],["IX",9],["V",5],["IV",4],["I",1]]);class Yl extends xr{constructor(e){super(0,0,1,Yl.getSymbol(e)),this.center=!0}static getSymbol(e){switch(e){case he.InvertedTurn:return re.OrnamentTurnInverted;case he.Turn:return re.OrnamentTurn;case he.UpperMordent:return re.OrnamentShortTrill;case he.LowerMordent:return re.OrnamentMordent}return re.None}paint(e,t,s){super.paint(e,t+this.height-4,s)}}class $l extends Jn{get notationElement(){return E.EffectNoteOrnament}get hideOnMultiTrack(){return!1}get canShareBand(){return!0}get sizingMode(){return rs.SingleOnBeat}shouldCreateGlyph(e,t){return t.notes.some((e=>e.ornament!==he.None))}createNewGlyph(e,t){return new Yl(t.notes.find((e=>e.ornament!==he.None)).ornament)}canExpand(e,t){return!1}}class ql extends Jn{get notationElement(){return E.EffectRasgueado}get canShareBand(){return!1}get hideOnMultiTrack(){return!1}shouldCreateGlyph(e,t){return t.hasRasgueado}get sizingMode(){return rs.GroupedOnBeat}createNewGlyph(e,t){return new oo("rasg.")}canExpand(e,t){return!0}}class jl extends kr{constructor(e){super(0,0),this._symbols=e}doLayout(){this.height=27}paint(e,t,s){s.fillMusicFontSymbols(e+this.x,t+this.y+this.height,.8,this._symbols,!0)}}class Kl extends kr{constructor(e){super(0,0),this._text=e}doLayout(){this.height=1.5*this.renderer.resources.directionsFont.size}paint(e,t,s){const i=s.font,a=s.textBaseline,r=s.textAlign;s.font=this.renderer.resources.directionsFont,s.textBaseline=oe.Middle,s.textAlign=ne.Right,s.fillText(this._text,e+this.x,t+this.y+this.height/2),s.font=i,s.textBaseline=a,s.textAlign=r}}class Ql extends Tr{constructor(e,t,s){super(e,t),this._barBeginGlyphs=[],this._barEndGlyphs=[],this._directions=s}doLayout(){const e=this._directions;e.has(Be.TargetSegnoSegno)&&this._barBeginGlyphs.push(new jl([re.Segno,re.Segno])),e.has(Be.TargetSegno)&&this._barBeginGlyphs.push(new jl([re.Segno])),e.has(Be.TargetDoubleCoda)&&this._barBeginGlyphs.push(new jl([re.Coda,re.Coda])),e.has(Be.TargetCoda)&&this._barBeginGlyphs.push(new jl([re.Coda])),e.has(Be.TargetFine)&&this._barEndGlyphs.push(new Kl("Fine")),e.has(Be.JumpDaDoubleCoda)&&this._barEndGlyphs.push(new Kl("To Double Coda")),e.has(Be.JumpDaCoda)&&this._barEndGlyphs.push(new Kl("To Coda")),e.has(Be.JumpDalSegnoSegno)&&this._barEndGlyphs.push(new Kl("D.S.S.")),e.has(Be.JumpDalSegnoSegnoAlCoda)&&this._barEndGlyphs.push(new Kl("D.S.S. al Coda")),e.has(Be.JumpDalSegnoSegnoAlDoubleCoda)&&this._barEndGlyphs.push(new Kl("D.S.S. al Double Coda")),e.has(Be.JumpDalSegnoSegnoAlFine)&&this._barEndGlyphs.push(new Kl("D.S.S. al Fine")),e.has(Be.JumpDalSegno)&&this._barEndGlyphs.push(new Kl("D.S.")),e.has(Be.JumpDalSegnoAlCoda)&&this._barEndGlyphs.push(new Kl("D.S. al Coda")),e.has(Be.JumpDalSegnoAlDoubleCoda)&&this._barEndGlyphs.push(new Kl("D.S. al Double Coda")),e.has(Be.JumpDalSegnoAlFine)&&this._barEndGlyphs.push(new Kl("D.S. al Fine")),e.has(Be.JumpDaCapo)&&this._barEndGlyphs.push(new Kl("D.C.")),e.has(Be.JumpDaCapoAlCoda)&&this._barEndGlyphs.push(new Kl("D.C. al Coda")),e.has(Be.JumpDaCapoAlDoubleCoda)&&this._barEndGlyphs.push(new Kl("D.C. al Double Coda")),e.has(Be.JumpDaCapoAlFine)&&this._barEndGlyphs.push(new Kl("D.C. al Fine"));const t=this.doSideLayout(this._barBeginGlyphs),s=this.doSideLayout(this._barEndGlyphs);this.height=Math.max(t,s)}doSideLayout(e){let t=0;for(const s of e)s.y=t,s.renderer=this.renderer,s.doLayout(),t+=s.height+3;return t}paint(e,t,s){for(const i of this._barBeginGlyphs)i.paint(e+this.x,t+this.y,s);for(const i of this._barEndGlyphs)i.paint(e+this.x+this.width,t+this.y,s)}}class Zl extends Jn{get notationElement(){return E.EffectDirections}get hideOnMultiTrack(){return!0}get canShareBand(){return!1}get sizingMode(){return rs.FullBar}shouldCreateGlyph(e,t){return 0===t.voice.index&&0===t.index&&null!==t.voice.bar.masterBar.directions&&t.voice.bar.masterBar.directions.size>0}createNewGlyph(e,t){return new Ql(0,0,t.voice.bar.masterBar.directions)}canExpand(e,t){return!0}}class ec extends Tr{constructor(e){super(0,0),this._text="",this._textWidth=0,this._textHeight=0,this._timer=e}doLayout(){const e=this._timer/6e4|0,t=(this._timer-6e4*e)/1e3|0;this._text=`${e}:${t.toString().padStart(2,"0")}`;const s=this.renderer.scoreRenderer.canvas;s.font=this.renderer.resources.timerFont;const i=s.measureText(this._text);this._textHeight=s.font.size+2*ec.PaddingY,this._textWidth=i.width+2*ec.PaddingX,this.height=this._textHeight+2*ec.MarginY}paint(e,t,s){const i=this._textWidth/2|0;s.strokeRect(e+this.x-i,t+this.y+ec.MarginY,this._textWidth,this._textHeight);const a=s.font,r=s.textBaseline,n=s.textAlign;s.font=this.renderer.resources.timerFont,s.textBaseline=oe.Middle,s.textAlign=ne.Center,s.fillText(this._text,e+this.x,t+this.y+this.height/2),s.font=a,s.textBaseline=r,s.textAlign=n}}ec.PaddingX=2,ec.PaddingY=2,ec.MarginY=2;class tc extends Jn{get notationElement(){return E.EffectBeatTimer}get hideOnMultiTrack(){return!0}get canShareBand(){return!0}get sizingMode(){return rs.SingleOnBeat}shouldCreateGlyph(e,t){return t.showTimer}createNewGlyph(e,t){return new ec(t.timer??0)}canExpand(e,t){return!0}}class sc{static print(e){e(`alphaTab ${sc.version}`),e(`commit: ${sc.commit}`),e(`build date: ${sc.date}`)}}sc.version="1.6.0-alpha.1397",sc.date="2025-05-04T17:39:41.423Z",sc.commit="bb8f811c764519039ff04a4150baf68f52bc680d";class ic{constructor(e,t){this.vertical=e,this.createLayout=t}}class ac{constructor(e,t){this.supportsWorkers=e,this.createCanvas=t}}class rc{static createStyleElement(e,t){let s=e.getElementById("alphaTabStyle");if(!s){if(!t)return void q.error("AlphaTab","Font directory could not be detected, cannot create style element");s=e.createElement("style"),s.id="alphaTabStyle";const i=`\n @font-face {\n font-display: block;\n font-family: 'alphaTab';\n src: url('${t}Bravura.eot');\n src: url('${t}Bravura.eot?#iefix') format('embedded-opentype')\n , url('${t}Bravura.woff') format('woff')\n , url('${t}Bravura.otf') format('opentype')\n , url('${t}Bravura.svg#Bravura') format('svg');\n font-weight: normal;\n font-style: normal;\n }\n .at-surface * {\n cursor: default;\n vertical-align: top;\n overflow: visible;\n }\n .at-surface-svg text {\n dominant-baseline: central;\n white-space:pre;\n }\n .at {\n font-family: 'alphaTab';\n speak: none;\n font-style: normal;\n font-weight: normal;\n font-variant: normal;\n text-transform: none;\n line-height: 1;\n line-height: 1;\n -webkit-font-smoothing: antialiased;\n -moz-osx-font-smoothing: grayscale;\n font-size: ${rc.MusicFontSize}px;\n overflow: visible !important;\n }`;s.innerHTML=i,e.getElementsByTagName("head").item(0).appendChild(s),rc.bravuraFontChecker.checkForFontAvailability()}}static get globalThis(){if(void 0===rc._globalThis){try{rc._globalThis=globalThis}catch(e){}void 0===rc._globalThis&&(rc._globalThis=self),void 0===rc._globalThis&&(rc._globalThis=global),void 0===rc._globalThis&&(rc._globalThis=window),void 0===rc._globalThis&&(rc._globalThis=Function("return this")())}return rc._globalThis}static get isRunningInWorker(){return"WorkerGlobalScope"in rc.globalThis}static get isRunningInAudioWorklet(){return"AudioWorkletGlobalScope"in rc.globalThis}static throttle(e,t){let s=0;return()=>{rc.globalThis.clearTimeout(s),s=rc.globalThis.setTimeout(e,t)}}static detectScriptFile(){if(!rc.isRunningInWorker&&rc.globalThis.ALPHATAB_ROOT){let e=rc.globalThis.ALPHATAB_ROOT;return e=rc.ensureFullUrl(e),e=rc.appendScriptName(e),e}try{const e=import.meta.url;if(e&&-1===e.indexOf("file://"))return e}catch(e){}return"document"in rc.globalThis&&document.currentScript?document.currentScript.src:null}static ensureFullUrl(e){if(!e)return"";if(!e.startsWith("http")&&!e.startsWith("https")&&!e.startsWith("file")){let t="";const s=rc.globalThis.location;if(t+=s.protocol?.toString(),t+="//"?.toString(),s.hostname&&(t+=s.hostname?.toString()),s.port&&(t+=":"?.toString(),t+=s.port?.toString()),!e.startsWith("/")){const e=s.pathname.split("/").slice(0,-1).join("/");e.length>0&&(e.startsWith("/")||(t+="/"?.toString()),t+=e?.toString())}return e.startsWith("/")||(t+="/"?.toString()),t+=e?.toString(),t}return e}static appendScriptName(e){return e&&!e.endsWith(".js")&&(e.endsWith("/")||(e+="/"),e+="alphaTab.js"),e}static detectFontDirectory(){if(!rc.isRunningInWorker&&rc.globalThis.ALPHATAB_FONT)return rc.ensureFullUrl(rc.globalThis.ALPHATAB_FONT);const e=rc.scriptFile;if(e){const t=e.lastIndexOf(String.fromCharCode(47));if(t>=0)return`${e.substr(0,t)}/font/`}return null}static registerJQueryPlugin(){if(!rc.isRunningInWorker&&rc.globalThis&&"jQuery"in rc.globalThis){const e=rc.globalThis.jQuery,t=new Qr;e.fn.alphaTab=function(e){const s=Array.prototype.slice.call(arguments,1);return 1===this.length?t.exec(this[0],e,s):this.each(((i,a)=>{t.exec(a,e,s)}))},e.alphaTab={restore:Qr.restore},e.fn.alphaTab.fn=t}}static getRenderEngineFactory(e){return e&&rc.renderEngines.has(e)?rc.renderEngines.get(e):rc.renderEngines.get("default")}static getLayoutEngineFactory(t){return t&&rc.layoutEngines.has(t)?rc.layoutEngines.get(t):rc.layoutEngines.get(e.Page)}static buildImporters(){return[new ut,new _s,new ms,new xs,new Sl,new dt]}static createDefaultRenderEngines(){const e=new Map;return e.set("svg",new ac(!0,(()=>new en))),e.set("default",e.get("svg")),e.set("skia",new ac(!1,(()=>new kl))),rc.createPlatformSpecificRenderEngines(e),e}static enableAlphaSkia(e,t){kl.enable(e,t)}static registerAlphaSkiaCustomFont(e){return kl.registerFont(e)}static createPlatformSpecificRenderEngines(e){e.set("html5",new ac(!1,(()=>new hr)))}static createDefaultRenderers(){return[new Un(rc.StaffIdBeforeSlashAlways,[new xo,new Do,new po,new Zl,new Yn,new Wl,new vo,new tc,new qn]),new Fl,new Un(rc.StaffIdBeforeScoreAlways,[new ao,new Jl,new $l,new ql,new Xl]),new Un(rc.StaffIdBeforeScoreHideable,[new Eo,new Fo,new mo(!0),new Lo,new wo,new Mo,new ko(!1),new al,new zl(de.Finger)],((e,t)=>t.showStandardNotation)),new Gh,new Un(rc.StaffIdBeforeNumberedAlways,[new Qn,new mo(!1),new eo,new zl(de.Thumb,((e,t)=>t.voice.bar.staff.showStandardNotation)),new Gl]),new Hl,new Un(rc.StaffIdBeforeTabAlways,[new uo]),new Un(rc.StaffIdBeforeTabHideable,[new Fo,new Lo,new wo,new Mo,new ko(!0),new To,new so,new ho(T.Natural),new ho(T.Artificial),new ho(T.Pinch),new ho(T.Tap),new ho(T.Semi),new ho(T.Feedback),new lo,new $n,new ro,new fo,new So,new yo,new al,new zl(de.Finger,((e,t)=>!t.voice.bar.staff.showStandardNotation))],((e,t)=>t.showTablature)),new sl,new Un(rc.StaffIdBeforeEndAlways,[new zl(de.Thumb,((e,t)=>!t.voice.bar.staff.showStandardNotation))])]}static createDefaultStaveProfiles(){const e=new Map,s=rc.createDefaultRenderers();e.set(t.Default,s),e.set(t.ScoreTab,s);const i=new Set([rc.StaffIdBeforeSlashAlways,rc.StaffIdBeforeScoreAlways,rc.StaffIdBeforeNumberedAlways,rc.StaffIdBeforeTabAlways,Vh.StaffId,rc.StaffIdBeforeEndAlways]);e.set(t.Score,s.filter((e=>i.has(e.staffId))));const a=new Set([rc.StaffIdBeforeSlashAlways,rc.StaffIdBeforeScoreAlways,rc.StaffIdBeforeNumberedAlways,rc.StaffIdBeforeTabAlways,tl.StaffId,rc.StaffIdBeforeEndAlways]);return e.set(t.Tab,rc.createDefaultRenderers().filter((e=>{if(e instanceof sl){const t=e;t.showTimeSignature=!0,t.showRests=!0,t.showTiedNotes=!0}return a.has(e.staffId)}))),e.set(t.TabMixed,rc.createDefaultRenderers().filter((e=>{if(e instanceof sl){const t=e;t.showTimeSignature=!1,t.showRests=!1,t.showTiedNotes=!1}return a.has(e.staffId)}))),e}static createDefaultLayoutEngines(){const t=new Map;return t.set(e.Page,new ic(!0,(e=>new Ro(e)))),t.set(e.Horizontal,new ic(!1,(e=>new Ao(e)))),t}static initializeMain(e,t){rc.isRunningInWorker||rc.isRunningInAudioWorklet||(rc.webPlatform!==Kt.Browser&&rc.webPlatform!==Kt.BrowserModule||(rc.registerJQueryPlugin(),rc.HighDpiFactor=window.devicePixelRatio,"ResizeObserver"in rc.globalThis||(rc.globalThis.ResizeObserver=_l),"IntersectionObserver"in rc.globalThis||(rc.globalThis.IntersectionObserver=wl),"replaceChildren"in Element.prototype||(Element.prototype.replaceChildren=function(...e){this.innerHTML="",this.append(...e)},Document.prototype.replaceChildren=Element.prototype.replaceChildren,DocumentFragment.prototype.replaceChildren=Element.prototype.replaceChildren),"replaceAll"in String.prototype||(String.prototype.replaceAll=function(e,t){return this.replace(new RegExp(e,"g"),t)})),rc.createWebWorker=e,rc.createAudioWorklet=t)}static get alphaTabWorker(){return rc.globalThis.Worker}static get alphaTabUrl(){return rc.globalThis.URL}static initializeWorker(){if(!rc.isRunningInWorker)throw new $e(Se.General,"Not running in worker, cannot run worker initialization");or.init(),ja.init(),rc.createWebWorker=e=>{throw new $e(Se.General,"Nested workers are not supported")}}static initializeAudioWorklet(){if(!rc.isRunningInAudioWorklet)throw new $e(Se.General,"Not running in audio worklet, cannot run worklet initialization");Yr.init()}static detectWebPack(){try{if("function"==typeof __webpack_require__)return!0}catch(e){}return!1}static detectVite(){try{if("string"==typeof __BASE__)return!0}catch(e){}return!1}static detectWebPlatform(){try{if("[object process]"===Object.prototype.toString.call("undefined"!=typeof process?process:0))return Kt.NodeJs}catch(e){}try{const e=import.meta.url;if(e&&"string"==typeof e&&!e.startsWith("file://"))return Kt.BrowserModule}catch(e){}return Kt.Browser}static printEnvironmentInfo(e=!0){const t=e?e=>{q.log.debug("VersionInfo",e)}:e=>{q.debug("VersionInfo",e)};sc.print(t),t(`High DPI: ${rc.HighDpiFactor}`),rc.printPlatformInfo(t)}static printPlatformInfo(e){e(`Browser: ${navigator.userAgent}`),e(`Platform: ${Kt[rc.webPlatform]}`),e(`WebPack: ${rc.isWebPackBundled}`),e(`Vite: ${rc.isViteBundled}`),rc.webPlatform!==Kt.NodeJs&&(e(`Window Size: ${window.outerWidth}x${window.outerHeight}`),e(`Screen Size: ${window.screen.width}x${window.screen.height}`))}}rc.StaffIdBeforeSlashAlways="before-slash-always",rc.StaffIdBeforeScoreAlways="before-score-always",rc.StaffIdBeforeScoreHideable="before-score-hideable",rc.StaffIdBeforeNumberedAlways="before-numbered-always",rc.StaffIdBeforeTabAlways="before-tab-always",rc.StaffIdBeforeTabHideable="before-tab-hideable",rc.StaffIdBeforeEndAlways="before-end-always",rc.MusicFontSize=34,rc.HighDpiFactor=1,rc._globalThis=void 0,rc.webPlatform=rc.detectWebPlatform(),rc.isWebPackBundled=rc.detectWebPack(),rc.isViteBundled=rc.detectVite(),rc.scriptFile=rc.detectScriptFile(),rc.fontDirectory=rc.detectFontDirectory(),rc.bravuraFontChecker=new Or(["alphaTab"]),rc.renderEngines=rc.createDefaultRenderEngines(),rc.layoutEngines=rc.createDefaultLayoutEngines(),rc.staveProfiles=rc.createDefaultStaveProfiles();class nc{constructor(){this.scriptFile=null,this.fontDirectory=null,this.file=null,this.tex=!1,this.tracks=null,this.enableLazyLoading=!0,this.engine="default",this.logLevel=L.Info,this.useWorkers=!0,this.includeNoteBounds=!1,this.scriptFile=rc.scriptFile,this.fontDirectory=rc.fontDirectory}}const oc=Object.freeze(Object.defineProperty({__proto__:null,ScoreImporter:Ye,ScoreLoader:Ir,UnsupportedFormatError:qe},Symbol.toStringTag,{value:"Module"})),hc=Object.freeze(Object.defineProperty({__proto__:null,ByteBuffer:ht,IOHelper:ot},Symbol.toStringTag,{value:"Module"}));class lc{init(e,t){this.data=e,this.settings=t}export(e,t=null){const s=ht.withCapacity(1024);return this.init(s,t??new Ba),this.writeScore(e),s.toArray()}}var cc;!function(e){e[e.SteelGuitar=1]="SteelGuitar",e[e.AcousticGuitar=2]="AcousticGuitar",e[e.TwelveStringGuitar=3]="TwelveStringGuitar",e[e.ElectricGuitar=4]="ElectricGuitar",e[e.Bass=5]="Bass",e[e.ClassicalGuitar=23]="ClassicalGuitar",e[e.UprightBass=6]="UprightBass",e[e.Ukulele=7]="Ukulele",e[e.Banjo=8]="Banjo",e[e.Mandolin=9]="Mandolin",e[e.Piano=10]="Piano",e[e.Synth=12]="Synth",e[e.Strings=11]="Strings",e[e.Brass=13]="Brass",e[e.Reed=14]="Reed",e[e.Woodwind=15]="Woodwind",e[e.Vocal=16]="Vocal",e[e.PitchedIdiophone=17]="PitchedIdiophone",e[e.Fx=21]="Fx",e[e.PercussionKit=18]="PercussionKit",e[e.Idiophone=19]="Idiophone",e[e.Membraphone=20]="Membraphone"}(cc||(cc={}));class dc{constructor(e,t,s=null){if(this.icon=cc.Piano,this.icon=e,this.instrumentSetName=t,s)this.instrumentSetType=s;else{const e=t.split(" ");e[0]=e[0].substr(0,1).toLowerCase()+e[0].substr(1),this.instrumentSetType=e.join("")}}}class uc{constructor(){this._rhythmIdLookup=new Map}writeXml(e){const t=new wt;return this._rhythmIdLookup=new Map,this.writeDom(t,e),t.toFormattedString("",!0)}writeDom(e,t){const s=e.addElement("GPIF");s.addElement("GPVersion").innerText="7";const i=s.addElement("GPRevision");i.innerText="7",i.attributes.set("required","12021"),i.attributes.set("recommended","12023"),i.innerText="12025",s.addElement("Encoding").addElement("EncodingDescription").innerText="GP7",this.writeScoreNode(s,t),this.writeMasterTrackNode(s,t),this.writeAudioTracksNode(s,t),this.writeTracksNode(s,t),this.writeMasterBarsNode(s,t);const a=s.addElement("Bars"),r=s.addElement("Voices"),n=s.addElement("Beats"),o=s.addElement("Notes"),h=s.addElement("Rhythms");for(const e of t.tracks)for(const t of e.staves)for(const e of t.bars){this.writeBarNode(a,e);for(const t of e.voices){this.writeVoiceNode(r,t);for(const e of t.beats){this.writeBeatNode(n,e,h);for(const t of e.notes)this.writeNoteNode(o,t)}}}}writeNoteNode(e,t){const s=e.addElement("Note");s.attributes.set("id",t.id.toString()),this.writeNoteProperties(s,t),t.isGhost&&(s.addElement("AntiAccent").innerText="normal"),t.isLetRing&&s.addElement("LetRing"),t.isTrill&&(s.addElement("Trill").innerText=t.trillValue.toString());let i=0;switch(t.isStaccato&&(i|=1),t.accentuated){case B.Normal:i|=8;break;case B.Heavy:i|=4;break;case B.Tenuto:i|=16}if(i>0&&(s.addElement("Accent").innerText=i.toString()),t.isTieOrigin||t.isTieDestination){const e=s.addElement("Tie");e.attributes.set("origin",t.isTieOrigin?"true":"false"),e.attributes.set("destination",t.isTieDestination?"true":"false")}switch(t.vibrato){case P.Slight:s.addElement("Vibrato").innerText="Slight";break;case P.Wide:s.addElement("Vibrato").innerText="Wide"}if(t.isFingering){switch(t.leftHandFinger){case k.Thumb:s.addElement("LeftFingering").innerText="P";break;case k.IndexFinger:s.addElement("LeftFingering").innerText="I";break;case k.MiddleFinger:s.addElement("LeftFingering").innerText="M";break;case k.AnnularFinger:s.addElement("LeftFingering").innerText="A";break;case k.LittleFinger:s.addElement("LeftFingering").innerText="C"}switch(t.rightHandFinger){case k.Thumb:s.addElement("RightFingering").innerText="P";break;case k.IndexFinger:s.addElement("RightFingering").innerText="I";break;case k.MiddleFinger:s.addElement("RightFingering").innerText="M";break;case k.AnnularFinger:s.addElement("RightFingering").innerText="A";break;case k.LittleFinger:s.addElement("RightFingering").innerText="C"}}t.percussionArticulation>=0?s.addElement("InstrumentArticulation").innerText=t.percussionArticulation.toString():s.addElement("InstrumentArticulation").innerText="0",t.ornament!==he.None&&(s.addElement("Ornament").innerText=he[t.ornament])}writeNoteProperties(e,t){const s=e.addElement("Properties");if(this.writeConcertPitch(s,t),this.writeTransposedPitch(s,t),t.isStringed&&(this.writeSimplePropertyNode(s,"String","String",(t.string-1).toString()),this.writeSimplePropertyNode(s,"Fret","Fret",t.fret.toString()),this.writeSimplePropertyNode(s,"Midi","Number",t.realValue.toString()),t.showStringNumber&&this.writeSimplePropertyNode(s,"ShowStringNumber","Enable",null)),t.isPiano&&(this.writeSimplePropertyNode(s,"Octave","Number",t.octave.toString()),this.writeSimplePropertyNode(s,"Tone","Step",t.tone.toString()),this.writeSimplePropertyNode(s,"Midi","Number",t.realValue.toString())),t.beat.tap&&this.writeSimplePropertyNode(s,"Tapped","Enable",null),t.harmonicType!==T.None){switch(t.harmonicType){case T.Natural:this.writeSimplePropertyNode(s,"HarmonicType","HType","Natural");break;case T.Artificial:this.writeSimplePropertyNode(s,"HarmonicType","HType","Artificial");break;case T.Pinch:this.writeSimplePropertyNode(s,"HarmonicType","HType","Pinch");break;case T.Tap:this.writeSimplePropertyNode(s,"HarmonicType","HType","Tap");break;case T.Semi:this.writeSimplePropertyNode(s,"HarmonicType","HType","Semi");break;case T.Feedback:this.writeSimplePropertyNode(s,"HarmonicType","HType","Feedback")}0!==t.harmonicValue&&this.writeSimplePropertyNode(s,"HarmonicFret","HFret",t.harmonicValue.toString())}t.isDead&&this.writeSimplePropertyNode(s,"Muted","Enable",null),t.isPalmMute&&this.writeSimplePropertyNode(s,"PalmMuted","Enable",null),t.hasBend&&this.writeBend(s,t),t.isHammerPullOrigin&&this.writeSimplePropertyNode(s,"HopoOrigin","Enable",null),t.isHammerPullDestination&&this.writeSimplePropertyNode(s,"HopoDestination","Enable",null),t.isLeftHandTapped&&this.writeSimplePropertyNode(s,"LeftHandTapped","Enable",null);let i=0;switch(t.slideInType){case x.IntoFromAbove:i|=32;break;case x.IntoFromBelow:i|=16}switch(t.slideOutType){case v.Shift:i|=1;break;case v.Legato:i|=2;break;case v.OutDown:i|=4;break;case v.OutUp:i|=8;break;case v.PickSlideDown:i|=64;break;case v.PickSlideUp:i|=128}i>0&&this.writeSimplePropertyNode(s,"Slide","Flags",i.toString())}writeTransposedPitch(e,t){t.isPercussion?this.writePitch(e,"ConcertPitch","C","-1",""):this.writePitchForValue(e,"TransposedPitch",t.displayValueWithoutBend,t.accidentalMode)}writeConcertPitch(e,t){t.isPercussion?this.writePitch(e,"ConcertPitch","C","-1",""):this.writePitchForValue(e,"ConcertPitch",t.realValueWithoutHarmonic,t.accidentalMode)}writePitchForValue(e,t,s,i){let a=0,r=0,n="",o="";const h=()=>{a=s%12,r=s/12|0,n=st.defaultSteps[a],o=st.defaultAccidentals[a]};switch(h(),i){case N.Default:break;case N.ForceNone:case N.ForceNatural:o="";break;case N.ForceSharp:o="#";break;case N.ForceDoubleSharp:"#"===o&&(s-=2,h()),o="x";break;case N.ForceFlat:"#"===o&&(s+=1,h()),o="b";break;case N.ForceDoubleFlat:"#"===o&&(s+=2,h()),o="bb"}this.writePitch(e,t,n,r.toString(),o)}writePitch(e,t,s,i,a){const r=e.addElement("Property");r.attributes.set("name",t);const n=r.addElement("Pitch");n.addElement("Step").innerText=s,n.addElement("Accidental").innerText=a,n.addElement("Octave").innerText=i}writeBend(e,t){t.hasBend&&t.bendPoints.length<=4&&this.writeStandardBend(e,t.bendPoints)}writeStandardBend(e,t){this.writeSimplePropertyNode(e,"Bended","Enable",null);const s=t[0],i=t[t.length-1];let a,r;switch(t.length){case 4:a=t[1],r=t[2];break;case 3:a=t[1],r=t[1];break;default:a=new X((s.offset+i.offset)/2,(s.value+i.value)/2),r=a}this.writeSimplePropertyNode(e,"BendDestinationOffset","Float",this.toBendOffset(i.offset).toString()),this.writeSimplePropertyNode(e,"BendDestinationValue","Float",this.toBendValue(i.value).toString()),this.writeSimplePropertyNode(e,"BendMiddleOffset1","Float",this.toBendOffset(a.offset).toString()),this.writeSimplePropertyNode(e,"BendMiddleOffset2","Float",this.toBendOffset(r.offset).toString()),this.writeSimplePropertyNode(e,"BendMiddleValue","Float",this.toBendValue(a.value).toString()),this.writeSimplePropertyNode(e,"BendOriginOffset","Float",this.toBendOffset(s.offset).toString()),this.writeSimplePropertyNode(e,"BendOriginValue","Float",this.toBendValue(s.value).toString())}toBendValue(e){return 25*e}toBendOffset(e){return e/X.MaxPosition*100}writeBeatNode(e,t,s){const i=e.addElement("Beat");if(i.attributes.set("id",t.id.toString()),i.addElement("Dynamic").innerText=g[t.dynamics],t.fade!==ue.None&&(i.addElement("Fadding").innerText=ue[t.fade]),t.isTremolo)switch(t.tremoloSpeed){case _.Eighth:i.addElement("Tremolo").innerText="1/2";break;case _.Sixteenth:i.addElement("Tremolo").innerText="1/4";break;case _.ThirtySecond:i.addElement("Tremolo").innerText="1/8"}switch(t.hasChord&&i.addElement("Chord").setCData(t.chordId),t.crescendo!==S.None&&(i.addElement("Hairpin").innerText=S[t.crescendo]),t.brushType){case b.ArpeggioUp:i.addElement("Arpeggio").innerText="Up";break;case b.ArpeggioDown:i.addElement("Arpeggio").innerText="Down"}switch(t.text&&i.addElement("FreeText").setCData(t.text),t.graceType){case w.OnBeat:case w.BeforeBeat:i.addElement("GraceNotes").innerText=w[t.graceType]}if(t.ottava!==o.Regular&&(i.addElement("Ottavia").innerText=o[t.ottava].substr(1)),t.hasWhammyBar&&this.writeWhammyNode(i,t),t.isLegatoOrigin||t.isLegatoDestination){const e=i.addElement("Legato");e.attributes.set("origin",t.isLegatoOrigin?"true":"false"),e.attributes.set("destination",t.isLegatoDestination?"true":"false")}if(this.writeRhythm(i,t,s),null!==t.preferredBeamDirection)switch(t.preferredBeamDirection){case Te.Up:i.addElement("TransposedPitchStemOrientation").innerText="Upward",i.addElement("UserTransposedPitchStemOrientation").innerText="Upward";break;case Te.Down:i.addElement("TransposedPitchStemOrientation").innerText="Downward",i.addElement("UserTransposedPitchStemOrientation").innerText="Downward"}i.addElement("ConcertPitchStemOrientation").innerText="Undefined",t.slashed&&i.addElement("Slashed"),t.deadSlapped&&i.addElement("DeadSlapped"),t.notes.length>0&&(i.addElement("Notes").innerText=t.notes.map((e=>e.id)).join(" ")),t.golpe!==de.None&&(i.addElement("Golpe").innerText=de[t.golpe]),t.wahPedal!==pe.None&&(i.addElement("Wah").innerText=pe[t.wahPedal]),t.showTimer&&(i.addElement("Timer").innerText=(t.timer??0).toString()),this.writeBeatProperties(i,t),this.writeBeatXProperties(i,t),t.lyrics&&t.lyrics.length>0&&this.writeBeatLyrics(i,t.lyrics)}writeBeatLyrics(e,t){const s=e.addElement("Lyrics");for(const e of t){s.addElement("Line").setCData(e)}}writeBeatXProperties(e,t){const s=e.addElement("XProperties");switch(t.brushDuration>0&&this.writeSimpleXPropertyNode(s,"687935489","Int",t.brushDuration.toString()),t.beamingMode){case fe.ForceSplitToNext:this.writeSimpleXPropertyNode(s,"1124204546","Int","2");break;case fe.ForceMergeWithNext:this.writeSimpleXPropertyNode(s,"1124204546","Int","1");break;case fe.ForceSplitOnSecondaryToNext:this.writeSimpleXPropertyNode(s,"1124204552","Int","1")}}writeBeatProperties(e,t){const s=e.addElement("Properties");switch(t.brushType){case b.BrushUp:this.writeSimplePropertyNode(s,"Brush","Direction","Up");break;case b.BrushDown:this.writeSimplePropertyNode(s,"Brush","Direction","Down")}switch(t.pickStroke){case ae.Up:this.writeSimplePropertyNode(s,"PickStroke","Direction","Up");break;case ae.Down:this.writeSimplePropertyNode(s,"PickStroke","Direction","Down")}switch(t.slap&&this.writeSimplePropertyNode(s,"Slapped","Enable",null),t.pop&&this.writeSimplePropertyNode(s,"Popped","Enable",null),t.vibrato){case P.Wide:this.writeSimplePropertyNode(s,"VibratoWTremBar","Strength","Wide");break;case P.Slight:this.writeSimplePropertyNode(s,"VibratoWTremBar","Strength","Slight")}if(t.isBarre)switch(this.writeSimplePropertyNode(s,"BarreFret","Fret",t.barreFret.toString()),t.barreShape){case ge.Full:this.writeSimplePropertyNode(s,"BarreString","String","0");break;case ge.Half:this.writeSimplePropertyNode(s,"BarreString","String","1")}if(t.rasgueado!==me.None){let e="";switch(t.rasgueado){case me.Ii:e="ii_1";break;case me.Mi:e="mi_1";break;case me.MiiTriplet:e="mii_1";break;case me.MiiAnapaest:e="mii_2";break;case me.PmpTriplet:e="pmp_1";break;case me.PmpAnapaest:e="pmp_2";break;case me.PeiTriplet:e="pei_1";break;case me.PeiAnapaest:e="pei_2";break;case me.PaiTriplet:e="pai_1";break;case me.PaiAnapaest:e="pai_2";break;case me.AmiTriplet:e="ami_1";break;case me.AmiAnapaest:e="ami_2";break;case me.Ppp:e="ppp_1";break;case me.Amii:e="amii_1";break;case me.Amip:e="amip_1";break;case me.Eami:e="eami_1";break;case me.Eamii:e="eamii_1";break;case me.Peami:e="peami_1"}this.writeSimplePropertyNode(s,"Rasgueado","Rasgueado",e)}}writeRhythm(e,t,s){const i=`${t.duration}_${t.dots}_${t.tupletNumerator}_${t.tupletDenominator}';`;let a;if(this._rhythmIdLookup.has(i))a=this._rhythmIdLookup.get(i);else{a=this._rhythmIdLookup.size.toString(),this._rhythmIdLookup.set(i,a);const e=s.addElement("Rhythm");if(e.attributes.set("id",a),t.hasTuplet){const s=e.addElement("PrimaryTuplet");s.attributes.set("num",t.tupletNumerator.toString()),s.attributes.set("den",t.tupletDenominator.toString())}t.dots>0&&e.addElement("AugmentationDot").attributes.set("count",t.dots.toString());let r="Quarter";switch(t.duration){case _.QuadrupleWhole:r="Long";break;case _.DoubleWhole:r="DoubleWhole";break;case _.Whole:r="Whole";break;case _.Half:r="Half";break;case _.Quarter:r="Quarter";break;case _.Eighth:r="Eighth";break;case _.Sixteenth:r="16th";break;case _.ThirtySecond:r="32nd";break;case _.SixtyFourth:r="64th";break;case _.OneHundredTwentyEighth:r="128th";break;case _.TwoHundredFiftySixth:r="256th"}e.addElement("NoteValue").innerText=r}e.addElement("Rhythm").attributes.set("ref",a)}writeWhammyNode(e,t){t.hasWhammyBar&&t.whammyBarPoints.length<=4&&this.writeStandardWhammy(e,t.whammyBarPoints)}writeStandardWhammy(e,t){const s=e.addElement("Whammy"),i=t[0],a=t[t.length-1];let r,n;switch(t.length){case 4:r=t[1],n=t[2];break;case 3:r=t[1],n=t[1];break;default:r=new X((i.offset+a.offset)/2,(i.value+a.value)/2),n=r}s.attributes.set("destinationOffset",this.toBendOffset(a.offset).toString()),s.attributes.set("destinationValue",this.toBendValue(a.value).toString()),s.attributes.set("middleOffset1",this.toBendOffset(r.offset).toString()),s.attributes.set("middleOffset2",this.toBendOffset(n.offset).toString()),s.attributes.set("middleValue",this.toBendValue(r.value).toString()),s.attributes.set("originOffset",this.toBendOffset(i.offset).toString()),s.attributes.set("originValue",this.toBendValue(i.value).toString())}writeScoreNode(e,t){const s=e.addElement("Score");s.addElement("Title").setCData(t.title),s.addElement("SubTitle").setCData(t.subTitle),s.addElement("Artist").setCData(t.artist),s.addElement("Album").setCData(t.album),s.addElement("Words").setCData(t.words),s.addElement("Music").setCData(t.music),s.addElement("WordsAndMusic").setCData(t.words===t.music?t.words:""),s.addElement("Copyright").setCData(t.copyright),s.addElement("Tabber").setCData(t.tab),s.addElement("Instructions").setCData(t.instructions),s.addElement("Notices").setCData(t.notices),s.addElement("FirstPageHeader").setCData(""),s.addElement("FirstPageFooter").setCData(""),s.addElement("PageHeader").setCData(""),s.addElement("PageFooter").setCData(""),s.addElement("ScoreSystemsDefaultLayout").setCData(t.defaultSystemsLayout.toString()),s.addElement("ScoreSystemsLayout").setCData(t.systemsLayout.join(" ")),s.addElement("ScoreZoomPolicy").innerText="Value",s.addElement("ScoreZoom").innerText="1",s.addElement("MultiVoice").innerText="1>"}writeMasterTrackNode(e,t){const s=e.addElement("MasterTrack");s.addElement("Tracks").innerText=t.tracks.map((e=>e.index)).join(" ");const i=s.addElement("Automations");if(t.masterBars.length>0&&t.masterBars[0].isAnacrusis&&s.addElement("Anacrusis"),0===t.masterBars[0].tempoAutomations.length){const e=i.addElement("Automation");e.addElement("Type").innerText="Tempo",e.addElement("Linear").innerText="false",e.addElement("Bar").innerText="0",e.addElement("Position").innerText="0",e.addElement("Visible").innerText="true",e.addElement("Value").innerText=`${t.tempo} 2`,t.tempoLabel&&(e.addElement("Text").innerText=t.tempoLabel)}for(const e of t.masterBars)for(const t of e.tempoAutomations){const s=i.addElement("Automation");s.addElement("Type").innerText="Tempo",s.addElement("Linear").innerText=t.isLinear?"true":"false",s.addElement("Bar").innerText=e.index.toString(),s.addElement("Position").innerText=t.ratioPosition.toString(),s.addElement("Visible").innerText="true",s.addElement("Value").innerText=`${t.value} 2`,t.text&&(s.addElement("Text").innerText=t.text)}}writeAudioTracksNode(e,t){e.addElement("AudioTracks")}writeTracksNode(e,t){const s=e.addElement("Tracks");for(const e of t.tracks)this.writeTrackNode(s,e)}writeTrackNode(e,t){const s=e.addElement("Track");s.attributes.set("id",t.index.toString()),s.addElement("Name").setCData(t.name),s.addElement("ShortName").setCData(t.shortName),s.addElement("Color").innerText=`${t.color.r} ${t.color.g} ${t.color.b}`,s.addElement("SystemsDefautLayout").innerText=t.defaultSystemsLayout.toString(),s.addElement("SystemsLayout").innerText=t.systemsLayout.join(" "),s.addElement("AutoBrush"),s.addElement("PalmMute").innerText="0",s.addElement("PlayingStyle").innerText=A.isGuitar(t.playbackInfo.program)?"StringedPick":"Default",s.addElement("UseOneChannelPerString"),s.addElement("IconId").innerText=uc.getIconId(t.playbackInfo).toString(),this.writeInstrumentSetNode(s,t),this.writeTransposeNode(s,t),this.writeRseNode(s,t),s.addElement("ForcedSound").innerText="-1",this.writeMidiConnectionNode(s,t),t.playbackInfo.isSolo?s.addElement("PlaybackState").innerText="Solo":t.playbackInfo.isMute?s.addElement("PlaybackState").innerText="Mute":s.addElement("PlaybackState").innerText="Default",s.addElement("AudioEngineState").innerText="MIDI",this.writeLyricsNode(s,t),this.writeStavesNode(s,t),this.writeSoundsAndAutomations(s,t)}static getIconId(e){return 9===e.primaryChannel?uc.DrumKitProgramInfo.icon:uc.MidiProgramInfoLookup.has(e.program)?uc.MidiProgramInfoLookup.get(e.program).icon:cc.SteelGuitar}writeSoundAndAutomation(e,t,s,i,a,r,n,o=0){const h=e.addElement("Sound");h.addElement("Name").setCData(s),h.addElement("Label").setCData(s),h.addElement("Path").setCData(i),h.addElement("Role").setCData(a);const l=h.addElement("MIDI");l.addElement("LSB").innerText="0",l.addElement("MSB").innerText="0",l.addElement("Program").innerText=n.toString();const c=t.addElement("Automation");c.addElement("Type").innerText="Sound",c.addElement("Linear").innerText="false",c.addElement("Bar").innerText=r.toString(),c.addElement("Position").innerText=o.toString(),c.addElement("Visible").innerText="true",c.addElement("Value").setCData(`${i};${s};${a}`)}writeSoundsAndAutomations(e,t){const s=e.addElement("Sounds"),i=e.addElement("Automations");if(t.staves.length>0&&t.staves[0].bars.length>0){const e=`Track_${t.index}_Initial`,a=`Midi/${t.playbackInfo.program}`,r="Factory";let n=!1;for(const o of t.staves)for(const h of o.bars)for(const o of h.voices)for(const l of o.beats){const o=l.getAutomation(m.Instrument),c=0===h.index&&0===l.index;if(o){const d=c?e:`ProgramChange_${l.id}`,u=c?a:`Midi/${o.value}`,p=c?r:"User";c||n||(this.writeSoundAndAutomation(s,i,e,a,r,t.staves[0].bars[0].index,t.playbackInfo.program),n=!0),this.writeSoundAndAutomation(s,i,d,u,p,h.index,o.value,o.ratioPosition),c&&(n=!0)}}}for(const e of t.staves)for(const t of e.bars)for(const e of t.sustainPedals)if(e.pedalType!==d.Hold){const s=i.addElement("Automation");switch(s.addElement("Type").innerText="SustainPedal",s.addElement("Linear").innerText="false",s.addElement("Bar").innerText=t.index.toString(),s.addElement("Position").innerText=e.ratioPosition.toString(),s.addElement("Visible").innerText="true",e.pedalType){case d.Down:s.addElement("Value").innerText="0 1";break;case d.Up:s.addElement("Value").innerText="0 3"}}}writeMidiConnectionNode(e,t){const s=e.addElement("MidiConnection");s.addElement("Port").innerText=t.playbackInfo.port.toString(),s.addElement("PrimaryChannel").innerText=t.playbackInfo.primaryChannel.toString(),s.addElement("SecondaryChannel").innerText=t.playbackInfo.secondaryChannel.toString(),s.addElement("ForeOneChannelPerString").innerText="false"}writeRseNode(e,t){const s=e.addElement("RSE").addElement("ChannelStrip");s.attributes.set("version","E56");s.addElement("Parameters").innerText=`0.5 0.5 0.5 0.5 0.5 0.5 0.5 0.5 0.5 1 0.5 ${t.playbackInfo.balance/16} ${t.playbackInfo.volume/16} 0.5 0.5 0.5`}writeStavesNode(e,t){const s=e.addElement("Staves");for(const e of t.staves)this.writeStaffNode(s,e)}writeStaffNode(e,t){const s=e.addElement("Staff").addElement("Properties");if(this.writeSimplePropertyNode(s,"CapoFret","Fret",t.capo.toString()),this.writeSimplePropertyNode(s,"FretCount","Fret","24"),t.tuning.length>0){const e=s.addElement("Property");switch(e.attributes.set("name","Tuning"),e.addElement("Pitches").innerText=t.tuning.slice().reverse().join(" "),e.addElement("Label").setCData(t.tuningName),e.addElement("LabelVisible").innerText=t.tuningName?"true":"false",e.addElement("Flat"),t.tuning.length){case 3:e.addElement("Instrument").innerText="Shamisen";break;case 4:105===t.track.playbackInfo.program?e.addElement("Instrument").innerText="Banjo":42===t.track.playbackInfo.program?e.addElement("Instrument").innerText="Cello":43===t.track.playbackInfo.program?e.addElement("Instrument").innerText="Contrabass":40===t.track.playbackInfo.program?e.addElement("Instrument").innerText="Violin":41===t.track.playbackInfo.program?e.addElement("Instrument").innerText="Viola":e.addElement("Instrument").innerText="Bass";break;case 5:105===t.track.playbackInfo.program?e.addElement("Instrument").innerText="Banjo":e.addElement("Instrument").innerText="Bass";break;case 6:105===t.track.playbackInfo.program?e.addElement("Instrument").innerText="Banjo":t.track.playbackInfo.program<=39?e.addElement("Instrument").innerText="Bass":e.addElement("Instrument").innerText="Guitar";break;case 7:t.track.playbackInfo.program<=39?e.addElement("Instrument").innerText="Bass":e.addElement("Instrument").innerText="Guitar";break;default:e.addElement("Instrument").innerText="Guitar"}}this.writeSimplePropertyNode(s,"PartialCapoFret","Fret","0"),this.writeSimplePropertyNode(s,"PartialCapoStringFlags","Bitset",t.tuning.map((e=>"0")).join("")),this.writeSimplePropertyNode(s,"TuningFlat","Enable",null),this.writeDiagramCollection(s,t,"DiagramCollection"),this.writeDiagramCollection(s,t,"DiagramWorkingSet")}writeDiagramCollection(e,t,s){const i=e.addElement("Property");i.attributes.set("name",s);const a=i.addElement("Items"),r=t.chords;if(r)for(const[e,t]of r){const s=a.addElement("Item");s.attributes.set("id",e),s.attributes.set("name",t.name);const i=s.addElement("Diagram");i.attributes.set("stringCount",t.strings.length.toString()),i.attributes.set("fretCount","5"),i.attributes.set("baseFret",(t.firstFret-1).toString()),i.attributes.set("barStates",t.strings.map((e=>"1")).join(" "));const r=[],n=new Map;for(let e=0;e<t.strings.length;e++){const s=t.strings[e];if(-1!==s){const a=i.addElement("Fret"),o=t.strings.length-1-e;a.attributes.set("string",o.toString()),a.attributes.set("fret",(s-t.firstFret+1).toString()),n.has(s)||(n.set(s,[]),r.push(s)),n.get(s).push(o)}}r.sort();const o=i.addElement("Fingering");if(t.barreFrets.length>0){const e=[k.LittleFinger,k.AnnularFinger,k.MiddleFinger,k.IndexFinger];for(const s of r){const i=n.get(s);if(i.length>1&&t.barreFrets.indexOf(s)>=0){const a=e.length>0?e.pop():k.IndexFinger;for(const e of i){const i=o.addElement("Position");switch(a){case k.LittleFinger:i.attributes.set("finger","Pinky");break;case k.AnnularFinger:i.attributes.set("finger","Ring");break;case k.MiddleFinger:i.attributes.set("finger","Middle");break;case k.IndexFinger:i.attributes.set("finger","Index")}i.attributes.set("fret",(s-t.firstFret+1).toString()),i.attributes.set("string",e.toString())}}}}const h=i.addElement("Property");h.attributes.set("name","ShowName"),h.attributes.set("type","bool"),h.attributes.set("value",t.showName?"true":"false");const l=i.addElement("Property");l.attributes.set("name","ShowDiagram"),l.attributes.set("type","bool"),l.attributes.set("value",t.showDiagram?"true":"false");const c=i.addElement("Property");c.attributes.set("name","ShowFingering"),c.attributes.set("type","bool"),c.attributes.set("value",t.showFingering?"true":"false");const d=i.addElement("Chord"),u=d.addElement("KeyNote");u.attributes.set("step","C"),u.attributes.set("accidental","Natural");const p=d.addElement("BassNote");p.attributes.set("step","C"),p.attributes.set("accidental","Natural");const g=d.addElement("Degree");g.attributes.set("interval","Third"),g.attributes.set("alteration","Major"),g.attributes.set("omitted","false");const m=d.addElement("Degree");m.attributes.set("interval","Fifth"),m.attributes.set("alteration","Perfect"),m.attributes.set("omitted","false")}}writeSimplePropertyNode(e,t,s,i){const a=e.addElement("Property");a.attributes.set("name",t);const r=a.addElement(s);return null!==i&&(r.innerText=i),a}writeSimpleXPropertyNode(e,t,s,i){const a=e.addElement("XProperty");a.attributes.set("id",t);const r=a.addElement(s);return null!==i&&(r.innerText=i),a}writeLyricsNode(e,t){const s=e.addElement("Lyrics");s.attributes.set("dispatched","true");const i=[];for(const e of t.staves[0].bars)for(const t of e.voices)if(!t.isEmpty)for(const s of t.beats)if(s.lyrics)for(let t=0;t<s.lyrics.length;t++){for(;t>=i.length;){const t=new Ke;t.startBar=e.index,t.text="[Empty]",i.push(t)}const a=i[t];a.text="[Empty]"===a.text?s.lyrics[t]:`${a.text} ${s.lyrics[t].split(" ").join("+")}`}for(let e=0;e<i.length;e++){const t=s.addElement("Line");t.addElement("Text").setCData(i[e].text),t.addElement("Offset").innerText=i[e].startBar.toString()}}writeTransposeNode(e,t){const s=e.addElement("Transpose"),i=Math.floor(t.staves[0].displayTranspositionPitch/12),a=t.staves[0].displayTranspositionPitch-12*i;s.addElement("Chromatic").innerText=a.toString(),s.addElement("Octave").innerText=i.toString()}writeInstrumentSetNode(e,t){const s=e.addElement("InstrumentSet"),i=t.staves[0];if(s.addElement("LineCount").innerText=i.standardNotationLineCount.toString(),t.percussionArticulations.length>0||i.isPercussion){const e=t.percussionArticulations.length>0?t.percussionArticulations:Array.from(Le.instrumentArticulations.values());s.addElement("Name").innerText=uc.DrumKitProgramInfo.instrumentSetName,s.addElement("Type").innerText=uc.DrumKitProgramInfo.instrumentSetType;let i="",a=new yt;const r=new Map,n=s.addElement("Elements");for(const t of e){{const e=n.addElement("Element");let s=t.elementType;if(r.has(s)){const e=r.get(s);s+=` ${e}`,r.set(s,e+1)}else r.set(s,1);i=s,e.addElement("Name").innerText=s,e.addElement("Type").innerText=t.elementType,a=e.addElement("Articulations")}const e=a.addElement("Articulation");switch(e.addElement("Name").innerText=`${i} ${a.childNodes.length}`,e.addElement("StaffLine").innerText=t.staffLine.toString(),e.addElement("Noteheads").innerText=[this.mapMusicSymbol(t.noteHeadDefault),this.mapMusicSymbol(t.noteHeadHalf),this.mapMusicSymbol(t.noteHeadWhole)].join(" "),t.techniqueSymbolPlacement){case oe.Top:e.addElement("TechniquePlacement").innerText="below";break;case oe.Middle:e.addElement("TechniquePlacement").innerText="inside";break;case oe.Bottom:e.addElement("TechniquePlacement").innerText="above"}e.addElement("TechniqueSymbol").innerText=this.mapMusicSymbol(t.techniqueSymbol),e.addElement("InputMidiNumbers").innerText="",e.addElement("OutputMidiNumber").innerText=t.outputMidiNumber.toString()}}else{const e=uc.MidiProgramInfoLookup.has(t.playbackInfo.program)?uc.MidiProgramInfoLookup.get(t.playbackInfo.program):uc.MidiProgramInfoLookup.get(0);s.addElement("Name").innerText=e.instrumentSetName,s.addElement("Type").innerText=e.instrumentSetType;const i=s.addElement("Elements").addElement("Element");i.addElement("Pitched").innerText="Pitched",i.addElement("Type").innerText="pitched",i.addElement("SoundbankName").innerText="";const a=i.addElement("Articulations").addElement("Articulation");a.addElement("Name").innerText="",a.addElement("StaffLine").innerText="0",a.addElement("Noteheads").innerText="noteheadBlack noteheadHalf noteheadWhole",a.addElement("TechniquePlacement").innerText="outside",a.addElement("TechniqueSymbol").innerText="",a.addElement("InputMidiNumbers").innerText="",a.addElement("OutputRSESound").innerText="",a.addElement("OutputMidiNumber").innerText="0"}}mapMusicSymbol(e){if(e===re.None)return"";const t=re[e];return t.substring(0,1).toLowerCase()+t.substring(1)}writeMasterBarsNode(e,t){const s=e.addElement("MasterBars");for(const e of t.masterBars)this.writeMasterBarNode(s,e)}writeMasterBarNode(e,t){const s=e.addElement("MasterBar"),i=s.addElement("Key");i.addElement("AccidentalCount").innerText=t.keySignature.toString(),i.addElement("Mode").innerText=c[t.keySignatureType],i.addElement("Sharps").innerText="Sharps",s.addElement("Time").innerText=`${t.timeSignatureNumerator}/${t.timeSignatureDenominator}`,t.isFreeTime&&s.addElement("FreeTime");const a=[];for(const e of t.score.tracks)for(const s of e.staves)a.push(s.bars[t.index].id.toString());if(s.addElement("Bars").innerText=a.join(" "),t.isDoubleBar&&s.addElement("DoubleBar"),t.isSectionStart){const e=s.addElement("Section");e.addElement("Letter").setCData(t.section.marker),e.addElement("Text").setCData(t.section.text)}if(t.isRepeatStart||t.isRepeatEnd){const e=s.addElement("Repeat");e.attributes.set("start",t.isRepeatStart?"true":"false"),e.attributes.set("end",t.isRepeatEnd?"true":"false"),t.isRepeatEnd&&e.attributes.set("count",t.repeatCount.toString())}if(t.alternateEndings>0){let e=t.alternateEndings;const i=[];let a=0;for(;e>0;)1==(e>>a&1)&&(i.push(a+1),e&=~(1<<a)),a++;s.addElement("AlternateEndings").innerText=i.join(" ")}if(t.tripletFeel!==M.NoTripletFeel&&(s.addElement("TripletFeel").innerText=M[t.tripletFeel]),t.directions&&t.directions.size>0){const e=s.addElement("Directions");for(const s of t.directions)switch(s){case Be.TargetFine:e.addElement("Target").innerText="Fine";break;case Be.TargetSegno:e.addElement("Target").innerText="Segno";break;case Be.TargetSegnoSegno:e.addElement("Target").innerText="SegnoSegno";break;case Be.TargetCoda:e.addElement("Target").innerText="Coda";break;case Be.TargetDoubleCoda:e.addElement("Target").innerText="DoubleCoda";break;case Be.JumpDaCapo:e.addElement("Jump").innerText="DaCapo";break;case Be.JumpDaCapoAlCoda:e.addElement("Jump").innerText="DaCapoAlCoda";break;case Be.JumpDaCapoAlDoubleCoda:e.addElement("Jump").innerText="DaCapoAlDoubleCoda";break;case Be.JumpDaCapoAlFine:e.addElement("Jump").innerText="DaCapoAlFine";break;case Be.JumpDalSegno:e.addElement("Jump").innerText="DaSegno";break;case Be.JumpDalSegnoAlCoda:e.addElement("Jump").innerText="DaSegnoAlCoda";break;case Be.JumpDalSegnoAlDoubleCoda:e.addElement("Jump").innerText="DaSegnoAlDoubleCoda";break;case Be.JumpDalSegnoAlFine:e.addElement("Jump").innerText="DaSegnoAlFine";break;case Be.JumpDalSegnoSegno:e.addElement("Jump").innerText="DaSegnoSegno";break;case Be.JumpDalSegnoSegnoAlCoda:e.addElement("Jump").innerText="DaSegnoSegnoAlCoda";break;case Be.JumpDalSegnoSegnoAlDoubleCoda:e.addElement("Jump").innerText="DaSegnoSegnoAlDoubleCoda";break;case Be.JumpDalSegnoSegnoAlFine:e.addElement("Jump").innerText="DaSegnoSegnoAlFine";break;case Be.JumpDaCoda:e.addElement("Jump").innerText="DaCoda";break;case Be.JumpDaDoubleCoda:e.addElement("Jump").innerText="DaDoubleCoda"}}this.writeFermatas(s,t)}writeFermatas(e,t){const s=t.fermata?.size??0;if(0!==s&&s>0){const s=e.addElement("Fermatas");for(const[e,i]of t.fermata)this.writeFermata(s,e,i)}}writeFermata(e,t,s){let i=-1,a=1;if(t>0)for(;a<10&&(i=t/z.QuarterTime*a,i!==Math.floor(i));)i=-1,a++;else i=0,a=1;if(-1===i)return;const r=e.addElement("Fermata");r.addElement("Type").innerText=ke[s.type],r.addElement("Length").innerText=s.length.toString(),r.addElement("Offset").innerText=`${i}/${a}`}writeBarNode(e,t){const s=e.addElement("Bar");s.attributes.set("id",t.id.toString()),s.addElement("Voices").innerText=t.voices.map((e=>e.isEmpty?"-1":e.id.toString())).join(" "),s.addElement("Clef").innerText=n[t.clef],t.clefOttava!==o.Regular&&(s.addElement("Ottavia").innerText=o[t.clefOttava].substr(1)),t.simileMark!==h.None&&(s.addElement("SimileMark").innerText=h[t.simileMark])}writeVoiceNode(e,t){if(t.isEmpty)return;const s=e.addElement("Voice");s.attributes.set("id",t.id.toString()),s.addElement("Beats").innerText=t.beats.map((e=>e.id)).join(" ")}}uc.MidiProgramInfoLookup=new Map([[0,new dc(cc.Piano,"Acoustic Piano")],[1,new dc(cc.Piano,"Acoustic Piano")],[2,new dc(cc.Piano,"Electric Piano")],[3,new dc(cc.Piano,"Acoustic Piano")],[4,new dc(cc.Piano,"Electric Piano")],[5,new dc(cc.Piano,"Electric Piano")],[6,new dc(cc.Piano,"Harpsichord")],[7,new dc(cc.Piano,"Harpsichord")],[8,new dc(cc.PitchedIdiophone,"Celesta")],[9,new dc(cc.PitchedIdiophone,"Vibraphone")],[10,new dc(cc.PitchedIdiophone,"Vibraphone")],[11,new dc(cc.PitchedIdiophone,"Vibraphone")],[12,new dc(cc.PitchedIdiophone,"Xylophone")],[13,new dc(cc.PitchedIdiophone,"Xylophone")],[14,new dc(cc.PitchedIdiophone,"Vibraphone")],[15,new dc(cc.Banjo,"Banjo")],[16,new dc(cc.Piano,"Electric Organ")],[17,new dc(cc.Piano,"Electric Organ")],[18,new dc(cc.Piano,"Electric Organ")],[19,new dc(cc.Piano,"Electric Organ")],[20,new dc(cc.Piano,"Electric Organ")],[21,new dc(cc.Piano,"Electric Organ")],[22,new dc(cc.Woodwind,"Recorder")],[23,new dc(cc.Piano,"Electric Organ")],[24,new dc(cc.ClassicalGuitar,"Nylon Guitar")],[25,new dc(cc.SteelGuitar,"Steel Guitar")],[26,new dc(cc.SteelGuitar,"Electric Guitar")],[27,new dc(cc.ElectricGuitar,"Electric Guitar")],[28,new dc(cc.ElectricGuitar,"Electric Guitar")],[29,new dc(cc.ElectricGuitar,"Electric Guitar")],[30,new dc(cc.SteelGuitar,"Electric Guitar")],[31,new dc(cc.SteelGuitar,"Electric Guitar")],[32,new dc(cc.Bass,"Acoustic Bass")],[33,new dc(cc.Bass,"Electric Bass")],[34,new dc(cc.Bass,"Electric Bass")],[35,new dc(cc.Bass,"Acoustic Bass")],[36,new dc(cc.Bass,"Electric Bass")],[37,new dc(cc.Bass,"Electric Bass")],[38,new dc(cc.Synth,"Synth Bass")],[39,new dc(cc.Synth,"Synth Bass")],[40,new dc(cc.Strings,"Violin")],[41,new dc(cc.Strings,"Viola")],[42,new dc(cc.Strings,"Cello")],[43,new dc(cc.Strings,"Contrabass")],[44,new dc(cc.Strings,"Violin")],[45,new dc(cc.Strings,"Violin")],[46,new dc(cc.Piano,"Harp")],[47,new dc(cc.Membraphone,"Timpani")],[48,new dc(cc.Strings,"Violin")],[49,new dc(cc.Strings,"Violin")],[50,new dc(cc.Strings,"Violin")],[51,new dc(cc.Strings,"Violin")],[52,new dc(cc.Vocal,"Voice")],[53,new dc(cc.Vocal,"Voice")],[54,new dc(cc.Vocal,"Voice")],[55,new dc(cc.Synth,"Pad Synthesizer")],[56,new dc(cc.Brass,"Trumpet")],[57,new dc(cc.Brass,"Trombone")],[58,new dc(cc.Brass,"Tuba")],[59,new dc(cc.Brass,"Trumpet")],[60,new dc(cc.Brass,"French Horn")],[61,new dc(cc.Brass,"Trumpet")],[62,new dc(cc.Brass,"Trumpet")],[63,new dc(cc.Brass,"Trumpet")],[64,new dc(cc.Reed,"Saxophone")],[65,new dc(cc.Reed,"Saxophone")],[66,new dc(cc.Reed,"Saxophone")],[67,new dc(cc.Reed,"Saxophone")],[68,new dc(cc.Reed,"Oboe")],[69,new dc(cc.Reed,"English Horn")],[70,new dc(cc.Reed,"Bassoon")],[71,new dc(cc.Reed,"Clarinet")],[72,new dc(cc.Reed,"Piccolo")],[73,new dc(cc.Woodwind,"Flute")],[74,new dc(cc.Woodwind,"Recorder")],[75,new dc(cc.Woodwind,"Flute")],[76,new dc(cc.Woodwind,"Recorder")],[77,new dc(cc.Woodwind,"Flute")],[78,new dc(cc.Woodwind,"Recorder")],[79,new dc(cc.Woodwind,"Flute")],[80,new dc(cc.Synth,"Lead Synthesizer")],[81,new dc(cc.Synth,"Lead Synthesizer")],[82,new dc(cc.Synth,"Lead Synthesizer")],[83,new dc(cc.Synth,"Lead Synthesizer")],[84,new dc(cc.Synth,"Lead Synthesizer")],[85,new dc(cc.Synth,"Lead Synthesizer")],[86,new dc(cc.Synth,"Lead Synthesizer")],[87,new dc(cc.Synth,"Lead Synthesizer")],[88,new dc(cc.Synth,"Pad Synthesizer")],[89,new dc(cc.Synth,"Pad Synthesizer")],[90,new dc(cc.Synth,"Pad Synthesizer")],[91,new dc(cc.Synth,"Pad Synthesizer")],[92,new dc(cc.Synth,"Pad Synthesizer")],[93,new dc(cc.Synth,"Pad Synthesizer")],[94,new dc(cc.Synth,"Pad Synthesizer")],[95,new dc(cc.Synth,"Pad Synthesizer")],[96,new dc(cc.Fx,"Pad Synthesizer")],[97,new dc(cc.Fx,"Pad Synthesizer")],[98,new dc(cc.Fx,"Pad Synthesizer")],[99,new dc(cc.Fx,"Pad Synthesizer")],[100,new dc(cc.Fx,"Lead Synthesizer")],[101,new dc(cc.Fx,"Lead Synthesizer")],[102,new dc(cc.Fx,"Lead Synthesizer")],[103,new dc(cc.Fx,"Trumpet")],[104,new dc(cc.ElectricGuitar,"Banjo")],[105,new dc(cc.Banjo,"Banjo")],[106,new dc(cc.Ukulele,"Ukulele")],[107,new dc(cc.Banjo,"Banjo")],[108,new dc(cc.PitchedIdiophone,"Xylophone")],[109,new dc(cc.Reed,"Bassoon")],[110,new dc(cc.Strings,"Violin")],[111,new dc(cc.Woodwind,"Flute")],[112,new dc(cc.PitchedIdiophone,"Xylophone")],[113,new dc(cc.Idiophone,"Celesta")],[114,new dc(cc.PitchedIdiophone,"Vibraphone")],[115,new dc(cc.Idiophone,"Xylophone")],[116,new dc(cc.Membraphone,"Xylophone")],[117,new dc(cc.Membraphone,"Xylophone")],[118,new dc(cc.Membraphone,"Xylophone")],[119,new dc(cc.Idiophone,"Celesta")],[120,new dc(cc.Fx,"Steel Guitar")],[121,new dc(cc.Fx,"Recorder")],[122,new dc(cc.Fx,"Recorder")],[123,new dc(cc.Fx,"Recorder")],[124,new dc(cc.Fx,"Recorder")],[125,new dc(cc.Fx,"Recorder")],[126,new dc(cc.Fx,"Recorder")],[127,new dc(cc.Fx,"Timpani")]]),uc.DrumKitProgramInfo=new dc(cc.PercussionKit,"Drums","drumKit");class pc{static buildCrc32Lookup(){const e=new Uint32Array(256);for(let t=0;t<e.length;t++){let s=t;for(let e=0;e<8;e++)s=1&~s?s>>>1:s>>>1^3988292384;e[t]=s}return e}get value(){return~this._checkValue}constructor(){this._checkValue=pc.CrcInit,this.reset()}update(e,t,s){for(let i=0;i<s;i++)this._checkValue=pc.Crc32Lookup[255&(this._checkValue^e[t+i])]^this._checkValue>>>8}reset(){this._checkValue=pc.CrcInit}}pc.Crc32Lookup=pc.buildCrc32Lookup(),pc.CrcInit=4294967295;class gc{}gc.MAX_WBITS=15,gc.WSIZE=1<<gc.MAX_WBITS,gc.WMASK=gc.WSIZE-1,gc.MIN_MATCH=3,gc.MAX_MATCH=258,gc.DEFAULT_MEM_LEVEL=8,gc.PENDING_BUF_SIZE=1<<gc.DEFAULT_MEM_LEVEL+8,gc.HASH_BITS=gc.DEFAULT_MEM_LEVEL+7,gc.HASH_SIZE=1<<gc.HASH_BITS,gc.HASH_SHIFT=(gc.HASH_BITS+gc.MIN_MATCH-1)/gc.MIN_MATCH,gc.HASH_MASK=gc.HASH_SIZE-1,gc.MIN_LOOKAHEAD=gc.MAX_MATCH+gc.MIN_MATCH+1,gc.MAX_DIST=gc.WSIZE-gc.MIN_LOOKAHEAD;class mc{constructor(e,t,s,i){this.length=null,this.numCodes=0,this.codes=null,this.huffman=e,this.minNumCodes=s,this.maxLength=i,this.freqs=new Int16Array(t),this.bitLengthCounts=new Int32Array(i)}reset(){for(let e=0;e<this.freqs.length;e++)this.freqs[e]=0;this.codes=null,this.length=null}buildTree(){const e=this.freqs.length,t=new Int32Array(e);let s=0,i=0;for(let a=0;a<e;a++){const e=this.freqs[a];if(0!==e){let r=s++;for(;r>0;){const s=Math.floor((r-1)/2);if(!(this.freqs[t[s]]>e))break;t[r]=t[s],r=s}t[r]=a,i=a}}for(;s<2;){const e=i<2?++i:0;t[s++]=e}this.numCodes=Math.max(i+1,this.minNumCodes);const a=s,r=new Int32Array(4*s-2),n=new Int32Array(2*s-1);let o=a;for(let e=0;e<s;e++){const s=t[e];r[2*e]=s,r[2*e+1]=-1,n[e]=this.freqs[s]<<8,t[e]=e}do{const e=t[0];let i=t[--s],a=0,h=1;for(;h<s;)h+1<s&&n[t[h]]>n[t[h+1]]&&h++,t[a]=t[h],a=h,h=2*h+1;let l=n[i];for(;h=a,a>0&&(a=Math.floor((h-1)/2),n[t[a]]>l);)t[h]=t[a];t[h]=i;const c=t[0];i=o++,r[2*i]=e,r[2*i+1]=c;const d=Math.min(255&n[e],255&n[c]);for(l=n[e]+n[c]-d+1,n[i]=l,a=0,h=1;h<s;)h+1<s&&n[t[h]]>n[t[h+1]]&&h++,t[a]=t[h],a=h,h=2*a+1;for(;h=a,h>0&&(a=Math.floor((h-1)/2),n[t[a]]>l);)t[h]=t[a];t[h]=i}while(s>1);this.buildLength(r)}buildLength(e){this.length=new Uint8Array(this.freqs.length);const t=Math.floor(e.length/2),s=Math.floor((t+1)/2);let i=0;for(let e=0;e<this.maxLength;e++)this.bitLengthCounts[e]=0;const a=new Int32Array(t);a[t-1]=0;for(let s=t-1;s>=0;s--)if(-1!==e[2*s+1]){let t=a[s]+1;t>this.maxLength&&(t=this.maxLength,i++),a[e[2*s]]=t,a[e[2*s+1]]=t}else{const t=a[s];this.bitLengthCounts[t-1]++,this.length[e[2*s]]=a[s]}if(0===i)return;let r=this.maxLength-1;do{for(;0===this.bitLengthCounts[--r];);do{this.bitLengthCounts[r]--,this.bitLengthCounts[++r]++,i-=1<<this.maxLength-1-r}while(i>0&&r<this.maxLength-1)}while(i>0);this.bitLengthCounts[this.maxLength-1]+=i,this.bitLengthCounts[this.maxLength-2]-=i;let n=2*s;for(let t=this.maxLength;0!==t;t--){let s=this.bitLengthCounts[t-1];for(;s>0;){const i=2*e[n++];-1===e[i+1]&&(this.length[e[i]]=t,s--)}}}getEncodedLength(){let e=0;for(let t=0;t<this.freqs.length;t++)e+=this.freqs[t]*this.length[t];return e}calcBLFreq(e){let t,s,i,a=-1,r=0;for(;r<this.numCodes;){i=1;const n=this.length[r];for(0===n?(t=138,s=3):(t=6,s=3,a!==n&&(e.freqs[n]++,i=0)),a=n,r++;r<this.numCodes&&a===this.length[r]&&(r++,!(++i>=t)););i<s?e.freqs[a]+=i:0!==a?e.freqs[mc.Repeat3To6]++:i<=10?e.freqs[mc.Repeat3To10]++:e.freqs[mc.Repeat11To138]++}}setStaticCodes(e,t){this.codes=e,this.length=t}buildCodes(){const e=new Int32Array(this.maxLength);let t=0;this.codes=new Int16Array(this.freqs.length);for(let s=0;s<this.maxLength;s++)e[s]=t,t+=this.bitLengthCounts[s]<<15-s;for(let t=0;t<this.numCodes;t++){const s=this.length[t];s>0&&(this.codes[t]=fc.bitReverse(e[s-1]),e[s-1]+=1<<16-s)}}writeTree(e){let t,s,i,a=-1,r=0;for(;r<this.numCodes;){i=1;const n=this.length[r];for(0===n?(t=138,s=3):(t=6,s=3,a!==n&&(e.writeSymbol(n),i=0)),a=n,r++;r<this.numCodes&&a===this.length[r]&&(r++,!(++i>=t)););if(i<s)for(;i-- >0;)e.writeSymbol(a);else 0!==a?(e.writeSymbol(mc.Repeat3To6),this.huffman.pending.writeBits(i-3,2)):i<=10?(e.writeSymbol(mc.Repeat3To10),this.huffman.pending.writeBits(i-3,3)):(e.writeSymbol(mc.Repeat11To138),this.huffman.pending.writeBits(i-11,7))}}writeSymbol(e){this.huffman.pending.writeBits(65535&this.codes[e],this.length[e])}}mc.Repeat3To6=16,mc.Repeat3To10=17,mc.Repeat11To138=18;class fc{static staticInit(){let e=0;for(;e<144;)fc.staticLCodes[e]=fc.bitReverse(48+e<<8),fc.staticLLength[e++]=8;for(;e<256;)fc.staticLCodes[e]=fc.bitReverse(256+e<<7),fc.staticLLength[e++]=9;for(;e<280;)fc.staticLCodes[e]=fc.bitReverse(-256+e<<9),fc.staticLLength[e++]=7;for(;e<fc.LITERAL_NUM;)fc.staticLCodes[e]=fc.bitReverse(-88+e<<8),fc.staticLLength[e++]=8;for(e=0;e<fc.DIST_NUM;e++)fc.staticDCodes[e]=fc.bitReverse(e<<11),fc.staticDLength[e]=5}static bitReverse(e){return fc.bit4Reverse[15&e]<<12|fc.bit4Reverse[e>>4&15]<<8|fc.bit4Reverse[e>>8&15]<<4|fc.bit4Reverse[e>>12]}constructor(e){this.last_lit=0,this.extra_bits=0,this.pending=e,this.literalTree=new mc(this,fc.LITERAL_NUM,257,15),this.distTree=new mc(this,fc.DIST_NUM,1,15),this.blTree=new mc(this,fc.BITLEN_NUM,4,7),this.d_buf=new Int16Array(fc.BUFSIZE),this.l_buf=new Uint8Array(fc.BUFSIZE)}isFull(){return this.last_lit>=fc.BUFSIZE}reset(){this.last_lit=0,this.extra_bits=0,this.literalTree.reset(),this.distTree.reset(),this.blTree.reset()}flushStoredBlock(e,t,s,i){this.pending.writeBits((fc.STORED_BLOCK<<1)+(i?1:0),3),this.pending.alignToByte(),this.pending.writeShort(s),this.pending.writeShort(~s),this.pending.writeBlock(e,t,s),this.reset()}flushBlock(e,t,s,i){this.literalTree.freqs[fc.EOF_SYMBOL]++,this.literalTree.buildTree(),this.distTree.buildTree(),this.literalTree.calcBLFreq(this.blTree),this.distTree.calcBLFreq(this.blTree),this.blTree.buildTree();let a=4;for(let e=18;e>a;e--)this.blTree.length[fc.BL_ORDER[e]]>0&&(a=e+1);let r=14+3*a+this.blTree.getEncodedLength()+this.literalTree.getEncodedLength()+this.distTree.getEncodedLength()+this.extra_bits,n=this.extra_bits;for(let e=0;e<fc.LITERAL_NUM;e++)n+=this.literalTree.freqs[e]*fc.staticLLength[e];for(let e=0;e<fc.DIST_NUM;e++)n+=this.distTree.freqs[e]*fc.staticDLength[e];r>=n&&(r=n),t>=0&&s+4<r>>3?this.flushStoredBlock(e,t,s,i):r===n?(this.pending.writeBits((fc.STATIC_TREES<<1)+(i?1:0),3),this.literalTree.setStaticCodes(fc.staticLCodes,fc.staticLLength),this.distTree.setStaticCodes(fc.staticDCodes,fc.staticDLength),this.compressBlock(),this.reset()):(this.pending.writeBits((fc.DYN_TREES<<1)+(i?1:0),3),this.sendAllTrees(a),this.compressBlock(),this.reset())}sendAllTrees(e){this.blTree.buildCodes(),this.literalTree.buildCodes(),this.distTree.buildCodes(),this.pending.writeBits(this.literalTree.numCodes-257,5),this.pending.writeBits(this.distTree.numCodes-1,5),this.pending.writeBits(e-4,4);for(let t=0;t<e;t++)this.pending.writeBits(this.blTree.length[fc.BL_ORDER[t]],3);this.literalTree.writeTree(this.blTree),this.distTree.writeTree(this.blTree)}compressBlock(){for(let e=0;e<this.last_lit;e++){const t=255&this.l_buf[e];let s=this.d_buf[e];if(0!=s--){const e=fc.Lcode(t);this.literalTree.writeSymbol(e);let i=Math.floor((e-261)/4);i>0&&i<=5&&this.pending.writeBits(t&(1<<i)-1,i);const a=fc.Dcode(s);this.distTree.writeSymbol(a),i=Math.floor(a/2)-1,i>0&&this.pending.writeBits(s&(1<<i)-1,i)}else this.literalTree.writeSymbol(t)}this.literalTree.writeSymbol(fc.EOF_SYMBOL)}tallyDist(e,t){this.d_buf[this.last_lit]=e,this.l_buf[this.last_lit++]=t-3;const s=fc.Lcode(t-3);this.literalTree.freqs[s]++,s>=265&&s<285&&(this.extra_bits+=Math.floor((s-261)/4));const i=fc.Dcode(e-1);return this.distTree.freqs[i]++,i>=4&&(this.extra_bits+=Math.floor(i/2)-1),this.isFull()}tallyLit(e){return this.d_buf[this.last_lit]=0,this.l_buf[this.last_lit++]=e,this.literalTree.freqs[e]++,this.isFull()}static Lcode(e){if(255===e)return 285;let t=257;for(;e>=8;)t+=4,e>>=1;return t+e}static Dcode(e){let t=0;for(;e>=4;)t+=2,e>>=1;return t+e}}fc.BUFSIZE=1<<gc.DEFAULT_MEM_LEVEL+6,fc.LITERAL_NUM=286,fc.STORED_BLOCK=0,fc.STATIC_TREES=1,fc.DYN_TREES=2,fc.DIST_NUM=30,fc.staticLCodes=new Int16Array(fc.LITERAL_NUM),fc.staticLLength=new Uint8Array(fc.LITERAL_NUM),fc.staticDCodes=new Int16Array(fc.DIST_NUM),fc.staticDLength=new Uint8Array(fc.DIST_NUM),fc.BL_ORDER=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15],fc.bit4Reverse=new Uint8Array([0,8,4,12,2,10,6,14,1,9,5,13,3,11,7,15]),fc.BITLEN_NUM=19,fc.EOF_SYMBOL=256,fc.staticInit();class yc{constructor(e){this.maxChain=128,this.niceLength=128,this.goodLength=8,this.insertHashIndex=0,this.lookahead=0,this.inputBuf=null,this.inputOff=0,this.inputEnd=0,this.prevAvailable=!1,this.matchStart=0,this.matchLen=0,this.pending=e,this.huffman=new fc(e),this.inputCrc=new pc,this.window=new Uint8Array(2*gc.WSIZE),this.head=new Int16Array(gc.HASH_SIZE),this.prev=new Int16Array(gc.WSIZE),this.blockStart=1,this.strstart=1}reset(){this.huffman.reset(),this.inputCrc.reset(),this.blockStart=1,this.strstart=1,this.lookahead=0,this.prevAvailable=!1,this.matchLen=gc.MIN_MATCH-1;for(let e=0;e<gc.HASH_SIZE;e++)this.head[e]=0;for(let e=0;e<gc.WSIZE;e++)this.prev[e]=0}updateHash(){this.insertHashIndex=this.window[this.strstart]<<gc.HASH_SHIFT^this.window[this.strstart+1]}needsInput(){return this.inputEnd===this.inputOff}setInput(e,t,s){const i=t+s;this.inputBuf=e,this.inputOff=t,this.inputEnd=i}deflate(e,t){let s;do{this.fillWindow();const i=e&&this.inputOff===this.inputEnd;s=this.deflateSlow(i,t)}while(this.pending.isFlushed&&s);return s}deflateSlow(e,t){if(this.lookahead<gc.MIN_LOOKAHEAD&&!e)return!1;for(;this.lookahead>=gc.MIN_LOOKAHEAD||e;){if(0===this.lookahead)return this.prevAvailable&&this.huffman.tallyLit(255&this.window[this.strstart-1]),this.prevAvailable=!1,this.huffman.flushBlock(this.window,this.blockStart,this.strstart-this.blockStart,t),this.blockStart=this.strstart,!1;this.strstart>=2*gc.WSIZE-gc.MIN_LOOKAHEAD&&this.slideWindow();const e=this.matchStart;let s=this.matchLen;if(this.lookahead>=gc.MIN_MATCH){const e=this.insertString();0!==e&&this.strstart-e<=gc.MAX_DIST&&this.findLongestMatch(e)&&this.matchLen===gc.MIN_MATCH&&this.strstart-this.matchStart>yc.TooFar&&(this.matchLen=gc.MIN_MATCH-1)}if(s>=gc.MIN_MATCH&&this.matchLen<=s){this.huffman.tallyDist(this.strstart-1-e,s),s-=2;do{this.strstart++,this.lookahead--,this.lookahead>=gc.MIN_MATCH&&this.insertString()}while(--s>0);this.strstart++,this.lookahead--,this.prevAvailable=!1,this.matchLen=gc.MIN_MATCH-1}else this.prevAvailable&&this.huffman.tallyLit(255&this.window[this.strstart-1]),this.prevAvailable=!0,this.strstart++,this.lookahead--;if(this.huffman.isFull()){let e=this.strstart-this.blockStart;this.prevAvailable&&e--;const s=t&&0===this.lookahead&&!this.prevAvailable;return this.huffman.flushBlock(this.window,this.blockStart,e,s),this.blockStart+=e,!s}}return!0}findLongestMatch(e){let t,s=this.strstart;const i=s+Math.min(gc.MAX_MATCH,this.lookahead)-1,a=Math.max(s-gc.MAX_DIST,0),r=this.window,n=this.prev;let o=this.maxChain;const h=Math.min(this.niceLength,this.lookahead);if(this.matchLen=Math.max(this.matchLen,gc.MIN_MATCH-1),s+this.matchLen>i)return!1;let l=r[s+this.matchLen-1],c=r[s+this.matchLen];this.matchLen>=this.goodLength&&(o>>=2);do{if(t=e,s=this.strstart,r[t+this.matchLen]===c&&r[t+this.matchLen-1]===l&&r[t]===r[s]&&r[++t]===r[++s]){switch((i-s)%8){case 1:if(r[++s]===r[++t])break;break;case 2:if(r[++s]===r[++t]&&r[++s]===r[++t])break;break;case 3:if(r[++s]===r[++t]&&r[++s]===r[++t]&&r[++s]===r[++t])break;break;case 4:if(r[++s]===r[++t]&&r[++s]===r[++t]&&r[++s]===r[++t]&&r[++s]===r[++t])break;break;case 5:if(r[++s]===r[++t]&&r[++s]===r[++t]&&r[++s]===r[++t]&&r[++s]===r[++t]&&r[++s]===r[++t])break;break;case 6:if(r[++s]===r[++t]&&r[++s]===r[++t]&&r[++s]===r[++t]&&r[++s]===r[++t]&&r[++s]===r[++t]&&r[++s]===r[++t])break;break;case 7:if(r[++s]===r[++t]&&r[++s]===r[++t]&&r[++s]===r[++t]&&r[++s]===r[++t]&&r[++s]===r[++t]&&r[++s]===r[++t]&&r[++s]===r[++t])break}if(r[s]===r[t])do{if(s===i){++s,++t;break}}while(r[++s]===r[++t]&&r[++s]===r[++t]&&r[++s]===r[++t]&&r[++s]===r[++t]&&r[++s]===r[++t]&&r[++s]===r[++t]&&r[++s]===r[++t]&&r[++s]===r[++t]);if(s-this.strstart>this.matchLen){if(this.matchStart=e,this.matchLen=s-this.strstart,this.matchLen>=h)break;l=r[s-1],c=r[s]}e=65535&n[e&gc.WMASK]}}while(e>a&&0!=--o);return this.matchLen>=gc.MIN_MATCH}insertString(){const e=(this.insertHashIndex<<gc.HASH_SHIFT^this.window[this.strstart+(gc.MIN_MATCH-1)])&gc.HASH_MASK,t=this.head[e];return this.prev[this.strstart&gc.WMASK]=t,this.head[e]=this.strstart,this.insertHashIndex=e,65535&t}fillWindow(){if(this.strstart>=gc.WSIZE+gc.MAX_DIST&&this.slideWindow(),this.lookahead<gc.MIN_LOOKAHEAD&&this.inputOff<this.inputEnd){let e=2*gc.WSIZE-this.lookahead-this.strstart;e>this.inputEnd-this.inputOff&&(e=this.inputEnd-this.inputOff),this.window.set(this.inputBuf.subarray(this.inputOff,this.inputOff+e),this.strstart+this.lookahead),this.inputCrc.update(this.inputBuf,this.inputOff,e),this.inputOff+=e,this.lookahead+=e}this.lookahead>=gc.MIN_MATCH&&this.updateHash()}slideWindow(){this.window.set(this.window.subarray(gc.WSIZE,gc.WSIZE+gc.WSIZE),0),this.matchStart-=gc.WSIZE,this.strstart-=gc.WSIZE,this.blockStart-=gc.WSIZE;for(let e=0;e<gc.HASH_SIZE;++e){const t=65535&this.head[e];this.head[e]=t>=gc.WSIZE?t-gc.WSIZE:0}for(let e=0;e<gc.WSIZE;e++){const t=65535&this.prev[e];this.prev[e]=t>=gc.WSIZE?t-gc.WSIZE:0}}}yc.TooFar=4096;class bc{get isFlushed(){return 0===this._end}constructor(e){this._start=0,this._end=0,this._bits=0,this.bitCount=0,this._buffer=new Uint8Array(e)}reset(){this._start=0,this._end=0,this.bitCount=0}writeShortMSB(e){this._buffer[this._end++]=e>>8&255,this._buffer[this._end++]=255&e}writeShort(e){this._buffer[this._end++]=e,this._buffer[this._end++]=e>>8}writeBlock(e,t,s){this._buffer.set(e.subarray(t,t+s),this._end),this._end+=s}flush(e,t,s){return this.bitCount>=8&&(this._buffer[this._end++]=255&this._bits,this._bits>>=8,this.bitCount-=8),s>this._end-this._start?(s=this._end-this._start,e.set(this._buffer.subarray(this._start,this._start+s),t),this._start=0,this._end=0):(e.set(this._buffer.subarray(this._start,this._start+s),t),this._start+=s),s}writeBits(e,t){this._bits|=e<<this.bitCount,this.bitCount+=t,this.bitCount>=16&&(this._buffer[this._end++]=255&this._bits,this._buffer[this._end++]=this._bits>>8&255,this._bits>>=16,this.bitCount-=16)}alignToByte(){this.bitCount>0&&(this._buffer[this._end++]=255&this._bits,this.bitCount>8&&(this._buffer[this._end++]=this._bits>>8&255)),this._bits=0,this.bitCount=0}}class Sc{get inputCrc(){return this._engine.inputCrc.value}constructor(){this._state=0,this._pending=new bc(gc.PENDING_BUF_SIZE),this._engine=new yc(this._pending),this.reset()}get isNeedingInput(){return this._engine.needsInput()}get isFinished(){return this._state===Sc.FinishedState&&this._pending.isFlushed}reset(){this._state=Sc.BusyState,this._pending.reset(),this._engine.reset()}setInput(e,t,s){this._engine.setInput(e,t,s)}deflate(e,t,s){const i=s;for(;;){const a=this._pending.flush(e,t,s);if(t+=a,0===(s-=a)||this._state===Sc.FinishedState)break;if(!this._engine.deflate(!!(this._state&Sc.IsFlushing),!!(this._state&Sc.IsFinishing)))switch(this._state){case Sc.BusyState:return i-s;case Sc.FlushingState:let e=8+(7&-this._pending.bitCount);for(;e>0;)this._pending.writeBits(2,10),e-=10;this._state=Sc.BusyState;break;case Sc.FinishingState:this._pending.alignToByte(),this._state=Sc.FinishedState}}return i-s}finish(){this._state|=Sc.IsFlushing|Sc.IsFinishing}}Sc.IsFlushing=4,Sc.IsFinishing=8,Sc.BusyState=16,Sc.FlushingState=20,Sc.FinishingState=28,Sc.FinishedState=30;class _c{constructor(e,t,s,i,a){this.entry=e,this.crc32=t,this.localHeaderOffset=s,this.compressionMode=i,this.compressedSize=a}}class wc{constructor(e){this._centralDirectoryHeaders=[],this._deflater=new Sc,this._data=e}writeEntry(e){const t=cs.CompressionMethodDeflate,s=ht.empty(),i=this.compress(s,e.data,t),a=s.toArray(),r=new _c(e,i,this._data.bytesWritten,t,s.length);this._centralDirectoryHeaders.push(r),ot.writeInt32LE(this._data,cs.LocalFileHeaderSignature),ot.writeUInt16LE(this._data,10),ot.writeUInt16LE(this._data,2048),ot.writeUInt16LE(this._data,t),ot.writeInt16LE(this._data,0),ot.writeInt16LE(this._data,0),ot.writeInt32LE(this._data,i),ot.writeInt32LE(this._data,a.length),ot.writeInt32LE(this._data,e.data.length),ot.writeInt16LE(this._data,e.fullName.length),ot.writeInt16LE(this._data,0);const n=ot.stringToBytes(e.fullName);this._data.write(n,0,n.length),this._data.write(a,0,a.length)}compress(e,t,s){if(s!==cs.CompressionMethodDeflate){const s=new pc;return s.update(t,0,t.length),e.write(t,0,t.length),s.value}const i=new Uint8Array(512);for(this._deflater.reset(),this._deflater.setInput(t,0,t.length);!this._deflater.isNeedingInput;){const t=this._deflater.deflate(i,0,i.length);if(t<=0)break;e.write(i,0,t)}for(this._deflater.finish();!this._deflater.isFinished;){const t=this._deflater.deflate(i,0,i.length);if(t<=0)break;e.write(i,0,t)}return this._deflater.inputCrc}end(){const e=this._data.bytesWritten;for(const e of this._centralDirectoryHeaders)this.writeCentralDirectoryHeader(e);const t=this._data.bytesWritten;this.writeEndOfCentralDirectoryRecord(e,t)}writeEndOfCentralDirectoryRecord(e,t){ot.writeInt32LE(this._data,cs.EndOfCentralDirSignature),ot.writeInt16LE(this._data,0),ot.writeInt16LE(this._data,0),ot.writeInt16LE(this._data,this._centralDirectoryHeaders.length),ot.writeInt16LE(this._data,this._centralDirectoryHeaders.length),ot.writeInt32LE(this._data,t-e),ot.writeInt32LE(this._data,e),ot.writeInt16LE(this._data,0)}writeCentralDirectoryHeader(e){ot.writeInt32LE(this._data,cs.CentralFileHeaderSignature),ot.writeUInt16LE(this._data,10),ot.writeUInt16LE(this._data,10),ot.writeUInt16LE(this._data,2048),ot.writeUInt16LE(this._data,e.compressionMode),ot.writeInt16LE(this._data,0),ot.writeInt16LE(this._data,0),ot.writeInt32LE(this._data,e.crc32),ot.writeInt32LE(this._data,e.compressedSize),ot.writeInt32LE(this._data,e.entry.data.length),ot.writeInt16LE(this._data,e.entry.fullName.length),ot.writeInt16LE(this._data,0),ot.writeInt16LE(this._data,0),ot.writeInt16LE(this._data,0),ot.writeInt16LE(this._data,0),ot.writeInt32LE(this._data,0),ot.writeInt32LE(this._data,e.localHeaderOffset);const t=ot.stringToBytes(e.entry.fullName);this._data.write(t,0,t.length)}}const Bc=Object.freeze(Object.defineProperty({__proto__:null,Gp7Exporter:class extends lc{get name(){return"Guitar Pro 7"}writeScore(e){q.debug(this.name,"Writing data entries");const t=(new uc).writeXml(e),s=ft.writeForScore(e),i=vt.writeForScore(e),a=gs.writeForScore(e);q.debug(this.name,"Writing ZIP entries");const r=new wc(this.data);r.writeEntry(new cs("VERSION",ot.stringToBytes("7.0"))),r.writeEntry(new cs("Content/",new Uint8Array(0))),r.writeEntry(new cs("Content/BinaryStylesheet",s)),r.writeEntry(new cs("Content/PartConfiguration",i)),r.writeEntry(new cs("Content/LayoutConfiguration",a)),r.writeEntry(new cs("Content/score.gpif",ot.stringToBytes(t))),r.end()}},ScoreExporter:lc},Symbol.toStringTag,{value:"Module"}));class kc extends Fs{constructor(){super(0,0,Rt.EndOfTrack)}writeTo(e){throw new $e(Se.General,"Deprecated event, serialization not supported")}}var Tc,Nc,xc;!function(e){e[e.SequenceNumber=0]="SequenceNumber",e[e.TextEvent=1]="TextEvent",e[e.CopyrightNotice=2]="CopyrightNotice",e[e.SequenceOrTrackName=3]="SequenceOrTrackName",e[e.InstrumentName=4]="InstrumentName",e[e.LyricText=5]="LyricText",e[e.MarkerText=6]="MarkerText",e[e.CuePoint=7]="CuePoint",e[e.PatchName=8]="PatchName",e[e.PortName=9]="PortName",e[e.MidiChannel=32]="MidiChannel",e[e.MidiPort=33]="MidiPort",e[e.EndOfTrack=47]="EndOfTrack",e[e.Tempo=81]="Tempo",e[e.SmpteOffset=84]="SmpteOffset",e[e.TimeSignature=88]="TimeSignature",e[e.KeySignature=89]="KeySignature",e[e.SequencerSpecific=127]="SequencerSpecific"}(Tc||(Tc={}));class vc extends kc{get metaStatus(){return Tc.EndOfTrack}}!function(e){e[e.SystemExclusive=240]="SystemExclusive",e[e.MtcQuarterFrame=241]="MtcQuarterFrame",e[e.SongPosition=242]="SongPosition",e[e.SongSelect=243]="SongSelect",e[e.TuneRequest=246]="TuneRequest",e[e.SystemExclusive2=247]="SystemExclusive2"}(Nc||(Nc={}));class Pc extends kc{}!function(e){e[e.MetronomeTick=0]="MetronomeTick",e[e.Rest=1]="Rest"}(xc||(xc={}));class Fc extends Pc{constructor(){super(...arguments),this.data=new Uint8Array}get isMetronome(){return!1}get metronomeNumerator(){return-1}get metronomeDurationInTicks(){return-1}get metronomeDurationInMilliseconds(){return-1}get isRest(){return!1}get manufacturerId(){return 0}}Fc.AlphaTabManufacturerId=125;const Cc=Object.freeze(Object.defineProperty({__proto__:null,AlphaSynthMidiFileHandler:lr,AlphaTabMetronomeEvent:Es,AlphaTabRestEvent:Ls,AlphaTabSysExEvent:Ds,get AlphaTabSystemExclusiveEvents(){return xc},BeatTickLookup:pr,BeatTickLookupItem:ur,ControlChangeEvent:Rs,get ControllerType(){return Xt},DeprecatedMidiEvent:kc,EndOfTrackEvent:Gs,MasterBarTickLookup:mr,MasterBarTickLookupTempoChange:gr,MetaDataEvent:class extends vc{constructor(){super(...arguments),this.data=new Uint8Array}},MetaEvent:vc,get MetaEventType(){return Tc},MetaNumberEvent:class extends vc{constructor(){super(...arguments),this.value=0}},Midi20PerNotePitchBendEvent:class extends kc{constructor(){super(...arguments),this.noteKey=0,this.pitch=0}},MidiEvent:Fs,get MidiEventType(){return Rt},MidiFile:Ps,get MidiFileFormat(){return At},MidiFileGenerator:wr,MidiTickLookup:yr,MidiTickLookupFindBeatResult:fr,get MidiTickLookupFindBeatResultCursorMode(){return Zt},MidiTrack:vs,NoteBendEvent:Vs,NoteEvent:Ms,NoteOffEvent:As,NoteOnEvent:Is,PitchBendEvent:Ws,ProgramChangeEvent:Os,SystemCommonEvent:Pc,get SystemCommonType(){return Nc},SystemExclusiveEvent:Fc,TempoChangeEvent:Hs,TimeSignatureEvent:Cs},Symbol.toStringTag,{value:"Module"})),Dc=Object.freeze(Object.defineProperty({__proto__:null,get AccentuationType(){return B},get AccidentalType(){return It},Automation:U,get AutomationType(){return m},Bar:G,get BarLineStyle(){return p},BarStyle:V,get BarSubElement(){return u},get BarreShape(){return ge},Beat:ze,get BeatBeamingMode(){return fe},BeatStyle:Ge,get BeatSubElement(){return ye},BendPoint:X,get BendStyle(){return f},get BendType(){return y},get BracketExtendMode(){return s},get BrushType(){return b},Chord:je,get Clef(){return n},Color:et,get CrescendoType(){return S},get Direction(){return Be},get Duration(){return _},get DynamicValue(){return g},ElementStyle:H,get FadeType(){return ue},Fermata:lt,get FermataType(){return ke},get Fingers(){return k},Font:na,get FontStyle(){return Jt},get FontWeight(){return Yt},get GolpeType(){return de},GraceGroup:Q,get GraceType(){return w},get HarmonicType(){return T},HeaderFooterStyle:Ue,InstrumentArticulation:Ee,JsonConverter:$a,get KeySignature(){return l},get KeySignatureType(){return c},Lyrics:Ke,MasterBar:j,get MusicFontSymbol(){return re},Note:Ae,get NoteAccidentalMode(){return N},get NoteOrnament(){return he},NoteStyle:Ie,get NoteSubElement(){return le},get Ottavia(){return o},get PickStroke(){return ae},PlaybackInformation:tt,get Rasgueado(){return me},RenderStylesheet:R,RepeatGroup:O,Score:Je,ScoreStyle:Xe,get ScoreSubElement(){return be},Section:Qe,get SimileMark(){return h},get SlideInType(){return x},get SlideOutType(){return v},Staff:it,SustainPedalMarker:W,get SustainPedalMarkerType(){return d},Track:rt,get TrackNameMode(){return a},get TrackNameOrientation(){return r},get TrackNamePolicy(){return i},TrackStyle:at,get TrackSubElement(){return we},get TripletFeel(){return M},Tuning:st,TupletGroup:Re,get VibratoType(){return P},Voice:ee,VoiceStyle:Z,get VoiceSubElement(){return I},get WahPedal(){return pe},get WhammyType(){return ce}},Symbol.toStringTag,{value:"Module"})),Ec=Object.freeze(Object.defineProperty({__proto__:null,BarBounds:er,get BeamDirection(){return Te},BeatBounds:tr,Bounds:mt,BoundsLookup:rr,MasterBarBounds:sr,NoteBounds:ir,RenderFinishedEventArgs:Za,ScoreRenderer:nr,StaffSystemBounds:ar},Symbol.toStringTag,{value:"Module"})),Lc=Object.freeze(Object.defineProperty({__proto__:null,CssFontSvgCanvas:en,Cursors:Jr,FontSizeDefinition:Ka,FontSizes:Qa,MeasuredText:De,SvgCanvas:Zr,get TextAlign(){return ne},get TextBaseline(){return oe}},Symbol.toStringTag,{value:"Module"})),Mc=Object.freeze(Object.defineProperty({__proto__:null,ActiveBeatsChangedEventArgs:Dr,AlphaSynth:sa,AlphaSynthAudioWorkletOutput:$r,AlphaSynthScriptProcessorOutput:Gr,AlphaSynthWebAudioOutputBase:Vr,AlphaSynthWebWorkerApi:Ur,CircularSampleBuffer:Hr,MidiEventsPlayedEventArgs:ea,PlaybackRange:Br,PlaybackRangeChangedEventArgs:ta,get PlayerState(){return Ot},PlayerStateChangedEventArgs:Ys,PositionChangedEventArgs:$s},Symbol.toStringTag,{value:"Module"})),Ic=Object.freeze(Object.defineProperty({__proto__:null},Symbol.toStringTag,{value:"Module"}));export{Kr as AlphaTabApi,Lr as AlphaTabApiBase,$e as AlphaTabError,Se as AlphaTabErrorType,$ as ConsoleLogger,nc as CoreSettings,ha as DisplaySettings,rc as Environment,Mr as FileLoadError,C as FingeringMode,Ze as FormatError,la as ImporterSettings,e as LayoutMode,L as LogLevel,q as Logger,E as NotationElement,D as NotationMode,J as NotationSettings,jt as PlayerOutputMode,ua as PlayerSettings,zr as ProgressEventArgs,ac as RenderEngineFactory,oa as RenderingResources,Cr as ResizeEventArgs,qt as ScrollMode,Ba as Settings,da as SlidePlaybackSettings,t as StaveProfile,$t as SystemsLayoutMode,F as TabRhythmMode,ca as VibratoPlaybackSettings,Kt as WebPlatform,Bc as exporter,oc as importer,hc as io,Ic as json,sc as meta,Cc as midi,Dc as model,Lc as platform,Ec as rendering,Mc as synth};
51
+ var e,t,s,i,a,r,n,o,h,l,c,d,u,p,g,m,f,y,b,S,_,w,B,k,T,N,x,v,P,F,C,D,E,L,M,I;void 0===Symbol.dispose&&(Symbol.dispose=Symbol("Symbol.dispose")),function(e){e[e.Page=0]="Page",e[e.Horizontal=1]="Horizontal"}(e||(e={})),function(e){e[e.Default=0]="Default",e[e.ScoreTab=1]="ScoreTab",e[e.Score=2]="Score",e[e.Tab=3]="Tab",e[e.TabMixed=4]="TabMixed"}(t||(t={}));class A{static getValue(e){return A._values||(A._values=new Map),e=e.toLowerCase().replaceAll(" ",""),A._values.has(e)?A._values.get(e):0}static isPiano(e){return e<=7||e>=16&&e<=23}static isGuitar(e){return e>=24&&e<=39||105===e||43===e}}A._values=new Map([["acousticgrandpiano",0],["brightacousticpiano",1],["electricgrandpiano",2],["honkytonkpiano",3],["electricpiano1",4],["electricpiano2",5],["harpsichord",6],["clavinet",7],["celesta",8],["glockenspiel",9],["musicbox",10],["vibraphone",11],["marimba",12],["xylophone",13],["tubularbells",14],["dulcimer",15],["drawbarorgan",16],["percussiveorgan",17],["rockorgan",18],["churchorgan",19],["reedorgan",20],["accordion",21],["harmonica",22],["tangoaccordion",23],["acousticguitarnylon",24],["acousticguitarsteel",25],["electricguitarjazz",26],["electricguitarclean",27],["electricguitarmuted",28],["overdrivenguitar",29],["distortionguitar",30],["guitarharmonics",31],["acousticbass",32],["electricbassfinger",33],["electricbasspick",34],["fretlessbass",35],["slapbass1",36],["slapbass2",37],["synthbass1",38],["synthbass2",39],["violin",40],["viola",41],["cello",42],["contrabass",43],["tremolostrings",44],["pizzicatostrings",45],["orchestralharp",46],["timpani",47],["stringensemble1",48],["stringensemble2",49],["synthstrings1",50],["synthstrings2",51],["choiraahs",52],["voiceoohs",53],["synthvoice",54],["orchestrahit",55],["trumpet",56],["trombone",57],["tuba",58],["mutedtrumpet",59],["frenchhorn",60],["brasssection",61],["synthbrass1",62],["synthbrass2",63],["sopranosax",64],["altosax",65],["tenorsax",66],["baritonesax",67],["oboe",68],["englishhorn",69],["bassoon",70],["clarinet",71],["piccolo",72],["flute",73],["recorder",74],["panflute",75],["blownbottle",76],["shakuhachi",77],["whistle",78],["ocarina",79],["lead1square",80],["lead2sawtooth",81],["lead3calliope",82],["lead4chiff",83],["lead5charang",84],["lead6voice",85],["lead7fifths",86],["lead8bassandlead",87],["pad1newage",88],["pad2warm",89],["pad3polysynth",90],["pad4choir",91],["pad5bowed",92],["pad6metallic",93],["pad7halo",94],["pad8sweep",95],["fx1rain",96],["fx2soundtrack",97],["fx3crystal",98],["fx4atmosphere",99],["fx5brightness",100],["fx6goblins",101],["fx7echoes",102],["fx8scifi",103],["sitar",104],["banjo",105],["shamisen",106],["koto",107],["kalimba",108],["bagpipe",109],["fiddle",110],["shanai",111],["tinklebell",112],["agogo",113],["steeldrums",114],["woodblock",115],["taikodrum",116],["melodictom",117],["synthdrum",118],["reversecymbal",119],["guitarfretnoise",120],["breathnoise",121],["seashore",122],["birdtweet",123],["telephonering",124],["helicopter",125],["applause",126],["gunshot",127]]),function(e){e[e.NoBrackets=0]="NoBrackets",e[e.GroupStaves=1]="GroupStaves",e[e.GroupSimilarInstruments=2]="GroupSimilarInstruments"}(s||(s={})),function(e){e[e.Hidden=0]="Hidden",e[e.FirstSystem=1]="FirstSystem",e[e.AllSystems=2]="AllSystems"}(i||(i={})),function(e){e[e.FullName=0]="FullName",e[e.ShortName=1]="ShortName"}(a||(a={})),function(e){e[e.Horizontal=0]="Horizontal",e[e.Vertical=1]="Vertical"}(r||(r={}));class R{constructor(){this.hideDynamics=!1,this.bracketExtendMode=s.GroupStaves,this.useSystemSignSeparator=!1,this.globalDisplayTuning=!0,this.perTrackDisplayTuning=null,this.globalDisplayChordDiagramsOnTop=!0,this.perTrackChordDiagramsOnTop=null,this.singleTrackTrackNamePolicy=i.FirstSystem,this.multiTrackTrackNamePolicy=i.FirstSystem,this.firstSystemTrackNameMode=a.ShortName,this.otherSystemsTrackNameMode=a.ShortName,this.firstSystemTrackNameOrientation=r.Vertical,this.otherSystemsTrackNameOrientation=r.Vertical,this.multiTrackMultiBarRest=!1,this.perTrackMultiBarRest=null}}class O{constructor(){this.masterBars=[],this.opening=null,this.closings=[],this.isClosed=!1}get openings(){const e=this.opening;return e?[e]:[]}get isOpened(){return!0===this.opening?.isRepeatStart}addMasterBar(e){null===this.opening&&(this.opening=e),this.masterBars.push(e),e.repeatGroup=this,e.isRepeatEnd&&(this.closings.push(e),this.isClosed=!0)}}class H{constructor(){this.colors=new Map}}!function(e){e[e.Neutral=0]="Neutral",e[e.C3=1]="C3",e[e.C4=2]="C4",e[e.F4=3]="F4",e[e.G2=4]="G2"}(n||(n={})),function(e){e[e._15ma=0]="_15ma",e[e._8va=1]="_8va",e[e.Regular=2]="Regular",e[e._8vb=3]="_8vb",e[e._15mb=4]="_15mb"}(o||(o={})),function(e){e[e.None=0]="None",e[e.Simple=1]="Simple",e[e.FirstOfDouble=2]="FirstOfDouble",e[e.SecondOfDouble=3]="SecondOfDouble"}(h||(h={})),function(e){e[e.Cb=-7]="Cb",e[e.Gb=-6]="Gb",e[e.Db=-5]="Db",e[e.Ab=-4]="Ab",e[e.Eb=-3]="Eb",e[e.Bb=-2]="Bb",e[e.F=-1]="F",e[e.C=0]="C",e[e.G=1]="G",e[e.D=2]="D",e[e.A=3]="A",e[e.E=4]="E",e[e.B=5]="B",e[e.FSharp=6]="FSharp",e[e.CSharp=7]="CSharp"}(l||(l={})),function(e){e[e.Major=0]="Major",e[e.Minor=1]="Minor"}(c||(c={})),function(e){e[e.Down=0]="Down",e[e.Hold=1]="Hold",e[e.Up=2]="Up"}(d||(d={}));class W{constructor(){this.ratioPosition=0,this.pedalType=d.Down,this.nextPedalMarker=null,this.previousPedalMarker=null}}!function(e){e[e.StandardNotationRepeats=0]="StandardNotationRepeats",e[e.GuitarTabsRepeats=1]="GuitarTabsRepeats",e[e.SlashRepeats=2]="SlashRepeats",e[e.NumberedRepeats=3]="NumberedRepeats",e[e.StandardNotationBarNumber=4]="StandardNotationBarNumber",e[e.GuitarTabsBarNumber=5]="GuitarTabsBarNumber",e[e.SlashBarNumber=6]="SlashBarNumber",e[e.NumberedBarNumber=7]="NumberedBarNumber",e[e.StandardNotationBarLines=8]="StandardNotationBarLines",e[e.GuitarTabsBarLines=9]="GuitarTabsBarLines",e[e.SlashBarLines=10]="SlashBarLines",e[e.NumberedBarLines=11]="NumberedBarLines",e[e.StandardNotationClef=12]="StandardNotationClef",e[e.GuitarTabsClef=13]="GuitarTabsClef",e[e.StandardNotationKeySignature=14]="StandardNotationKeySignature",e[e.NumberedKeySignature=15]="NumberedKeySignature",e[e.StandardNotationTimeSignature=16]="StandardNotationTimeSignature",e[e.GuitarTabsTimeSignature=17]="GuitarTabsTimeSignature",e[e.SlashTimeSignature=18]="SlashTimeSignature",e[e.NumberedTimeSignature=19]="NumberedTimeSignature",e[e.StandardNotationStaffLine=20]="StandardNotationStaffLine",e[e.GuitarTabsStaffLine=21]="GuitarTabsStaffLine",e[e.SlashStaffLine=22]="SlashStaffLine",e[e.NumberedStaffLine=23]="NumberedStaffLine"}(u||(u={}));class V extends H{}!function(e){e[e.Automatic=0]="Automatic",e[e.Dashed=1]="Dashed",e[e.Dotted=2]="Dotted",e[e.Heavy=3]="Heavy",e[e.HeavyHeavy=4]="HeavyHeavy",e[e.HeavyLight=5]="HeavyLight",e[e.LightHeavy=6]="LightHeavy",e[e.LightLight=7]="LightLight",e[e.None=8]="None",e[e.Regular=9]="Regular",e[e.Short=10]="Short",e[e.Tick=11]="Tick"}(p||(p={}));class G{constructor(){this.id=G._globalBarId++,this.index=0,this.nextBar=null,this.previousBar=null,this.clef=n.G2,this.clefOttava=o.Regular,this.voices=[],this.simileMark=h.None,this.isMultiVoice=!1,this.displayScale=1,this.displayWidth=-1,this.sustainPedals=[],this._isEmpty=!0,this._isRestOnly=!0,this.barLineLeft=p.Automatic,this.barLineRight=p.Automatic,this.keySignature=l.C,this.keySignatureType=c.Major}static resetIds(){G._globalBarId=0}get masterBar(){return this.staff.track.score.masterBars[this.index]}get isEmpty(){return this._isEmpty}get isRestOnly(){return this._isRestOnly}getActualBarLineLeft(e){return G.actualBarLine(this,!1,e)}getActualBarLineRight(){return G.actualBarLine(this,!0,!1)}static automaticToActualType(e,t,s){let i;return i=t?e.isRepeatEnd?p.LightHeavy:e.nextMasterBar?e.isFreeTime?p.Dashed:e.isDoubleBar?p.LightLight:p.Regular:p.LightHeavy:e.isRepeatStart?p.HeavyLight:s?p.Regular:p.None,i}static actualBarLine(e,t,s){const i=e.masterBar,a=t?e.barLineRight:e.barLineLeft;let r;return r=a===p.Automatic?G.automaticToActualType(i,t,s):a,r}addVoice(e){e.bar=this,e.index=this.voices.length,this.voices.push(e)}finish(e,t=null){this.isMultiVoice=!1,this._isEmpty=!0,this._isRestOnly=!0;for(let s=0,i=this.voices.length;s<i;s++){const i=this.voices[s];i.finish(e,t),s>0&&!i.isEmpty&&(this.isMultiVoice=!0),i.isEmpty||(this._isEmpty=!1),i.isRestOnly||(this._isRestOnly=!1)}const s=this.sustainPedals;if(s.length>0){let e=null;this.sustainPedals=[],this.previousBar&&this.previousBar.sustainPedals.length>0&&(e=this.previousBar.sustainPedals[this.previousBar.sustainPedals.length-1]);const t=null!==e&&e.pedalType!==d.Up;for(const i of s){if(e&&e.pedalType!==d.Up){if(e.bar===this&&i.ratioPosition<=e.ratioPosition)continue;e.nextPedalMarker=i,i.previousPedalMarker=e}t&&i.pedalType===d.Down&&(i.pedalType=d.Hold),i.bar=this,this.sustainPedals.push(i),e=i}}else if(this.previousBar&&this.previousBar.sustainPedals.length>0){const e=this.previousBar.sustainPedals[this.previousBar.sustainPedals.length-1];if(e.pedalType!==d.Up){const t=new W;t.ratioPosition=0,t.bar=this,t.pedalType=d.Hold,this.sustainPedals.push(t),e.nextPedalMarker=t,t.previousPedalMarker=e}}}calculateDuration(){let e=0;for(const t of this.voices){const s=t.calculateDuration();s>e&&(e=s)}return e}}G._globalBarId=0,function(e){e[e.PPP=0]="PPP",e[e.PP=1]="PP",e[e.P=2]="P",e[e.MP=3]="MP",e[e.MF=4]="MF",e[e.F=5]="F",e[e.FF=6]="FF",e[e.FFF=7]="FFF",e[e.PPPP=8]="PPPP",e[e.PPPPP=9]="PPPPP",e[e.PPPPPP=10]="PPPPPP",e[e.FFFF=11]="FFFF",e[e.FFFFF=12]="FFFFF",e[e.FFFFFF=13]="FFFFFF",e[e.SF=14]="SF",e[e.SFP=15]="SFP",e[e.SFPP=16]="SFPP",e[e.FP=17]="FP",e[e.RF=18]="RF",e[e.RFZ=19]="RFZ",e[e.SFZ=20]="SFZ",e[e.SFFZ=21]="SFFZ",e[e.FZ=22]="FZ",e[e.N=23]="N",e[e.PF=24]="PF",e[e.SFZP=25]="SFZP"}(g||(g={}));class z{static ticksToMillis(e,t){return e*(6e4/(t*z.QuarterTime))|0}static millisToTicks(e,t){return e/(6e4/(t*z.QuarterTime))|0}static toTicks(e){return z.valueToTicks(e)}static valueToTicks(e){let t=e;return t<0&&(t=1/-t),z.QuarterTime*(4/t)|0}static applyDot(e,t){return t?e+3*(e/4|0):e+(e/2|0)}static applyTuplet(e,t,s){return e*s/t|0}static removeTuplet(e,t,s){return e*t/s|0}static dynamicToVelocity(e,t=0){let s=1;switch(e){case g.PPP:s=z.MinVelocity+0*z.VelocityIncrement;break;case g.PP:s=z.MinVelocity+1*z.VelocityIncrement;break;case g.P:s=z.MinVelocity+2*z.VelocityIncrement;break;case g.MP:s=z.MinVelocity+3*z.VelocityIncrement;break;case g.MF:s=z.MinVelocity+4*z.VelocityIncrement;break;case g.F:s=z.MinVelocity+5*z.VelocityIncrement;break;case g.FF:s=z.MinVelocity+6*z.VelocityIncrement;break;case g.FFF:s=z.MinVelocity+7*z.VelocityIncrement;break;case g.PPPP:s=10;break;case g.PPPPP:s=5;break;case g.PPPPPP:s=3;break;case g.FFFF:s=z.MinVelocity+8*z.VelocityIncrement;break;case g.FFFFF:s=z.MinVelocity+9*z.VelocityIncrement;break;case g.FFFFFF:s=z.MinVelocity+10*z.VelocityIncrement;break;case g.SF:case g.SFP:case g.SFZP:case g.SFPP:case g.SFZ:case g.FZ:s=z.MinVelocity+6*z.VelocityIncrement;break;case g.FP:case g.RF:case g.RFZ:case g.SFFZ:s=z.MinVelocity+5*z.VelocityIncrement;break;case g.N:s=1;break;case g.PF:s=z.MinVelocity+(4.5*z.VelocityIncrement|0)}return s+=t*z.VelocityIncrement,Math.min(Math.max(s,1),127)}}z.QuarterTime=960,z.MinVelocity=15,z.VelocityIncrement=16,function(e){e[e.Tempo=0]="Tempo",e[e.Volume=1]="Volume",e[e.Instrument=2]="Instrument",e[e.Balance=3]="Balance"}(m||(m={}));class U{constructor(){this.isLinear=!1,this.type=m.Tempo,this.value=0,this.ratioPosition=0,this.text=""}static buildTempoAutomation(e,t,s,i){(i<1||i>5)&&(i=2);const a=new Float32Array([1,.5,1,1.5,2,3]),r=new U;return r.type=m.Tempo,r.isLinear=e,r.ratioPosition=t,r.value=s*a[i],r}static buildInstrumentAutomation(e,t,s){const i=new U;return i.type=m.Instrument,i.isLinear=e,i.ratioPosition=t,i.value=s,i}}class X{constructor(e=0,t=0){this.offset=e,this.value=t}}X.MaxPosition=60,X.MaxValue=12,function(e){e[e.Default=0]="Default",e[e.Gradual=1]="Gradual",e[e.Fast=2]="Fast"}(f||(f={})),function(e){e[e.None=0]="None",e[e.Custom=1]="Custom",e[e.Bend=2]="Bend",e[e.Release=3]="Release",e[e.BendRelease=4]="BendRelease",e[e.Hold=5]="Hold",e[e.Prebend=6]="Prebend",e[e.PrebendBend=7]="PrebendBend",e[e.PrebendRelease=8]="PrebendRelease"}(y||(y={})),function(e){e[e.None=0]="None",e[e.BrushUp=1]="BrushUp",e[e.BrushDown=2]="BrushDown",e[e.ArpeggioUp=3]="ArpeggioUp",e[e.ArpeggioDown=4]="ArpeggioDown"}(b||(b={})),function(e){e[e.None=0]="None",e[e.Crescendo=1]="Crescendo",e[e.Decrescendo=2]="Decrescendo"}(S||(S={})),function(e){e[e.QuadrupleWhole=-4]="QuadrupleWhole",e[e.DoubleWhole=-2]="DoubleWhole",e[e.Whole=1]="Whole",e[e.Half=2]="Half",e[e.Quarter=4]="Quarter",e[e.Eighth=8]="Eighth",e[e.Sixteenth=16]="Sixteenth",e[e.ThirtySecond=32]="ThirtySecond",e[e.SixtyFourth=64]="SixtyFourth",e[e.OneHundredTwentyEighth=128]="OneHundredTwentyEighth",e[e.TwoHundredFiftySixth=256]="TwoHundredFiftySixth"}(_||(_={})),function(e){e[e.None=0]="None",e[e.OnBeat=1]="OnBeat",e[e.BeforeBeat=2]="BeforeBeat",e[e.BendGrace=3]="BendGrace"}(w||(w={})),function(e){e[e.None=0]="None",e[e.Normal=1]="Normal",e[e.Heavy=2]="Heavy",e[e.Tenuto=3]="Tenuto"}(B||(B={})),function(e){e[e.Unknown=-2]="Unknown",e[e.NoOrDead=-1]="NoOrDead",e[e.Thumb=0]="Thumb",e[e.IndexFinger=1]="IndexFinger",e[e.MiddleFinger=2]="MiddleFinger",e[e.AnnularFinger=3]="AnnularFinger",e[e.LittleFinger=4]="LittleFinger"}(k||(k={})),function(e){e[e.None=0]="None",e[e.Natural=1]="Natural",e[e.Artificial=2]="Artificial",e[e.Pinch=3]="Pinch",e[e.Tap=4]="Tap",e[e.Semi=5]="Semi",e[e.Feedback=6]="Feedback"}(T||(T={})),function(e){e[e.Default=0]="Default",e[e.ForceNone=1]="ForceNone",e[e.ForceNatural=2]="ForceNatural",e[e.ForceSharp=3]="ForceSharp",e[e.ForceDoubleSharp=4]="ForceDoubleSharp",e[e.ForceFlat=5]="ForceFlat",e[e.ForceDoubleFlat=6]="ForceDoubleFlat"}(N||(N={})),function(e){e[e.None=0]="None",e[e.IntoFromBelow=1]="IntoFromBelow",e[e.IntoFromAbove=2]="IntoFromAbove"}(x||(x={})),function(e){e[e.None=0]="None",e[e.Shift=1]="Shift",e[e.Legato=2]="Legato",e[e.OutUp=3]="OutUp",e[e.OutDown=4]="OutDown",e[e.PickSlideDown=5]="PickSlideDown",e[e.PickSlideUp=6]="PickSlideUp"}(v||(v={})),function(e){e[e.None=0]="None",e[e.Slight=1]="Slight",e[e.Wide=2]="Wide"}(P||(P={})),function(e){e[e.Hidden=0]="Hidden",e[e.ShowWithBeams=1]="ShowWithBeams",e[e.ShowWithBars=2]="ShowWithBars",e[e.Automatic=3]="Automatic"}(F||(F={})),function(e){e[e.ScoreDefault=0]="ScoreDefault",e[e.ScoreForcePiano=1]="ScoreForcePiano",e[e.SingleNoteEffectBand=2]="SingleNoteEffectBand",e[e.SingleNoteEffectBandForcePiano=3]="SingleNoteEffectBandForcePiano"}(C||(C={})),function(e){e[e.GuitarPro=0]="GuitarPro",e[e.SongBook=1]="SongBook"}(D||(D={})),function(e){e[e.ScoreTitle=0]="ScoreTitle",e[e.ScoreSubTitle=1]="ScoreSubTitle",e[e.ScoreArtist=2]="ScoreArtist",e[e.ScoreAlbum=3]="ScoreAlbum",e[e.ScoreWords=4]="ScoreWords",e[e.ScoreMusic=5]="ScoreMusic",e[e.ScoreWordsAndMusic=6]="ScoreWordsAndMusic",e[e.ScoreCopyright=7]="ScoreCopyright",e[e.GuitarTuning=8]="GuitarTuning",e[e.TrackNames=9]="TrackNames",e[e.ChordDiagrams=10]="ChordDiagrams",e[e.ParenthesisOnTiedBends=11]="ParenthesisOnTiedBends",e[e.TabNotesOnTiedBends=12]="TabNotesOnTiedBends",e[e.ZerosOnDiveWhammys=13]="ZerosOnDiveWhammys",e[e.EffectAlternateEndings=14]="EffectAlternateEndings",e[e.EffectCapo=15]="EffectCapo",e[e.EffectChordNames=16]="EffectChordNames",e[e.EffectCrescendo=17]="EffectCrescendo",e[e.EffectDynamics=18]="EffectDynamics",e[e.EffectFadeIn=19]="EffectFadeIn",e[e.EffectFermata=20]="EffectFermata",e[e.EffectFingering=21]="EffectFingering",e[e.EffectHarmonics=22]="EffectHarmonics",e[e.EffectLetRing=23]="EffectLetRing",e[e.EffectLyrics=24]="EffectLyrics",e[e.EffectMarker=25]="EffectMarker",e[e.EffectOttavia=26]="EffectOttavia",e[e.EffectPalmMute=27]="EffectPalmMute",e[e.EffectPickSlide=28]="EffectPickSlide",e[e.EffectPickStroke=29]="EffectPickStroke",e[e.EffectSlightBeatVibrato=30]="EffectSlightBeatVibrato",e[e.EffectSlightNoteVibrato=31]="EffectSlightNoteVibrato",e[e.EffectTap=32]="EffectTap",e[e.EffectTempo=33]="EffectTempo",e[e.EffectText=34]="EffectText",e[e.EffectTrill=35]="EffectTrill",e[e.EffectTripletFeel=36]="EffectTripletFeel",e[e.EffectWhammyBar=37]="EffectWhammyBar",e[e.EffectWideBeatVibrato=38]="EffectWideBeatVibrato",e[e.EffectWideNoteVibrato=39]="EffectWideNoteVibrato",e[e.EffectLeftHandTap=40]="EffectLeftHandTap",e[e.EffectFreeTime=41]="EffectFreeTime",e[e.EffectSustainPedal=42]="EffectSustainPedal",e[e.EffectGolpe=43]="EffectGolpe",e[e.EffectWahPedal=44]="EffectWahPedal",e[e.EffectBeatBarre=45]="EffectBeatBarre",e[e.EffectNoteOrnament=46]="EffectNoteOrnament",e[e.EffectRasgueado=47]="EffectRasgueado",e[e.EffectDirections=48]="EffectDirections",e[e.EffectBeatTimer=49]="EffectBeatTimer"}(E||(E={}));class J{constructor(){this.notationMode=D.GuitarPro,this.fingeringMode=C.ScoreDefault,this.elements=new Map,this.rhythmMode=F.Automatic,this.rhythmHeight=15,this.transpositionPitches=[],this.displayTranspositionPitches=[],this.smallGraceTabNotes=!0,this.extendBendArrowsOnTiedNotes=!0,this.extendLineEffectsToBeatEnd=!1,this.slurHeight=5}isNotationElementVisible(e){return this.elements.has(e)?this.elements.get(e):!J.defaultElements.has(e)||J.defaultElements.get(e)}}J.defaultElements=new Map([[E.ZerosOnDiveWhammys,!1]]);class Y{constructor(e){this._value=void 0,this._factory=e}get value(){return void 0===this._value&&(this._value=this._factory()),this._value}}!function(e){e[e.None=0]="None",e[e.Debug=1]="Debug",e[e.Info=2]="Info",e[e.Warning=3]="Warning",e[e.Error=4]="Error"}(L||(L={}));class ${static format(e,t){return`[AlphaTab][${e}] ${t}`}debug(e,t,...s){console.debug($.format(e,t),...s)}warning(e,t,...s){console.warn($.format(e,t),...s)}info(e,t,...s){console.info($.format(e,t),...s)}error(e,t,...s){console.error($.format(e,t),...s)}}$.logLevel=L.Info;class q{static shouldLog(e){return q.logLevel!==L.None&&e>=q.logLevel}static debug(e,t,...s){q.shouldLog(L.Debug)&&q.log.debug(e,t,...s)}static warning(e,t,...s){q.shouldLog(L.Warning)&&q.log.warning(e,t,...s)}static info(e,t,...s){q.shouldLog(L.Info)&&q.log.info(e,t,...s)}static error(e,t,...s){q.shouldLog(L.Error)&&q.log.error(e,t,...s)}}q.logLevel=L.Info,q.log=new $,function(e){e[e.NoTripletFeel=0]="NoTripletFeel",e[e.Triplet16th=1]="Triplet16th",e[e.Triplet8th=2]="Triplet8th",e[e.Dotted16th=3]="Dotted16th",e[e.Dotted8th=4]="Dotted8th",e[e.Scottish16th=5]="Scottish16th",e[e.Scottish8th=6]="Scottish8th"}(M||(M={}));class j{constructor(){this.alternateEndings=0,this.nextMasterBar=null,this.previousMasterBar=null,this.index=0,this.isDoubleBar=!1,this.isRepeatStart=!1,this.repeatCount=0,this.timeSignatureNumerator=4,this.timeSignatureDenominator=4,this.timeSignatureCommon=!1,this.isFreeTime=!1,this.tripletFeel=M.NoTripletFeel,this.section=null,this.tempoAutomations=[],this.fermata=null,this.start=0,this.isAnacrusis=!1,this.displayScale=1,this.displayWidth=-1,this.directions=null}get keySignature(){return this.score.tracks[0].staves[0].bars[this.index].keySignature}set keySignature(e){this.score.tracks[0].staves[0].bars[this.index].keySignature=e}get keySignatureType(){return this.score.tracks[0].staves[0].bars[this.index].keySignatureType}set keySignatureType(e){this.score.tracks[0].staves[0].bars[this.index].keySignatureType=e}get isRepeatEnd(){return this.repeatCount>0}get isSectionStart(){return!!this.section}get tempoAutomation(){return this.tempoAutomations.length>0?this.tempoAutomations[0]:null}calculateDuration(e=!0){if(this.isAnacrusis&&e){let e=0;for(const t of this.score.tracks)for(const s of t.staves){const t=this.index<s.bars.length?s.bars[this.index].calculateDuration():0;t>e&&(e=t)}return e}return this.timeSignatureNumerator*z.valueToTicks(this.timeSignatureDenominator)}addFermata(e,t){let s=this.fermata;null===s&&(s=new Map,this.fermata=s),s.set(e,t)}addDirection(e){null==this.directions&&(this.directions=new Set),this.directions.add(e)}getFermata(e){const t=this.fermata;return null===t?null:t.has(e.playbackStart)?t.get(e.playbackStart):null}}j.MaxAlternateEndings=8;class K{}K.DefaultChannelCount=17,K.MetronomeChannel=K.DefaultChannelCount-1,K.MetronomeKey=33,K.AudioChannels=2,K.MinVolume=0,K.MinProgram=0,K.MaxProgram=127,K.MinPlaybackSpeed=.125,K.MaxPlaybackSpeed=8,K.PercussionChannel=9,K.PercussionBank=128,K.MaxPitchWheel=16384,K.MaxPitchWheel20=4294967296,K.DefaultPitchWheel=K.MaxPitchWheel/2,K.MicroBufferCount=32,K.MicroBufferSize=64;class Q{constructor(){this.beats=[],this.id="empty",this.isComplete=!1}addBeat(e){e.graceIndex=this.beats.length,e.graceGroup=this,this.beats.push(e)}finish(){this.beats.length>0&&(this.id=`${this.beats[0].absoluteDisplayStart}_${this.beats[0].voice.index}`)}}!function(e){e[e.Glyphs=0]="Glyphs"}(I||(I={}));class Z extends H{}let ee=class e{constructor(){this._isEmpty=!0,this._isRestOnly=!0,this.id=e._globalVoiceId++,this.index=0,this.beats=[]}static resetIds(){e._globalVoiceId=0}get isEmpty(){return this._isEmpty}forceNonEmpty(){this._isEmpty=!1}get isRestOnly(){return this._isRestOnly}insertBeat(e,t){t.nextBeat=e.nextBeat,t.nextBeat&&(t.nextBeat.previousBeat=t),t.previousBeat=e,t.voice=this,e.nextBeat=t,this.beats.splice(e.index+1,0,t)}addBeat(e){e.voice=this,e.index=this.beats.length,this.beats.push(e),e.isEmpty||(this._isEmpty=!1),e.isRest||(this._isRestOnly=!1)}chain(e,t=null){if(this.bar){if(e.index<this.beats.length-1)e.nextBeat=this.beats[e.index+1],e.nextBeat.previousBeat=e;else if(e.isLastOfVoice&&e.voice.bar.nextBar){const t=this.bar.nextBar.voices[this.index];t.beats.length>0?(e.nextBeat=t.beats[0],e.nextBeat.previousBeat=e):e.nextBeat.previousBeat=e}e.chain(t)}}addGraceBeat(e){if(0===this.beats.length)return void this.addBeat(e);const t=this.beats[this.beats.length-1];this.beats.splice(this.beats.length-1,1),this.addBeat(e),this.addBeat(t),this._isEmpty=!1,this._isRestOnly=!1}getBeatAtPlaybackStart(e){return this._beatLookup.has(e)?this._beatLookup.get(e):null}finish(e,t=null){this._isEmpty=!0,this._isRestOnly=!0,this._beatLookup=new Map;let s=null;for(let e=0;e<this.beats.length;e++){const i=this.beats[e];i.index=e,this.chain(i,t),i.graceType===w.None?(i.graceGroup=s,s&&(s.isComplete=!0),s=null):(s||(s=new Q),s.addBeat(i)),i.isEmpty||(this._isEmpty=!1),i.isRest||(this._isRestOnly=!1)}let i=0,a=0;for(let s=0;s<this.beats.length;s++){const r=this.beats[s];if(r.index=s,r.finish(e,t),r.graceType===w.None){if(r.graceGroup){const e=r.graceGroup.beats[0],t=r.graceGroup.beats[r.graceGroup.beats.length-1];if(e.graceType!==w.BendGrace){const s=t.playbackStart+t.playbackDuration-e.playbackStart;switch(e.graceType){case w.BeforeBeat:e.previousBeat?(e.previousBeat.playbackDuration-=s,a=e.previousBeat.voice===this?e.previousBeat.playbackStart+e.previousBeat.playbackDuration:-s):a=-s;for(const e of r.graceGroup.beats)this._beatLookup.delete(e.playbackStart),e.playbackStart=a,this._beatLookup.set(e.playbackStart,r),a+=e.playbackDuration;break;case w.OnBeat:r.playbackDuration-=s,a=t.voice===this?t.playbackStart+t.playbackDuration:-s}}}r.displayStart=i,r.playbackStart=a,r.fermata?this.bar.masterBar.addFermata(r.playbackStart,r.fermata):r.fermata=this.bar.masterBar.getFermata(r),this._beatLookup.set(r.playbackStart,r)}else r.displayStart=i,r.playbackStart=a;r.finishTuplet(),r.graceGroup&&r.graceGroup.finish(),i+=r.displayDuration,a+=r.playbackDuration}}calculateDuration(){if(this.isEmpty||0===this.beats.length)return 0;const e=this.beats[this.beats.length-1],t=this.beats[0];return e.playbackStart+e.playbackDuration-t.playbackStart}};ee._globalVoiceId=0;class te{constructor(){this.note=null,this.tone=new se,this.octave=0}get realValue(){return 12*this.octave+this.tone.noteValue}}class se{constructor(e=0,t=N.Default){this.noteValue=e,this.accidentalMode=t}}class ie{static getIndex(e){return e<0?0:0|Math.log2(e)}static keySignatureIsFlat(e){return e<0}static keySignatureIsNatural(e){return 0===e}static keySignatureIsSharp(e){return e>0}static applyPitchOffsets(e,t){for(let s=0;s<t.tracks.length;s++){if(s<e.notation.displayTranspositionPitches.length)for(const i of t.tracks[s].staves)i.displayTranspositionPitch=-e.notation.displayTranspositionPitches[s];if(s<e.notation.transpositionPitches.length)for(const i of t.tracks[s].staves)i.transpositionPitch=-e.notation.transpositionPitches[s]}}static fingerToString(e,t,s,i){if(e.notation.fingeringMode===C.ScoreForcePiano||e.notation.fingeringMode===C.SingleNoteEffectBandForcePiano||A.isPiano(t.voice.bar.staff.track.playbackInfo.program))switch(s){case k.Unknown:case k.NoOrDead:return null;case k.Thumb:return"1";case k.IndexFinger:return"2";case k.MiddleFinger:return"3";case k.AnnularFinger:return"4";case k.LittleFinger:return"5";default:return null}if(i)switch(s){case k.Unknown:return null;case k.NoOrDead:return"0";case k.Thumb:return"t";case k.IndexFinger:return"1";case k.MiddleFinger:return"2";case k.AnnularFinger:return"3";case k.LittleFinger:return"4";default:return null}switch(s){case k.Unknown:case k.NoOrDead:return null;case k.Thumb:return"p";case k.IndexFinger:return"i";case k.MiddleFinger:return"m";case k.AnnularFinger:return"a";case k.LittleFinger:return"c";default:return null}}static isTuning(e){return!!ie.parseTuning(e)}static parseTuning(e){let t="",s="";for(let i=0;i<e.length;i++){const a=e.charCodeAt(i);if(a>=48&&a<=57){if(!t)return null;s+=String.fromCharCode(a)}else{if(!ie.TuningLetters.has(a))return null;t+=String.fromCharCode(a)}}if(!s||!t)return null;const i=new te;return i.octave=Number.parseInt(s)+1,i.note=t.toLowerCase(),i.tone=ie.getToneForText(i.note),i.tone.noteValue<0&&(i.octave--,i.tone.noteValue+=12),i}static getTuningForText(e){const t=ie.parseTuning(e);return t?t.realValue:-1}static getToneForText(e){const t=e.substring(0,1),s=e.substring(1);let i,a;switch(t.toLowerCase()){case"c":default:i=0;break;case"d":i=2;break;case"e":i=4;break;case"f":i=5;break;case"g":i=7;break;case"a":i=9;break;case"b":i=11}switch(a=ie.parseAccidentalMode(s),a){case N.Default:case N.ForceNone:case N.ForceNatural:break;case N.ForceSharp:i++;break;case N.ForceDoubleSharp:i+=2;break;case N.ForceFlat:i--;break;case N.ForceDoubleFlat:i-=2}return new se(i,a)}static parseAccidentalMode(e){const t=e.toLowerCase();return ie.accidentalModeMapping.has(t)?ie.accidentalModeMapping.get(t):N.Default}static newGuid(){return`${Math.floor(65536*(1+Math.random())).toString(16).substring(1)+Math.floor(65536*(1+Math.random())).toString(16).substring(1)}-${Math.floor(65536*(1+Math.random())).toString(16).substring(1)}-${Math.floor(65536*(1+Math.random())).toString(16).substring(1)}-${Math.floor(65536*(1+Math.random())).toString(16).substring(1)}-${Math.floor(65536*(1+Math.random())).toString(16).substring(1)}${Math.floor(65536*(1+Math.random())).toString(16).substring(1)}${Math.floor(65536*(1+Math.random())).toString(16).substring(1)}`}static isAlmostEqualTo(e,t){return Math.abs(e-t)<1e-5}static toHexString(e,t=0){let s="";do{s=String.fromCharCode("0123456789ABCDEF".charCodeAt(15&e))+s,e>>=4}while(e>0);for(;s.length<t;)s=`0${s}`;return s}static getAlternateEndingsList(e){const t=[];for(let s=0;s<j.MaxAlternateEndings;s++)e&1<<s&&t.push(s);return t}static deltaFretToHarmonicValue(e){switch(e){case 2:return 2.4;case 3:return 3.2;case 4:case 5:case 7:case 9:case 12:case 16:case 17:case 19:case 24:return e;case 8:return 8.2;case 10:return 9.6;case 14:case 15:return 14.7;case 21:case 22:return 21.7;default:return 12}}static clamp(e,t,s){return e<=t?t:e>=s?s:e}static buildMultiBarRestInfo(e,t,s){if(!e)return null;const i=e[0].score.stylesheet;if(!(e.length>1?i.multiTrackMultiBarRest:!0===i.perTrackMultiBarRest?.has(e[0].index)))return null;const a=new Map,r=e[0].score;let n=t;for(;n<=s;){const i=n;let o=null;for(;n<=s;){const s=r.masterBars[n];if(s.alternateEndings||s.isRepeatStart&&s.index!==i||s.isFreeTime||s.isAnacrusis||null!==s.section||s.index!==i&&s.tempoAutomations.length>0||null!==s.fermata&&s.fermata.size>0||null!==s.directions&&s.directions.size>0)break;if(i>t&&s.previousMasterBar&&(s.timeSignatureCommon!==s.previousMasterBar.timeSignatureCommon||s.timeSignatureNumerator!==s.previousMasterBar.timeSignatureNumerator||s.timeSignatureDenominator!==s.previousMasterBar.timeSignatureDenominator||s.tripletFeel!==s.previousMasterBar.tripletFeel))break;let a=!0;for(const t of e){for(const e of t.staves){const t=e.bars[s.index];if(!t.isRestOnly){a=!1;break}if(t.index>0&&(t.keySignature!==t.previousBar.keySignature||t.keySignatureType!==t.previousBar.keySignatureType)){a=!1;break}}if(!a)break}if(!a)break;if(n++,s.index>i&&(null===o?o=[s.index]:o.push(s.index)),s.isRepeatEnd)break}o?a.set(i,o):n++}return a}static computeFirstDisplayedBarIndex(e,t){let s=t.display.startBar;return s--,s=Math.min(e.masterBars.length-1,Math.max(0,s)),s}static computeLastDisplayedBarIndex(e,t,s){let i=t.display.barCount;return i<0&&(i=e.masterBars.length),i=s+i-1,i=Math.min(e.masterBars.length-1,Math.max(0,i)),i}static getOrCreateHeaderFooterStyle(e,t){let s,i=e.style;if(e.style||(i=new Xe,e.style=i),i.headerAndFooter.has(t))s=i.headerAndFooter.get(t);else{if(s=new Ue,Xe.defaultHeaderAndFooter.has(t)){const e=Xe.defaultHeaderAndFooter.get(t);s.template=e.template,s.textAlign=e.textAlign}i.headerAndFooter.set(t,s)}return s}static consolidate(e){if(0===e.masterBars.length){const t=new j;e.addMasterBar(t);const s=new U;s.isLinear=!1,s.type=m.Tempo,s.value=e.tempo,t.tempoAutomations.push(s);const i=new G;e.tracks[0].staves[0].addBar(i);const a=new ee;i.addVoice(a);const r=new ze;return r.isEmpty=!0,void a.addBeat(r)}const t=new Set([K.PercussionChannel]);for(const s of e.tracks){if(1===s.staves.length&&s.staves[0].isPercussion)s.playbackInfo.primaryChannel=K.PercussionChannel,s.playbackInfo.secondaryChannel=K.PercussionChannel;else{if(s.playbackInfo.primaryChannel!==K.PercussionChannel)for(;t.has(s.playbackInfo.primaryChannel);)s.playbackInfo.primaryChannel++;if(t.add(s.playbackInfo.primaryChannel),s.playbackInfo.secondaryChannel!==K.PercussionChannel)for(;t.has(s.playbackInfo.secondaryChannel);)s.playbackInfo.secondaryChannel++;t.add(s.playbackInfo.secondaryChannel)}for(const t of s.staves){for(const e of t.bars)for(const t of e.voices)if(t.isEmpty&&0===t.beats.length){const e=new ze;e.isEmpty=!0,t.addBeat(e)}const s=0===t.bars.length?1:t.bars[0].voices.length;for(;t.bars.length<e.masterBars.length;){const e=new G;t.addBar(e);const i=e.previousBar;i&&(e.clef=i.clef,e.clefOttava=i.clefOttava,e.keySignature=e.previousBar.keySignature,e.keySignatureType=e.previousBar.keySignatureType);for(let t=0;t<s;t++){const t=new ee;e.addVoice(t);const s=new ze;s.isEmpty=!0,t.addBeat(s)}}}}}}var ae,re,ne,oe,he,le,ce,de,ue,pe,ge,me,fe,ye,be,Se,_e,we,Be,ke,Te,Ne,xe,ve,Pe,Fe,Ce;ie.TuningLetters=new Set([67,68,69,70,71,65,66,99,100,101,102,103,97,98,35]),ie.accidentalModeMapping=new Map([["default",N.Default],["d",N.Default],["forcenone",N.ForceNone],["-",N.ForceNone],["forcenatural",N.ForceNatural],["n",N.ForceNatural],["forcesharp",N.ForceSharp],["#",N.ForceSharp],["forcedoublesharp",N.ForceDoubleSharp],["##",N.ForceDoubleSharp],["x",N.ForceDoubleSharp],["forceflat",N.ForceFlat],["b",N.ForceFlat],["forcedoubleflat",N.ForceDoubleFlat],["bb",N.ForceDoubleFlat]]),function(e){e[e.None=0]="None",e[e.Up=1]="Up",e[e.Down=2]="Down"}(ae||(ae={})),function(e){e[e.None=-1]="None",e[e.Space=32]="Space",e[e.Brace=57344]="Brace",e[e.BracketTop=57347]="BracketTop",e[e.BracketBottom=57348]="BracketBottom",e[e.SystemDivider=57351]="SystemDivider",e[e.GClef=57424]="GClef",e[e.CClef=57436]="CClef",e[e.FClef=57442]="FClef",e[e.UnpitchedPercussionClef1=57449]="UnpitchedPercussionClef1",e[e.SixStringTabClef=57453]="SixStringTabClef",e[e.FourStringTabClef=57454]="FourStringTabClef",e[e.TimeSig0=57472]="TimeSig0",e[e.TimeSig1=57473]="TimeSig1",e[e.TimeSig2=57474]="TimeSig2",e[e.TimeSig3=57475]="TimeSig3",e[e.TimeSig4=57476]="TimeSig4",e[e.TimeSig5=57477]="TimeSig5",e[e.TimeSig6=57478]="TimeSig6",e[e.TimeSig7=57479]="TimeSig7",e[e.TimeSig8=57480]="TimeSig8",e[e.TimeSig9=57481]="TimeSig9",e[e.TimeSigCommon=57482]="TimeSigCommon",e[e.TimeSigCutCommon=57483]="TimeSigCutCommon",e[e.NoteheadDoubleWholeSquare=57505]="NoteheadDoubleWholeSquare",e[e.NoteheadDoubleWhole=57504]="NoteheadDoubleWhole",e[e.NoteheadWhole=57506]="NoteheadWhole",e[e.NoteheadHalf=57507]="NoteheadHalf",e[e.NoteheadBlack=57508]="NoteheadBlack",e[e.NoteheadNull=57509]="NoteheadNull",e[e.NoteheadXOrnate=57514]="NoteheadXOrnate",e[e.NoteheadPlusDoubleWhole=57516]="NoteheadPlusDoubleWhole",e[e.NoteheadPlusWhole=57517]="NoteheadPlusWhole",e[e.NoteheadPlusHalf=57518]="NoteheadPlusHalf",e[e.NoteheadPlusBlack=57519]="NoteheadPlusBlack",e[e.NoteheadSquareWhite=57528]="NoteheadSquareWhite",e[e.NoteheadSquareBlack=57529]="NoteheadSquareBlack",e[e.NoteheadTriangleUpDoubleWhole=57530]="NoteheadTriangleUpDoubleWhole",e[e.NoteheadTriangleUpWhole=57531]="NoteheadTriangleUpWhole",e[e.NoteheadTriangleUpHalf=57532]="NoteheadTriangleUpHalf",e[e.NoteheadTriangleUpBlack=57534]="NoteheadTriangleUpBlack",e[e.NoteheadTriangleRightWhite=57537]="NoteheadTriangleRightWhite",e[e.NoteheadTriangleRightBlack=57538]="NoteheadTriangleRightBlack",e[e.NoteheadTriangleDownDoubleWhole=57548]="NoteheadTriangleDownDoubleWhole",e[e.NoteheadTriangleDownWhole=57540]="NoteheadTriangleDownWhole",e[e.NoteheadTriangleDownHalf=57541]="NoteheadTriangleDownHalf",e[e.NoteheadTriangleDownBlack=57543]="NoteheadTriangleDownBlack",e[e.NoteheadDiamondDoubleWhole=57559]="NoteheadDiamondDoubleWhole",e[e.NoteheadDiamondWhole=57560]="NoteheadDiamondWhole",e[e.NoteheadDiamondHalf=57561]="NoteheadDiamondHalf",e[e.NoteheadDiamondBlack=57563]="NoteheadDiamondBlack",e[e.NoteheadDiamondBlackWide=57564]="NoteheadDiamondBlackWide",e[e.NoteheadDiamondWhite=57565]="NoteheadDiamondWhite",e[e.NoteheadDiamondWhiteWide=57566]="NoteheadDiamondWhiteWide",e[e.NoteheadCircleXDoubleWhole=57520]="NoteheadCircleXDoubleWhole",e[e.NoteheadCircleXWhole=57521]="NoteheadCircleXWhole",e[e.NoteheadCircleXHalf=57522]="NoteheadCircleXHalf",e[e.NoteheadCircleX=57523]="NoteheadCircleX",e[e.NoteheadXDoubleWhole=57510]="NoteheadXDoubleWhole",e[e.NoteheadXWhole=57511]="NoteheadXWhole",e[e.NoteheadXHalf=57512]="NoteheadXHalf",e[e.NoteheadXBlack=57513]="NoteheadXBlack",e[e.NoteheadParenthesis=57550]="NoteheadParenthesis",e[e.NoteheadSlashedBlack1=57551]="NoteheadSlashedBlack1",e[e.NoteheadSlashedBlack2=57552]="NoteheadSlashedBlack2",e[e.NoteheadSlashedHalf1=57553]="NoteheadSlashedHalf1",e[e.NoteheadSlashedHalf2=57554]="NoteheadSlashedHalf2",e[e.NoteheadSlashedWhole1=57555]="NoteheadSlashedWhole1",e[e.NoteheadSlashedWhole2=57556]="NoteheadSlashedWhole2",e[e.NoteheadSlashedDoubleWhole1=57557]="NoteheadSlashedDoubleWhole1",e[e.NoteheadSlashedDoubleWhole2=57558]="NoteheadSlashedDoubleWhole2",e[e.NoteheadCircledBlack=57572]="NoteheadCircledBlack",e[e.NoteheadCircledHalf=57573]="NoteheadCircledHalf",e[e.NoteheadCircledWhole=57574]="NoteheadCircledWhole",e[e.NoteheadCircledDoubleWhole=57575]="NoteheadCircledDoubleWhole",e[e.NoteheadCircleSlash=57591]="NoteheadCircleSlash",e[e.NoteheadHeavyX=57592]="NoteheadHeavyX",e[e.NoteheadHeavyXHat=57593]="NoteheadHeavyXHat",e[e.NoteheadSlashVerticalEnds=57600]="NoteheadSlashVerticalEnds",e[e.NoteheadSlashWhiteWhole=57602]="NoteheadSlashWhiteWhole",e[e.NoteheadSlashWhiteHalf=57603]="NoteheadSlashWhiteHalf",e[e.NoteheadRoundWhiteWithDot=57621]="NoteheadRoundWhiteWithDot",e[e.NoteheadSquareBlackLarge=57626]="NoteheadSquareBlackLarge",e[e.NoteheadSquareBlackWhite=57627]="NoteheadSquareBlackWhite",e[e.NoteheadClusterDoubleWhole3rd=57640]="NoteheadClusterDoubleWhole3rd",e[e.NoteheadClusterWhole3rd=57641]="NoteheadClusterWhole3rd",e[e.NoteheadClusterHalf3rd=57642]="NoteheadClusterHalf3rd",e[e.NoteheadClusterQuarter3rd=57643]="NoteheadClusterQuarter3rd",e[e.NoteShapeRoundWhite=57776]="NoteShapeRoundWhite",e[e.NoteShapeRoundBlack=57777]="NoteShapeRoundBlack",e[e.NoteShapeSquareWhite=57778]="NoteShapeSquareWhite",e[e.NoteShapeSquareBlack=57779]="NoteShapeSquareBlack",e[e.NoteShapeTriangleRightWhite=57780]="NoteShapeTriangleRightWhite",e[e.NoteShapeTriangleRightBlack=57781]="NoteShapeTriangleRightBlack",e[e.NoteShapeTriangleLeftWhite=57782]="NoteShapeTriangleLeftWhite",e[e.NoteShapeTriangleLeftBlack=57783]="NoteShapeTriangleLeftBlack",e[e.NoteShapeDiamondWhite=57784]="NoteShapeDiamondWhite",e[e.NoteShapeDiamondBlack=57785]="NoteShapeDiamondBlack",e[e.NoteShapeTriangleUpWhite=57786]="NoteShapeTriangleUpWhite",e[e.NoteShapeTriangleUpBlack=57787]="NoteShapeTriangleUpBlack",e[e.NoteShapeMoonWhite=57788]="NoteShapeMoonWhite",e[e.NoteShapeMoonBlack=57789]="NoteShapeMoonBlack",e[e.NoteShapeTriangleRoundWhite=57790]="NoteShapeTriangleRoundWhite",e[e.NoteShapeTriangleRoundBlack=57791]="NoteShapeTriangleRoundBlack",e[e.NoteQuarterUp=57813]="NoteQuarterUp",e[e.NoteEighthUp=57815]="NoteEighthUp",e[e.TextBlackNoteLongStem=57841]="TextBlackNoteLongStem",e[e.TextBlackNoteFrac8thLongStem=57843]="TextBlackNoteFrac8thLongStem",e[e.TextBlackNoteFrac16thLongStem=57845]="TextBlackNoteFrac16thLongStem",e[e.TextBlackNoteFrac32ndLongStem=57846]="TextBlackNoteFrac32ndLongStem",e[e.TextCont8thBeamLongStem=57848]="TextCont8thBeamLongStem",e[e.TextCont16thBeamLongStem=57850]="TextCont16thBeamLongStem",e[e.TextCont32ndBeamLongStem=57851]="TextCont32ndBeamLongStem",e[e.TextAugmentationDot=57852]="TextAugmentationDot",e[e.TextTupletBracketStartLongStem=57857]="TextTupletBracketStartLongStem",e[e.TextTuplet3LongStem=57858]="TextTuplet3LongStem",e[e.TextTupletBracketEndLongStem=57859]="TextTupletBracketEndLongStem",e[e.Tremolo3=57890]="Tremolo3",e[e.Tremolo2=57889]="Tremolo2",e[e.Tremolo1=57888]="Tremolo1",e[e.FlagEighthUp=57920]="FlagEighthUp",e[e.FlagEighthDown=57921]="FlagEighthDown",e[e.FlagSixteenthUp=57922]="FlagSixteenthUp",e[e.FlagSixteenthDown=57923]="FlagSixteenthDown",e[e.FlagThirtySecondUp=57924]="FlagThirtySecondUp",e[e.FlagThirtySecondDown=57925]="FlagThirtySecondDown",e[e.FlagSixtyFourthUp=57926]="FlagSixtyFourthUp",e[e.FlagSixtyFourthDown=57927]="FlagSixtyFourthDown",e[e.FlagOneHundredTwentyEighthUp=57928]="FlagOneHundredTwentyEighthUp",e[e.FlagOneHundredTwentyEighthDown=57929]="FlagOneHundredTwentyEighthDown",e[e.FlagTwoHundredFiftySixthUp=57930]="FlagTwoHundredFiftySixthUp",e[e.FlagTwoHundredFiftySixthDown=57931]="FlagTwoHundredFiftySixthDown",e[e.AccidentalFlat=57952]="AccidentalFlat",e[e.AccidentalNatural=57953]="AccidentalNatural",e[e.AccidentalSharp=57954]="AccidentalSharp",e[e.AccidentalDoubleSharp=57955]="AccidentalDoubleSharp",e[e.AccidentalDoubleFlat=57956]="AccidentalDoubleFlat",e[e.AccidentalQuarterToneFlatArrowUp=57968]="AccidentalQuarterToneFlatArrowUp",e[e.AccidentalQuarterToneSharpArrowUp=57972]="AccidentalQuarterToneSharpArrowUp",e[e.AccidentalQuarterToneNaturalArrowUp=57970]="AccidentalQuarterToneNaturalArrowUp",e[e.Segno=57415]="Segno",e[e.Coda=57416]="Coda",e[e.ArticAccentAbove=58528]="ArticAccentAbove",e[e.ArticAccentBelow=58529]="ArticAccentBelow",e[e.ArticStaccatoAbove=58530]="ArticStaccatoAbove",e[e.ArticStaccatoBelow=58531]="ArticStaccatoBelow",e[e.ArticTenutoAbove=58532]="ArticTenutoAbove",e[e.ArticTenutoBelow=58533]="ArticTenutoBelow",e[e.ArticMarcatoAbove=58540]="ArticMarcatoAbove",e[e.ArticMarcatoBelow=58541]="ArticMarcatoBelow",e[e.FermataAbove=58560]="FermataAbove",e[e.FermataShortAbove=58564]="FermataShortAbove",e[e.FermataLongAbove=58566]="FermataLongAbove",e[e.RestLonga=58593]="RestLonga",e[e.RestDoubleWhole=58594]="RestDoubleWhole",e[e.RestWhole=58595]="RestWhole",e[e.RestHalf=58596]="RestHalf",e[e.RestQuarter=58597]="RestQuarter",e[e.RestEighth=58598]="RestEighth",e[e.RestSixteenth=58599]="RestSixteenth",e[e.RestThirtySecond=58600]="RestThirtySecond",e[e.RestSixtyFourth=58601]="RestSixtyFourth",e[e.RestOneHundredTwentyEighth=58602]="RestOneHundredTwentyEighth",e[e.RestTwoHundredFiftySixth=58603]="RestTwoHundredFiftySixth",e[e.RestHBarLeft=58607]="RestHBarLeft",e[e.RestHBarMiddle=58608]="RestHBarMiddle",e[e.RestHBarRight=58609]="RestHBarRight",e[e.Repeat1Bar=58624]="Repeat1Bar",e[e.Repeat2Bars=58625]="Repeat2Bars",e[e.Ottava=58640]="Ottava",e[e.OttavaAlta=58641]="OttavaAlta",e[e.OttavaBassaVb=58652]="OttavaBassaVb",e[e.Quindicesima=58644]="Quindicesima",e[e.QuindicesimaAlta=58645]="QuindicesimaAlta",e[e.DynamicPPPPPP=58663]="DynamicPPPPPP",e[e.DynamicPPPPP=58664]="DynamicPPPPP",e[e.DynamicPPPP=58665]="DynamicPPPP",e[e.DynamicPPP=58666]="DynamicPPP",e[e.DynamicPP=58667]="DynamicPP",e[e.DynamicPiano=58656]="DynamicPiano",e[e.DynamicMP=58668]="DynamicMP",e[e.DynamicMF=58669]="DynamicMF",e[e.DynamicPF=58670]="DynamicPF",e[e.DynamicForte=58658]="DynamicForte",e[e.DynamicFF=58671]="DynamicFF",e[e.DynamicFFF=58672]="DynamicFFF",e[e.DynamicFFFF=58673]="DynamicFFFF",e[e.DynamicFFFFF=58674]="DynamicFFFFF",e[e.DynamicFFFFFF=58675]="DynamicFFFFFF",e[e.DynamicFortePiano=58676]="DynamicFortePiano",e[e.DynamicNiente=58662]="DynamicNiente",e[e.DynamicSforzando1=58678]="DynamicSforzando1",e[e.DynamicSforzandoPiano=58679]="DynamicSforzandoPiano",e[e.DynamicSforzandoPianissimo=58680]="DynamicSforzandoPianissimo",e[e.DynamicSforzato=58681]="DynamicSforzato",e[e.DynamicSforzatoPiano=58682]="DynamicSforzatoPiano",e[e.DynamicSforzatoFF=58683]="DynamicSforzatoFF",e[e.DynamicRinforzando1=58684]="DynamicRinforzando1",e[e.DynamicRinforzando2=58685]="DynamicRinforzando2",e[e.DynamicForzando=58677]="DynamicForzando",e[e.OrnamentTrill=58726]="OrnamentTrill",e[e.OrnamentTurn=58727]="OrnamentTurn",e[e.OrnamentTurnInverted=58728]="OrnamentTurnInverted",e[e.OrnamentShortTrill=58732]="OrnamentShortTrill",e[e.OrnamentMordent=58733]="OrnamentMordent",e[e.StringsDownBow=58896]="StringsDownBow",e[e.StringsUpBow=58898]="StringsUpBow",e[e.KeyboardPedalPed=58960]="KeyboardPedalPed",e[e.KeyboardPedalUp=58965]="KeyboardPedalUp",e[e.PictEdgeOfCymbal=59177]="PictEdgeOfCymbal",e[e.GuitarString0=59443]="GuitarString0",e[e.GuitarString1=59444]="GuitarString1",e[e.GuitarString2=59445]="GuitarString2",e[e.GuitarString3=59446]="GuitarString3",e[e.GuitarString4=59447]="GuitarString4",e[e.GuitarString5=59448]="GuitarString5",e[e.GuitarString6=59449]="GuitarString6",e[e.GuitarString7=59450]="GuitarString7",e[e.GuitarString8=59451]="GuitarString8",e[e.GuitarString9=59452]="GuitarString9",e[e.GuitarOpenPedal=59453]="GuitarOpenPedal",e[e.GuitarClosePedal=59455]="GuitarClosePedal",e[e.GuitarGolpe=59458]="GuitarGolpe",e[e.GuitarFadeIn=59459]="GuitarFadeIn",e[e.GuitarFadeOut=59460]="GuitarFadeOut",e[e.GuitarVolumeSwell=59461]="GuitarVolumeSwell",e[e.FretboardX=59481]="FretboardX",e[e.FretboardO=59482]="FretboardO",e[e.WiggleTrill=60068]="WiggleTrill",e[e.WiggleVibratoMediumFast=60126]="WiggleVibratoMediumFast",e[e.OctaveBaselineM=60565]="OctaveBaselineM",e[e.OctaveBaselineB=60563]="OctaveBaselineB"}(re||(re={})),function(e){e[e.Left=0]="Left",e[e.Center=1]="Center",e[e.Right=2]="Right"}(ne||(ne={})),function(e){e[e.Top=0]="Top",e[e.Middle=1]="Middle",e[e.Bottom=2]="Bottom"}(oe||(oe={}));class De{constructor(e,t){this.width=e,this.height=t}}class Ee{constructor(e="",t=0,s=0,i=re.None,a=re.None,r=re.None,n=re.None,o=oe.Middle){this.elementType=e,this.outputMidiNumber=s,this.staffLine=t,this.noteHeadDefault=i,this.noteHeadHalf=a!==re.None?a:i,this.noteHeadWhole=r!==re.None?r:i,this.techniqueSymbol=n,this.techniqueSymbolPlacement=o}getSymbol(e){switch(e){case _.Whole:return this.noteHeadWhole;case _.Half:return this.noteHeadHalf;default:return this.noteHeadDefault}}}class Le{static articulationFromElementVariation(e,t){return e<Le.gp6ElementAndVariationToArticulation.length?(t>=Le.gp6ElementAndVariationToArticulation.length&&(t=0),Le.gp6ElementAndVariationToArticulation[e][t]):38}static getArticulation(e){const t=e.percussionArticulation;if(t<0)return null;const s=e.beat.voice.bar.staff.track.percussionArticulations;return t<s.length?s[t]:Le.getArticulationByInputMidiNumber(t)}static getElementAndVariation(e){const t=Le.getArticulation(e);if(!t)return[-1,-1];for(let e=0;e<Le.gp6ElementAndVariationToArticulation.length;e++){const s=Le.gp6ElementAndVariationToArticulation[e];for(let i=0;i<s.length;i++){const a=Le.getArticulationByInputMidiNumber(s[i]);if(a?.outputMidiNumber===t.outputMidiNumber)return[e,i]}}return[-1,-1]}static getArticulationByInputMidiNumber(e){return Le.instrumentArticulations.has(e)?Le.instrumentArticulations.get(e):null}}Le.gp6ElementAndVariationToArticulation=[[35,35,35],[38,91,37],[99,100,99],[56,100,56],[102,103,102],[43,43,43],[45,45,45],[47,47,47],[48,48,48],[50,50,50],[42,92,46],[44,44,44],[57,98,57],[49,97,49],[55,95,55],[51,93,127],[52,96,52]],Le.instrumentArticulations=new Map([[38,new Ee("snare",3,38,re.NoteheadBlack,re.NoteheadHalf,re.NoteheadWhole)],[37,new Ee("snare",3,37,re.NoteheadXBlack,re.NoteheadXBlack,re.NoteheadXBlack)],[91,new Ee("snare",3,38,re.NoteheadDiamondWhite,re.NoteheadDiamondWhite,re.NoteheadDiamondWhite)],[42,new Ee("hiHat",-1,42,re.NoteheadXBlack,re.NoteheadXBlack,re.NoteheadXBlack)],[92,new Ee("hiHat",-1,46,re.NoteheadCircleSlash,re.NoteheadCircleSlash,re.NoteheadCircleSlash)],[46,new Ee("hiHat",-1,46,re.NoteheadCircleX,re.NoteheadCircleX,re.NoteheadCircleX)],[44,new Ee("hiHat",9,44,re.NoteheadXBlack,re.NoteheadXBlack,re.NoteheadXBlack)],[35,new Ee("kickDrum",8,35,re.NoteheadBlack,re.NoteheadHalf,re.NoteheadWhole)],[36,new Ee("kickDrum",7,36,re.NoteheadBlack,re.NoteheadHalf,re.NoteheadWhole)],[50,new Ee("tom",1,50,re.NoteheadBlack,re.NoteheadHalf,re.NoteheadWhole)],[48,new Ee("tom",2,48,re.NoteheadBlack,re.NoteheadHalf,re.NoteheadWhole)],[47,new Ee("tom",4,47,re.NoteheadBlack,re.NoteheadHalf,re.NoteheadWhole)],[45,new Ee("tom",5,45,re.NoteheadBlack,re.NoteheadHalf,re.NoteheadWhole)],[43,new Ee("tom",6,43,re.NoteheadBlack,re.NoteheadHalf,re.NoteheadWhole)],[93,new Ee("ride",0,51,re.NoteheadXBlack,re.NoteheadXBlack,re.NoteheadXBlack,re.PictEdgeOfCymbal,oe.Bottom)],[51,new Ee("ride",0,51,re.NoteheadXBlack,re.NoteheadXBlack,re.NoteheadXBlack)],[53,new Ee("ride",0,53,re.NoteheadDiamondWhite,re.NoteheadDiamondWhite,re.NoteheadDiamondWhite)],[94,new Ee("ride",0,51,re.NoteheadXBlack,re.NoteheadXBlack,re.NoteheadXBlack,re.ArticStaccatoAbove,oe.Top)],[55,new Ee("splash",-2,55,re.NoteheadXBlack,re.NoteheadXBlack,re.NoteheadXBlack)],[95,new Ee("splash",-2,55,re.NoteheadXBlack,re.NoteheadXBlack,re.NoteheadXBlack,re.ArticStaccatoAbove,oe.Bottom)],[52,new Ee("china",-3,52,re.NoteheadHeavyXHat,re.NoteheadHeavyXHat,re.NoteheadHeavyXHat)],[96,new Ee("china",-3,52,re.NoteheadHeavyXHat,re.NoteheadHeavyXHat,re.NoteheadHeavyXHat)],[49,new Ee("crash",-2,49,re.NoteheadHeavyX,re.NoteheadHeavyX,re.NoteheadHeavyX)],[97,new Ee("crash",-2,49,re.NoteheadHeavyX,re.NoteheadHeavyX,re.NoteheadHeavyX,re.ArticStaccatoAbove,oe.Bottom)],[57,new Ee("crash",-1,57,re.NoteheadHeavyX,re.NoteheadHeavyX,re.NoteheadHeavyX)],[98,new Ee("crash",-1,57,re.NoteheadHeavyX,re.NoteheadHeavyX,re.NoteheadHeavyX,re.ArticStaccatoAbove,oe.Bottom)],[99,new Ee("cowbell",1,56,re.NoteheadTriangleUpBlack,re.NoteheadTriangleUpHalf,re.NoteheadTriangleUpWhole)],[100,new Ee("cowbell",1,56,re.NoteheadXBlack,re.NoteheadXHalf,re.NoteheadXWhole)],[56,new Ee("cowbell",0,56,re.NoteheadTriangleUpBlack,re.NoteheadTriangleUpHalf,re.NoteheadTriangleUpWhole)],[101,new Ee("cowbell",0,56,re.NoteheadXBlack,re.NoteheadXHalf,re.NoteheadXWhole)],[102,new Ee("cowbell",-1,56,re.NoteheadTriangleUpBlack,re.NoteheadTriangleUpHalf,re.NoteheadTriangleUpWhole)],[103,new Ee("cowbell",-1,56,re.NoteheadXBlack,re.NoteheadXHalf,re.NoteheadXWhole)],[77,new Ee("woodblock",-9,77,re.NoteheadTriangleUpBlack,re.NoteheadTriangleUpBlack,re.NoteheadTriangleUpBlack)],[76,new Ee("woodblock",-10,76,re.NoteheadTriangleUpBlack,re.NoteheadTriangleUpBlack,re.NoteheadTriangleUpBlack)],[60,new Ee("bongo",-4,60,re.NoteheadBlack,re.NoteheadHalf,re.NoteheadWhole)],[104,new Ee("bongo",-5,60,re.NoteheadBlack,re.NoteheadHalf,re.NoteheadWhole,re.NoteheadParenthesis,oe.Middle)],[105,new Ee("bongo",-6,60,re.NoteheadXBlack,re.NoteheadXBlack,re.NoteheadXBlack)],[61,new Ee("bongo",-7,61,re.NoteheadBlack,re.NoteheadHalf,re.NoteheadWhole)],[106,new Ee("bongo",-8,61,re.NoteheadBlack,re.NoteheadHalf,re.NoteheadWhole,re.NoteheadParenthesis,oe.Middle)],[107,new Ee("bongo",-16,61,re.NoteheadXBlack,re.NoteheadXBlack,re.NoteheadXBlack)],[66,new Ee("timbale",10,66,re.NoteheadBlack,re.NoteheadHalf,re.NoteheadWhole)],[65,new Ee("timbale",9,65,re.NoteheadBlack,re.NoteheadHalf,re.NoteheadWhole)],[68,new Ee("agogo",12,68,re.NoteheadBlack,re.NoteheadHalf,re.NoteheadWhole)],[67,new Ee("agogo",11,67,re.NoteheadBlack,re.NoteheadHalf,re.NoteheadWhole)],[64,new Ee("conga",17,64,re.NoteheadBlack,re.NoteheadHalf,re.NoteheadWhole)],[108,new Ee("conga",16,64,re.NoteheadXBlack,re.NoteheadXBlack,re.NoteheadXBlack)],[109,new Ee("conga",15,64,re.NoteheadBlack,re.NoteheadHalf,re.NoteheadWhole,re.NoteheadParenthesis,oe.Middle)],[63,new Ee("conga",14,63,re.NoteheadBlack,re.NoteheadHalf,re.NoteheadWhole)],[110,new Ee("conga",13,63,re.NoteheadXBlack,re.NoteheadXBlack,re.NoteheadXBlack)],[62,new Ee("conga",19,62,re.NoteheadBlack,re.NoteheadHalf,re.NoteheadWhole,re.NoteheadParenthesis,oe.Middle)],[72,new Ee("whistle",-11,72,re.NoteheadBlack,re.NoteheadHalf,re.NoteheadWhole)],[71,new Ee("whistle",-17,71,re.NoteheadBlack,re.NoteheadHalf,re.NoteheadWhole)],[73,new Ee("guiro",38,73,re.NoteheadBlack,re.NoteheadHalf,re.NoteheadWhole)],[74,new Ee("guiro",37,74,re.NoteheadBlack,re.NoteheadHalf,re.NoteheadWhole)],[86,new Ee("surdo",36,86,re.NoteheadBlack,re.NoteheadHalf,re.NoteheadWhole)],[87,new Ee("surdo",35,87,re.NoteheadXBlack,re.NoteheadXBlack,re.NoteheadXBlack,re.NoteheadParenthesis,oe.Middle)],[54,new Ee("tambourine",3,54,re.NoteheadTriangleUpBlack,re.NoteheadTriangleUpBlack,re.NoteheadTriangleUpBlack)],[111,new Ee("tambourine",2,54,re.NoteheadTriangleUpBlack,re.NoteheadTriangleUpBlack,re.NoteheadTriangleUpBlack,re.StringsUpBow,oe.Bottom)],[112,new Ee("tambourine",1,54,re.NoteheadTriangleUpBlack,re.NoteheadTriangleUpBlack,re.NoteheadTriangleUpBlack,re.StringsDownBow,oe.Bottom)],[113,new Ee("tambourine",-7,54,re.NoteheadXBlack,re.NoteheadXBlack,re.NoteheadXBlack)],[79,new Ee("cuica",30,79,re.NoteheadBlack,re.NoteheadHalf,re.NoteheadWhole)],[78,new Ee("cuica",29,78,re.NoteheadXBlack,re.NoteheadXBlack,re.NoteheadXBlack)],[58,new Ee("vibraslap",28,58,re.NoteheadBlack,re.NoteheadHalf,re.NoteheadWhole)],[81,new Ee("triangle",27,81,re.NoteheadBlack,re.NoteheadHalf,re.NoteheadWhole)],[80,new Ee("triangle",26,80,re.NoteheadXBlack,re.NoteheadXBlack,re.NoteheadXBlack,re.NoteheadParenthesis,oe.Middle)],[114,new Ee("grancassa",25,43,re.NoteheadBlack,re.NoteheadHalf,re.NoteheadWhole)],[115,new Ee("piatti",18,49,re.NoteheadBlack,re.NoteheadHalf,re.NoteheadWhole)],[116,new Ee("piatti",24,49,re.NoteheadXBlack,re.NoteheadXBlack,re.NoteheadXBlack)],[69,new Ee("cabasa",23,69,re.NoteheadBlack,re.NoteheadHalf,re.NoteheadWhole)],[117,new Ee("cabasa",22,69,re.NoteheadBlack,re.NoteheadHalf,re.NoteheadWhole,re.StringsUpBow,oe.Bottom)],[85,new Ee("castanets",21,85,re.NoteheadBlack,re.NoteheadHalf,re.NoteheadWhole)],[75,new Ee("claves",20,75,re.NoteheadBlack,re.NoteheadHalf,re.NoteheadWhole)],[70,new Ee("maraca",-12,70,re.NoteheadBlack,re.NoteheadHalf,re.NoteheadWhole)],[118,new Ee("maraca",-13,70,re.NoteheadBlack,re.NoteheadHalf,re.NoteheadWhole,re.StringsUpBow,oe.Bottom)],[119,new Ee("maraca",-14,70,re.NoteheadBlack,re.NoteheadHalf,re.NoteheadWhole)],[120,new Ee("maraca",-15,70,re.NoteheadBlack,re.NoteheadHalf,re.NoteheadWhole,re.StringsUpBow,oe.Bottom)],[82,new Ee("shaker",-23,54,re.NoteheadBlack,re.NoteheadHalf,re.NoteheadWhole)],[122,new Ee("shaker",-24,54,re.NoteheadBlack,re.NoteheadHalf,re.NoteheadWhole,re.StringsUpBow,oe.Bottom)],[84,new Ee("bellTree",-18,53,re.NoteheadBlack,re.NoteheadHalf,re.NoteheadWhole)],[123,new Ee("bellTree",-19,53,re.NoteheadBlack,re.NoteheadHalf,re.NoteheadWhole,re.StringsUpBow,oe.Bottom)],[83,new Ee("jingleBell",-20,53,re.NoteheadBlack,re.NoteheadHalf,re.NoteheadWhole)],[124,new Ee("unpitched",-21,62,re.NoteheadNull,re.NoteheadNull,re.NoteheadNull,re.GuitarGolpe,oe.Top)],[125,new Ee("unpitched",-22,62,re.NoteheadNull,re.NoteheadNull,re.NoteheadNull,re.GuitarGolpe,oe.Bottom)],[39,new Ee("handClap",3,39,re.NoteheadBlack,re.NoteheadHalf,re.NoteheadWhole)],[40,new Ee("snare",3,40,re.NoteheadBlack,re.NoteheadHalf,re.NoteheadWhole)],[31,new Ee("snare",3,40,re.NoteheadSlashedBlack2,re.NoteheadSlashedBlack2,re.NoteheadSlashedBlack2)],[41,new Ee("tom",5,41,re.NoteheadBlack,re.NoteheadHalf,re.NoteheadWhole)],[59,new Ee("ride",2,59,re.NoteheadXBlack,re.NoteheadXBlack,re.NoteheadXBlack,re.PictEdgeOfCymbal,oe.Bottom)],[126,new Ee("ride",2,59,re.NoteheadXBlack,re.NoteheadXBlack,re.NoteheadXBlack)],[127,new Ee("ride",2,59,re.NoteheadDiamondWhite,re.NoteheadDiamondWhite,re.NoteheadDiamondWhite)],[29,new Ee("ride",2,59,re.NoteheadXBlack,re.NoteheadXBlack,re.NoteheadXBlack,re.ArticStaccatoAbove,oe.Top)],[30,new Ee("crash",-3,49,re.NoteheadXBlack,re.NoteheadXBlack,re.NoteheadXBlack)],[33,new Ee("snare",3,37,re.NoteheadXBlack,re.NoteheadXBlack,re.NoteheadXBlack)],[34,new Ee("snare",3,38,re.NoteheadBlack,re.NoteheadBlack,re.NoteheadBlack)]]),Le.instrumentArticulationNames=new Map([["Ride (choke)",29],["Cymbal (hit)",30],["Snare (side stick)",31],["Snare (side stick) 2",33],["Snare (hit)",34],["Kick (hit)",35],["Kick (hit) 2",36],["Snare (side stick) 3",37],["Snare (hit) 2",38],["Hand Clap (hit)",39],["Snare (hit) 3",40],["Low Floor Tom (hit)",41],["Hi-Hat (closed)",42],["Very Low Tom (hit)",43],["Pedal Hi-Hat (hit)",44],["Low Tom (hit)",45],["Hi-Hat (open)",46],["Mid Tom (hit)",47],["High Tom (hit)",48],["Crash high (hit)",49],["High Floor Tom (hit)",50],["Ride (middle)",51],["China (hit)",52],["Ride (bell)",53],["Tambourine (hit)",54],["Splash (hit)",55],["Cowbell medium (hit)",56],["Crash medium (hit)",57],["Vibraslap (hit)",58],["Ride (edge)",59],["Hand (hit)",60],["Hand (hit)",61],["Conga high (mute)",62],["Conga high (hit)",63],["Conga low (hit)",64],["Timbale high (hit)",65],["Timbale low (hit)",66],["Agogo high (hit)",67],["Agogo tow (hit)",68],["Cabasa (hit)",69],["Left Maraca (hit)",70],["Whistle high (hit)",71],["Whistle low (hit)",72],["Guiro (hit)",73],["Guiro (scrap-return)",74],["Claves (hit)",75],["Woodblock high (hit)",76],["Woodblock low (hit)",77],["Cuica (mute)",78],["Cuica (open)",79],["Triangle (rnute)",80],["Triangle (hit)",81],["Shaker (hit)",82],["Tinkle Bell (hat)",83],["Jingle Bell (hit)",83],["Bell Tree (hit)",84],["Castanets (hit)",85],["Surdo (hit)",86],["Surdo (mute)",87],["Snare (rim shot)",91],["Hi-Hat (half)",92],["Ride (edge) 2",93],["Ride (choke) 2",94],["Splash (choke)",95],["China (choke)",96],["Crash high (choke)",97],["Crash medium (choke)",98],["Cowbell low (hit)",99],["Cowbell low (tip)",100],["Cowbell medium (tip)",101],["Cowbell high (hit)",102],["Cowbell high (tip)",103],["Hand (mute)",104],["Hand (slap)",105],["Hand (mute) 2",106],["Hand (slap) 2",107],["Conga low (slap)",108],["Conga low (mute)",109],["Conga high (slap)",110],["Tambourine (return)",111],["Tambourine (roll)",112],["Tambourine (hand)",113],["Grancassa (hit)",114],["Piatti (hat)",115],["Piatti (hand)",116],["Cabasa (return)",117],["Left Maraca (return)",118],["Right Maraca (hit)",119],["Right Maraca (return)",120],["Shaker (return)",122],["Bell Tee (return)",123],["Golpe (thumb)",124],["Golpe (finger)",125],["Ride (middle) 2",126],["Ride (bell) 2",127]]),function(e){e[e.None=0]="None",e[e.InvertedTurn=1]="InvertedTurn",e[e.Turn=2]="Turn",e[e.UpperMordent=3]="UpperMordent",e[e.LowerMordent=4]="LowerMordent"}(he||(he={}));class Me{constructor(){this.tieDestinationNoteId=-1,this.tieOriginNoteId=-1,this.slurDestinationNoteId=-1,this.slurOriginNoteId=-1,this.hammerPullDestinationNoteId=-1,this.hammerPullOriginNoteId=-1,this.slideTargetNoteId=-1,this.slideOriginNoteId=-1}}!function(e){e[e.Effects=0]="Effects",e[e.StandardNotationNoteHead=1]="StandardNotationNoteHead",e[e.StandardNotationAccidentals=2]="StandardNotationAccidentals",e[e.StandardNotationEffects=3]="StandardNotationEffects",e[e.GuitarTabFretNumber=4]="GuitarTabFretNumber",e[e.GuitarTabEffects=5]="GuitarTabEffects",e[e.SlashNoteHead=6]="SlashNoteHead",e[e.SlashEffects=7]="SlashEffects",e[e.NumberedNumber=8]="NumberedNumber",e[e.NumberedAccidentals=9]="NumberedAccidentals",e[e.NumberedEffects=10]="NumberedEffects"}(le||(le={}));class Ie extends H{}class Ae{constructor(){this.id=Ae.GlobalNoteId++,this.index=0,this.accentuated=B.None,this.bendType=y.None,this.bendStyle=f.Default,this.bendOrigin=null,this.isContinuedBend=!1,this.bendPoints=null,this.maxBendPoint=null,this.fret=-1,this.string=-1,this.showStringNumber=!1,this.octave=-1,this.tone=-1,this.percussionArticulation=-1,this.isVisible=!0,this.isLeftHandTapped=!1,this.isHammerPullOrigin=!1,this.hammerPullOrigin=null,this.hammerPullDestination=null,this.isSlurDestination=!1,this.slurOrigin=null,this.slurDestination=null,this.harmonicType=T.None,this.harmonicValue=0,this.isGhost=!1,this.isLetRing=!1,this.letRingDestination=null,this.isPalmMute=!1,this.palmMuteDestination=null,this.isDead=!1,this.isStaccato=!1,this.slideInType=x.None,this.slideOutType=v.None,this.slideTarget=null,this.slideOrigin=null,this.vibrato=P.None,this.tieOrigin=null,this.tieDestination=null,this.isTieDestination=!1,this.leftHandFinger=k.Unknown,this.rightHandFinger=k.Unknown,this.trillValue=-1,this.trillSpeed=_.ThirtySecond,this.durationPercent=1,this.accidentalMode=N.Default,this.dynamics=g.F,this.isEffectSlurOrigin=!1,this.hasEffectSlur=!1,this.effectSlurOrigin=null,this.effectSlurDestination=null,this.ornament=he.None,this._noteIdBag=null}static resetIds(){Ae.GlobalNoteId=0}get hasBend(){return null!==this.bendPoints&&this.bendType!==y.None}get isStringed(){return this.string>=0}get isPiano(){return!this.isStringed&&this.octave>=0&&this.tone>=0}get isPercussion(){return!this.isStringed&&this.percussionArticulation>=0}get element(){return this.isPercussion?Le.getElementAndVariation(this)[0]:-1}get variation(){return this.isPercussion?Le.getElementAndVariation(this)[1]:-1}get isHammerPullDestination(){return!!this.hammerPullOrigin}get isSlurOrigin(){return!!this.slurDestination}get isHarmonic(){return this.harmonicType!==T.None}get isTieOrigin(){return null!==this.tieDestination}get isFingering(){return this.leftHandFinger!==k.Unknown||this.rightHandFinger!==k.Unknown}get trillFret(){return this.trillValue-this.stringTuning}get isTrill(){return this.trillValue>=0}get isEffectSlurDestination(){return!!this.effectSlurOrigin}get stringTuning(){return this.beat.voice.bar.staff.capo+Ae.getStringTuning(this.beat.voice.bar.staff,this.string)}static getStringTuning(e,t){return e.tuning.length>0?e.tuning[e.tuning.length-(t-1)-1]:0}get realValue(){return this.calculateRealValue(!0,!0)}get realValueWithoutHarmonic(){return this.calculateRealValue(!0,!1)}calculateRealValue(e,t){const s=e?this.beat.voice.bar.staff.transpositionPitch:0;if(t){let t=this.calculateRealValue(e,!1);return this.isStringed&&(this.harmonicType===T.Natural?t=this.harmonicPitch+this.stringTuning-s:t+=this.harmonicPitch),t}return this.isPercussion?this.percussionArticulation:this.isStringed?this.fret+this.stringTuning-s:this.isPiano?12*this.octave+this.tone-s:0}get harmonicPitch(){if(this.harmonicType===T.None||!this.isStringed)return 0;const e=this.harmonicValue;return ie.isAlmostEqualTo(e,2.4)?36:ie.isAlmostEqualTo(e,2.7)?34:e<3?0:e<=3.5?31:e<=4?28:e<=5?24:e<=6?34:e<=7?19:e<=8.5?36:e<=9?28:e<=10?34:e<=11?0:e<=12?12:e<14?0:e<=15?34:e<=16?28:e<=17?36:e<=18?0:e<=19?19:e<=21?0:e<=22?36:e<=24?24:0}get initialBendValue(){return this.hasBend?Math.floor(this.bendPoints[0].value/2):this.bendOrigin?Math.floor(this.bendOrigin.bendPoints[this.bendOrigin.bendPoints.length-1].value/2):this.isTieDestination&&this.tieOrigin.bendOrigin?Math.floor(this.tieOrigin.bendOrigin.bendPoints[this.tieOrigin.bendOrigin.bendPoints.length-1].value/2):this.beat.hasWhammyBar?Math.floor(this.beat.whammyBarPoints[0].value/2):this.beat.isContinuedWhammy?Math.floor(this.beat.previousBeat.whammyBarPoints[this.beat.previousBeat.whammyBarPoints.length-1].value/2):0}get displayValue(){return this.displayValueWithoutBend+this.initialBendValue}get displayValueWithoutBend(){let e=this.realValue;switch(this.harmonicType!==T.Natural&&this.harmonicType!==T.None&&(e-=this.harmonicPitch),this.beat.ottava){case o._15ma:e-=24;break;case o._8va:e-=12;break;case o.Regular:break;case o._8vb:e+=12;break;case o._15mb:e+=24}switch(this.beat.voice.bar.clefOttava){case o._15ma:e-=24;break;case o._8va:e-=12;break;case o.Regular:break;case o._8vb:e+=12;break;case o._15mb:e+=24}return e-this.beat.voice.bar.staff.displayTranspositionPitch}get hasQuarterToneOffset(){return this.hasBend?this.bendPoints[0].value%2!=0:this.bendOrigin?this.bendOrigin.bendPoints[this.bendOrigin.bendPoints.length-1].value%2!=0:this.beat.hasWhammyBar?this.beat.whammyBarPoints[0].value%2!=0:!!this.beat.isContinuedWhammy&&this.beat.previousBeat.whammyBarPoints[this.beat.previousBeat.whammyBarPoints.length-1].value%2!=0}addBendPoint(e){let t=this.bendPoints;null===t&&(t=[],this.bendPoints=t),t.push(e),(!this.maxBendPoint||e.value>this.maxBendPoint.value)&&(this.maxBendPoint=e),this.bendType===y.None&&(this.bendType=y.Custom)}finish(e,t=null){const s=new Y((()=>Ae.nextNoteOnSameLine(this))),i=e&&e.notation.notationMode===D.SongBook;if(this.isTieDestination&&(this.chain(t),i&&this.tieOrigin&&this.tieOrigin.isLetRing&&(this.isLetRing=!0)),this.isLetRing&&(s.value&&s.value.isLetRing?this.letRingDestination=s.value:this.letRingDestination=this,i&&this.isTieDestination&&!this.tieOrigin.hasBend&&(this.isVisible=!1)),this.isPalmMute&&(s.value&&s.value.isPalmMute?this.palmMuteDestination=s.value:this.palmMuteDestination=this),this.isHammerPullOrigin){const e=Ae.findHammerPullDestination(this);e?(this.hammerPullDestination=e,e.hammerPullOrigin=this):this.isHammerPullOrigin=!1}switch(this.slideOutType){case v.Shift:case v.Legato:this.slideTarget||(this.slideTarget=s.value),this.slideTarget?this.slideTarget.slideOrigin=this:this.slideOutType=v.None}let a=null;this.isHammerPullOrigin&&this.hammerPullDestination?a=this.hammerPullDestination:this.slideOutType===v.Legato&&this.slideTarget&&(a=this.slideTarget),a&&(this.hasEffectSlur=!0,this.effectSlurOrigin&&this.beat.pickStroke===ae.None?(this.effectSlurOrigin.effectSlurDestination=a,this.effectSlurOrigin.effectSlurDestination.effectSlurOrigin=this.effectSlurOrigin,this.effectSlurOrigin=null):(this.isEffectSlurOrigin=!0,this.effectSlurDestination=a,this.effectSlurDestination.effectSlurOrigin=this));const r=this.bendPoints,n=null!=r&&r.length>0;if(n){const e=this.isTieDestination&&this.tieOrigin.hasBend;this.isContinuedBend=e}else this.bendType=y.None;if(n&&this.bendType===y.Custom)if(4===r.length){const e=r[0],t=r[1],s=r[2],i=r[3];t.value===s.value?i.value>e.value?t.value>i.value?this.bendType=y.BendRelease:!this.isContinuedBend&&e.value>0?(this.bendType=y.PrebendBend,r.splice(2,1),r.splice(1,1)):(this.bendType=y.Bend,r.splice(2,1),r.splice(1,1)):i.value<e.value?this.isContinuedBend?(this.bendType=y.Release,r.splice(2,1),r.splice(1,1)):(this.bendType=y.PrebendRelease,r.splice(2,1),r.splice(1,1)):t.value>e.value?this.bendType=y.BendRelease:e.value>0&&!this.isContinuedBend?(this.bendType=y.Prebend,r.splice(2,1),r.splice(1,1)):(this.bendType=y.Hold,r.splice(2,1),r.splice(1,1)):q.warning("Model","Unsupported bend type detected, fallback to custom",null)}else if(2===r.length){const e=r[0],t=r[1];t.value>e.value?!this.isContinuedBend&&e.value>0?this.bendType=y.PrebendBend:this.bendType=y.Bend:t.value<e.value?this.isContinuedBend?this.bendType=y.Release:this.bendType=y.PrebendRelease:e.value>0&&!this.isContinuedBend?this.bendType=y.Prebend:this.bendType=y.Hold}this.initialBendValue>0&&(this.accidentalMode=N.Default)}static nextNoteOnSameLine(e){let t=e.beat.nextBeat;for(;t&&t.voice.bar.index<=e.beat.voice.bar.index+Ae.MaxOffsetForSameLineSearch;){const s=t.getNoteOnString(e.string);if(s)return s;t=t.nextBeat}return null}static findHammerPullDestination(e){let t=e.beat.nextBeat;for(;t&&t.voice.bar.index<=e.beat.voice.bar.index+Ae.MaxOffsetForSameLineSearch;){let s=t.getNoteOnString(e.string);if(s)return s;for(let i=e.string;i>0;i--)if(s=t.getNoteOnString(i),s){if(s.isLeftHandTapped)return s;break}for(let i=e.string;i<=e.beat.voice.bar.staff.tuning.length;i++)if(s=t.getNoteOnString(i),s){if(s.isLeftHandTapped)return s;break}t=t.nextBeat}return null}static findTieOrigin(e){let t=e.beat.previousBeat;for(;t&&t.voice.bar.index>=e.beat.voice.bar.index-Ae.MaxOffsetForSameLineSearch;){if(e.isStringed){const s=t.getNoteOnString(e.string);if(s)return s}else if(-1===e.octave&&-1===e.tone){if(e.index<t.notes.length)return t.notes[e.index]}else{const s=t.getNoteWithRealValue(e.realValue);if(s)return s}t=t.previousBeat}return null}chain(e=null){if(null!==e)if(null!==this._noteIdBag){let t;e.has(Ae.NoteIdLookupKey)?t=e.get(Ae.NoteIdLookupKey):(t=new Map,e.set(Ae.NoteIdLookupKey,t)),-1===this._noteIdBag.hammerPullDestinationNoteId&&-1===this._noteIdBag.tieDestinationNoteId&&-1===this._noteIdBag.slurDestinationNoteId&&-1===this._noteIdBag.slideTargetNoteId||t.set(this.id,this),-1!==this._noteIdBag.hammerPullOriginNoteId&&(this.hammerPullOrigin=t.get(this._noteIdBag.hammerPullOriginNoteId),this.hammerPullOrigin.hammerPullDestination=this),-1!==this._noteIdBag.tieOriginNoteId&&(this.tieOrigin=t.get(this._noteIdBag.tieOriginNoteId),this.tieOrigin.tieDestination=this),-1!==this._noteIdBag.slurOriginNoteId&&(this.slurOrigin=t.get(this._noteIdBag.slurOriginNoteId),this.slurOrigin.slurDestination=this),-1!==this._noteIdBag.slideOriginNoteId&&(this.slideOrigin=t.get(this._noteIdBag.slideOriginNoteId),this.slideOrigin.slideTarget=this),this._noteIdBag=null}else{if(!this.isTieDestination&&null===this.tieOrigin)return;const e=this.tieOrigin??Ae.findTieOrigin(this);e?(e.tieDestination=this,this.tieOrigin=e,this.fret=e.fret,this.octave=e.octave,this.tone=e.tone,e.hasBend&&(this.bendOrigin=this.tieOrigin)):this.isTieDestination=!1}}toJson(e){null!==this.tieDestination&&e.set("tiedestinationnoteid",this.tieDestination.id),null!==this.tieOrigin&&e.set("tieoriginnoteid",this.tieOrigin.id),null!==this.slurDestination&&e.set("slurdestinationnoteid",this.slurDestination.id),null!==this.slurOrigin&&e.set("sluroriginnoteid",this.slurOrigin.id),null!==this.hammerPullOrigin&&e.set("hammerpulloriginnoteid",this.hammerPullOrigin.id),null!==this.hammerPullDestination&&e.set("hammerpulldestinationnoteid",this.hammerPullDestination.id),null!==this.slideTarget&&e.set("slidetargetnoteid",this.slideTarget.id),null!==this.slideOrigin&&e.set("slideoriginnoteid",this.slideOrigin.id)}setProperty(e,t){switch(e){case"tiedestinationnoteid":return null==this._noteIdBag&&(this._noteIdBag=new Me),this._noteIdBag.tieDestinationNoteId=t,!0;case"tieoriginnoteid":return null==this._noteIdBag&&(this._noteIdBag=new Me),this._noteIdBag.tieOriginNoteId=t,!0;case"slurdestinationnoteid":return null==this._noteIdBag&&(this._noteIdBag=new Me),this._noteIdBag.slurDestinationNoteId=t,!0;case"sluroriginnoteid":return null==this._noteIdBag&&(this._noteIdBag=new Me),this._noteIdBag.slurOriginNoteId=t,!0;case"hammerpulloriginnoteid":return null==this._noteIdBag&&(this._noteIdBag=new Me),this._noteIdBag.hammerPullOriginNoteId=t,!0;case"hammerpulldestinationnoteid":return null==this._noteIdBag&&(this._noteIdBag=new Me),this._noteIdBag.hammerPullDestinationNoteId=t,!0;case"slidetargetnoteid":return null==this._noteIdBag&&(this._noteIdBag=new Me),this._noteIdBag.slideTargetNoteId=t,!0;case"slideoriginnoteid":return null==this._noteIdBag&&(this._noteIdBag=new Me),this._noteIdBag.slideOriginNoteId=t,!0}return!1}}Ae.GlobalNoteId=0,Ae.MaxOffsetForSameLineSearch=3,Ae.NoteIdLookupKey="NoteIdLookup";class Re{constructor(e){this._isEqualLengthTuplet=!0,this.totalDuration=0,this.beats=[],this.isFull=!1,this.voice=e}check(e){if(0===this.beats.length)return this.beats.push(e),this.totalDuration+=e.playbackDuration,!0;if(e.graceType!==w.None)return!0;if(e.voice!==this.voice||this.isFull||e.tupletNumerator!==this.beats[0].tupletNumerator||e.tupletDenominator!==this.beats[0].tupletDenominator)return!1;if(e.playbackDuration!==this.beats[0].playbackDuration&&(this._isEqualLengthTuplet=!1),this.beats.push(e),this.totalDuration+=e.playbackDuration,this._isEqualLengthTuplet)this.beats.length===this.beats[0].tupletNumerator&&(this.isFull=!0);else{const e=this.beats[0].tupletNumerator/this.beats[0].tupletDenominator|0;for(const t of Re.AllTicks)if(this.totalDuration===t*e){this.isFull=!0;break}}return!0}}Re.HalfTicks=1920,Re.QuarterTicks=960,Re.EighthTicks=480,Re.SixteenthTicks=240,Re.ThirtySecondTicks=120,Re.SixtyFourthTicks=60,Re.OneHundredTwentyEighthTicks=30,Re.TwoHundredFiftySixthTicks=15,Re.AllTicks=[Re.HalfTicks,Re.QuarterTicks,Re.EighthTicks,Re.SixteenthTicks,Re.ThirtySecondTicks,Re.SixtyFourthTicks,Re.OneHundredTwentyEighthTicks,Re.TwoHundredFiftySixthTicks],function(e){e[e.None=0]="None",e[e.Custom=1]="Custom",e[e.Dive=2]="Dive",e[e.Dip=3]="Dip",e[e.Hold=4]="Hold",e[e.Predive=5]="Predive",e[e.PrediveDive=6]="PrediveDive"}(ce||(ce={}));class Oe{static clone(e){const t=new X;return t.offset=e.offset,t.value=e.value,t}}class He{static clone(e){const t=new Ae;if(t.index=e.index,t.accentuated=e.accentuated,t.bendType=e.bendType,t.bendStyle=e.bendStyle,t.isContinuedBend=e.isContinuedBend,e.bendPoints){t.bendPoints=[];for(const s of e.bendPoints)t.addBendPoint(Oe.clone(s))}return t.fret=e.fret,t.string=e.string,t.showStringNumber=e.showStringNumber,t.octave=e.octave,t.tone=e.tone,t.percussionArticulation=e.percussionArticulation,t.isVisible=e.isVisible,t.isLeftHandTapped=e.isLeftHandTapped,t.isHammerPullOrigin=e.isHammerPullOrigin,t.isSlurDestination=e.isSlurDestination,t.harmonicType=e.harmonicType,t.harmonicValue=e.harmonicValue,t.isGhost=e.isGhost,t.isLetRing=e.isLetRing,t.isPalmMute=e.isPalmMute,t.isDead=e.isDead,t.isStaccato=e.isStaccato,t.slideInType=e.slideInType,t.slideOutType=e.slideOutType,t.vibrato=e.vibrato,t.isTieDestination=e.isTieDestination,t.leftHandFinger=e.leftHandFinger,t.rightHandFinger=e.rightHandFinger,t.trillValue=e.trillValue,t.trillSpeed=e.trillSpeed,t.durationPercent=e.durationPercent,t.accidentalMode=e.accidentalMode,t.dynamics=e.dynamics,t.ornament=e.ornament,t}}class We{static clone(e){const t=new U;return t.isLinear=e.isLinear,t.type=e.type,t.value=e.value,t.ratioPosition=e.ratioPosition,t.text=e.text,t}}class Ve{static clone(e){const t=new ze;t.index=e.index,t.notes=[];for(const s of e.notes)t.addNote(He.clone(s));t.isEmpty=e.isEmpty,t.whammyStyle=e.whammyStyle,t.ottava=e.ottava,t.isLegatoOrigin=e.isLegatoOrigin,t.duration=e.duration,t.isLetRing=e.isLetRing,t.isPalmMute=e.isPalmMute,t.automations=[];for(const s of e.automations)t.automations.push(We.clone(s));if(t.dots=e.dots,t.fade=e.fade,t.lyrics=e.lyrics?e.lyrics.slice():null,t.pop=e.pop,t.slap=e.slap,t.tap=e.tap,t.text=e.text,t.slashed=e.slashed,t.deadSlapped=e.deadSlapped,t.brushType=e.brushType,t.brushDuration=e.brushDuration,t.tupletDenominator=e.tupletDenominator,t.tupletNumerator=e.tupletNumerator,t.isContinuedWhammy=e.isContinuedWhammy,t.whammyBarType=e.whammyBarType,e.whammyBarPoints){t.whammyBarPoints=[];for(const s of e.whammyBarPoints)t.addWhammyBarPoint(Oe.clone(s))}return t.vibrato=e.vibrato,t.chordId=e.chordId,t.graceType=e.graceType,t.pickStroke=e.pickStroke,t.tremoloSpeed=e.tremoloSpeed,t.crescendo=e.crescendo,t.displayStart=e.displayStart,t.playbackStart=e.playbackStart,t.displayDuration=e.displayDuration,t.playbackDuration=e.playbackDuration,t.overrideDisplayDuration=e.overrideDisplayDuration,t.golpe=e.golpe,t.dynamics=e.dynamics,t.invertBeamDirection=e.invertBeamDirection,t.preferredBeamDirection=e.preferredBeamDirection,t.isEffectSlurOrigin=e.isEffectSlurOrigin,t.beamingMode=e.beamingMode,t.wahPedal=e.wahPedal,t.barreFret=e.barreFret,t.barreShape=e.barreShape,t.rasgueado=e.rasgueado,t.showTimer=e.showTimer,t.timer=e.timer,t}}!function(e){e[e.None=0]="None",e[e.Thumb=1]="Thumb",e[e.Finger=2]="Finger"}(de||(de={})),function(e){e[e.None=0]="None",e[e.FadeIn=1]="FadeIn",e[e.FadeOut=2]="FadeOut",e[e.VolumeSwell=3]="VolumeSwell"}(ue||(ue={})),function(e){e[e.None=0]="None",e[e.Open=1]="Open",e[e.Closed=2]="Closed"}(pe||(pe={})),function(e){e[e.None=0]="None",e[e.Full=1]="Full",e[e.Half=2]="Half"}(ge||(ge={})),function(e){e[e.None=0]="None",e[e.Ii=1]="Ii",e[e.Mi=2]="Mi",e[e.MiiTriplet=3]="MiiTriplet",e[e.MiiAnapaest=4]="MiiAnapaest",e[e.PmpTriplet=5]="PmpTriplet",e[e.PmpAnapaest=6]="PmpAnapaest",e[e.PeiTriplet=7]="PeiTriplet",e[e.PeiAnapaest=8]="PeiAnapaest",e[e.PaiTriplet=9]="PaiTriplet",e[e.PaiAnapaest=10]="PaiAnapaest",e[e.AmiTriplet=11]="AmiTriplet",e[e.AmiAnapaest=12]="AmiAnapaest",e[e.Ppp=13]="Ppp",e[e.Amii=14]="Amii",e[e.Amip=15]="Amip",e[e.Eami=16]="Eami",e[e.Eamii=17]="Eamii",e[e.Peami=18]="Peami"}(me||(me={})),function(e){e[e.Auto=0]="Auto",e[e.ForceSplitToNext=1]="ForceSplitToNext",e[e.ForceMergeWithNext=2]="ForceMergeWithNext",e[e.ForceSplitOnSecondaryToNext=3]="ForceSplitOnSecondaryToNext"}(fe||(fe={})),function(e){e[e.Effects=0]="Effects",e[e.StandardNotationStem=1]="StandardNotationStem",e[e.StandardNotationFlags=2]="StandardNotationFlags",e[e.StandardNotationBeams=3]="StandardNotationBeams",e[e.StandardNotationTuplet=4]="StandardNotationTuplet",e[e.StandardNotationEffects=5]="StandardNotationEffects",e[e.StandardNotationRests=6]="StandardNotationRests",e[e.GuitarTabStem=7]="GuitarTabStem",e[e.GuitarTabFlags=8]="GuitarTabFlags",e[e.GuitarTabBeams=9]="GuitarTabBeams",e[e.GuitarTabTuplet=10]="GuitarTabTuplet",e[e.GuitarTabEffects=11]="GuitarTabEffects",e[e.GuitarTabRests=12]="GuitarTabRests",e[e.SlashStem=13]="SlashStem",e[e.SlashFlags=14]="SlashFlags",e[e.SlashBeams=15]="SlashBeams",e[e.SlashTuplet=16]="SlashTuplet",e[e.SlashRests=17]="SlashRests",e[e.SlashEffects=18]="SlashEffects",e[e.NumberedDuration=19]="NumberedDuration",e[e.NumberedEffects=20]="NumberedEffects",e[e.NumberedRests=21]="NumberedRests",e[e.NumberedTuplet=22]="NumberedTuplet"}(ye||(ye={}));class Ge extends H{}class ze{constructor(){this.id=ze._globalBeatId++,this.index=0,this.previousBeat=null,this.nextBeat=null,this.notes=[],this.noteStringLookup=new Map,this.noteValueLookup=new Map,this.isEmpty=!1,this.whammyStyle=f.Default,this.ottava=o.Regular,this.fermata=null,this.isLegatoOrigin=!1,this.minNote=null,this.maxNote=null,this.maxStringNote=null,this.minStringNote=null,this.duration=_.Quarter,this.isLetRing=!1,this.isPalmMute=!1,this.automations=[],this.dots=0,this.fade=ue.None,this.lyrics=null,this.pop=!1,this.slap=!1,this.tap=!1,this.text=null,this.slashed=!1,this.deadSlapped=!1,this.brushType=b.None,this.brushDuration=0,this.tupletDenominator=-1,this.tupletNumerator=-1,this.tupletGroup=null,this.isContinuedWhammy=!1,this.whammyBarType=ce.None,this.whammyBarPoints=null,this.maxWhammyPoint=null,this.minWhammyPoint=null,this.vibrato=P.None,this.chordId=null,this.graceType=w.None,this.graceGroup=null,this.graceIndex=-1,this.pickStroke=ae.None,this.tremoloSpeed=null,this.crescendo=S.None,this.displayStart=0,this.playbackStart=0,this.displayDuration=0,this.playbackDuration=0,this.golpe=de.None,this.dynamics=g.F,this.invertBeamDirection=!1,this.preferredBeamDirection=null,this.isEffectSlurOrigin=!1,this.effectSlurOrigin=null,this.effectSlurDestination=null,this.beamingMode=fe.Auto,this.wahPedal=pe.None,this.barreFret=-1,this.barreShape=ge.None,this.rasgueado=me.None,this.showTimer=!1,this.timer=null}static resetIds(){ze._globalBeatId=0}get isLastOfVoice(){return this.index===this.voice.beats.length-1}get isLegatoDestination(){return!!this.previousBeat&&this.previousBeat.isLegatoOrigin}get isRest(){return this.isEmpty||!this.deadSlapped&&0===this.notes.length}get isFullBarRest(){return this.isRest&&1===this.voice.beats.length&&this.duration===_.Whole}get fadeIn(){return this.fade===ue.FadeIn}set fadeIn(e){this.fade=e?ue.FadeIn:ue.None}get hasRasgueado(){return this.rasgueado!==me.None}get hasTuplet(){return!(-1===this.tupletDenominator&&-1===this.tupletNumerator||1===this.tupletDenominator&&1===this.tupletNumerator)}get hasWhammyBar(){return null!==this.whammyBarPoints&&this.whammyBarType!==ce.None}get hasChord(){return!!this.chordId}get chord(){return this.chordId?this.voice.bar.staff.getChord(this.chordId):null}get isTremolo(){return!!this.tremoloSpeed}get displayEnd(){return this.displayStart+this.displayDuration}get absoluteDisplayStart(){return this.voice.bar.masterBar.start+this.displayStart}get absolutePlaybackStart(){return this.voice.bar.masterBar.start+this.playbackStart}get isEffectSlurDestination(){return!!this.effectSlurOrigin}get isBarre(){return this.barreShape!==ge.None&&this.barreFret>=0}addWhammyBarPoint(e){let t=this.whammyBarPoints;null===t&&(t=[],this.whammyBarPoints=t),t.push(e),(!this.maxWhammyPoint||e.value>this.maxWhammyPoint.value)&&(this.maxWhammyPoint=e),(!this.minWhammyPoint||e.value<this.minWhammyPoint.value)&&(this.minWhammyPoint=e),this.whammyBarType===ce.None&&(this.whammyBarType=ce.Custom)}removeWhammyBarPoint(e){const t=this.whammyBarPoints;if(null===t||e<0||e>=t.length)return;t.splice(e,1);const s=t[e];if(s===this.maxWhammyPoint){this.maxWhammyPoint=null;for(const e of t)(!this.maxWhammyPoint||e.value>this.maxWhammyPoint.value)&&(this.maxWhammyPoint=e)}if(s===this.minWhammyPoint){this.minWhammyPoint=null;for(const e of t)(!this.minWhammyPoint||e.value<this.minWhammyPoint.value)&&(this.minWhammyPoint=e)}}addNote(e){e.beat=this,e.index=this.notes.length,this.notes.push(e),e.isStringed&&this.noteStringLookup.set(e.string,e)}removeNote(e){const t=this.notes.indexOf(e);t>=0&&(this.notes.splice(t,1),e.isStringed&&this.noteStringLookup.delete(e.string))}getAutomation(e){for(let t=0,s=this.automations.length;t<s;t++){const s=this.automations[t];if(s.type===e)return s}return null}getNoteOnString(e){return this.noteStringLookup.has(e)?this.noteStringLookup.get(e):null}calculateDuration(){if(void 0!==this.overrideDisplayDuration)return this.overrideDisplayDuration;if(this.isFullBarRest)return this.voice.bar.masterBar.calculateDuration();let e=z.toTicks(this.duration);return 2===this.dots?e=z.applyDot(e,!0):1===this.dots&&(e=z.applyDot(e,!1)),this.tupletDenominator>0&&this.tupletNumerator>=0&&(e=z.applyTuplet(e,this.tupletNumerator,this.tupletDenominator)),e}updateDurations(){const e=this.calculateDuration();switch(this.playbackDuration=e,this.graceType){case w.BeforeBeat:case w.OnBeat:switch(this.duration){case _.Sixteenth:this.playbackDuration=z.toTicks(_.SixtyFourth);break;case _.ThirtySecond:this.playbackDuration=z.toTicks(_.OneHundredTwentyEighth);break;default:this.playbackDuration=z.toTicks(_.ThirtySecond)}this.displayDuration=0;break;case w.BendGrace:this.playbackDuration/=2,this.displayDuration=0;break;default:this.displayDuration=e;const t=this.previousBeat;t&&t.graceType===w.BendGrace&&(this.playbackDuration=t.playbackDuration)}}finishTuplet(){const e=this.previousBeat;let t=e?e.tupletGroup:null;if((this.hasTuplet||this.graceType!==w.None&&t)&&(e&&t&&t.check(this)||(t=new Re(this.voice),t.check(this)),this.tupletGroup=t),this.index>0){const e=this.voice.bar.masterBar.calculateDuration(),t=[];for(const s of this.automations)0===s.ratioPosition&&(s.ratioPosition=this.playbackStart/e),s.type!==m.Volume&&t.push(s);this.automations=t}}finish(e,t=null){switch(null===this.getAutomation(m.Instrument)&&0===this.index&&0===this.voice.index&&0===this.voice.bar.index&&0===this.voice.bar.staff.index&&this.automations.push(U.buildInstrumentAutomation(!1,0,this.voice.bar.staff.track.playbackInfo.program)),this.graceType){case w.OnBeat:case w.BeforeBeat:const e=this.graceGroup.beats.length;this.duration=1===e?_.Eighth:2===e?_.Sixteenth:_.ThirtySecond}const s=e?e.notation.notationMode:D.GuitarPro;let i="grad"===this.text||"grad."===this.text;i&&s===D.SongBook&&(this.text="");let a=!1;this.minNote=null,this.maxNote=null,this.minStringNote=null,this.maxStringNote=null;let r=0,n=!1;for(let o=0,h=this.notes.length;o<h;o++){const h=this.notes[o];if(h.dynamics=this.dynamics,h.finish(e,t),h.isLetRing&&(this.isLetRing=!0),h.isPalmMute&&(this.isPalmMute=!0),s===D.SongBook&&h.hasBend&&this.graceType!==w.BendGrace){if(!h.isTieOrigin)switch(h.bendType){case y.Bend:case y.PrebendRelease:case y.PrebendBend:a=!0}i||h.bendStyle===f.Gradual?(i=!0,h.bendStyle=f.Gradual,a=!1):h.bendStyle=f.Fast}h.isVisible&&(r++,(!this.minNote||h.realValue<this.minNote.realValue)&&(this.minNote=h),(!this.maxNote||h.realValue>this.maxNote.realValue)&&(this.maxNote=h),(!this.minStringNote||h.string<this.minStringNote.string)&&(this.minStringNote=h),(!this.maxStringNote||h.string>this.maxStringNote.string)&&(this.maxStringNote=h),h.hasEffectSlur&&(n=!0))}if(n&&(this.effectSlurOrigin?(this.effectSlurOrigin.effectSlurDestination=this.nextBeat,this.effectSlurOrigin.effectSlurDestination&&(this.effectSlurOrigin.effectSlurDestination.effectSlurOrigin=this.effectSlurOrigin),this.effectSlurOrigin=null):(this.isEffectSlurOrigin=!0,this.effectSlurDestination=this.nextBeat,this.effectSlurDestination&&(this.effectSlurDestination.effectSlurOrigin=this))),this.notes.length>0&&0===r&&(this.isEmpty=!0),this.isRest||this.isLetRing&&this.isPalmMute)this.isRest&&this.previousBeat&&e&&e.notation.notationMode===D.GuitarPro&&(this.previousBeat.isLetRing&&(this.isLetRing=!0),this.previousBeat.isPalmMute&&(this.isPalmMute=!0));else{let e=this.previousBeat;for(;e&&e.isRest;)this.isLetRing||(e.isLetRing=!1),this.isPalmMute||(e.isPalmMute=!1),e=e.previousBeat}const o=this.whammyBarPoints,h=null!==o&&o.length>0;if(h){const e=!!this.previousBeat&&this.previousBeat.hasWhammyBar;this.isContinuedWhammy=e}else this.whammyBarType=ce.None;if(h&&this.whammyBarType===ce.Custom&&(s===D.SongBook&&(this.whammyStyle=i?f.Gradual:f.Fast),4===o.length)){const e=o[0],t=o[1],i=o[2],a=o[3];t.value===i.value&&(e.value<t.value&&t.value<a.value||e.value>t.value&&t.value>a.value?(0===e.value||this.isContinuedWhammy?this.whammyBarType=ce.Dive:this.whammyBarType=ce.PrediveDive,o.splice(2,1),o.splice(1,1)):e.value>t.value&&t.value<a.value||e.value<t.value&&t.value>a.value?(this.whammyBarType=ce.Dip,t.offset!==i.offset&&s!==D.SongBook||o.splice(2,1)):e.value===t.value&&t.value===a.value&&(0===e.value||this.isContinuedWhammy?this.whammyBarType=ce.Hold:this.whammyBarType=ce.Predive,o.splice(2,1),o.splice(1,1)))}if(this.updateDurations(),a){const e=Ve.clone(this);e.id=ze._globalBeatId++,e.pickStroke=ae.None;for(let t=0,s=e.notes.length;t<s;t++){const s=e.notes[t],i=this.notes[t];if(s.bendType=y.None,s.maxBendPoint=null,s.bendPoints=null,s.bendStyle=f.Default,s.id=Ae.GlobalNoteId++,i.isTieOrigin&&(s.tieDestination=i.tieDestination,i.tieDestination.tieOrigin=s),i.isTieDestination&&(s.tieOrigin=i.tieOrigin?i.tieOrigin:null,i.tieOrigin.tieDestination=s),i.hasBend&&i.isTieOrigin){const e=Ae.findTieOrigin(i);if(e&&e.hasBend){s.bendType=y.Hold;const e=i.bendPoints[i.bendPoints.length-1];s.addBendPoint(new X(0,e.value)),s.addBendPoint(new X(X.MaxPosition,e.value))}}s.isTieDestination=!0}this.graceType=w.BendGrace,this.graceGroup=new Q,this.graceGroup.addBeat(this),this.graceGroup.isComplete=!0,this.graceGroup.finish(),this.updateDurations(),this.voice.insertBeat(this,e),e.graceGroup=new Q,e.graceGroup.addBeat(this),e.graceGroup.isComplete=!0,e.graceGroup.finish()}}isBefore(e){return this.voice.bar.index<e.voice.bar.index||e.voice.bar.index===this.voice.bar.index&&this.index<e.index}isAfter(e){return this.voice.bar.index>e.voice.bar.index||e.voice.bar.index===this.voice.bar.index&&this.index>e.index}hasNoteOnString(e){return this.noteStringLookup.has(e)}getNoteWithRealValue(e){return this.noteValueLookup.has(e)?this.noteValueLookup.get(e):null}chain(e=null){for(const t of this.notes)this.noteValueLookup.set(t.realValue,t),t.chain(e)}}ze._globalBeatId=0,function(e){e[e.Title=0]="Title",e[e.SubTitle=1]="SubTitle",e[e.Artist=2]="Artist",e[e.Album=3]="Album",e[e.Words=4]="Words",e[e.Music=5]="Music",e[e.WordsAndMusic=6]="WordsAndMusic",e[e.Transcriber=7]="Transcriber",e[e.Copyright=8]="Copyright",e[e.CopyrightSecondLine=9]="CopyrightSecondLine",e[e.ChordDiagramList=10]="ChordDiagramList"}(be||(be={}));class Ue{constructor(e="",t=void 0,s=ne.Left){this.template=e,this.isVisible=t,this.textAlign=s}buildText(e){let t=!1,s=!1;const i=this.template.replace(Ue.PlaceholderPattern,((i,a)=>{s=!0;let r="";switch(a){case"TITLE":r=e.title;break;case"SUBTITLE":r=e.subTitle;break;case"ARTIST":r=e.artist;break;case"ALBUM":r=e.album;break;case"WORDS":case"WORDSMUSIC":r=e.words;break;case"MUSIC":r=e.music;break;case"TABBER":r=e.tab;break;case"COPYRIGHT":r=e.copyright;break;default:r=""}return r&&(t=!0),r}));return s&&!t?"":i}}Ue.PlaceholderPattern=/%([^%]+)%/g;class Xe extends H{constructor(){super(...arguments),this.headerAndFooter=new Map}}Xe.defaultHeaderAndFooter=new Map([[be.Title,new Ue("%TITLE%",void 0,ne.Center)],[be.SubTitle,new Ue("%SUBTITLE%",void 0,ne.Center)],[be.Artist,new Ue("%ARTIST%",void 0,ne.Center)],[be.Album,new Ue("%ALBUM%",void 0,ne.Center)],[be.Words,new Ue("Words by %WORDS%",void 0,ne.Left)],[be.Music,new Ue("Music by %MUSIC%",void 0,ne.Right)],[be.WordsAndMusic,new Ue("Words & Music by %MUSIC%",void 0,ne.Right)],[be.Transcriber,new Ue("Tabbed by %TABBER%",!1,ne.Right)],[be.Copyright,new Ue("%COPYRIGHT%",void 0,ne.Center)],[be.CopyrightSecondLine,new Ue("All Rights Reserved - International Copyright Secured",!0,ne.Center)]]);class Je{constructor(){this._currentRepeatGroup=null,this._openedRepeatGroups=[],this._properlyOpenedRepeatGroups=0,this.album="",this.artist="",this.copyright="",this.instructions="",this.music="",this.notices="",this.subTitle="",this.title="",this.words="",this.tab="",this.tempo=120,this.tempoLabel="",this.masterBars=[],this.tracks=[],this.defaultSystemsLayout=3,this.systemsLayout=[],this.stylesheet=new R}static resetIds(){G.resetIds(),ze.resetIds(),ee.resetIds(),Ae.resetIds()}rebuildRepeatGroups(){this._currentRepeatGroup=null,this._openedRepeatGroups=[],this._properlyOpenedRepeatGroups=0;for(const e of this.masterBars)this.addMasterBarToRepeatGroups(e)}addMasterBar(e){e.score=this,e.index=this.masterBars.length,0!==this.masterBars.length&&(e.previousMasterBar=this.masterBars[this.masterBars.length-1],e.previousMasterBar.nextMasterBar=e,e.start=e.previousMasterBar.start+(e.previousMasterBar.isAnacrusis?0:e.previousMasterBar.calculateDuration())),this.addMasterBarToRepeatGroups(e),this.masterBars.push(e)}addMasterBarToRepeatGroups(e){e.isRepeatStart?(this._currentRepeatGroup?.isClosed&&(this._openedRepeatGroups.pop(),this._properlyOpenedRepeatGroups--),this._currentRepeatGroup=new O,this._openedRepeatGroups.push(this._currentRepeatGroup),this._properlyOpenedRepeatGroups++):this._currentRepeatGroup||(this._currentRepeatGroup=new O,this._openedRepeatGroups.push(this._currentRepeatGroup)),this._currentRepeatGroup.addMasterBar(e),e.isRepeatEnd&&this._properlyOpenedRepeatGroups>1&&(this._openedRepeatGroups.pop(),this._properlyOpenedRepeatGroups--,this._currentRepeatGroup=this._openedRepeatGroups.length>0?this._openedRepeatGroups[this._openedRepeatGroups.length-1]:null)}addTrack(e){e.score=this,e.index=this.tracks.length,this.tracks.push(e)}finish(e){const t=new Map;for(let s=0,i=this.tracks.length;s<i;s++)this.tracks[s].finish(e,t)}}class Ye{init(e,t){this.data=e,this.settings=t,Je.resetIds()}}!function(e){e[e.General=0]="General",e[e.Format=1]="Format",e[e.AlphaTex=2]="AlphaTex"}(Se||(Se={}));class $e extends Error{constructor(e,t="",s){super(t??"",{cause:s}),this.type=e,Object.setPrototypeOf(this,$e.prototype)}}class qe extends $e{constructor(e=null,t){super(Se.Format,e??"Unsupported format",t),Object.setPrototypeOf(this,qe.prototype)}}class je{constructor(){this.name="",this.firstFret=1,this.strings=[],this.barreFrets=[],this.showName=!0,this.showDiagram=!0,this.showFingering=!0}get uniqueId(){return[this.name,this.firstFret.toString(),this.strings.join(","),this.barreFrets.join(","),this.showDiagram.toString(),this.showFingering.toString(),this.showName.toString()].join("|")}}!function(e){e[e.IgnoreSpaces=0]="IgnoreSpaces",e[e.Begin=1]="Begin",e[e.Text=2]="Text",e[e.Comment=3]="Comment",e[e.Dash=4]="Dash"}(_e||(_e={}));class Ke{constructor(){this.startBar=0,this.text=""}finish(e=!1){this.chunks=[],this.parse(this.text,0,this.chunks,e)}parse(e,t,s,i){if(!e)return;let a=_e.Begin,r=_e.Begin,n=!1,o=0;for(;t<e.length;){const s=e.charCodeAt(t);switch(a){case _e.IgnoreSpaces:switch(s){case Ke.CharCodeLF:case Ke.CharCodeCR:case Ke.CharCodeTab:break;case Ke.CharCodeSpace:if(!n){a=r;continue}break;default:n=!1,a=r;continue}break;case _e.Begin:if(s!==Ke.CharCodeBrackedOpen){o=t,a=_e.Text;continue}a=_e.Comment;break;case _e.Comment:if(s===Ke.CharCodeBrackedClose)a=_e.Begin;break;case _e.Text:switch(s){case Ke.CharCodeDash:a=_e.Dash;break;case Ke.CharCodeCR:case Ke.CharCodeLF:case Ke.CharCodeSpace:const s=e.substr(o,t-o);this.addChunk(s,i),a=_e.IgnoreSpaces,r=_e.Begin}break;case _e.Dash:if(s!==Ke.CharCodeDash){const s=e.substr(o,t-o);this.addChunk(s,i),n=!0,a=_e.IgnoreSpaces,r=_e.Begin;continue}}t+=1}a===_e.Text&&t!==o&&this.addChunk(e.substr(o,t-o),i)}addChunk(e,t){e=this.prepareChunk(e),(!t||e.length>0&&"-"!==e)&&this.chunks.push(e)}prepareChunk(e){const t=e.split("+").join(" ");let s=t.length;for(;s>0&&"_"===t.charAt(s-1);)s--;return s!==t.length?t.substr(0,s):t}}Ke.CharCodeLF=10,Ke.CharCodeTab=9,Ke.CharCodeCR=13,Ke.CharCodeSpace=32,Ke.CharCodeBrackedClose=93,Ke.CharCodeBrackedOpen=91,Ke.CharCodeDash=45;class Qe{constructor(){this.marker="",this.text=""}}class Ze extends $e{constructor(e){super(Se.Format,e),Object.setPrototypeOf(this,Ze.prototype)}}class et{constructor(e,t,s,i=255){this.raw=0,this.raw=(255&i)<<24|(255&e)<<16|(255&t)<<8|255&s,this.updateRgba()}updateRgba(){255===this.a?this.rgba=`#${ie.toHexString(this.r,2)}${ie.toHexString(this.g,2)}${ie.toHexString(this.b,2)}`:this.rgba=`rgba(${this.r},${this.g},${this.b},${this.a/255})`}get a(){return this.raw>>24&255}get r(){return this.raw>>16&255}get g(){return this.raw>>8&255}get b(){return 255&this.raw}static random(e=100){return new et(255*Math.random()|0,255*Math.random()|0,255*Math.random()|0,e)}static fromJson(e){if(e instanceof et)return e;switch(typeof e){case"number":{const t=new et(0,0,0,0);return t.raw=e,t.updateRgba(),t}case"string":{const t=e;if(t.startsWith("#")){if(4===t.length)return new et(17*Number.parseInt(t[1],16),17*Number.parseInt(t[2],16),17*Number.parseInt(t[3],16));if(5===t.length)return new et(17*Number.parseInt(t[1],16),17*Number.parseInt(t[2],16),17*Number.parseInt(t[3],16),17*Number.parseInt(t[4],16));if(7===t.length)return new et(Number.parseInt(t.substring(1,3),16),Number.parseInt(t.substring(3,5),16),Number.parseInt(t.substring(5,7),16));if(9===t.length)return new et(Number.parseInt(t.substring(1,3),16),Number.parseInt(t.substring(3,5),16),Number.parseInt(t.substring(5,7),16),Number.parseInt(t.substring(7,9),16))}else if(t.startsWith("rgba")||t.startsWith("rgb")){const e=t.indexOf("("),s=t.lastIndexOf(")");if(-1===e||-1===s)throw new Ze("No values specified for rgb/rgba function");const i=t.substring(e+1,s).split(",");if(3===i.length)return new et(Number.parseInt(i[0]),Number.parseInt(i[1]),Number.parseInt(i[2]));if(4===i.length)return new et(Number.parseInt(i[0]),Number.parseInt(i[1]),Number.parseInt(i[2]),255*Number.parseFloat(i[3]))}return null}}throw new Ze("Unsupported format for color")}static toJson(e){return null===e?null:e.raw}}et.BlackRgb="#000000";class tt{constructor(){this.volume=15,this.balance=8,this.port=1,this.program=0,this.primaryChannel=0,this.secondaryChannel=0,this.isMute=!1,this.isSolo=!1}}class st{static getTextForTuning(e,t){const s=st.getTextPartsForTuning(e);return t?s.join(""):s[0]}static getTextPartsForTuning(e,t=-1){return[["C","Db","D","Eb","E","F","Gb","G","Ab","A","Bb","B"][e%12],((e/12|0)+t).toString()]}static getDefaultTuningFor(e){return st._defaultTunings.has(e)?st._defaultTunings.get(e):null}static getPresetsFor(e){switch(e){case 7:return st._sevenStrings;case 6:return st._sixStrings;case 5:return st._fiveStrings;case 4:return st._fourStrings}return[]}static initialize(){st._defaultTunings.set(7,new st("Guitar 7 strings",[64,59,55,50,45,40,35],!0)),st._sevenStrings.push(st._defaultTunings.get(7)),st._defaultTunings.set(6,new st("Guitar Standard Tuning",[64,59,55,50,45,40],!0)),st._sixStrings.push(st._defaultTunings.get(6)),st._sixStrings.push(new st("Guitar Tune down ½ step",[63,58,54,49,44,39],!1)),st._sixStrings.push(new st("Guitar Tune down 1 step",[62,57,53,48,43,38],!1)),st._sixStrings.push(new st("Guitar Tune down 2 step",[60,55,51,46,41,36],!1)),st._sixStrings.push(new st("Guitar Dropped D Tuning",[64,59,55,50,45,38],!1)),st._sixStrings.push(new st("Guitar Dropped D Tuning variant",[64,57,55,50,45,38],!1)),st._sixStrings.push(new st("Guitar Double Dropped D Tuning",[62,59,55,50,45,38],!1)),st._sixStrings.push(new st("Guitar Dropped E Tuning",[66,61,57,52,47,40],!1)),st._sixStrings.push(new st("Guitar Dropped C Tuning",[62,57,53,48,43,36],!1)),st._sixStrings.push(new st("Guitar Open C Tuning",[64,60,55,48,43,36],!1)),st._sixStrings.push(new st("Guitar Open Cm Tuning",[63,60,55,48,43,36],!1)),st._sixStrings.push(new st("Guitar Open C6 Tuning",[64,57,55,48,43,36],!1)),st._sixStrings.push(new st("Guitar Open Cmaj7 Tuning",[64,59,55,52,43,36],!1)),st._sixStrings.push(new st("Guitar Open D Tuning",[62,57,54,50,45,38],!1)),st._sixStrings.push(new st("Guitar Open Dm Tuning",[62,57,53,50,45,38],!1)),st._sixStrings.push(new st("Guitar Open D5 Tuning",[62,57,50,50,45,38],!1)),st._sixStrings.push(new st("Guitar Open D6 Tuning",[62,59,54,50,45,38],!1)),st._sixStrings.push(new st("Guitar Open Dsus4 Tuning",[62,57,55,50,45,38],!1)),st._sixStrings.push(new st("Guitar Open E Tuning",[64,59,56,52,47,40],!1)),st._sixStrings.push(new st("Guitar Open Em Tuning",[64,59,55,52,47,40],!1)),st._sixStrings.push(new st("Guitar Open Esus11 Tuning",[64,59,55,52,45,40],!1)),st._sixStrings.push(new st("Guitar Open F Tuning",[65,60,53,48,45,41],!1)),st._sixStrings.push(new st("Guitar Open G Tuning",[62,59,55,50,43,38],!1)),st._sixStrings.push(new st("Guitar Open Gm Tuning",[62,58,55,50,43,38],!1)),st._sixStrings.push(new st("Guitar Open G6 Tuning",[64,59,55,50,43,38],!1)),st._sixStrings.push(new st("Guitar Open Gsus4 Tuning",[62,60,55,50,43,38],!1)),st._sixStrings.push(new st("Guitar Open A Tuning",[64,61,57,52,45,40],!1)),st._sixStrings.push(new st("Guitar Open Am Tuning",[64,60,57,52,45,40],!1)),st._sixStrings.push(new st("Guitar Nashville Tuning",[64,59,67,62,57,52],!1)),st._sixStrings.push(new st("Bass 6 Strings Tuning",[48,43,38,33,28,23],!1)),st._sixStrings.push(new st("Lute or Vihuela Tuning",[64,59,54,50,45,40],!1)),st._defaultTunings.set(5,new st("Bass 5 Strings Tuning",[43,38,33,28,23],!0)),st._fiveStrings.push(st._defaultTunings.get(5)),st._fiveStrings.push(new st("Banjo Dropped C Tuning",[62,59,55,48,67],!1)),st._fiveStrings.push(new st("Banjo Open D Tuning",[62,57,54,50,69],!1)),st._fiveStrings.push(new st("Banjo Open G Tuning",[62,59,55,50,67],!1)),st._fiveStrings.push(new st("Banjo G Minor Tuning",[62,58,55,50,67],!1)),st._fiveStrings.push(new st("Banjo G Modal Tuning",[62,57,55,50,67],!1)),st._defaultTunings.set(4,new st("Bass Standard Tuning",[43,38,33,28],!0)),st._fourStrings.push(st._defaultTunings.get(4)),st._fourStrings.push(new st("Bass Tune down ½ step",[42,37,32,27],!1)),st._fourStrings.push(new st("Bass Tune down 1 step",[41,36,31,26],!1)),st._fourStrings.push(new st("Bass Tune down 2 step",[39,34,29,24],!1)),st._fourStrings.push(new st("Bass Dropped D Tuning",[43,38,33,26],!1)),st._fourStrings.push(new st("Ukulele C Tuning",[45,40,36,43],!1)),st._fourStrings.push(new st("Ukulele G Tuning",[52,47,43,38],!1)),st._fourStrings.push(new st("Mandolin Standard Tuning",[64,57,50,43],!1)),st._fourStrings.push(new st("Mandolin or Violin Tuning",[76,69,62,55],!1)),st._fourStrings.push(new st("Viola Tuning",[69,62,55,48],!1)),st._fourStrings.push(new st("Cello Tuning",[57,50,43,36],!1))}static findTuning(e){const t=st.getPresetsFor(e.length);for(let s=0,i=t.length;s<i;s++){const i=t[s];let a=!0;for(let t=0,s=e.length;t<s;t++)if(e[t]!==i.tunings[t]){a=!1;break}if(a)return i}return null}constructor(e="",t=null,s=!1){this.isStandard=s,this.name=e,this.tunings=t??[]}finish(){const e=st.findTuning(this.tunings);e&&(this.name=e.name,this.isStandard=e.isStandard),this.name=this.name.trim()}}st._sevenStrings=[],st._sixStrings=[],st._fiveStrings=[],st._fourStrings=[],st._defaultTunings=new Map,st.defaultAccidentals=["","#","","#","","","#","","#","","#",""],st.defaultSteps=["C","C","D","D","E","F","F","G","G","A","A","B"],st.initialize();class it{constructor(){this.index=0,this.bars=[],this.chords=null,this.capo=0,this.transpositionPitch=0,this.displayTranspositionPitch=0,this.stringTuning=new st("",[],!1),this.showSlash=!1,this.showNumbered=!1,this.showTablature=!0,this.showStandardNotation=!0,this.isPercussion=!1,this.standardNotationLineCount=it.DefaultStandardNotationLineCount}get tuning(){return this.stringTuning.tunings}get tuningName(){return this.stringTuning.name}get isStringed(){return this.stringTuning.tunings.length>0}finish(e,t=null){this.stringTuning.finish();for(let s=0,i=this.bars.length;s<i;s++)this.bars[s].finish(e,t)}addChord(e,t){t.staff=this;let s=this.chords;null===s&&(s=new Map,this.chords=s),s.set(e,t)}hasChord(e){return this.chords?.has(e)??!1}getChord(e){return this.chords?.get(e)??null}addBar(e){const t=this.bars;e.staff=this,e.index=t.length,t.length>0&&(e.previousBar=t[t.length-1],e.previousBar.nextBar=e),t.push(e)}}it.DefaultStandardNotationLineCount=5,function(e){e[e.TrackName=0]="TrackName",e[e.BracesAndBrackets=1]="BracesAndBrackets",e[e.SystemSeparator=2]="SystemSeparator",e[e.StringTuning=3]="StringTuning"}(we||(we={}));class at extends H{}class rt{constructor(){this.index=0,this.staves=[],this.playbackInfo=new tt,this.color=new et(200,0,0,255),this.name="",this.isVisibleOnMultiTrack=!0,this.shortName="",this.defaultSystemsLayout=3,this.systemsLayout=[],this.percussionArticulations=[]}addLineBreaks(e){this.lineBreaks||(this.lineBreaks=new Set),this.lineBreaks.add(e)}ensureStaveCount(e){for(;this.staves.length<e;)this.addStaff(new it)}addStaff(e){e.index=this.staves.length,e.track=this,this.staves.push(e)}finish(e,t=null){this.shortName||(this.shortName=this.name,this.shortName.length>rt.ShortNameMaxLength&&(this.shortName=this.shortName.substr(0,rt.ShortNameMaxLength)));for(let s=0,i=this.staves.length;s<i;s++)this.staves[s].finish(e,t)}applyLyrics(e){for(const t of e)t.finish();const t=this.staves[0];for(let s=0;s<e.length;s++){const i=e[s];if(i.startBar>=0&&i.startBar<t.bars.length){let a=t.bars[i.startBar].voices[0].beats[0];for(let t=0;t<i.chunks.length&&a;t++){for(;a&&(a.isEmpty||a.isRest);)a=a.nextBeat;a&&(a.lyrics||(a.lyrics=new Array(e.length),a.lyrics.fill("")),a.lyrics[s]=i.chunks[t],a=a.nextBeat)}}}}}rt.ShortNameMaxLength=10;class nt{static float64ToBytes(e){return nt._dataView.setFloat64(0,e,!0),nt._conversionByteArray}static bytesToInt64LE(e){nt._conversionByteArray.set(e,0);const t=nt._dataView.getBigInt64(0,!0);return t<=Number.MAX_SAFE_INTEGER&&t>=Number.MIN_SAFE_INTEGER?Number(t):Number.MAX_SAFE_INTEGER}static bytesToFloat64LE(e){return nt._conversionByteArray.set(e,0),nt._dataView.getFloat64(0,!0)}static bytesToFloat32LE(e){return nt._conversionByteArray.set(e,0),nt._dataView.getFloat32(0,!0)}static float32BEToBytes(e){return nt._dataView.setFloat32(0,e,!1),nt._conversionByteArray.slice(0,4)}static uint16ToInt16(e){return nt._dataView.setUint16(0,e,!0),nt._dataView.getInt16(0,!0)}static int16ToUint32(e){return nt._dataView.setInt16(0,e,!0),nt._dataView.getUint32(0,!0)}static int32ToUint16(e){return nt._dataView.setInt32(0,e,!0),nt._dataView.getUint16(0,!0)}static int32ToInt16(e){return nt._dataView.setInt32(0,e,!0),nt._dataView.getInt16(0,!0)}static int32ToUint32(e){return nt._dataView.setInt32(0,e,!0),nt._dataView.getUint32(0,!0)}static uint8ToInt8(e){return nt._dataView.setUint8(0,e),nt._dataView.getInt8(0)}}nt._conversionBuffer=new ArrayBuffer(8),nt._conversionByteArray=new Uint8Array(nt._conversionBuffer),nt._dataView=new DataView(nt._conversionBuffer);class ot{static readInt32BE(e){return e.readByte()<<24|e.readByte()<<16|e.readByte()<<8|e.readByte()}static readFloat32BE(e){const t=new Uint8Array(4);return e.read(t,0,t.length),t.reverse(),nt.bytesToFloat32LE(t)}static readFloat64BE(e){const t=new Uint8Array(8);return e.read(t,0,t.length),t.reverse(),nt.bytesToFloat64LE(t)}static readInt32LE(e){const t=e.readByte(),s=e.readByte(),i=e.readByte();return e.readByte()<<24|i<<16|s<<8|t}static readInt64LE(e){const t=new Uint8Array(8);return e.read(t,0,t.length),nt.bytesToInt64LE(t)}static readUInt32LE(e){const t=e.readByte(),s=e.readByte(),i=e.readByte();return e.readByte()<<24|i<<16|s<<8|t}static decodeUInt32LE(e,t){const s=e[t],i=e[t+1],a=e[t+2];return e[t+3]<<24|a<<16|i<<8|s}static readUInt16LE(e){const t=e.readByte(),s=e.readByte();return nt.int32ToUint16(s<<8|t)}static readInt16LE(e){const t=e.readByte(),s=e.readByte();return nt.int32ToInt16(s<<8|t)}static readUInt32BE(e){const t=e.readByte(),s=e.readByte(),i=e.readByte(),a=e.readByte();return nt.int32ToUint32(t<<24|s<<16|i<<8|a)}static readUInt16BE(e){const t=e.readByte(),s=e.readByte();return nt.int32ToInt16(t<<8|s)}static readInt16BE(e){const t=e.readByte(),s=e.readByte();return nt.int32ToInt16(t<<8|s)}static readByteArray(e,t){const s=new Uint8Array(t);return e.read(s,0,t),s}static read8BitChars(e,t){const s=new Uint8Array(t);return e.read(s,0,s.length),ot.toString(s,"utf-8")}static read8BitString(e){let t="",s=e.readByte();for(;0!==s;)t+=String.fromCharCode(s),s=e.readByte();return t}static read8BitStringLength(e,t){let s="",i=-1;for(let a=0;a<t;a++){const t=e.readByte();0===t&&-1===i&&(i=a),s+=String.fromCharCode(t)}const a=s;return i>=0?a.substr(0,i):a}static readSInt8(e){const t=e.readByte();return-256*((255&t)>>7)+(255&t)}static readInt24(e,t){let s=e[t]|e[t+1]<<8|e[t+2]<<16;return 8388608&~s||(s|=255<<24),s}static readInt16(e,t){return nt.int32ToInt16(e[t]|e[t+1]<<8)}static toString(e,t){const s=ot.detectEncoding(e);s&&(t=s),t||(t="utf-8");return new TextDecoder(t).decode(e.buffer)}static detectEncoding(e){return e.length>2&&254===e[0]&&255===e[1]?"utf-16be":e.length>2&&255===e[0]&&254===e[1]?"utf-16le":e.length>4&&0===e[0]&&0===e[1]&&254===e[2]&&255===e[3]?"utf-32be":e.length>4&&255===e[0]&&254===e[1]&&0===e[2]&&0===e[3]?"utf-32le":null}static stringToBytes(e){return(new TextEncoder).encode(e)}static writeInt32BE(e,t){e.writeByte(t>>24&255),e.writeByte(t>>16&255),e.writeByte(t>>8&255),e.writeByte(255&t)}static writeInt32LE(e,t){e.writeByte(255&t),e.writeByte(t>>8&255),e.writeByte(t>>16&255),e.writeByte(t>>24&255)}static writeUInt16LE(e,t){e.writeByte(255&t),e.writeByte(t>>8&255)}static writeInt16LE(e,t){e.writeByte(255&t),e.writeByte(t>>8&255)}static writeInt16BE(e,t){e.writeByte(t>>8&255),e.writeByte(255&t)}static writeFloat32BE(e,t){const s=nt.float32BEToBytes(t);e.write(s,0,s.length)}}class ht{constructor(){this.length=0,this.position=0}get bytesWritten(){return this.position}getBuffer(){return this._buffer}static empty(){return ht.withCapacity(0)}static withCapacity(e){const t=new ht;return t._buffer=new Uint8Array(e),t}static fromBuffer(e){const t=new ht;return t._buffer=e,t.length=e.length,t}static fromString(e){const t=ot.stringToBytes(e);return ht.fromBuffer(t)}reset(){this.position=0}skip(e){this.position+=e}readByte(){return this.length-this.position<=0?-1:this._buffer[this.position++]}read(e,t,s){let i=this.length-this.position;return i>s&&(i=s),i<=0?0:(e.set(this._buffer.subarray(this.position,this.position+i),t),this.position+=i,i)}writeByte(e){const t=this.position+1;this.ensureCapacity(t),this._buffer[this.position]=255&e,t>this.length&&(this.length=t),this.position=t}write(e,t,s){const i=this.position+s;this.ensureCapacity(i);const a=Math.min(s,e.length-t);this._buffer.set(e.subarray(t,t+a),this.position),i>this.length&&(this.length=i),this.position=i}ensureCapacity(e){if(e>this._buffer.length){let t=e;t<256&&(t=256),t<2*this._buffer.length&&(t=2*this._buffer.length);const s=new Uint8Array(t);this.length>0&&s.set(this._buffer.subarray(0,0+this.length),0),this._buffer=s}}readAll(){return this.toArray()}toArray(){const e=new Uint8Array(this.length);return e.set(this._buffer.subarray(0,0+this.length),0),e}copyTo(e){e.write(this._buffer,0,this.length)}}!function(e){e[e.TargetFine=0]="TargetFine",e[e.TargetSegno=1]="TargetSegno",e[e.TargetSegnoSegno=2]="TargetSegnoSegno",e[e.TargetCoda=3]="TargetCoda",e[e.TargetDoubleCoda=4]="TargetDoubleCoda",e[e.JumpDaCapo=5]="JumpDaCapo",e[e.JumpDaCapoAlCoda=6]="JumpDaCapoAlCoda",e[e.JumpDaCapoAlDoubleCoda=7]="JumpDaCapoAlDoubleCoda",e[e.JumpDaCapoAlFine=8]="JumpDaCapoAlFine",e[e.JumpDalSegno=9]="JumpDalSegno",e[e.JumpDalSegnoAlCoda=10]="JumpDalSegnoAlCoda",e[e.JumpDalSegnoAlDoubleCoda=11]="JumpDalSegnoAlDoubleCoda",e[e.JumpDalSegnoAlFine=12]="JumpDalSegnoAlFine",e[e.JumpDalSegnoSegno=13]="JumpDalSegnoSegno",e[e.JumpDalSegnoSegnoAlCoda=14]="JumpDalSegnoSegnoAlCoda",e[e.JumpDalSegnoSegnoAlDoubleCoda=15]="JumpDalSegnoSegnoAlDoubleCoda",e[e.JumpDalSegnoSegnoAlFine=16]="JumpDalSegnoSegnoAlFine",e[e.JumpDaCoda=17]="JumpDaCoda",e[e.JumpDaDoubleCoda=18]="JumpDaDoubleCoda"}(Be||(Be={})),function(e){e[e.Short=0]="Short",e[e.Medium=1]="Medium",e[e.Long=2]="Long"}(ke||(ke={}));class lt{constructor(){this.type=ke.Short,this.length=0}}!function(e){e[e.Up=0]="Up",e[e.Down=1]="Down"}(Te||(Te={})),function(e){e[e.No=0]="No",e[e.Eof=1]="Eof",e[e.Number=2]="Number",e[e.DoubleDot=3]="DoubleDot",e[e.Dot=4]="Dot",e[e.String=5]="String",e[e.Tuning=6]="Tuning",e[e.LParensis=7]="LParensis",e[e.RParensis=8]="RParensis",e[e.LBrace=9]="LBrace",e[e.RBrace=10]="RBrace",e[e.Pipe=11]="Pipe",e[e.MetaCommand=12]="MetaCommand",e[e.Multiply=13]="Multiply",e[e.LowerThan=14]="LowerThan"}(Ne||(Ne={})),function(e){e[e.KnownStaffMeta=0]="KnownStaffMeta",e[e.UnknownStaffMeta=1]="UnknownStaffMeta",e[e.EndOfMetaDetected=2]="EndOfMetaDetected"}(xe||(xe={}));class ct extends $e{constructor(e,t,s,i,a,r,n,o=null){super(Se.AlphaTex,e),this.position=t,this.line=s,this.col=i,this.nonTerm=a??"",this.expected=r??Ne.No,this.symbol=n??Ne.No,this.symbolData=o,Object.setPrototypeOf(this,ct.prototype)}static symbolError(e,t,s,i,a,r,n=null){let o=`MalFormed AlphaTex: @${e} (line ${t}, col ${s}): Error on block ${i}`;return a!==r?(o+=`, expected a ${Ne[a]} found a ${Ne[r]}`,null!==n&&(o+=`: '${n}'`)):o+=`, invalid value: '${n}'`,new ct(o,e,t,s,i,a,r,n)}static errorMessage(e,t,s,i){return new ct(e=`MalFormed AlphaTex: @${t} (line ${s}, col ${i}): ${e}`,t,s,i,null,null,null,null)}}!function(e){e[e.Auto=0]="Auto",e[e.Explicit=1]="Explicit"}(ve||(ve={}));class dt extends Ye{constructor(){super(...arguments),this._trackChannel=0,this._barIndex=0,this._voiceIndex=0,this._input="",this._ch=dt.Eof,this._curChPos=0,this._line=1,this._col=0,this._lastValidSpot=[0,1,0],this._sy=Ne.No,this._syData="",this._allowNegatives=!1,this._allowFloat=!1,this._allowTuning=!1,this._currentDuration=_.QuadrupleWhole,this._currentDynamics=g.PPP,this._currentTuplet=0,this._staffHasExplicitDisplayTransposition=!1,this._staffHasExplicitTuning=!1,this._staffTuningApplied=!1,this._percussionArticulationNames=new Map,this._sustainPedalToBeat=new Map,this._slurs=new Map,this._articulationValueToIndex=new Map,this._accidentalMode=ve.Explicit,this.logErrors=!1}get name(){return"AlphaTex"}initFromString(e,t){this.data=ht.empty(),this._input=e,this.settings=t,Je.resetIds()}readScore(){try{if(this.data.length>0&&(this._input=ot.toString(this.data.readAll(),this.settings.importer.encoding)),this._allowTuning=!0,this._lyrics=new Map,this._sustainPedalToBeat=new Map,this.createDefaultScore(),this._curChPos=0,this._line=1,this._col=0,this.saveValidSpot(),this._currentDuration=_.Quarter,this._currentDynamics=g.F,this._currentTuplet=1,this._ch=this.nextChar(),this._sy=this.newSy(),this._sy===Ne.LowerThan)throw new qe("Unknown start sign '<' (meant to import as XML?)");if(this._sy!==Ne.Eof){const e=this.metaData(),t=this.bars();if(!e&&!t)throw new qe("No alphaTex data found")}ie.consolidate(this._score),this._score.finish(this.settings),this._score.rebuildRepeatGroups();for(const[e,t]of this._lyrics)this._score.tracks[e].applyLyrics(t);for(const[e,t]of this._sustainPedalToBeat){const s=t.voice.bar.masterBar.calculateDuration();e.ratioPosition=t.playbackStart/s}return this._score}catch(e){if(e instanceof ct)throw new qe(e.message,e);throw e}}error(e,t,s=!0){let i,a=!1;s?(i=this._sy,i!==Ne.String&&i!==Ne.Number&&i!==Ne.MetaCommand||(a=!0)):i=t;const r=ct.symbolError(this._lastValidSpot[0],this._lastValidSpot[1],this._lastValidSpot[2],e,t,i,a?this._syData:null);throw this.logErrors&&q.error(this.name,r.message),r}errorMessage(e){const t=ct.errorMessage(e,this._lastValidSpot[0],this._lastValidSpot[1],this._lastValidSpot[2]);throw this.logErrors&&q.error(this.name,t.message),t}createDefaultScore(){this._score=new Je,this._score.tempo=120,this._score.tempoLabel="",this.newTrack()}newTrack(){this._currentTrack=new rt,this._currentTrack.ensureStaveCount(1),this._currentTrack.playbackInfo.program=25,this._currentTrack.playbackInfo.primaryChannel=this._trackChannel++,this._currentTrack.playbackInfo.secondaryChannel=this._trackChannel++;const e=this._currentTrack.staves[0];e.displayTranspositionPitch=0,e.stringTuning.tunings=st.getDefaultTuningFor(6).tunings,this._articulationValueToIndex.clear(),this.beginStaff(e),this._score.addTrack(this._currentTrack),this._lyrics.set(this._currentTrack.index,[]),this._currentDynamics=g.F}parseClefFromString(e){switch(e.toLowerCase()){case"g2":case"treble":default:return n.G2;case"f4":case"bass":return n.F4;case"c3":case"tenor":return n.C3;case"c4":case"alto":return n.C4;case"n":case"neutral":return n.Neutral}}parseClefFromInt(e){switch(e){case 43:default:return n.G2;case 65:return n.F4;case 48:return n.C3;case 60:return n.C4}}parseTripletFeelFromString(e){switch(e.toLowerCase()){case"no":case"none":default:return M.NoTripletFeel;case"t16":case"triplet-16th":return M.Triplet16th;case"t8":case"triplet-8th":return M.Triplet8th;case"d16":case"dotted-16th":return M.Dotted16th;case"d8":case"dotted-8th":return M.Dotted8th;case"s16":case"scottish-16th":return M.Scottish16th;case"s8":case"scottish-8th":return M.Scottish8th}}parseTripletFeelFromInt(e){switch(e){case 0:default:return M.NoTripletFeel;case 1:return M.Triplet16th;case 2:return M.Triplet8th;case 3:return M.Dotted16th;case 4:return M.Dotted8th;case 5:return M.Scottish16th;case 6:return M.Scottish8th}}parseKeySignature(e){switch(e.toLowerCase()){case"cb":case"cbmajor":case"abminor":return l.Cb;case"gb":case"gbmajor":case"ebminor":return l.Gb;case"db":case"dbmajor":case"bbminor":return l.Db;case"ab":case"abmajor":case"fminor":return l.Ab;case"eb":case"ebmajor":case"cminor":return l.Eb;case"bb":case"bbmajor":case"gminor":return l.Bb;case"f":case"fmajor":case"dminor":return l.F;case"c":case"cmajor":case"aminor":default:return l.C;case"g":case"gmajor":case"eminor":return l.G;case"d":case"dmajor":case"bminor":return l.D;case"a":case"amajor":case"f#minor":return l.A;case"e":case"emajor":case"c#minor":return l.E;case"b":case"bmajor":case"g#minor":return l.B;case"f#":case"f#major":case"d#minor":return l.FSharp;case"c#":case"c#major":case"a#minor":return l.CSharp}}parseKeySignatureType(e){return e.toLowerCase().endsWith("minor")?c.Minor:c.Major}nextChar(){return this._curChPos<this._input.length?(this._ch=this._input.charCodeAt(this._curChPos++),10===this._ch?(this._line++,this._col=0):this._col++):this._ch=dt.Eof,this._ch}saveValidSpot(){this._lastValidSpot=[this._curChPos,this._line,this._col]}newSy(){for(this.saveValidSpot(),this._sy=Ne.No;this._sy===Ne.No;)if(this._ch===dt.Eof)this._sy=Ne.Eof;else if(dt.isWhiteSpace(this._ch))this._ch=this.nextChar(),this.saveValidSpot();else if(47===this._ch){if(this._ch=this.nextChar(),47===this._ch)for(;13!==this._ch&&10!==this._ch&&this._ch!==dt.Eof;)this._ch=this.nextChar();else if(42===this._ch)for(;this._ch!==dt.Eof;)if(42===this._ch){if(this._ch=this.nextChar(),47===this._ch){this._ch=this.nextChar();break}}else this._ch=this.nextChar();else this.error("comment",Ne.String,!1);this.saveValidSpot()}else if(34===this._ch||39===this._ch){const e=this._ch;this._ch=this.nextChar();let t="";for(this._sy=Ne.String;this._ch!==e&&this._ch!==dt.Eof;)92===this._ch?(this._ch=this.nextChar(),92===this._ch?t+="\\":this._ch===e?t+=String.fromCharCode(this._ch):82===this._ch||114===this._ch?t+="\r":78===this._ch||110===this._ch?t+="\n":84===this._ch||116===this._ch?t+="\t":this.errorMessage("Unsupported escape sequence")):t+=String.fromCharCode(this._ch),this._ch=this.nextChar();this._ch===dt.Eof&&this.errorMessage("String opened but never closed"),this._syData=t,this._ch=this.nextChar()}else if(45===this._ch)this._allowNegatives?this.readNumberOrName():(this._sy=Ne.String,this._syData=this.readName());else if(46===this._ch)this._sy=Ne.Dot,this._ch=this.nextChar();else if(58===this._ch)this._sy=Ne.DoubleDot,this._ch=this.nextChar();else if(40===this._ch)this._sy=Ne.LParensis,this._ch=this.nextChar();else if(92===this._ch)this._ch=this.nextChar(),this._sy=Ne.MetaCommand,92===this._ch&&(this._ch=this.nextChar()),this._syData=this.readName();else if(41===this._ch)this._sy=Ne.RParensis,this._ch=this.nextChar();else if(123===this._ch)this._sy=Ne.LBrace,this._ch=this.nextChar();else if(125===this._ch)this._sy=Ne.RBrace,this._ch=this.nextChar();else if(124===this._ch)this._sy=Ne.Pipe,this._ch=this.nextChar();else if(42===this._ch)this._sy=Ne.Multiply,this._ch=this.nextChar();else if(60===this._ch)this._sy=Ne.LowerThan,this._ch=this.nextChar();else if(this.isDigit(this._ch))this.readNumberOrName();else if(dt.isNameLetter(this._ch)){const e=this.readName(),t=this._allowTuning?ie.parseTuning(e):null;t?(this._sy=Ne.Tuning,this._syData=t):(this._sy=Ne.String,this._syData=e)}else this.error("symbol",Ne.String,!1);return this._sy}readNumberOrName(){let e="",t=!0;do{e+=String.fromCharCode(this._ch),this.isDigit(this._ch)||(t=!1),this._ch=this.nextChar()}while(this.isDigit(this._ch)||dt.isNameLetter(this._ch));t?(this._sy=Ne.Number,this._syData=this._allowFloat?Number.parseFloat(e):Number.parseInt(e)):(this._sy=Ne.String,this._syData=e)}static isNameLetter(e){return!dt.isTerminal(e)&&(33<=e&&e<=47||58<=e&&e<=126||128<=e)}static isTerminal(e){return 46===e||123===e||125===e||91===e||93===e||40===e||41===e||124===e||39===e||34===e||42===e||92===e}static isWhiteSpace(e){return 9===e||10===e||11===e||13===e||32===e}isDigit(e){return e>=48&&e<=57||this._allowNegatives&&45===e||this._allowFloat&&46===e}readName(){let e="";do{e+=String.fromCharCode(this._ch),this._ch=this.nextChar()}while(dt.isNameLetter(this._ch)||this.isDigit(this._ch));return e}metaData(){let e=!1,t=!1,s=!0;for(;this._sy===Ne.MetaCommand&&s;){const i=this._syData.toLowerCase();switch(i){case"title":case"subtitle":case"artist":case"album":case"words":case"music":case"copyright":case"instructions":case"notices":case"tab":this._sy=this.newSy(),this._sy!==Ne.String&&this.error(i,Ne.String,!0);const a=this._syData;this._sy=this.newSy(),e=!0;let r=be.ChordDiagramList;switch(i){case"title":this._score.title=a,r=be.Title;break;case"subtitle":this._score.subTitle=a,r=be.SubTitle;break;case"artist":this._score.artist=a,r=be.Artist;break;case"album":this._score.album=a,r=be.Album;break;case"words":this._score.words=a,r=be.Words;break;case"music":this._score.music=a,r=be.Music;break;case"copyright":this._score.copyright=a,r=be.Copyright;break;case"instructions":this._score.instructions=a;break;case"notices":this._score.notices=a;break;case"tab":this._score.tab=a,r=be.Transcriber}r!==be.ChordDiagramList&&this.headerFooterStyle(r);break;case"copyright2":this._sy=this.newSy(),this._sy!==Ne.String&&this.error(i,Ne.String,!0),this.headerFooterStyle(be.CopyrightSecondLine),e=!0;break;case"wordsandmusic":this._sy=this.newSy(),this._sy!==Ne.String&&this.error(i,Ne.String,!0),this.headerFooterStyle(be.WordsAndMusic),e=!0;break;case"tempo":this._allowFloat=!0,this._sy=this.newSy(),this._allowFloat=!1,this._sy===Ne.Number?this._score.tempo=this._syData:this.error("tempo",Ne.Number,!0),this._sy=this.newSy(),this._sy===Ne.String&&(this._score.tempoLabel=this._syData,this._sy=this.newSy()),e=!0;break;case"defaultsystemslayout":this._sy=this.newSy(),this._sy===Ne.Number?(this._score.defaultSystemsLayout=this._syData,this._sy=this.newSy(),e=!0):this.error("default-systems-layout",Ne.Number,!0);break;case"systemslayout":for(this._sy=this.newSy(),e=!0;this._sy===Ne.Number;)this._score.systemsLayout.push(this._syData),this._sy=this.newSy();break;case"hidedynamics":this._score.stylesheet.hideDynamics=!0,this._sy=this.newSy(),e=!0;break;case"showdynamics":this._score.stylesheet.hideDynamics=!1,this._sy=this.newSy(),e=!0;break;case"bracketextendmode":this._sy=this.newSy(),this._sy!==Ne.String&&this.error("bracketExtendMode",Ne.String,!0),this._score.stylesheet.bracketExtendMode=this.parseBracketExtendMode(this._syData),this._sy=this.newSy(),e=!0;break;case"usesystemsignseparator":this._score.stylesheet.useSystemSignSeparator=!0,this._sy=this.newSy(),e=!0;break;case"multibarrest":this._score.stylesheet.multiTrackMultiBarRest=!0,this._sy=this.newSy(),e=!0;break;case"singletracktracknamepolicy":this._sy=this.newSy(),this._sy!==Ne.String&&this.error("singleTrackTrackNamePolicy",Ne.String,!0),this._score.stylesheet.singleTrackTrackNamePolicy=this.parseTrackNamePolicy(this._syData),this._sy=this.newSy(),e=!0;break;case"multitracktracknamepolicy":this._sy=this.newSy(),this._sy!==Ne.String&&this.error("multiTrackTrackNamePolicy",Ne.String,!0),this._score.stylesheet.multiTrackTrackNamePolicy=this.parseTrackNamePolicy(this._syData),this._sy=this.newSy(),e=!0;break;case"firstsystemtracknamemode":this._sy=this.newSy(),this._sy!==Ne.String&&this.error("firstSystemTrackNameMode",Ne.String,!0),this._score.stylesheet.firstSystemTrackNameMode=this.parseTrackNameMode(this._syData),this._sy=this.newSy(),e=!0;break;case"othersystemstracknamemode":this._sy=this.newSy(),this._sy!==Ne.String&&this.error("otherSystemsTrackNameMode",Ne.String,!0),this._score.stylesheet.otherSystemsTrackNameMode=this.parseTrackNameMode(this._syData),this._sy=this.newSy(),e=!0;break;case"firstsystemtracknameorientation":this._sy=this.newSy(),this._sy!==Ne.String&&this.error("firstSystemTrackNameOrientation",Ne.String,!0),this._score.stylesheet.firstSystemTrackNameOrientation=this.parseTrackNameOrientation(this._syData),this._sy=this.newSy(),e=!0;break;case"othersystemstracknameorientation":this._sy=this.newSy(),this._sy!==Ne.String&&this.error("otherSystemsTrackNameOrientation",Ne.String,!0),this._score.stylesheet.otherSystemsTrackNameOrientation=this.parseTrackNameOrientation(this._syData),this._sy=this.newSy(),e=!0;break;default:switch(this.handleStaffMeta()){case xe.KnownStaffMeta:t=!0;break;case xe.UnknownStaffMeta:e||t?this.error("metaDataTags",Ne.String,!1):s=!1;break;case xe.EndOfMetaDetected:s=!1}}}return e?(this._sy!==Ne.Dot&&this.error("song",Ne.Dot,!0),this._sy=this.newSy()):this._sy===Ne.Dot&&(this._sy=this.newSy(),e=!0),e||t}headerFooterStyle(e){const t=ie.getOrCreateHeaderFooterStyle(this._score,e);if(void 0===t.isVisible&&(t.isVisible=!0),this._sy===Ne.String){const e=this._syData;e?t.template=e:t.isVisible=!1,this._sy=this.newSy()}if(this._sy===Ne.String){switch(this._syData.toLowerCase()){case"left":t.textAlign=ne.Left;break;case"center":t.textAlign=ne.Center;break;case"right":t.textAlign=ne.Right}this._sy=this.newSy()}}parseTrackNamePolicy(e){switch(e.toLowerCase()){case"hidden":return i.Hidden;case"allsystems":return i.AllSystems;default:return i.FirstSystem}}parseTrackNameMode(e){return"fullname"===e.toLowerCase()?a.FullName:a.ShortName}parseTrackNameOrientation(e){return"horizontal"===e.toLowerCase()?r.Horizontal:r.Vertical}handleStaffMeta(){switch(this._syData.toLowerCase()){case"capo":return this._sy=this.newSy(),this._sy===Ne.Number?this._currentStaff.capo=this._syData:this.error("capo",Ne.Number,!0),this._sy=this.newSy(),xe.KnownStaffMeta;case"tuning":this._sy=this.newSy();const e=this._currentStaff.tuning.length;switch(this._staffHasExplicitTuning=!0,this._staffTuningApplied=!1,this._sy){case Ne.String:const e=this._syData.toLowerCase();"piano"===e||"none"===e||"voice"===e?this.makeCurrentStaffPitched():this.error("tuning",Ne.Tuning,!0),this._sy=this.newSy();break;case Ne.Tuning:const t=[];do{const e=this._syData;t.push(e.realValue),this._sy=this.newSy()}while(this._sy===Ne.Tuning);this._currentStaff.stringTuning.tunings=t;break;default:this.error("tuning",Ne.Tuning,!0)}return this._sy===Ne.String&&"hide"===this._syData.toLowerCase()&&(this._score.stylesheet.perTrackDisplayTuning||(this._score.stylesheet.perTrackDisplayTuning=new Map),this._score.stylesheet.perTrackDisplayTuning.set(this._currentTrack.index,!1),this._sy=this.newSy()),e!==this._currentStaff.tuning.length&&(this._currentStaff.chords?.size??0)>0&&this.errorMessage("Tuning must be defined before any chord"),xe.KnownStaffMeta;case"instrument":if(this._sy=this.newSy(),this._staffTuningApplied=!1,this._sy===Ne.Number){const e=this._syData;e>=0&&e<=127?this._currentTrack.playbackInfo.program=this._syData:this.error("instrument",Ne.Number,!1)}else if(this._sy===Ne.String){const e=this._syData.toLowerCase();if("percussion"===e){for(const e of this._currentTrack.staves)this.applyPercussionStaff(e);this._currentTrack.playbackInfo.primaryChannel=K.PercussionChannel,this._currentTrack.playbackInfo.secondaryChannel=K.PercussionChannel}else this._currentTrack.playbackInfo.program=A.getValue(e)}else this.error("instrument",Ne.Number,!0);return this._sy=this.newSy(),xe.KnownStaffMeta;case"lyrics":this._sy=this.newSy();const t=new Ke;return t.startBar=0,t.text="",this._sy===Ne.Number&&(t.startBar=this._syData,this._sy=this.newSy()),this._sy===Ne.String?(t.text=this._syData,this._sy=this.newSy()):this.error("lyrics",Ne.String,!0),this._lyrics.get(this._currentTrack.index).push(t),xe.KnownStaffMeta;case"chord":this._sy=this.newSy();const s=new je;this.chordProperties(s),this._sy===Ne.String?(s.name=this._syData,this._sy=this.newSy()):this.error("chord-name",Ne.String,!0);for(let e=0;e<this._currentStaff.tuning.length;e++)this._sy===Ne.Number?s.strings.push(this._syData):this._sy===Ne.String&&"x"===this._syData.toLowerCase()&&s.strings.push(-1),this._sy=this.newSy();return this._currentStaff.addChord(this.getChordId(this._currentStaff,s.name),s),xe.KnownStaffMeta;case"articulation":this._sy=this.newSy();let i="";if(this._sy===Ne.String?(i=this._syData,this._sy=this.newSy()):this.error("articulation-name",Ne.String,!0),"defaults"===i){for(const[e,t]of Le.instrumentArticulationNames)this._percussionArticulationNames.set(e.toLowerCase(),t),this._percussionArticulationNames.set(dt.toArticulationId(e),t);return xe.KnownStaffMeta}let a=0;return this._sy===Ne.Number?(a=this._syData,this._sy=this.newSy()):this.error("articulation-number",Ne.Number,!0),Le.instrumentArticulations.has(a)||this.errorMessage(`Unknown articulation ${a}. Refer to https://www.alphatab.net/docs/alphatex/percussion for available ids`),this._percussionArticulationNames.set(i.toLowerCase(),a),xe.KnownStaffMeta;case"accidentals":return this.handleAccidentalMode(),xe.KnownStaffMeta;case"displaytranspose":return this._allowNegatives=!0,this._sy=this.newSy(),this._sy===Ne.Number?(this._currentStaff.displayTranspositionPitch=-1*this._syData,this._staffHasExplicitDisplayTransposition=!0):this.error("displaytranspose",Ne.Number,!0),this._allowNegatives=!1,this._sy=this.newSy(),xe.KnownStaffMeta;case"transpose":return this._allowNegatives=!0,this._sy=this.newSy(),this._sy===Ne.Number?this._currentStaff.transpositionPitch=-1*this._syData:this.error("transpose",Ne.Number,!0),this._allowNegatives=!1,this._sy=this.newSy(),xe.KnownStaffMeta;case"track":case"staff":return xe.EndOfMetaDetected;case"voice":return this._sy=this.newSy(),this.handleNewVoice()?xe.EndOfMetaDetected:xe.KnownStaffMeta;default:return xe.UnknownStaffMeta}}handleAccidentalMode(){switch(this._sy=this.newSy(),this._sy!==Ne.String&&this.error("accidental-mode",Ne.String,!0),this._syData){case"auto":this._accidentalMode=ve.Auto;break;case"explicit":this._accidentalMode=ve.Explicit}this._sy=this.newSy()}makeCurrentStaffPitched(){this._currentStaff.stringTuning.tunings=[],this._staffHasExplicitDisplayTransposition||(this._currentStaff.displayTranspositionPitch=0)}static toArticulationId(e){return e.replace(/[^a-zA-Z0-9]/g,"").toLowerCase()}applyPercussionStaff(e){e.isPercussion=!0,e.showTablature=!1}chordProperties(e){if(this._sy===Ne.LBrace){for(this._sy=this.newSy();this._sy===Ne.String;)switch(this._syData.toLowerCase()){case"firstfret":if(this._sy=this.newSy(),this._sy===Ne.Number)e.firstFret=this._syData;else this.error("chord-firstfret",Ne.Number,!0);this._sy=this.newSy();break;case"showdiagram":switch(this._sy=this.newSy(),this._sy){case Ne.String:e.showDiagram="false"!==this._syData.toLowerCase();break;case Ne.Number:e.showDiagram=0!==this._syData;break;default:this.error("chord-showdiagram",Ne.String,!0)}this._sy=this.newSy();break;case"showfingering":switch(this._sy=this.newSy(),this._sy){case Ne.String:e.showDiagram="false"!==this._syData.toLowerCase();break;case Ne.Number:e.showFingering=0!==this._syData;break;default:this.error("chord-showfingering",Ne.String,!0)}this._sy=this.newSy();break;case"showname":switch(this._sy=this.newSy(),this._sy){case Ne.String:e.showName="false"!==this._syData.toLowerCase();break;case Ne.Number:e.showName=0!==this._syData;break;default:this.error("chord-showname",Ne.String,!0)}this._sy=this.newSy();break;case"barre":for(this._sy=this.newSy();this._sy===Ne.Number;)e.barreFrets.push(this._syData),this._sy=this.newSy();break;default:this.error("chord-properties",Ne.String,!1)}this._sy!==Ne.RBrace&&this.error("chord-properties",Ne.RBrace,!0),this._sy=this.newSy()}}bars(){const e=this.bar();for(;this._sy!==Ne.Eof;)if(this._sy===Ne.Pipe)this._sy=this.newSy(),this.bar();else{if(this._sy!==Ne.MetaCommand)break;this.bar()}return e}trackStaffMeta(){if(this._sy!==Ne.MetaCommand)return!1;if("track"===this._syData.toLowerCase()&&(this._staffHasExplicitDisplayTransposition=!1,this._staffHasExplicitTuning=!1,this._staffTuningApplied=!1,this._sy=this.newSy(),this._score.masterBars.length>0&&this.newTrack(),this._sy===Ne.String&&(this._currentTrack.name=this._syData,this._sy=this.newSy()),this._sy===Ne.String&&(this._currentTrack.shortName=this._syData,this._sy=this.newSy()),this.trackProperties()),this._sy===Ne.MetaCommand&&"staff"===this._syData.toLowerCase()){if(this._staffHasExplicitDisplayTransposition=!1,this._staffHasExplicitTuning=!1,this._staffTuningApplied=!1,this._sy=this.newSy(),this._currentTrack.staves[0].bars.length>0){const e=this._currentStaff.isPercussion;this._currentTrack.ensureStaveCount(this._currentTrack.staves.length+1),this.beginStaff(this._currentTrack.staves[this._currentTrack.staves.length-1]),e&&this.applyPercussionStaff(this._currentStaff),this._currentDynamics=g.F}this.staffProperties()}return this._sy===Ne.MetaCommand&&"voice"===this._syData.toLowerCase()&&(this._sy=this.newSy(),this.handleNewVoice()),!0}handleNewVoice(){if(0===this._voiceIndex&&(0===this._currentStaff.bars.length||1===this._currentStaff.bars.length&&this._currentStaff.bars[0].isEmpty))return!1;for(const e of this._currentStaff.bars){const t=new ee;e.addVoice(t)}return this._voiceIndex++,this._barIndex=0,!0}beginStaff(e){this._currentStaff=e,this._slurs.clear(),this._barIndex=0,this._voiceIndex=0}trackProperties(){if(this._sy===Ne.LBrace){for(this._sy=this.newSy();this._sy===Ne.String;)switch(this._syData.toLowerCase()){case"color":this._sy=this.newSy(),this._sy!==Ne.String&&this.error("track-color",Ne.String,!0),this._currentTrack.color=et.fromJson(this._syData),this._sy=this.newSy();break;case"defaultsystemslayout":this._sy=this.newSy(),this._sy===Ne.Number?(this._currentTrack.defaultSystemsLayout=this._syData,this._sy=this.newSy()):this.error("default-systems-layout",Ne.Number,!0);break;case"systemslayout":for(this._sy=this.newSy();this._sy===Ne.Number;)this._currentTrack.systemsLayout.push(this._syData),this._sy=this.newSy();break;case"volume":this._sy=this.newSy(),this._sy!==Ne.Number&&this.error("track-volume",Ne.Number,!0),this._currentTrack.playbackInfo.volume=ie.clamp(this._syData,0,16),this._sy=this.newSy();break;case"balance":this._sy=this.newSy(),this._sy!==Ne.Number&&this.error("track-balance",Ne.Number,!0),this._currentTrack.playbackInfo.balance=ie.clamp(this._syData,0,16),this._sy=this.newSy();break;case"mute":this._sy=this.newSy(),this._currentTrack.playbackInfo.isMute=!0;break;case"solo":this._sy=this.newSy(),this._currentTrack.playbackInfo.isSolo=!0;break;case"multibarrest":this._sy=this.newSy(),this._score.stylesheet.perTrackMultiBarRest||(this._score.stylesheet.perTrackMultiBarRest=new Set),this._score.stylesheet.perTrackMultiBarRest.add(this._currentTrack.index);break;default:this.error("track-properties",Ne.String,!1)}this._sy!==Ne.RBrace&&this.error("track-properties",Ne.RBrace,!0),this._sy=this.newSy()}}staffProperties(){if(this._sy!==Ne.LBrace)return;this._sy=this.newSy();let e=!1,t=!1,s=!1,i=!1;for(;this._sy===Ne.String;)switch(this._syData.toLowerCase()){case"score":e=!0,this._sy=this.newSy(),this._sy===Ne.Number&&(this._currentStaff.standardNotationLineCount=this._syData,this._sy=this.newSy());break;case"tabs":t=!0,this._sy=this.newSy();break;case"slash":s=!0,this._sy=this.newSy();break;case"numbered":i=!0,this._sy=this.newSy();break;default:this.error("staff-properties",Ne.String,!1)}(e||t||s||i)&&(this._currentStaff.showStandardNotation=e,this._currentStaff.showTablature=t,this._currentStaff.showSlash=s,this._currentStaff.showNumbered=i),this._sy!==Ne.RBrace&&this.error("staff-properties",Ne.RBrace,!0),this._sy=this.newSy()}bar(){const e=this.trackStaffMeta(),t=this.newBar(this._currentStaff);if(this._currentStaff.bars.length>this._score.masterBars.length){const e=new j;this._score.addMasterBar(e),e.index>0&&(e.timeSignatureDenominator=e.previousMasterBar.timeSignatureDenominator,e.timeSignatureNumerator=e.previousMasterBar.timeSignatureNumerator,e.tripletFeel=e.previousMasterBar.tripletFeel)}const s=this.barMeta(t),i=this._currentTrack.playbackInfo.program;this._staffTuningApplied||this._staffHasExplicitTuning||(this._currentStaff.stringTuning.tunings=[],15===i||i>=24&&i<=31?this._currentStaff.stringTuning.tunings=st.getDefaultTuningFor(6).tunings:i>=32&&i<=39?this._currentStaff.stringTuning.tunings=[43,38,33,28]:40===i||44===i||45===i||48===i||49===i||50===i||51===i?this._currentStaff.stringTuning.tunings=[52,57,50,43]:41===i?this._currentStaff.stringTuning.tunings=[57,50,43,36]:42===i?this._currentStaff.stringTuning.tunings=[45,38,31,24]:43===i?this._currentStaff.stringTuning.tunings=[43,38,33,28]:105===i?this._currentStaff.stringTuning.tunings=[50,47,43,38,55]:106===i?this._currentStaff.stringTuning.tunings=[57,52,45]:107===i?this._currentStaff.stringTuning.tunings=[52,45,38,31]:110===i&&(this._currentStaff.stringTuning.tunings=[64,57,50,43]),this._staffTuningApplied=!0),this._staffHasExplicitDisplayTransposition||(this._currentStaff.displayTranspositionPitch=i>=24&&i<=31||i>=32&&i<=39||43===i?-12:0);let a=!1;const r=t.voices[this._voiceIndex];if(!(this._sy===Ne.MetaCommand&&("track"===this._syData.toLowerCase()||"staff"===this._syData.toLowerCase())))for(;this._sy!==Ne.Pipe&&this._sy!==Ne.Eof&&this.beat(r);)a=!0;if(0===r.beats.length){const e=new ze;e.isEmpty=!0,r.addBeat(e)}return e||s||a}newBar(e){if(this._barIndex<e.bars.length){const t=e.bars[this._barIndex];return this._barIndex++,t}const t=0===e.bars.length?1:e.bars[0].voices.length,s=new G;e.addBar(s),s.previousBar&&(s.clef=s.previousBar.clef,s.clefOttava=s.previousBar.clefOttava,s.keySignature=s.previousBar.keySignature,s.keySignatureType=s.previousBar.keySignatureType),this._barIndex++;for(let e=0;e<t;e++){const e=new ee;s.addVoice(e)}return s}beat(e){this.beatDuration();const t=new ze;if(e.addBeat(t),this._allowTuning=!this._currentStaff.isPercussion,this._sy===Ne.LParensis){for(this._sy=this.newSy(),this.note(t);this._sy!==Ne.RParensis&&this._sy!==Ne.Eof&&(this._allowTuning=!this._currentStaff.isPercussion,this.note(t)););this._sy!==Ne.RParensis&&this.error("note-list",Ne.RParensis,!0),this._sy=this.newSy()}else if(this._sy===Ne.String&&"r"===this._syData.toLowerCase())this._sy=this.newSy();else if(!this.note(t))return e.beats.splice(e.beats.length-1,1),!1;this._sy===Ne.Dot&&(this._allowNegatives=!0,this._sy=this.newSy(),this._allowNegatives=!1,this._sy!==Ne.Number&&this.error("duration",Ne.Number,!0),this._currentDuration=this.parseDuration(this._syData),this._sy=this.newSy()),t.duration=this._currentDuration,t.dynamics=this._currentDynamics,1===this._currentTuplet||t.hasTuplet||dt.applyTuplet(t,this._currentTuplet);let s=1;this._sy===Ne.Multiply&&(this._sy=this.newSy(),this._sy!==Ne.Number?this.error("multiplier",Ne.Number,!0):s=this._syData,this._sy=this.newSy()),this.beatEffects(t);for(let i=0;i<s-1;i++)e.addBeat(Ve.clone(t));return!0}beatDuration(){if(this._sy===Ne.DoubleDot&&(this._allowNegatives=!0,this._sy=this.newSy(),this._allowNegatives=!1,this._sy!==Ne.Number&&this.error("duration",Ne.Number,!0),this._currentDuration=this.parseDuration(this._syData),this._currentTuplet=1,this._sy=this.newSy(),this._sy===Ne.LBrace)){for(this._sy=this.newSy();this._sy===Ne.String;){if("tu"===this._syData.toLowerCase())this._sy=this.newSy(),this._sy!==Ne.Number&&this.error("duration-tuplet",Ne.Number,!0),this._currentTuplet=this._syData,this._sy=this.newSy();else this.error("beat-duration",Ne.String,!1)}this._sy!==Ne.RBrace&&this.error("beat-duration",Ne.RBrace,!0),this._sy=this.newSy()}}beatEffects(e){if(this._sy===Ne.LBrace){for(this._sy=this.newSy();this._sy===Ne.String;)this.applyBeatEffect(e)||this.error("beat-effects",Ne.String,!1);this._sy!==Ne.RBrace&&this.error("beat-effects",Ne.RBrace,!0),this._sy=this.newSy()}}applyBeatEffect(e){const t=this._syData.toLowerCase();if("f"===t)e.fade=ue.FadeIn;else if("fo"===t)e.fade=ue.FadeOut;else if("vs"===t)e.fade=ue.VolumeSwell;else if("v"===t)e.vibrato=P.Slight;else if("vw"===t)e.vibrato=P.Wide;else if("s"===t)e.slap=!0;else if("p"===t)e.pop=!0;else if("tt"===t)e.tap=!0;else if("txt"===t){if(this._sy=this.newSy(),this._sy!==Ne.String)return this.error("beat-text",Ne.String,!0),!1;e.text=this._syData}else if("dd"===t)e.dots=2;else if("d"===t)e.dots=1;else if("su"===t)e.pickStroke=ae.Up;else if("sd"===t)e.pickStroke=ae.Down;else{if("tu"===t){if(this._sy=this.newSy(),this._sy!==Ne.Number)return this.error("tuplet",Ne.Number,!0),!1;const t=this._syData;if(this._sy=this.newSy(),this._sy===Ne.Number){const s=this._syData;this._sy=this.newSy(),e.tupletNumerator=t,e.tupletDenominator=s}else dt.applyTuplet(e,t);return!0}if("tb"===t||"tbe"===t){this._sy=this.newSy();const s="tbe"===t;for(this._sy===Ne.String&&(e.whammyBarType=this.parseWhammyType(this._syData),this._sy=this.newSy()),this._sy===Ne.String&&(e.whammyStyle=this.parseBendStyle(this._syData),this._sy=this.newSy()),this._sy!==Ne.LParensis&&this.error("tremolobar-effect",Ne.LParensis,!0),this._allowNegatives=!0,this._allowFloat=!0,this._sy=this.newSy();this._sy!==Ne.RParensis&&this._sy!==Ne.Eof;){let t=0,i=0;s?(this._sy!==Ne.Number&&this.error("tremolobar-effect",Ne.Number,!0),t=this._syData,this._sy=this.newSy(),this._sy!==Ne.Number&&this.error("tremolobar-effect",Ne.Number,!0),i=this._syData):(this._sy!==Ne.Number&&this.error("tremolobar-effect",Ne.Number,!0),t=0,i=this._syData),e.addWhammyBarPoint(new X(t,i)),this._sy=this.newSy()}if(null!=e.whammyBarPoints){for(;e.whammyBarPoints.length>60;)e.removeWhammyBarPoint(e.whammyBarPoints.length-1);if(s)e.whammyBarPoints.sort(((e,t)=>e.offset-t.offset));else{const t=e.whammyBarPoints.length,s=60/t|0;let i=0;for(;i<t;)e.whammyBarPoints[i].offset=Math.min(60,i*s),i++}}this._allowNegatives=!1,this._allowFloat=!1,this._sy!==Ne.RParensis&&this.error("tremolobar-effect",Ne.RParensis,!0)}else{if("bu"===t||"bd"===t||"au"===t||"ad"===t){switch(t){case"bu":e.brushType=b.BrushUp;break;case"bd":e.brushType=b.BrushDown;break;case"au":e.brushType=b.ArpeggioUp;break;case"ad":e.brushType=b.ArpeggioDown}return this._sy=this.newSy(),this._sy===Ne.Number?(e.brushDuration=this._syData,this._sy=this.newSy(),!0):(e.updateDurations(),"bu"===t||"bd"===t?e.brushDuration=e.playbackDuration/4/e.notes.length:"au"!==t&&"ad"!==t||(e.brushDuration=e.playbackDuration/e.notes.length),!0)}if("ch"===t){this._sy=this.newSy();const t=this._syData,s=this.getChordId(this._currentStaff,t);if(!this._currentStaff.hasChord(s)){const e=new je;e.showDiagram=!1,e.name=t,this._currentStaff.addChord(s,e)}e.chordId=s}else{if("gr"===t)return this._sy=this.newSy(),"ob"===this._syData.toLowerCase()?(e.graceType=w.OnBeat,this._sy=this.newSy()):"b"===this._syData.toLowerCase()?(e.graceType=w.BendGrace,this._sy=this.newSy()):e.graceType=w.BeforeBeat,!0;if("dy"===t){this._sy=this.newSy();const t=this._syData.toUpperCase();switch(t){case"PPP":case"PP":case"P":case"MP":case"MF":case"F":case"FF":case"FFF":case"PPPP":case"PPPPP":case"PPPPPP":case"FFFF":case"FFFFF":case"FFFFFF":case"SF":case"SFP":case"SFPP":case"FP":case"RF":case"RFZ":case"SFZ":case"SFFZ":case"FZ":case"N":case"PF":case"SFZP":e.dynamics=g[t]}this._currentDynamics=e.dynamics}else if("cre"===t)e.crescendo=S.Crescendo;else if("dec"===t)e.crescendo=S.Decrescendo;else{if("tempo"===t){const t=this.readTempoAutomation();return e.automations.push(t),e.voice.bar.masterBar.tempoAutomations.push(t),!0}if("tp"===t){if(this._sy=this.newSy(),e.tremoloSpeed=_.Eighth,this._sy===Ne.Number){switch(this._syData){case 8:default:e.tremoloSpeed=_.Eighth;break;case 16:e.tremoloSpeed=_.Sixteenth;break;case 32:e.tremoloSpeed=_.ThirtySecond}this._sy=this.newSy()}return!0}if("spd"===t){const t=new W;return t.pedalType=d.Down,t.ratioPosition=e.voice.bar.sustainPedals.length,this._sustainPedalToBeat.set(t,e),e.voice.bar.sustainPedals.push(t),this._sy=this.newSy(),!0}if("spu"===t){const t=new W;return t.pedalType=d.Up,t.ratioPosition=e.voice.bar.sustainPedals.length,this._sustainPedalToBeat.set(t,e),e.voice.bar.sustainPedals.push(t),this._sy=this.newSy(),!0}if("spe"===t){const t=new W;return t.pedalType=d.Up,t.ratioPosition=1,e.voice.bar.sustainPedals.push(t),this._sy=this.newSy(),!0}if("slashed"===t)return e.slashed=!0,this._sy=this.newSy(),!0;if("ds"===t)return e.deadSlapped=!0,this._sy=this.newSy(),!0;if("glpf"===t)return this._sy=this.newSy(),e.golpe=de.Finger,!0;if("glpt"===t)return this._sy=this.newSy(),e.golpe=de.Thumb,!0;if("waho"===t)return this._sy=this.newSy(),e.wahPedal=pe.Open,!0;if("wahc"===t)return this._sy=this.newSy(),e.wahPedal=pe.Closed,!0;if("barre"===t){if(this._sy=this.newSy(),this._sy!==Ne.Number&&this.error("beat-barre",Ne.Number,!0),e.barreFret=this._syData,e.barreShape=ge.Full,this._sy=this.newSy(),this._sy===Ne.String)switch(this._syData.toLowerCase()){case"full":e.barreShape=ge.Full,this._sy=this.newSy();break;case"half":e.barreShape=ge.Half,this._sy=this.newSy()}return!0}if("rasg"===t){switch(this._sy=this.newSy(),this._sy!==Ne.String&&this.error("rasgueado",Ne.String,!0),this._syData.toLowerCase()){case"ii":e.rasgueado=me.Ii;break;case"mi":e.rasgueado=me.Mi;break;case"miitriplet":e.rasgueado=me.MiiTriplet;break;case"miianapaest":e.rasgueado=me.MiiAnapaest;break;case"pmptriplet":e.rasgueado=me.PmpTriplet;break;case"pmpanapaest":e.rasgueado=me.PmpAnapaest;break;case"peitriplet":e.rasgueado=me.PeiTriplet;break;case"peianapaest":e.rasgueado=me.PeiAnapaest;break;case"paitriplet":e.rasgueado=me.PaiTriplet;break;case"paianapaest":e.rasgueado=me.PaiAnapaest;break;case"amitriplet":e.rasgueado=me.AmiTriplet;break;case"amianapaest":e.rasgueado=me.AmiAnapaest;break;case"ppp":e.rasgueado=me.Ppp;break;case"amii":e.rasgueado=me.Amii;break;case"amip":e.rasgueado=me.Amip;break;case"eami":e.rasgueado=me.Eami;break;case"eamii":e.rasgueado=me.Eamii;break;case"peami":e.rasgueado=me.Peami}return this._sy=this.newSy(),!0}if("ot"===t)this._sy=this.newSy(),this._sy!==Ne.String&&this.error("beat-ottava",Ne.String,!0),e.ottava=this.parseClefOttavaFromString(this._syData);else if("legatoorigin"===t)e.isLegatoOrigin=!0;else{if("instrument"!==t){if("fermata"===t){this._sy=this.newSy(),this._sy!==Ne.String&&this.error("fermata",Ne.Number,!0);const t=new lt;return t.type=this.parseFermataFromString(this._syData),this._allowFloat=!0,this._sy=this.newSy(),this._sy===Ne.Number&&(t.length=this._syData,this._sy=this.newSy()),this._allowFloat=!1,e.fermata=t,!0}if("beam"===t){switch(this._sy=this.newSy(),this._sy!==Ne.String&&this.error("beam",Ne.Number,!0),this._syData.toLowerCase()){case"invert":e.invertBeamDirection=!0;break;case"up":e.preferredBeamDirection=Te.Up;break;case"down":e.preferredBeamDirection=Te.Down;break;case"auto":e.beamingMode=fe.Auto;break;case"split":e.beamingMode=fe.ForceSplitToNext;break;case"merge":e.beamingMode=fe.ForceMergeWithNext;break;case"splitsecondary":e.beamingMode=fe.ForceSplitOnSecondaryToNext}return this._sy=this.newSy(),!0}return"timer"===t&&(e.showTimer=!0,this._sy=this.newSy(),!0)}{this._sy=this.newSy();let t=0;this._sy===Ne.Number?t=this._syData:this._sy===Ne.String?t=A.getValue(this._syData):this.error("instrument-change",Ne.Number,!0);const s=new U;s.isLinear=!1,s.type=m.Instrument,s.value=t,e.automations.push(s)}}}}}}return this._sy=this.newSy(),!0}parseBracketExtendMode(e){switch(e.toLowerCase()){case"nobrackets":return s.NoBrackets;case"groupstaves":default:return s.GroupStaves;case"groupsimilarinstruments":return s.GroupSimilarInstruments}}parseFermataFromString(e){switch(e.toLowerCase()){case"short":return ke.Short;case"medium":default:return ke.Medium;case"long":return ke.Long}}parseClefOttavaFromString(e){switch(e.toLowerCase()){case"15ma":return o._15ma;case"8va":return o._8va;case"regular":default:return o.Regular;case"8vb":return o._8vb;case"15mb":return o._15mb}}getChordId(e,t){return t.toLowerCase()+e.index+e.track.index}static applyTuplet(e,t){switch(t){case 3:e.tupletNumerator=3,e.tupletDenominator=2;break;case 5:e.tupletNumerator=5,e.tupletDenominator=4;break;case 6:e.tupletNumerator=6,e.tupletDenominator=4;break;case 7:e.tupletNumerator=7,e.tupletDenominator=4;break;case 9:e.tupletNumerator=9,e.tupletDenominator=8;break;case 10:e.tupletNumerator=10,e.tupletDenominator=8;break;case 11:e.tupletNumerator=11,e.tupletDenominator=8;break;case 12:e.tupletNumerator=12,e.tupletDenominator=8;break;default:e.tupletNumerator=1,e.tupletDenominator=1}}isNoteText(e){return"x"===e||"-"===e||"r"===e}note(e){let t=!1,s=!1,i=-1,a=-1,r=-1,n=N.Default;switch(this._sy){case Ne.Number:i=this._syData,this._currentStaff.isPercussion&&!Le.instrumentArticulations.has(i)&&this.errorMessage(`Unknown percussion articulation ${i}`);break;case Ne.String:if(this._currentStaff.isPercussion){const e=this._syData.toLowerCase();this._percussionArticulationNames.has(e)?i=this._percussionArticulationNames.get(e):this.errorMessage(`Unknown percussion articulation '${this._syData}'`)}else t="x"===this._syData,s="-"===this._syData,s||t?i=0:this.error("note-fret",Ne.Number,!0);break;case Ne.Tuning:0===e.index&&0===e.voice.index&&0===e.voice.bar.index&&this.makeCurrentStaffPitched();const o=this._syData;a=o.octave,r=o.tone.noteValue,this._accidentalMode===ve.Explicit&&(n=o.tone.accidentalMode);break;default:return!1}this._sy=this.newSy();const o=-1===a&&this._currentStaff.tuning.length>0&&!this._currentStaff.isPercussion;let h=-1;o&&(this._sy!==Ne.Dot&&this.error("note",Ne.Dot,!0),this._sy=this.newSy(),this._sy!==Ne.Number&&this.error("note-string",Ne.Number,!0),h=this._syData,(h<1||h>this._currentStaff.tuning.length)&&this.error("note-string",Ne.Number,!1),this._sy=this.newSy());const l=new Ae;if(o)l.string=this._currentStaff.tuning.length-(h-1),l.isDead=t,l.isTieDestination=s,s||(l.fret=i);else if(this._currentStaff.isPercussion){const e=i;let t=0;if(this._articulationValueToIndex.has(e))t=this._articulationValueToIndex.get(e);else{t=this._currentTrack.percussionArticulations.length;const s=Le.getArticulationByInputMidiNumber(e);null===s&&this.errorMessage(`Unknown articulation value ${e}`),this._currentTrack.percussionArticulations.push(s),this._articulationValueToIndex.set(e,t)}l.percussionArticulation=t}else l.octave=a,l.tone=r,l.accidentalMode=n,l.isTieDestination=s;return e.addNote(l),this.noteEffects(l),!0}noteEffects(e){if(this._sy===Ne.LBrace){for(this._sy=this.newSy();this._sy===Ne.String;){const t=this._syData.toLowerCase();if("b"===t||"be"===t){this._sy=this.newSy();const s="be"===t;for(this._sy===Ne.String&&(e.bendType=this.parseBendType(this._syData),this._sy=this.newSy()),this._sy===Ne.String&&(e.bendStyle=this.parseBendStyle(this._syData),this._sy=this.newSy()),this._sy!==Ne.LParensis&&this.error("bend-effect",Ne.LParensis,!0),this._sy=this.newSy();this._sy!==Ne.RParensis&&this._sy!==Ne.Eof;){let t=0,i=0;s?(this._sy!==Ne.Number&&this.error("bend-effect-value",Ne.Number,!0),t=this._syData,this._sy=this.newSy(),this._sy!==Ne.Number&&this.error("bend-effect-value",Ne.Number,!0),i=this._syData):(this._sy!==Ne.Number&&this.error("bend-effect-value",Ne.Number,!0),i=this._syData),e.addBendPoint(new X(t,i)),this._sy=this.newSy()}const i=e.bendPoints;if(null!=i){for(;i.length>60;)i.splice(i.length-1,1);if(s)i.sort(((e,t)=>e.offset-t.offset));else{const e=i.length,t=60/(e-1)|0;let s=0;for(;s<e;)i[s].offset=Math.min(60,s*t),s++}}this._sy!==Ne.RParensis&&this.error("bend-effect",Ne.RParensis,!0),this._sy=this.newSy()}else if("nh"===t)e.harmonicType=T.Natural,e.harmonicValue=ie.deltaFretToHarmonicValue(e.fret),this._sy=this.newSy();else if("ah"===t)e.harmonicType=T.Artificial,e.harmonicValue=this.harmonicValue(e.harmonicValue);else if("th"===t)e.harmonicType=T.Tap,e.harmonicValue=this.harmonicValue(e.harmonicValue);else if("ph"===t)e.harmonicType=T.Pinch,e.harmonicValue=this.harmonicValue(e.harmonicValue);else if("sh"===t)e.harmonicType=T.Semi,e.harmonicValue=this.harmonicValue(e.harmonicValue);else if("fh"===t)e.harmonicType=T.Feedback,e.harmonicValue=this.harmonicValue(e.harmonicValue);else if("tr"===t){this._sy=this.newSy(),this._sy!==Ne.Number&&this.error("trill-effect",Ne.Number,!0);const t=this._syData;this._sy=this.newSy();let s=_.Sixteenth;if(this._sy===Ne.Number){switch(this._syData){case 16:default:s=_.Sixteenth;break;case 32:s=_.ThirtySecond;break;case 64:s=_.SixtyFourth}this._sy=this.newSy()}e.trillValue=t+e.stringTuning,e.trillSpeed=s}else if("v"===t)this._sy=this.newSy(),e.vibrato=P.Slight;else if("sl"===t)this._sy=this.newSy(),e.slideOutType=v.Legato;else if("ss"===t)this._sy=this.newSy(),e.slideOutType=v.Shift;else if("sib"===t)this._sy=this.newSy(),e.slideInType=x.IntoFromBelow;else if("sia"===t)this._sy=this.newSy(),e.slideInType=x.IntoFromAbove;else if("sou"===t)this._sy=this.newSy(),e.slideOutType=v.OutUp;else if("sod"===t)this._sy=this.newSy(),e.slideOutType=v.OutDown;else if("psd"===t)this._sy=this.newSy(),e.slideOutType=v.PickSlideDown;else if("psu"===t)this._sy=this.newSy(),e.slideOutType=v.PickSlideUp;else if("h"===t)this._sy=this.newSy(),e.isHammerPullOrigin=!0;else if("lht"===t)this._sy=this.newSy(),e.isLeftHandTapped=!0;else if("g"===t)this._sy=this.newSy(),e.isGhost=!0;else if("ac"===t)this._sy=this.newSy(),e.accentuated=B.Normal;else if("hac"===t)this._sy=this.newSy(),e.accentuated=B.Heavy;else if("ten"===t)this._sy=this.newSy(),e.accentuated=B.Tenuto;else if("pm"===t)this._sy=this.newSy(),e.isPalmMute=!0;else if("st"===t)this._sy=this.newSy(),e.isStaccato=!0;else if("lr"===t)this._sy=this.newSy(),e.isLetRing=!0;else if("x"===t)this._sy=this.newSy(),e.fret=0,e.isDead=!0;else if("-"===t||"t"===t)this._sy=this.newSy(),e.isTieDestination=!0;else if("lf"===t){this._sy=this.newSy();let t=k.Thumb;this._sy===Ne.Number&&(t=this.toFinger(this._syData),this._sy=this.newSy()),e.leftHandFinger=t}else if("rf"===t){this._sy=this.newSy();let t=k.Thumb;this._sy===Ne.Number&&(t=this.toFinger(this._syData),this._sy=this.newSy()),e.rightHandFinger=t}else if("acc"===t)this._sy=this.newSy(),this._sy!==Ne.String&&this.error("note-accidental",Ne.String,!0),e.accidentalMode=ie.parseAccidentalMode(this._syData),this._sy=this.newSy();else if("turn"===t)this._sy=this.newSy(),e.ornament=he.Turn;else if("iturn"===t)this._sy=this.newSy(),e.ornament=he.InvertedTurn;else if("umordent"===t)this._sy=this.newSy(),e.ornament=he.UpperMordent;else if("lmordent"===t)this._sy=this.newSy(),e.ornament=he.LowerMordent;else if("string"===t)this._sy=this.newSy(),e.showStringNumber=!0;else if("hide"===t)this._sy=this.newSy(),e.isVisible=!1;else if("slur"===t){this._sy=this.newSy(),this._sy!==Ne.String&&this.error("slur",Ne.String,!0);const t=this._syData;if(this._slurs.has(t)){const s=this._slurs.get(t);s.slurDestination=e,e.slurOrigin=s,e.isSlurDestination=!0}else this._slurs.set(t,e);this._sy=this.newSy()}else this.applyBeatEffect(e.beat)||this.error(t,Ne.String,!1)}this._sy!==Ne.RBrace&&this.error("note-effect",Ne.RBrace,!1),this._sy=this.newSy()}}harmonicValue(e){return this._allowNegatives=!0,this._allowFloat=!0,this._sy=this.newSy(),this._sy===Ne.Number&&(e=this._syData,this._sy=this.newSy()),this._allowNegatives=!1,this._allowFloat=!1,e}toFinger(e){switch(e){case 1:return k.Thumb;case 2:return k.IndexFinger;case 3:return k.MiddleFinger;case 4:return k.AnnularFinger;case 5:return k.LittleFinger}return k.Thumb}parseDuration(e){switch(e){case-4:return _.QuadrupleWhole;case-2:return _.DoubleWhole;case 1:return _.Whole;case 2:return _.Half;case 4:return _.Quarter;case 8:return _.Eighth;case 16:return _.Sixteenth;case 32:return _.ThirtySecond;case 64:return _.SixtyFourth;case 128:return _.OneHundredTwentyEighth;case 256:return _.TwoHundredFiftySixth;default:return _.Quarter}}parseBendStyle(e){switch(e.toLowerCase()){case"gradual":return f.Gradual;case"fast":return f.Fast;default:return f.Default}}parseBendType(e){switch(e.toLowerCase()){case"none":return y.None;case"custom":default:return y.Custom;case"bend":return y.Bend;case"release":return y.Release;case"bendrelease":return y.BendRelease;case"hold":return y.Hold;case"prebend":return y.Prebend;case"prebendbend":return y.PrebendBend;case"prebendrelease":return y.PrebendRelease}}barMeta(e){let t=!1;const s=e.masterBar;let i=!1;for(;!i&&this._sy===Ne.MetaCommand;){t=!0;const a=this._syData.toLowerCase();if("ts"===a)this._sy=this.newSy(),this._sy===Ne.String?"common"===this._syData.toLowerCase()?(s.timeSignatureCommon=!0,s.timeSignatureNumerator=4,s.timeSignatureDenominator=4,this._sy=this.newSy()):this.error("timesignature-numerator",Ne.String,!0):(this._sy!==Ne.Number&&this.error("timesignature-numerator",Ne.Number,!0),s.timeSignatureNumerator=this._syData,this._sy=this.newSy(),this._sy!==Ne.Number&&this.error("timesignature-denominator",Ne.Number,!0),s.timeSignatureDenominator=this._syData,this._sy=this.newSy());else if("ft"===a)s.isFreeTime=!0,this._sy=this.newSy();else if("ro"===a)s.isRepeatStart=!0,this._sy=this.newSy();else if("rc"===a)this._sy=this.newSy(),this._sy!==Ne.Number&&this.error("repeatclose",Ne.Number,!0),this._syData>2048&&this.error("repeatclose",Ne.Number,!1),s.repeatCount=this._syData,this._sy=this.newSy();else if("ae"===a)if(this._sy=this.newSy(),this._sy===Ne.LParensis){for(this._sy=this.newSy(),this._sy!==Ne.Number&&this.error("alternateending",Ne.Number,!0),this.applyAlternateEnding(s);this._sy===Ne.Number;)this.applyAlternateEnding(s);this._sy!==Ne.RParensis&&this.error("alternateending-list",Ne.RParensis,!0),this._sy=this.newSy()}else this._sy!==Ne.Number&&this.error("alternateending",Ne.Number,!0),this.applyAlternateEnding(s);else if("ks"===a)this._sy=this.newSy(),this._sy!==Ne.String&&this.error("keysignature",Ne.String,!0),e.keySignature=this.parseKeySignature(this._syData),e.keySignatureType=this.parseKeySignatureType(this._syData),this._sy=this.newSy();else if("clef"===a){switch(this._sy=this.newSy(),this._sy){case Ne.String:e.clef=this.parseClefFromString(this._syData);break;case Ne.Number:e.clef=this.parseClefFromInt(this._syData);break;case Ne.Tuning:const t=this._syData;e.clef=this.parseClefFromInt(t.realValue);break;default:this.error("clef",Ne.String,!0)}this._sy=this.newSy()}else if("tempo"===a){const e=this.readTempoAutomation();s.tempoAutomations.push(e)}else if("section"===a){this._sy=this.newSy(),this._sy!==Ne.String&&this.error("section",Ne.String,!0);let e=this._syData;this._sy=this.newSy();let t="";this._sy!==Ne.String||this.isNoteText(this._syData.toLowerCase())||(t=e,e=this._syData,this._sy=this.newSy());const i=new Qe;i.marker=t,i.text=e,s.section=i}else if("tf"===a){switch(this._allowTuning=!1,this._sy=this.newSy(),this._allowTuning=!0,this._sy){case Ne.String:s.tripletFeel=this.parseTripletFeelFromString(this._syData);break;case Ne.Number:s.tripletFeel=this.parseTripletFeelFromInt(this._syData);break;default:this.error("triplet-feel",Ne.String,!0)}this._sy=this.newSy()}else if("ac"===a)s.isAnacrusis=!0,this._sy=this.newSy();else if("db"===a)s.isDoubleBar=!0,e.barLineRight=p.LightLight,this._sy=this.newSy();else if("barlineleft"===a)this._sy=this.newSy(),this._sy!==Ne.String&&this.error("barlineleft",Ne.String,!0),e.barLineLeft=this.parseBarLineStyle(this._syData),this._sy=this.newSy();else if("barlineright"===a)this._sy=this.newSy(),this._sy!==Ne.String&&this.error("barlineright",Ne.String,!0),e.barLineRight=this.parseBarLineStyle(this._syData),this._sy=this.newSy();else if("accidentals"===a)this.handleAccidentalMode();else if("jump"===a)this.handleDirections(s);else if("ottava"===a)this._sy=this.newSy(),this._sy!==Ne.String&&this.error("ottava",Ne.String,!0),e.clefOttava=this.parseClefOttavaFromString(this._syData),this._sy=this.newSy();else if("simile"===a)this._sy=this.newSy(),this._sy!==Ne.String&&this.error("simile",Ne.String,!0),e.simileMark=this.parseSimileMarkFromString(this._syData),this._sy=this.newSy();else if("scale"===a)this._allowFloat=!0,this._sy=this.newSy(),this._allowFloat=!1,this._sy!==Ne.Number&&this.error("scale",Ne.Number,!0),s.displayScale=this._syData,e.displayScale=this._syData,this._sy=this.newSy();else if("width"===a)this._sy=this.newSy(),this._sy!==Ne.Number&&this.error("width",Ne.Number,!0),s.displayWidth=this._syData,e.displayWidth=this._syData,this._sy=this.newSy();else if(0===e.index)switch(this.handleStaffMeta()){case xe.KnownStaffMeta:break;case xe.UnknownStaffMeta:this.error("measure-effects",Ne.String,!1);break;case xe.EndOfMetaDetected:i=!0}else if(this.handleStaffMeta()===xe.EndOfMetaDetected)i=!0;else this.error("measure-effects",Ne.String,!1)}if(0===s.index&&0===s.tempoAutomations.length){const e=new U;e.isLinear=!1,e.type=m.Tempo,e.value=this._score.tempo,e.text=this._score.tempoLabel,s.tempoAutomations.push(e)}return t}parseBarLineStyle(e){switch(e.toLowerCase()){case"automatic":return p.Automatic;case"dashed":return p.Dashed;case"dotted":return p.Dotted;case"heavy":return p.Heavy;case"heavyheavy":return p.HeavyHeavy;case"heavylight":return p.HeavyLight;case"lightheavy":return p.LightHeavy;case"lightlight":return p.LightLight;case"none":return p.None;case"regular":return p.Regular;case"short":return p.Short;case"tick":return p.Tick}return p.Automatic}parseSimileMarkFromString(e){switch(e.toLowerCase()){case"none":default:return h.None;case"simple":return h.Simple;case"firstofdouble":return h.FirstOfDouble;case"secondofdouble":return h.SecondOfDouble}}handleDirections(e){switch(this._sy=this.newSy(),this._sy!==Ne.String&&this.error("direction",Ne.String,!0),this._syData.toLowerCase()){case"fine":e.addDirection(Be.TargetFine);break;case"segno":e.addDirection(Be.TargetSegno);break;case"segnosegno":e.addDirection(Be.TargetSegnoSegno);break;case"coda":e.addDirection(Be.TargetCoda);break;case"doublecoda":e.addDirection(Be.TargetDoubleCoda);break;case"dacapo":e.addDirection(Be.JumpDaCapo);break;case"dacapoalcoda":e.addDirection(Be.JumpDaCapoAlCoda);break;case"dacapoaldoublecoda":e.addDirection(Be.JumpDaCapoAlDoubleCoda);break;case"dacapoalfine":e.addDirection(Be.JumpDaCapoAlFine);break;case"dalsegno":e.addDirection(Be.JumpDalSegno);break;case"dalsegnoalcoda":e.addDirection(Be.JumpDalSegnoAlCoda);break;case"dalsegnoaldoublecoda":e.addDirection(Be.JumpDalSegnoAlDoubleCoda);break;case"dalsegnoalfine":e.addDirection(Be.JumpDalSegnoAlFine);break;case"dalsegnosegno":e.addDirection(Be.JumpDalSegnoSegno);break;case"dalsegnosegnoalcoda":e.addDirection(Be.JumpDalSegnoSegnoAlCoda);break;case"dalsegnosegnoaldoublecoda":e.addDirection(Be.JumpDalSegnoSegnoAlDoubleCoda);break;case"dalsegnosegnoalfine":e.addDirection(Be.JumpDalSegnoSegnoAlFine);break;case"dacoda":e.addDirection(Be.JumpDaCoda);break;case"dadoublecoda":e.addDirection(Be.JumpDaDoubleCoda);break;default:return void this.errorMessage(`Unexpected direction value: '${this._syData}'`)}this._sy=this.newSy()}readTempoAutomation(){this._allowFloat=!0,this._sy=this.newSy(),this._allowFloat=!1,this._sy!==Ne.Number&&this.error("tempo",Ne.Number,!0);const e=new U;return e.isLinear=!1,e.type=m.Tempo,e.value=this._syData,this._sy=this.newSy(),this._sy===Ne.String&&(e.text=this._syData,this._sy=this.newSy()),e}applyAlternateEnding(e){const t=this._syData;t<1&&this.error("alternateending",Ne.Number,!0),e.alternateEndings|=1<<t-1,this._sy=this.newSy()}parseWhammyType(e){switch(e.toLowerCase()){case"none":return ce.None;case"custom":default:return ce.Custom;case"dive":return ce.Dive;case"dip":return ce.Dip;case"hold":return ce.Hold;case"predive":return ce.Predive;case"predivedive":return ce.PrediveDive}}}dt.Eof=0;class ut extends Ye{constructor(){super(...arguments),this._versionNumber=0,this._globalTripletFeel=M.NoTripletFeel,this._lyricsTrack=0,this._lyrics=[],this._barCount=0,this._trackCount=0,this._playbackInfos=[],this._doubleBars=new Set,this._keySignatures=new Map,this._beatTextChunksByTrack=new Map,this._directionLookup=new Map}get name(){return"Guitar Pro 3-5"}readScore(){if(this._directionLookup.clear(),this.readVersion(),this._score=new Je,this.readScoreInformation(),this._versionNumber<500&&(this._globalTripletFeel=pt.gpReadBool(this.data)?M.Triplet8th:M.NoTripletFeel),this._versionNumber>=400&&this.readLyrics(),this._versionNumber>=510&&this.data.skip(19),this._versionNumber>=500&&(this.readPageSetup(),this._score.tempoLabel=pt.gpReadStringIntByte(this.data,this.settings.importer.encoding)),this._score.tempo=ot.readInt32LE(this.data),this._versionNumber>=510&&pt.gpReadBool(this.data),ot.readInt32LE(this.data),this._versionNumber>=400&&this.data.readByte(),this.readPlaybackInfos(),this._versionNumber>=500&&(this.readDirection(Be.TargetCoda),this.readDirection(Be.TargetDoubleCoda),this.readDirection(Be.TargetSegno),this.readDirection(Be.TargetSegnoSegno),this.readDirection(Be.TargetFine),this.readDirection(Be.JumpDaCapo),this.readDirection(Be.JumpDaCapoAlCoda),this.readDirection(Be.JumpDaCapoAlDoubleCoda),this.readDirection(Be.JumpDaCapoAlFine),this.readDirection(Be.JumpDalSegno),this.readDirection(Be.JumpDalSegnoAlCoda),this.readDirection(Be.JumpDalSegnoAlDoubleCoda),this.readDirection(Be.JumpDalSegnoAlFine),this.readDirection(Be.JumpDalSegnoSegno),this.readDirection(Be.JumpDalSegnoSegnoAlCoda),this.readDirection(Be.JumpDalSegnoSegnoAlDoubleCoda),this.readDirection(Be.JumpDalSegnoSegnoAlFine),this.readDirection(Be.JumpDaCoda),this.readDirection(Be.JumpDaDoubleCoda),this.data.skip(4)),this._barCount=ot.readInt32LE(this.data),this._trackCount=ot.readInt32LE(this.data),this.readMasterBars(),this.readTracks(),this.readBars(),this._score.masterBars.length>0){const e=U.buildTempoAutomation(!1,0,this._score.tempo,2);e.text=this._score.tempoLabel,this._score.masterBars[0].tempoAutomations.push(e)}return ie.consolidate(this._score),this._score.finish(this.settings),this._lyrics&&this._lyricsTrack>=0&&this._score.tracks[this._lyricsTrack].applyLyrics(this._lyrics),this._score}readDirection(e){let t,s=ot.readInt16LE(this.data);-1!==s&&(s--,this._directionLookup.has(s)?t=this._directionLookup.get(s):(t=[],this._directionLookup.set(s,t)),t.push(e))}readVersion(){let e=pt.gpReadStringByteLength(this.data,30,this.settings.importer.encoding);if(!e.startsWith(ut.VersionString))throw new qe("Unsupported format");e=e.substr(ut.VersionString.length+1);const t=e.indexOf(String.fromCharCode(46));this._versionNumber=100*Number.parseInt(e.substr(0,t))+Number.parseInt(e.substr(t+1)),q.debug(this.name,`Guitar Pro version ${e} detected`)}readScoreInformation(){this._score.title=pt.gpReadStringIntUnused(this.data,this.settings.importer.encoding),this._score.subTitle=pt.gpReadStringIntUnused(this.data,this.settings.importer.encoding),this._score.artist=pt.gpReadStringIntUnused(this.data,this.settings.importer.encoding),this._score.album=pt.gpReadStringIntUnused(this.data,this.settings.importer.encoding),this._score.words=pt.gpReadStringIntUnused(this.data,this.settings.importer.encoding),this._score.music=this._versionNumber>=500?pt.gpReadStringIntUnused(this.data,this.settings.importer.encoding):this._score.words,this._score.copyright=pt.gpReadStringIntUnused(this.data,this.settings.importer.encoding),this._score.tab=pt.gpReadStringIntUnused(this.data,this.settings.importer.encoding),this._score.instructions=pt.gpReadStringIntUnused(this.data,this.settings.importer.encoding);const e=ot.readInt32LE(this.data);let t="";for(let s=0;s<e;s++)s>0&&(t+="\r\n"),t+=pt.gpReadStringIntUnused(this.data,this.settings.importer.encoding)?.toString();this._score.notices=t}readLyrics(){this._lyrics=[],this._lyricsTrack=ot.readInt32LE(this.data)-1;for(let e=0;e<5;e++){const e=new Ke;e.startBar=ot.readInt32LE(this.data)-1,e.text=pt.gpReadStringInt(this.data,this.settings.importer.encoding),this._lyrics.push(e)}}readPageSetup(){this.data.skip(28);const e=ot.readInt16LE(this.data);ie.getOrCreateHeaderFooterStyle(this._score,be.Title).isVisible=!!(1&e),ie.getOrCreateHeaderFooterStyle(this._score,be.Title).template=pt.gpReadStringIntByte(this.data,this.settings.importer.encoding),ie.getOrCreateHeaderFooterStyle(this._score,be.SubTitle).isVisible=!!(2&e),ie.getOrCreateHeaderFooterStyle(this._score,be.SubTitle).template=pt.gpReadStringIntByte(this.data,this.settings.importer.encoding),ie.getOrCreateHeaderFooterStyle(this._score,be.Artist).isVisible=!!(4&e),ie.getOrCreateHeaderFooterStyle(this._score,be.Artist).template=pt.gpReadStringIntByte(this.data,this.settings.importer.encoding),ie.getOrCreateHeaderFooterStyle(this._score,be.Album).isVisible=!!(8&e),ie.getOrCreateHeaderFooterStyle(this._score,be.Album).template=pt.gpReadStringIntByte(this.data,this.settings.importer.encoding),ie.getOrCreateHeaderFooterStyle(this._score,be.Words).isVisible=!!(16&e),ie.getOrCreateHeaderFooterStyle(this._score,be.Words).template=pt.gpReadStringIntByte(this.data,this.settings.importer.encoding),ie.getOrCreateHeaderFooterStyle(this._score,be.Music).isVisible=!!(32&e),ie.getOrCreateHeaderFooterStyle(this._score,be.Music).template=pt.gpReadStringIntByte(this.data,this.settings.importer.encoding),ie.getOrCreateHeaderFooterStyle(this._score,be.WordsAndMusic).isVisible=!!(64&e),ie.getOrCreateHeaderFooterStyle(this._score,be.WordsAndMusic).template=pt.gpReadStringIntByte(this.data,this.settings.importer.encoding),ie.getOrCreateHeaderFooterStyle(this._score,be.Copyright).isVisible=!!(128&e),ie.getOrCreateHeaderFooterStyle(this._score,be.Copyright).template=pt.gpReadStringIntByte(this.data,this.settings.importer.encoding),ie.getOrCreateHeaderFooterStyle(this._score,be.CopyrightSecondLine).isVisible=!!(128&e),ie.getOrCreateHeaderFooterStyle(this._score,be.CopyrightSecondLine).template=pt.gpReadStringIntByte(this.data,this.settings.importer.encoding),pt.gpReadStringIntByte(this.data,this.settings.importer.encoding)}readPlaybackInfos(){this._playbackInfos=[];let e=0;for(let t=0;t<64;t++){const t=new tt;t.primaryChannel=e++,t.secondaryChannel=e++,t.program=ot.readInt32LE(this.data),t.volume=this.data.readByte(),t.balance=this.data.readByte(),this.data.skip(6),this._playbackInfos.push(t)}}readMasterBars(){for(let e=0;e<this._barCount;e++)this.readMasterBar()}readMasterBar(){let e=null;this._score.masterBars.length>0&&(e=this._score.masterBars[this._score.masterBars.length-1]);const t=new j,s=this.data.readByte();if(1&s?t.timeSignatureNumerator=this.data.readByte():e&&(t.timeSignatureNumerator=e.timeSignatureNumerator),2&s?t.timeSignatureDenominator=this.data.readByte():e&&(t.timeSignatureDenominator=e.timeSignatureDenominator),t.isRepeatStart=!!(4&s),8&s&&(t.repeatCount=this.data.readByte()+(this._versionNumber>=500?0:1)),16&s&&this._versionNumber<500){let s=e,i=0;for(;s&&(!s.isRepeatEnd||s===e)&&!s.isRepeatStart;)i|=s.alternateEndings,s=s.previousMasterBar;let a=0;const r=this.data.readByte();for(let e=0;e<8;e++){const t=1<<e;r>e&&!(i&t)&&(a|=t)}t.alternateEndings=a}if(32&s){const e=new Qe;e.text=pt.gpReadStringIntByte(this.data,this.settings.importer.encoding),e.marker="",pt.gpReadColor(this.data,!1),t.section=e}if(64&s&&this._keySignatures.set(this._score.masterBars.length,[ot.readSInt8(this.data),this.data.readByte()]),this._versionNumber>=500&&3&s&&this.data.skip(4),this._versionNumber>=500&&(t.alternateEndings=this.data.readByte()),this._versionNumber>=500){switch(this.data.readByte()){case 1:t.tripletFeel=M.Triplet8th;break;case 2:t.tripletFeel=M.Triplet16th}this.data.readByte()}else t.tripletFeel=this._globalTripletFeel;const i=!!(128&s);t.isDoubleBar=i;const a=this._score.masterBars.length;if(this._directionLookup.has(a))for(const e of this._directionLookup.get(a))t.addDirection(e);this._score.addMasterBar(t),i&&this._doubleBars.add(t.index)}readTracks(){for(let e=0;e<this._trackCount;e++)this.readTrack()}readTrack(){const e=new rt;e.ensureStaveCount(1),this._score.addTrack(e);const t=e.staves[0],s=this.data.readByte();e.name=pt.gpReadStringByteLength(this.data,40,this.settings.importer.encoding),1&s&&(t.isPercussion=!0),this._versionNumber>=500&&(e.isVisibleOnMultiTrack=!!(8&s)),null===this._score.stylesheet.perTrackDisplayTuning&&(this._score.stylesheet.perTrackDisplayTuning=new Map),this._score.stylesheet.perTrackDisplayTuning.set(e.index,!!(128&s));const i=ot.readInt32LE(this.data),a=[];for(let e=0;e<7;e++){const t=ot.readInt32LE(this.data);i>e&&a.push(t)}t.stringTuning.tunings=a;const r=ot.readInt32LE(this.data),n=ot.readInt32LE(this.data)-1,o=ot.readInt32LE(this.data)-1;if(this.data.skip(4),n>=0&&n<this._playbackInfos.length){const i=this._playbackInfos[n];i.port=r,i.isSolo=!!(16&s),i.isMute=!!(32&s),i.secondaryChannel=o,A.isGuitar(i.program)&&(t.displayTranspositionPitch=-12),e.playbackInfo=i}if(t.capo=ot.readInt32LE(this.data),e.color=pt.gpReadColor(this.data,!1),this._versionNumber>=500){const s=this.data.readByte();t.showTablature=!!(1&s),t.showStandardNotation=!!(2&s);const i=!!(100&s);null===this._score.stylesheet.perTrackChordDiagramsOnTop&&(this._score.stylesheet.perTrackChordDiagramsOnTop=new Map),this._score.stylesheet.perTrackChordDiagramsOnTop.set(e.index,i),this.data.readByte(),this.data.skip(43)}this._versionNumber>=510&&(this.data.skip(4),pt.gpReadStringIntByte(this.data,this.settings.importer.encoding),pt.gpReadStringIntByte(this.data,this.settings.importer.encoding))}readBars(){for(let e=0;e<this._barCount;e++)for(let e=0;e<this._trackCount;e++)this.readBar(this._score.tracks[e])}readBar(e){const t=new G,s=e.staves[0];if(s.isPercussion&&(t.clef=n.Neutral),s.addBar(t),this._keySignatures.has(t.index)){const e=this._keySignatures.get(t.index);t.keySignature=e[0],t.keySignatureType=e[1]}else t.index>0&&(t.keySignature=t.previousBar.keySignature,t.keySignatureType=t.previousBar.keySignatureType);this._doubleBars.has(t.index)&&(t.barLineRight=p.LightLight);let i=1;this._versionNumber>=500&&(this.data.readByte(),i=2);for(let s=0;s<i;s++)this.readVoice(e,t)}readVoice(e,t){const s=ot.readInt32LE(this.data);if(0===s)return;const i=new ee;t.addVoice(i);for(let a=0;a<s;a++)this.readBeat(e,t,i)}readBeat(e,t,s){const i=new ze,a=this.data.readByte();if(1&a&&(i.dots=1),64&a){const e=this.data.readByte();i.isEmpty=!(2&e)}s.addBeat(i);switch(ot.readSInt8(this.data)){case-2:i.duration=_.Whole;break;case-1:i.duration=_.Half;break;case 0:i.duration=_.Quarter;break;case 1:i.duration=_.Eighth;break;case 2:i.duration=_.Sixteenth;break;case 3:i.duration=_.ThirtySecond;break;case 4:i.duration=_.SixtyFourth;break;default:i.duration=_.Quarter}if(32&a)switch(i.tupletNumerator=ot.readInt32LE(this.data),i.tupletNumerator){case 1:i.tupletDenominator=1;break;case 3:i.tupletDenominator=2;break;case 5:case 6:case 7:i.tupletDenominator=4;break;case 9:case 10:case 11:case 12:case 13:i.tupletDenominator=8;break;case 2:case 4:case 8:break;default:i.tupletNumerator=1,i.tupletDenominator=1}2&a&&this.readChord(i);const r=this.settings.importer.beatTextAsLyrics&&e.index!==this._lyricsTrack;if(4&a){const t=pt.gpReadStringIntUnused(this.data,this.settings.importer.encoding);if(r){const s=new Ke;s.text=t.trim(),s.finish(!0);const i=[];for(let e=s.chunks.length-1;e>=0;e--)i.push(s.chunks[e]);this._beatTextChunksByTrack.set(e.index,i)}else i.text=t}let n=T.None;8&a&&(n=this.readBeatEffects(i)),16&a&&this.readMixTableChange(i);const h=this.data.readByte();for(let a=6;a>=0;a--)if(h&1<<a&&6-a<t.staff.tuning.length){const r=this.readNote(e,t,s,i,6-a);n!==T.None&&(r.harmonicType=n,r.harmonicType===T.Natural&&(r.harmonicValue=ie.deltaFretToHarmonicValue(r.fret)))}if(this._versionNumber>=500){const e=ot.readInt16LE(this.data);if(1&e&&i.index>0&&(s.beats[i.index-1].beamingMode=fe.ForceSplitToNext),2&e&&(i.preferredBeamDirection=Te.Down),4&e&&i.index>0&&(s.beats[i.index-1].beamingMode=fe.ForceMergeWithNext),8&e&&(i.preferredBeamDirection=Te.Up),16&e&&(i.ottava=o._8va),32&e&&(i.ottava=o._8vb),64&e&&(i.ottava=o._15ma),256&e&&(i.ottava=o._15mb),2048&e){const e=0!==this.data.readByte();i.index>0&&e&&(s.beats[i.index-1].beamingMode=fe.ForceSplitOnSecondaryToNext)}}r&&!i.isRest&&this._beatTextChunksByTrack.has(e.index)&&this._beatTextChunksByTrack.get(e.index).length>0&&(i.lyrics=[this._beatTextChunksByTrack.get(e.index).pop()])}readChord(e){const t=new je,s=ie.newGuid();if(this._versionNumber>=500){this.data.skip(17),t.name=pt.gpReadStringByteLength(this.data,21,this.settings.importer.encoding),this.data.skip(4),t.firstFret=ot.readInt32LE(this.data);for(let s=0;s<7;s++){const i=ot.readInt32LE(this.data);s<e.voice.bar.staff.tuning.length&&t.strings.push(i)}const s=this.data.readByte(),i=new Uint8Array(5);this.data.read(i,0,i.length);for(let e=0;e<s;e++)t.barreFrets.push(i[e]);this.data.skip(26)}else if(0!==this.data.readByte())if(this._versionNumber>=400){this.data.skip(16),t.name=pt.gpReadStringByteLength(this.data,21,this.settings.importer.encoding),this.data.skip(4),t.firstFret=ot.readInt32LE(this.data);for(let s=0;s<7;s++){const i=ot.readInt32LE(this.data);s<e.voice.bar.staff.tuning.length&&t.strings.push(i)}const s=this.data.readByte(),i=new Uint8Array(5);this.data.read(i,0,i.length);for(let e=0;e<s;e++)t.barreFrets.push(i[e]);this.data.skip(26)}else{this.data.skip(25),t.name=pt.gpReadStringByteLength(this.data,34,this.settings.importer.encoding),t.firstFret=ot.readInt32LE(this.data);for(let s=0;s<6;s++){const i=ot.readInt32LE(this.data);s<e.voice.bar.staff.tuning.length&&t.strings.push(i)}this.data.skip(36)}else{const s=this._versionNumber>=406?7:6;if(t.name=pt.gpReadStringIntByte(this.data,this.settings.importer.encoding),t.firstFret=ot.readInt32LE(this.data),t.firstFret>0)for(let i=0;i<s;i++){const s=ot.readInt32LE(this.data);i<e.voice.bar.staff.tuning.length&&t.strings.push(s)}}t.name&&(e.chordId=s,e.voice.bar.staff.addChord(e.chordId,t))}readBeatEffects(e){const t=this.data.readByte();let s=0;if(this._versionNumber>=400&&(s=this.data.readByte()),16&t&&(e.fade=ue.FadeIn),(this._versionNumber<400&&1&t||2&t)&&(e.vibrato=P.Slight),1&s&&(e.rasgueado=me.Ii),32&t&&this._versionNumber>=400){switch(ot.readSInt8(this.data)){case 1:e.tap=!0;break;case 2:e.slap=!0;break;case 3:e.pop=!0}}else if(32&t){switch(ot.readSInt8(this.data)){case 1:e.tap=!0;break;case 2:e.slap=!0;break;case 3:e.pop=!0}this.data.skip(4)}if(4&s&&this.readTremoloBarEffect(e),64&t){let t=0,s=0;this._versionNumber<500?(s=this.data.readByte(),t=this.data.readByte()):(t=this.data.readByte(),s=this.data.readByte()),t>0?(e.brushType=b.BrushUp,e.brushDuration=ut.toStrokeValue(t)):s>0&&(e.brushType=b.BrushDown,e.brushDuration=ut.toStrokeValue(s))}if(2&s)switch(ot.readSInt8(this.data)){case 0:e.pickStroke=ae.None;break;case 1:e.pickStroke=ae.Up;break;case 2:e.pickStroke=ae.Down}if(this._versionNumber<400){if(4&t)return T.Natural;if(8&t)return T.Artificial}return T.None}readTremoloBarEffect(e){this.data.readByte(),ot.readInt32LE(this.data);const t=ot.readInt32LE(this.data);if(t>0)for(let s=0;s<t;s++){const t=new X(0,0);t.offset=ot.readInt32LE(this.data),t.value=ot.readInt32LE(this.data)/ut.BendStep|0,pt.gpReadBool(this.data),e.addWhammyBarPoint(t)}}static toStrokeValue(e){switch(e){case 1:case 2:return 30;case 3:return 60;case 4:return 120;case 5:return 240;case 6:return 480;default:return 0}}readMixTableChange(e){const t=new gt;t.instrument=ot.readSInt8(this.data),this._versionNumber>=500&&this.data.skip(16),t.volume=ot.readSInt8(this.data),t.balance=ot.readSInt8(this.data);const s=ot.readSInt8(this.data),i=ot.readSInt8(this.data),a=ot.readSInt8(this.data),r=ot.readSInt8(this.data);if(this._versionNumber>=500&&(t.tempoName=pt.gpReadStringIntByte(this.data,this.settings.importer.encoding)),t.tempo=ot.readInt32LE(this.data),t.volume>=0&&this.data.readByte(),t.balance>=0&&this.data.readByte(),s>=0&&this.data.readByte(),i>=0&&this.data.readByte(),a>=0&&this.data.readByte(),r>=0&&this.data.readByte(),t.tempo>=0&&(t.duration=ot.readSInt8(this.data),this._versionNumber>=510&&this.data.readByte()),this._versionNumber>=400&&this.data.readByte(),this._versionNumber>=500){const t=ot.readSInt8(this.data);t>=100?e.wahPedal=pe.Closed:t>=0&&(e.wahPedal=pe.Open)}if(this._versionNumber>=510&&(pt.gpReadStringIntByte(this.data,this.settings.importer.encoding),pt.gpReadStringIntByte(this.data,this.settings.importer.encoding)),t.volume>=0){const s=new U;s.isLinear=!0,s.type=m.Volume,s.value=t.volume,e.automations.push(s)}if(t.balance>=0){const s=new U;s.isLinear=!0,s.type=m.Balance,s.value=t.balance,e.automations.push(s)}if(t.instrument>=0){const s=new U;s.isLinear=!0,s.type=m.Instrument,s.value=t.instrument,e.automations.push(s)}if(t.tempo>=0){const s=new U;s.isLinear=!0,s.type=m.Tempo,s.value=t.tempo,e.automations.push(s),e.voice.bar.masterBar.tempoAutomations.push(s)}}readNote(e,t,s,i,a){const r=new Ae;r.string=t.staff.tuning.length-a;const n=this.data.readByte();if(2&n?r.accentuated=B.Heavy:64&n&&(r.accentuated=B.Normal),r.isGhost=!!(4&n),32&n){const e=this.data.readByte();3===e?r.isDead=!0:2===e&&(r.isTieDestination=!0)}if(1&n&&this._versionNumber<500&&(this.data.readByte(),this.data.readByte()),16&n){const e=ot.readSInt8(this.data);r.dynamics=this.toDynamicValue(e),i.dynamics=r.dynamics}32&n&&(r.fret=ot.readSInt8(this.data)),128&n&&(r.leftHandFinger=ot.readSInt8(this.data),r.rightHandFinger=ot.readSInt8(this.data));let o=!1;if(this._versionNumber>=500){1&n&&(r.durationPercent=ot.readFloat64BE(this.data));o=!!(2&this.data.readByte())}if(i.addNote(r),8&n&&this.readNoteEffects(e,s,i,r),t.staff.isPercussion&&(r.percussionArticulation=r.fret,r.string=-1,r.fret=-1),o){const e=st.defaultAccidentals[r.realValueWithoutHarmonic%12];"#"===e?r.accidentalMode=N.ForceFlat:"b"===e&&(r.accidentalMode=N.ForceSharp)}return r}toDynamicValue(e){switch(e){case 1:return g.PPP;case 2:return g.PP;case 3:return g.P;case 4:return g.MP;case 5:return g.MF;case 6:default:return g.F;case 7:return g.FF;case 8:return g.FFF}}readNoteEffects(e,t,s,i){const a=this.data.readByte();let r=0;this._versionNumber>=400&&(r=this.data.readByte()),1&a&&this.readBend(i),16&a&&this.readGrace(t,i),4&r&&this.readTremoloPicking(s),8&r?this.readSlide(i):this._versionNumber<400&&4&a&&(i.slideOutType=v.Shift),16&r&&this.readArtificialHarmonic(i),32&r&&this.readTrill(i),i.isLetRing=!!(8&a),i.isHammerPullOrigin=!!(2&a),64&r&&(i.vibrato=P.Slight),i.isPalmMute=!!(2&r),i.isStaccato=!!(1&r)}readBend(e){this.data.readByte(),ot.readInt32LE(this.data);const t=ot.readInt32LE(this.data);if(t>0)for(let s=0;s<t;s++){const t=new X(0,0);t.offset=ot.readInt32LE(this.data),t.value=ot.readInt32LE(this.data)/ut.BendStep|0,pt.gpReadBool(this.data),e.addBendPoint(t)}}readGrace(e,t){const s=new ze,i=new Ae;i.string=t.string,i.fret=ot.readSInt8(this.data),s.duration=_.ThirtySecond,s.dynamics=this.toDynamicValue(ot.readSInt8(this.data));switch(ot.readSInt8(this.data)){case 0:case 2:break;case 1:i.slideOutType=v.Legato,i.slideTarget=t;break;case 3:i.isHammerPullOrigin=!0}if(i.dynamics=s.dynamics,this.data.skip(1),this._versionNumber<500)s.graceType=w.BeforeBeat;else{const e=this.data.readByte();i.isDead=!!(1&e),s.graceType=2&e?w.OnBeat:w.BeforeBeat}e.addGraceBeat(s),s.addNote(i)}readTremoloPicking(e){switch(this.data.readByte()){case 1:e.tremoloSpeed=_.Eighth;break;case 2:e.tremoloSpeed=_.Sixteenth;break;case 3:e.tremoloSpeed=_.ThirtySecond}}readSlide(e){if(this._versionNumber>=500){const t=ot.readSInt8(this.data);1&t?e.slideOutType=v.Shift:2&t?e.slideOutType=v.Legato:4&t?e.slideOutType=v.OutDown:8&t&&(e.slideOutType=v.OutUp),16&t?e.slideInType=x.IntoFromBelow:32&t&&(e.slideInType=x.IntoFromAbove)}else{switch(ot.readSInt8(this.data)){case 1:e.slideOutType=v.Shift;break;case 2:e.slideOutType=v.Legato;break;case 3:e.slideOutType=v.OutDown;break;case 4:e.slideOutType=v.OutUp;break;case-1:e.slideInType=x.IntoFromBelow;break;case-2:e.slideInType=x.IntoFromAbove}}}readArtificialHarmonic(e){const t=this.data.readByte();if(this._versionNumber>=500)switch(t){case 1:e.harmonicType=T.Natural,e.harmonicValue=ie.deltaFretToHarmonicValue(e.fret);break;case 2:this.data.readByte(),this.data.readByte(),this.data.readByte(),e.harmonicType=T.Artificial;break;case 3:e.harmonicType=T.Tap,e.harmonicValue=ie.deltaFretToHarmonicValue(this.data.readByte());break;case 4:e.harmonicType=T.Pinch,e.harmonicValue=12;break;case 5:e.harmonicType=T.Semi,e.harmonicValue=12}else if(this._versionNumber>=400)switch(t){case 1:e.harmonicType=T.Natural;break;case 3:e.harmonicType=T.Tap;break;case 4:e.harmonicType=T.Pinch;break;case 5:e.harmonicType=T.Semi;break;case 15:case 17:case 22:e.harmonicType=T.Artificial}}readTrill(e){switch(e.trillValue=this.data.readByte()+e.stringTuning,this.data.readByte()){case 1:e.trillSpeed=_.Sixteenth;break;case 2:e.trillSpeed=_.ThirtySecond;break;case 3:e.trillSpeed=_.SixtyFourth}}}ut.VersionString="FICHIER GUITAR PRO ",ut.BendStep=25;class pt{static gpReadColor(e,t=!1){const s=e.readByte(),i=e.readByte(),a=e.readByte();let r=255;return t?r=e.readByte():e.skip(1),new et(s,i,a,r)}static gpReadBool(e){return 0!==e.readByte()}static gpReadStringIntUnused(e,t){return e.skip(4),pt.gpReadString(e,e.readByte(),t)}static gpReadStringInt(e,t){return pt.gpReadString(e,ot.readInt32LE(e),t)}static gpReadStringIntByte(e,t){const s=ot.readInt32LE(e)-1;return e.readByte(),pt.gpReadString(e,s,t)}static gpReadString(e,t,s){const i=new Uint8Array(t);return e.read(i,0,i.length),ot.toString(i,s)}static gpWriteString(e,t){const s=ot.stringToBytes(t);e.writeByte(t.length),e.write(s,0,s.length)}static gpReadStringByteLength(e,t,s){const i=e.readByte(),a=pt.gpReadString(e,i,s);return i<t&&e.skip(t-i),a}}class gt{constructor(){this.volume=-1,this.balance=-1,this.instrument=-1,this.tempoName="",this.tempo=-1,this.duration=-1}}class mt{constructor(){this.x=0,this.y=0,this.w=0,this.h=0}scaleWith(e){this.x*=e,this.y*=e,this.w*=e,this.h*=e}}!function(e){e[e.Boolean=0]="Boolean",e[e.Integer=1]="Integer",e[e.Float=2]="Float",e[e.String=3]="String",e[e.Point=4]="Point",e[e.Size=5]="Size",e[e.Rectangle=6]="Rectangle",e[e.Color=7]="Color"}(Pe||(Pe={}));class ft{constructor(e){this._types=new Map,this.raw=new Map,e&&this.read(e)}read(e){const t=ht.fromBuffer(e),s=ot.readInt32BE(t);for(let e=0;e<s;e++){const e=pt.gpReadString(t,t.readByte(),"utf-8"),s=t.readByte();switch(this._types.set(e,s),s){case Pe.Boolean:const s=1===t.readByte();this.addValue(e,s);break;case Pe.Integer:const i=ot.readInt32BE(t);this.addValue(e,i);break;case Pe.Float:const a=ot.readFloat32BE(t);this.addValue(e,a);break;case Pe.String:const r=pt.gpReadString(t,ot.readInt16BE(t),"utf-8");this.addValue(e,r);break;case Pe.Point:const n=ot.readInt32BE(t),o=ot.readInt32BE(t);this.addValue(e,new X(n,o));break;case Pe.Size:const h=ot.readInt32BE(t),l=ot.readInt32BE(t);this.addValue(e,new X(h,l));break;case Pe.Rectangle:const c=new mt;c.x=ot.readInt32BE(t),c.y=ot.readInt32BE(t),c.w=ot.readInt32BE(t),c.h=ot.readInt32BE(t),this.addValue(e,c);break;case Pe.Color:const d=pt.gpReadColor(t,!0);this.addValue(e,d)}}}apply(e){for(const[t,s]of this.raw)switch(t){case"StandardNotation/hideDynamics":e.stylesheet.hideDynamics=s;break;case"System/bracketExtendMode":e.stylesheet.bracketExtendMode=s;break;case"Global/useSystemSignSeparator":e.stylesheet.useSystemSignSeparator=s;break;case"Global/DisplayTuning":e.stylesheet.globalDisplayTuning=s;break;case"Global/DrawChords":e.stylesheet.globalDisplayChordDiagramsOnTop=s;break;case"System/showTrackNameSingle":s||(e.stylesheet.singleTrackTrackNamePolicy=i.Hidden);break;case"System/showTrackNameMulti":s||(e.stylesheet.multiTrackTrackNamePolicy=i.Hidden);break;case"System/trackNameModeSingle":if(e.stylesheet.singleTrackTrackNamePolicy!==i.Hidden)switch(s){case 0:case 1:e.stylesheet.singleTrackTrackNamePolicy=i.FirstSystem;break;case 2:e.stylesheet.singleTrackTrackNamePolicy=i.AllSystems}break;case"System/trackNameModeMulti":if(e.stylesheet.multiTrackTrackNamePolicy!==i.Hidden)switch(s){case 0:case 1:e.stylesheet.multiTrackTrackNamePolicy=i.FirstSystem;break;case 2:e.stylesheet.multiTrackTrackNamePolicy=i.AllSystems}break;case"System/shortTrackNameOnFirstSystem":e.stylesheet.firstSystemTrackNameMode=s?a.ShortName:a.FullName;break;case"System/shortTrackNameOnOtherSystems":e.stylesheet.otherSystemsTrackNameMode=s?a.ShortName:a.FullName;break;case"System/horizontalTrackNameOnFirstSystem":e.stylesheet.firstSystemTrackNameOrientation=s?r.Horizontal:r.Vertical;break;case"System/horizontalTrackNameOnOtherSystems":e.stylesheet.otherSystemsTrackNameOrientation=s?r.Horizontal:r.Vertical;break;case"Header/Title":ie.getOrCreateHeaderFooterStyle(e,be.Title).template=s;break;case"Header/TitleAlignment":ie.getOrCreateHeaderFooterStyle(e,be.Title).textAlign=this.toTextAlign(s);break;case"Header/drawTitle":ie.getOrCreateHeaderFooterStyle(e,be.Title).isVisible=s;break;case"Header/Subtitle":ie.getOrCreateHeaderFooterStyle(e,be.SubTitle).template=s;break;case"Header/SubtitleAlignment":ie.getOrCreateHeaderFooterStyle(e,be.SubTitle).textAlign=this.toTextAlign(s);break;case"Header/drawSubtitle":ie.getOrCreateHeaderFooterStyle(e,be.SubTitle).isVisible=s;break;case"Header/Artist":ie.getOrCreateHeaderFooterStyle(e,be.Artist).template=s;break;case"Header/ArtistAlignment":ie.getOrCreateHeaderFooterStyle(e,be.Artist).textAlign=this.toTextAlign(s);break;case"Header/drawArtist":ie.getOrCreateHeaderFooterStyle(e,be.Artist).isVisible=s;break;case"Header/Album":ie.getOrCreateHeaderFooterStyle(e,be.Album).template=s;break;case"Header/AlbumAlignment":ie.getOrCreateHeaderFooterStyle(e,be.Album).textAlign=this.toTextAlign(s);break;case"Header/drawAlbum":ie.getOrCreateHeaderFooterStyle(e,be.Album).isVisible=s;break;case"Header/Words":ie.getOrCreateHeaderFooterStyle(e,be.Words).template=s;break;case"Header/WordsAlignment":ie.getOrCreateHeaderFooterStyle(e,be.Words).textAlign=this.toTextAlign(s);break;case"Header/drawWords":ie.getOrCreateHeaderFooterStyle(e,be.Words).isVisible=s;break;case"Header/Music":ie.getOrCreateHeaderFooterStyle(e,be.Music).template=s;break;case"Header/MusicAlignment":ie.getOrCreateHeaderFooterStyle(e,be.Music).textAlign=this.toTextAlign(s);break;case"Header/drawMusic":ie.getOrCreateHeaderFooterStyle(e,be.Music).isVisible=s;break;case"Header/WordsAndMusic":ie.getOrCreateHeaderFooterStyle(e,be.WordsAndMusic).template=s;break;case"Header/WordsAndMusicAlignment":ie.getOrCreateHeaderFooterStyle(e,be.WordsAndMusic).textAlign=this.toTextAlign(s);break;case"Header/drawWordsAndMusic":ie.getOrCreateHeaderFooterStyle(e,be.WordsAndMusic).isVisible=s;break;case"Header/Tabber":ie.getOrCreateHeaderFooterStyle(e,be.Transcriber).template=s;break;case"Header/TabberAlignment":ie.getOrCreateHeaderFooterStyle(e,be.Transcriber).textAlign=this.toTextAlign(s);break;case"Header/drawTabber":ie.getOrCreateHeaderFooterStyle(e,be.Transcriber).isVisible=s;break;case"Footer/Copyright":ie.getOrCreateHeaderFooterStyle(e,be.Copyright).template=s;break;case"Footer/CopyrightAlignment":ie.getOrCreateHeaderFooterStyle(e,be.Copyright).textAlign=this.toTextAlign(s);break;case"Footer/drawCopyright":ie.getOrCreateHeaderFooterStyle(e,be.Copyright).isVisible=s;break;case"Footer/Copyright2":ie.getOrCreateHeaderFooterStyle(e,be.CopyrightSecondLine).template=s;break;case"Footer/Copyright2Alignment":ie.getOrCreateHeaderFooterStyle(e,be.CopyrightSecondLine).textAlign=this.toTextAlign(s);break;case"Footer/drawCopyright2":ie.getOrCreateHeaderFooterStyle(e,be.CopyrightSecondLine).isVisible=s}}toTextAlign(e){switch(e){case 0:return ne.Left;case 1:return ne.Center;case 2:return ne.Right}return ne.Left}addValue(e,t,s){this.raw.set(e,t),void 0!==s&&this._types.set(e,s)}writeTo(e){ot.writeInt32BE(e,this.raw.size);for(const[t,s]of this.raw){const i=this.getDataType(t,s);switch(pt.gpWriteString(e,t),e.writeByte(i),i){case Pe.Boolean:e.writeByte(s?1:0);break;case Pe.Integer:ot.writeInt32BE(e,s);break;case Pe.Float:ot.writeFloat32BE(e,s);break;case Pe.String:const t=ot.stringToBytes(s);ot.writeInt16BE(e,t.length),e.write(t,0,t.length);break;case Pe.Point:case Pe.Size:ot.writeInt32BE(e,s.offset),ot.writeInt32BE(e,s.value);break;case Pe.Rectangle:ot.writeInt32BE(e,s.x),ot.writeInt32BE(e,s.y),ot.writeInt32BE(e,s.w),ot.writeInt32BE(e,s.h);break;case Pe.Color:e.writeByte(s.r),e.writeByte(s.g),e.writeByte(s.b),e.writeByte(s.a)}}}getDataType(e,t){if(this._types.has(e))return this._types.get(e);const s=typeof t;switch(typeof t){case"string":return Pe.String;case"number":return t===(0|t)?Pe.Integer:Pe.Float;case"object":if(t instanceof X)return Pe.Point;if(t instanceof mt)return Pe.Rectangle;if(t instanceof et)return Pe.Color}throw new $e(Se.General,`Unknown value type in BinaryStylesheet: ${s}`)}static writeForScore(e){const t=new ft;switch(t.addValue("StandardNotation/hideDynamics",e.stylesheet.hideDynamics,Pe.Boolean),t.addValue("System/bracketExtendMode",e.stylesheet.bracketExtendMode,Pe.Integer),t.addValue("Global/useSystemSignSeparator",e.stylesheet.useSystemSignSeparator,Pe.Boolean),t.addValue("Global/DisplayTuning",e.stylesheet.globalDisplayTuning,Pe.Boolean),t.addValue("Global/DrawChords",e.stylesheet.globalDisplayChordDiagramsOnTop,Pe.Boolean),e.stylesheet.singleTrackTrackNamePolicy){case i.Hidden:t.addValue("System/showTrackNameSingle",!1,Pe.Boolean);break;case i.FirstSystem:t.addValue("System/trackNameModeSingle",0,Pe.Integer);break;case i.AllSystems:t.addValue("System/trackNameModeSingle",2,Pe.Integer)}switch(e.stylesheet.multiTrackTrackNamePolicy){case i.Hidden:t.addValue("System/trackNameModeMulti",!1,Pe.Boolean);break;case i.FirstSystem:t.addValue("System/trackNameModeMulti",0,Pe.Integer);break;case i.AllSystems:t.addValue("System/trackNameModeMulti",2,Pe.Integer)}switch(e.stylesheet.firstSystemTrackNameMode){case a.FullName:t.addValue("System/shortTrackNameOnFirstSystem",!1,Pe.Boolean);break;case a.ShortName:t.addValue("System/shortTrackNameOnFirstSystem",!0,Pe.Boolean)}switch(e.stylesheet.otherSystemsTrackNameMode){case a.FullName:t.addValue("System/shortTrackNameOnOtherSystems",!1,Pe.Boolean);break;case a.ShortName:t.addValue("System/shortTrackNameOnOtherSystems",!0,Pe.Boolean)}switch(e.stylesheet.firstSystemTrackNameOrientation){case r.Horizontal:t.addValue("System/horizontalTrackNameOnFirstSystem",!0,Pe.Boolean);break;case r.Vertical:t.addValue("System/horizontalTrackNameOnFirstSystem",!1,Pe.Boolean)}switch(e.stylesheet.otherSystemsTrackNameOrientation){case r.Horizontal:t.addValue("System/horizontalTrackNameOnOtherSystems",!0,Pe.Boolean);break;case r.Vertical:t.addValue("System/horizontalTrackNameOnOtherSystems",!1,Pe.Boolean)}const s=e.style;if(s)for(const[e,i]of s.headerAndFooter)switch(e){case be.Title:ft.addHeaderAndFooter(t,i,"Header/","Title");break;case be.SubTitle:ft.addHeaderAndFooter(t,i,"Header/","Subtitle");break;case be.Artist:ft.addHeaderAndFooter(t,i,"Header/","Artist");break;case be.Album:ft.addHeaderAndFooter(t,i,"Header/","Album");break;case be.Words:ft.addHeaderAndFooter(t,i,"Header/","Words");break;case be.Music:ft.addHeaderAndFooter(t,i,"Header/","Music");break;case be.WordsAndMusic:ft.addHeaderAndFooter(t,i,"Header/","WordsAndMusic");break;case be.Transcriber:ft.addHeaderAndFooter(t,i,"Header/","Tabber");break;case be.Copyright:ft.addHeaderAndFooter(t,i,"Footer/","Copyright");break;case be.CopyrightSecondLine:ft.addHeaderAndFooter(t,i,"Footer/","Copyright2")}const n=ht.withCapacity(128);return t.writeTo(n),n.toArray()}static addHeaderAndFooter(e,t,s,i){void 0!==t.template&&e.addValue(`${s}${i}`,t.template,Pe.String),e.addValue(`${s}${i}Alignment`,t.textAlign,Pe.Integer),void 0!==t.isVisible&&e.addValue(`${s}draw${i}`,t.isVisible,Pe.Boolean)}}!function(e){e[e.None=0]="None",e[e.Element=1]="Element",e[e.Text=2]="Text",e[e.CDATA=3]="CDATA",e[e.Document=4]="Document",e[e.DocumentType=5]="DocumentType"}(Fe||(Fe={}));class yt{constructor(){this.nodeType=Fe.None,this.localName=null,this.value=null,this.childNodes=[],this.attributes=new Map,this.firstChild=null,this.firstElement=null}*childElements(){for(const e of this.childNodes)e.nodeType===Fe.Element&&(yield e)}addChild(e){this.childNodes.push(e),this.firstChild=e,e.nodeType!==Fe.Element&&e.nodeType!==Fe.CDATA||(this.firstElement=e)}getAttribute(e,t=""){return this.attributes.has(e)?this.attributes.get(e):t}getElementsByTagName(e,t=!1){const s=[];return this.searchElementsByTagName(this.childNodes,s,e,t),s}searchElementsByTagName(e,t,s,i=!1){for(const a of e)a&&a.nodeType===Fe.Element&&a.localName===s&&t.push(a),i&&this.searchElementsByTagName(a.childNodes,t,s,!0)}findChildElement(e){for(const t of this.childNodes)if(t&&t.nodeType===Fe.Element&&t.localName===e)return t;return null}addElement(e){const t=new yt;return t.nodeType=Fe.Element,t.localName=e,this.addChild(t),t}get innerText(){if(this.nodeType===Fe.Element||this.nodeType===Fe.Document){if(this.firstElement&&this.firstElement.nodeType===Fe.CDATA)return this.firstElement.innerText;let e="";for(const t of this.childNodes)e+=t.innerText?.toString();return e.trim()}return this.value??""}set innerText(e){const t=new yt;t.nodeType=Fe.Text,t.value=e,this.childNodes=[t]}setCData(e){const t=new yt;t.nodeType=Fe.CDATA,t.value=e,this.childNodes=[t]}}class bt extends $e{constructor(e,t,s){super(Se.Format,e),this.pos=0,this.xml=t,this.pos=s,Object.setPrototypeOf(this,bt.prototype)}}!function(e){e[e.IgnoreSpaces=0]="IgnoreSpaces",e[e.Begin=1]="Begin",e[e.BeginNode=2]="BeginNode",e[e.TagName=3]="TagName",e[e.Body=4]="Body",e[e.AttribName=5]="AttribName",e[e.Equals=6]="Equals",e[e.AttvalBegin=7]="AttvalBegin",e[e.AttribVal=8]="AttribVal",e[e.Childs=9]="Childs",e[e.Close=10]="Close",e[e.WaitEnd=11]="WaitEnd",e[e.WaitEndRet=12]="WaitEndRet",e[e.Pcdata=13]="Pcdata",e[e.Header=14]="Header",e[e.Comment=15]="Comment",e[e.Doctype=16]="Doctype",e[e.Cdata=17]="Cdata",e[e.Escape=18]="Escape"}(Ce||(Ce={}));class St{static parse(e,t,s){let i=e.charCodeAt(t),a=Ce.Begin,r=Ce.Begin,n=0,o="",h=Ce.Begin,l=null,c=null,d=0,u=0;for(;t<e.length;){switch(i=e.charCodeAt(t),a){case Ce.IgnoreSpaces:switch(i){case St.CharCodeLF:case St.CharCodeCR:case St.CharCodeTab:case St.CharCodeSpace:break;default:a=r;continue}break;case Ce.Begin:if(i!==St.CharCodeLowerThan){n=t,a=Ce.Pcdata;continue}a=Ce.IgnoreSpaces,r=Ce.BeginNode;break;case Ce.Pcdata:if(i===St.CharCodeLowerThan){o+=e.substr(n,t-n);const i=new yt;i.nodeType=Fe.Text,i.value=o,o="",s.addChild(i),a=Ce.IgnoreSpaces,r=Ce.BeginNode}else i===St.CharCodeAmp&&(o+=e.substr(n,t-n),a=Ce.Escape,h=Ce.Pcdata,n=t+1);break;case Ce.Cdata:if(i===St.CharCodeBrackedClose&&e.charCodeAt(t+1)===St.CharCodeBrackedClose&&e.charCodeAt(t+2)===St.CharCodeGreaterThan){const i=new yt;i.nodeType=Fe.CDATA,i.value=e.substr(n,t-n),s.addChild(i),t+=2,a=Ce.Begin}break;case Ce.BeginNode:switch(i){case St.CharCodeExclamation:if(e.charCodeAt(t+1)===St.CharCodeBrackedOpen){if(t+=2,"CDATA["!==e.substr(t,6).toUpperCase())throw new bt("Expected <![CDATA[",e,t);t+=5,a=Ce.Cdata,n=t+1}else if(e.charCodeAt(t+1)===St.CharCodeUpperD||e.charCodeAt(t+1)===St.CharCodeLowerD){if("OCTYPE"!==e.substr(t+2,6).toUpperCase())throw new bt("Expected <!DOCTYPE",e,t);t+=8,a=Ce.Doctype,n=t+1}else{if(e.charCodeAt(t+1)!==St.CharCodeMinus||e.charCodeAt(t+2)!==St.CharCodeMinus)throw new bt("Expected \x3c!--",e,t);t+=2,a=Ce.Comment,n=t+1}break;case St.CharCodeQuestion:a=Ce.Header,n=t;break;case St.CharCodeSlash:if(!s)throw new bt("Expected node name",e,t);n=t+1,a=Ce.IgnoreSpaces,r=Ce.Close;break;default:a=Ce.TagName,n=t;continue}break;case Ce.TagName:if(!St.isValidChar(i)){if(t===n)throw new bt("Expected node name",e,t);l=new yt,l.nodeType=Fe.Element,l.localName=e.substr(n,t-n),s.addChild(l),a=Ce.IgnoreSpaces,r=Ce.Body;continue}break;case Ce.Body:switch(i){case St.CharCodeSlash:a=Ce.WaitEnd;break;case St.CharCodeGreaterThan:a=Ce.Childs;break;default:a=Ce.AttribName,n=t;continue}break;case Ce.AttribName:if(!St.isValidChar(i)){if(n===t)throw new bt("Expected attribute name",e,t);if(c=e.substr(n,t-n),l.attributes.has(c))throw new bt(`Duplicate attribute [${c}]`,e,t);a=Ce.IgnoreSpaces,r=Ce.Equals;continue}break;case Ce.Equals:if(i!==St.CharCodeEquals)throw new bt("Expected =",e,t);a=Ce.IgnoreSpaces,r=Ce.AttvalBegin;break;case Ce.AttvalBegin:switch(i){case St.CharCodeDoubleQuote:case St.CharCodeSingleQuote:o="",a=Ce.AttribVal,n=t+1,u=i}break;case Ce.AttribVal:if(i===St.CharCodeAmp)o+=e.substr(n,t-n),a=Ce.Escape,h=Ce.AttribVal,n=t+1;else if(i===u){o+=e.substr(n,t-n);const s=o;o="",l.attributes.set(c,s),a=Ce.IgnoreSpaces,r=Ce.Body}break;case Ce.Childs:n=t=St.parse(e,t,l),a=Ce.Begin;break;case Ce.WaitEnd:if(i!==St.CharCodeGreaterThan)throw new bt("Expected >",e,t);a=Ce.Begin;break;case Ce.WaitEndRet:if(i===St.CharCodeGreaterThan)return t;throw new bt("Expected >",e,t);case Ce.Close:if(!St.isValidChar(i)){if(n===t)throw new bt("Expected node name",e,t);if(e.substr(n,t-n)!==s.localName)throw new bt(`Expected </${s.localName}>`,e,t);a=Ce.IgnoreSpaces,r=Ce.WaitEndRet;continue}break;case Ce.Comment:i===St.CharCodeMinus&&e.charCodeAt(t+1)===St.CharCodeMinus&&e.charCodeAt(t+2)===St.CharCodeGreaterThan&&(t+=2,a=Ce.Begin);break;case Ce.Doctype:if(i===St.CharCodeBrackedOpen)d++;else if(i===St.CharCodeBrackedClose)d--;else if(i===St.CharCodeGreaterThan&&0===d){const i=new yt;i.nodeType=Fe.DocumentType,i.value=e.substr(n,t-n),s.addChild(i),a=Ce.Begin}break;case Ce.Header:i===St.CharCodeQuestion&&e.charCodeAt(t+1)===St.CharCodeGreaterThan&&(t++,a=Ce.Begin);break;case Ce.Escape:if(i===St.CharCodeSemi){const s=e.substr(n,t-n);if(s.charCodeAt(0)===St.CharCodeSharp){const e=s.charCodeAt(1)===St.CharCodeLowerX?Number.parseInt(`0${s.substr(1,s.length-1)}`):Number.parseInt(s.substr(1,s.length-1));o+=String.fromCharCode(e)}else St.Escapes.has(s)?o+=St.Escapes.get(s):o+=`&${s};`?.toString();n=t+1,a=h}else St.isValidChar(i)||i===St.CharCodeSharp||(o+="&",o+=e.substr(n,t-n),n=--t+1,a=h)}t++}if(a===Ce.Begin&&(n=t,a=Ce.Pcdata),a===Ce.Pcdata){if(t!==n){o+=e.substr(n,t-n);const i=new yt;i.nodeType=Fe.Text,i.value=o,s.addChild(i)}return t}if(a===Ce.Escape&&h===Ce.Pcdata){o+="&",o+=e.substr(n,t-n);const i=new yt;return i.nodeType=Fe.Text,i.value=o,s.addChild(i),t}throw new bt("Unexpected end",e,t)}static isValidChar(e){return e>=St.CharCodeLowerA&&e<=St.CharCodeLowerZ||e>=St.CharCodeUpperA&&e<=St.CharCodeUpperZ||e>=St.CharCode0&&e<=St.CharCode9||e===St.CharCodeColon||e===St.CharCodeDot||e===St.CharCodeUnderscore||e===St.CharCodeMinus}}St.CharCodeLF=10,St.CharCodeTab=9,St.CharCodeCR=13,St.CharCodeSpace=32,St.CharCodeLowerThan=60,St.CharCodeAmp=38,St.CharCodeBrackedClose=93,St.CharCodeBrackedOpen=91,St.CharCodeGreaterThan=62,St.CharCodeExclamation=33,St.CharCodeUpperD=68,St.CharCodeLowerD=100,St.CharCodeMinus=45,St.CharCodeQuestion=63,St.CharCodeSlash=47,St.CharCodeEquals=61,St.CharCodeDoubleQuote=34,St.CharCodeSingleQuote=39,St.CharCodeSharp=35,St.CharCodeLowerX=120,St.CharCodeLowerA=97,St.CharCodeLowerZ=122,St.CharCodeUpperA=65,St.CharCodeUpperZ=90,St.CharCode0=48,St.CharCode9=57,St.CharCodeColon=58,St.CharCodeDot=46,St.CharCodeUnderscore=95,St.CharCodeSemi=59,St.Escapes=new Map([["lt","<"],["gt",">"],["amp","&"],["quot",'"'],["apos","'"]]);class _t{static write(e,t,s){const i=new _t(t,s);return i.writeNode(e),i.toString()}constructor(e,t){this._result=[],this._indention=e,this._xmlHeader=t,this._currentIndention="",this._isStartOfLine=!0}writeNode(e){switch(e.nodeType){case Fe.None:break;case Fe.Element:this._result.length>0&&this.writeLine(),this.write(`<${e.localName}`);for(const[t,s]of e.attributes)this.write(` ${t}="`),this.writeAttributeValue(s),this.write('"');if(0===e.childNodes.length)this.write("/>");else{if(this.write(">"),1!==e.childNodes.length||e.firstElement){this.indent();for(const t of e.childNodes)t.nodeType===Fe.Element&&this.writeNode(t);this.unindend(),this.writeLine()}else this.writeNode(e.childNodes[0]);this.write(`</${e.localName}>`)}break;case Fe.Text:e.value&&this.write(e.value);break;case Fe.CDATA:null!==e.value&&this.write(`<![CDATA[${e.value}]]>`);break;case Fe.Document:this._xmlHeader&&this.write('<?xml version="1.0" encoding="utf-8"?>');for(const t of e.childNodes)this.writeNode(t);break;case Fe.DocumentType:this.write(`<!DOCTYPE ${e.value}>`)}}unindend(){this._currentIndention=this._currentIndention.substr(0,this._currentIndention.length-this._indention.length)}indent(){this._currentIndention+=this._indention}writeAttributeValue(e){for(let t=0;t<e.length;t++){const s=e.charAt(t);switch(s){case"<":this._result.push("&lt;");break;case">":this._result.push("&gt;");break;case"&":this._result.push("&amp;");break;case"'":this._result.push("&apos;");break;case'"':this._result.push("&quot;");break;default:this._result.push(s)}}}write(e){this._isStartOfLine&&this._result.push(this._currentIndention),this._result.push(e),this._isStartOfLine=!1}writeLine(e=null){e&&this.write(e),this._indention.length>0&&!this._isStartOfLine&&(this._result.push("\n"),this._isStartOfLine=!0)}toString(){return this._result.join("").trimRight()}}class wt extends yt{constructor(){super(),this.nodeType=Fe.Document}parse(e){St.parse(e,0,this)}toString(){return this.toFormattedString()}toFormattedString(e="",t=!1){return _t.write(this,e,t)}}class Bt{constructor(){this.id="",this.dots=0,this.tupletDenominator=-1,this.tupletNumerator=-1,this.value=_.Quarter}}class kt{constructor(){this.name="",this.path="",this.role="",this.program=0}get uniqueId(){return`${this.path};${this.name};${this.role}`}}class Tt{constructor(){this._hasAnacrusis=!1,this._skipApplyLyrics=!1,this._doubleBars=new Set,this._keySignatures=new Map}parseXml(e,t){this._masterTrackAutomations=new Map,this._automationsPerTrackIdAndBarIndex=new Map,this._sustainPedalsPerTrackIdAndBarIndex=new Map,this._tracksMapping=[],this._tracksById=new Map,this._masterBars=[],this._barsOfMasterBar=[],this._voicesOfBar=new Map,this._barsById=new Map,this._voiceById=new Map,this._beatsOfVoice=new Map,this._beatById=new Map,this._rhythmOfBeat=new Map,this._rhythmById=new Map,this._notesOfBeat=new Map,this._noteById=new Map,this._tappedNotes=new Map,this._lyricsByTrack=new Map,this._soundsByTrack=new Map,this._skipApplyLyrics=!1;const s=new wt;try{s.parse(e)}catch(e){throw new qe("Could not parse XML",e)}if(this.parseDom(s),this.buildModel(),ie.consolidate(this.score),this.score.finish(t),!this._skipApplyLyrics&&this._lyricsByTrack.size>0)for(const[e,t]of this._lyricsByTrack){this._tracksById.get(e).applyLyrics(t)}}parseDom(e){const t=e.firstElement;if(t){if("GPIF"!==t.localName)throw new qe("Root node of XML was not GPIF");this.score=new Je;for(const e of t.childElements())switch(e.localName){case"Score":this.parseScoreNode(e);break;case"MasterTrack":this.parseMasterTrackNode(e);break;case"Tracks":this.parseTracksNode(e);break;case"MasterBars":this.parseMasterBarsNode(e);break;case"Bars":this.parseBars(e);break;case"Voices":this.parseVoices(e);break;case"Beats":this.parseBeats(e);break;case"Notes":this.parseNotes(e);break;case"Rhythms":this.parseRhythms(e)}}}parseScoreNode(e){for(const t of e.childElements())switch(t.localName){case"Title":this.score.title=t.innerText;break;case"SubTitle":this.score.subTitle=t.innerText;break;case"Artist":this.score.artist=t.innerText;break;case"Album":this.score.album=t.innerText;break;case"Words":this.score.words=t.innerText;break;case"Music":this.score.music=t.innerText;break;case"WordsAndMusic":const e=t.innerText;""!==e&&(e&&!this.score.words&&(this.score.words=e),e&&!this.score.music&&(this.score.music=e));break;case"Copyright":this.score.copyright=t.innerText;break;case"Tabber":this.score.tab=t.innerText;break;case"Instructions":this.score.instructions=t.innerText;break;case"Notices":this.score.notices=t.innerText;break;case"ScoreSystemsDefaultLayout":this.score.defaultSystemsLayout=Tt.parseIntSafe(t.innerText,4);break;case"ScoreSystemsLayout":this.score.systemsLayout=Tt.splitSafe(t.innerText).map((e=>Tt.parseIntSafe(e,4)))}}static parseIntSafe(e,t){if(!e)return t;const s=Number.parseInt(e);return Number.isNaN(s)?t:s}static parseFloatSafe(e,t){if(!e)return t;const s=Number.parseFloat(e);return Number.isNaN(s)?t:s}static splitSafe(e,t=" "){return e?e.split(t).map((e=>e.trim())).filter((e=>e.length>0)):[]}parseMasterTrackNode(e){for(const t of e.childElements())switch(t.localName){case"Automations":this.parseAutomations(t,this._masterTrackAutomations,null,null);break;case"Tracks":this._tracksMapping=Tt.splitSafe(t.innerText);break;case"Anacrusis":this._hasAnacrusis=!0}}parseAutomations(e,t,s,i){for(const a of e.childElements())if("Automation"===a.localName)this.parseAutomation(a,t,s,i)}parseAutomation(e,t,s,i){let a=null,r=!1,n=-1,o=0,h=0,l=null,c=0,u=null;for(const t of e.childElements())switch(t.localName){case"Type":a=t.innerText;break;case"Linear":r="true"===t.innerText.toLowerCase();break;case"Bar":n=Tt.parseIntSafe(t.innerText,0);break;case"Position":o=Tt.parseFloatSafe(t.innerText,0);break;case"Value":if(t.firstElement&&t.firstElement.nodeType===Fe.CDATA)l=t.innerText;else{const e=Tt.splitSafe(t.innerText);1===e.length?(h=Tt.parseFloatSafe(e[0],0),c=1):(h=Tt.parseFloatSafe(e[0],0),c=Tt.parseIntSafe(e[1],0))}break;case"Text":u=t.innerText}if(!a)return;let p=null;switch(a){case"Tempo":p=U.buildTempoAutomation(r,o,h,c);break;case"Sound":l&&s&&s.has(l)&&(p=U.buildInstrumentAutomation(r,o,s.get(l).program));break;case"SustainPedal":if(i){let e;i.has(n)?e=i.get(n):(e=[],i.set(n,e));const t=new W;switch(t.ratioPosition=o,c){case 1:t.pedalType=d.Down;break;case 3:t.pedalType=d.Up}e.push(t)}}p&&(u&&(p.text=u),n>=0&&(t.has(n)||t.set(n,[]),t.get(n).push(p)))}parseTracksNode(e){for(const t of e.childElements())if("Track"===t.localName)this.parseTrack(t)}parseTrack(e){this._articulationByName=new Map;const t=new rt;t.ensureStaveCount(1);t.staves[0].showStandardNotation=!0;const s=e.getAttribute("id");for(const i of e.childElements())switch(i.localName){case"Name":t.name=i.innerText;break;case"Color":const e=Tt.splitSafe(i.innerText);if(e.length>=3){const s=Tt.parseIntSafe(e[0],0),i=Tt.parseIntSafe(e[1],0),a=Tt.parseIntSafe(e[2],0);t.color=new et(s,i,a,255)}break;case"Instrument":const a=i.getAttribute("ref");(a.endsWith("-gs")||a.endsWith("GrandStaff"))&&(t.ensureStaveCount(2),t.staves[1].showStandardNotation=!0);break;case"InstrumentSet":this.parseInstrumentSet(t,i);break;case"NotationPatch":this.parseNotationPatch(t,i);break;case"ShortName":t.shortName=i.innerText;break;case"SystemsDefautLayout":t.defaultSystemsLayout=Tt.parseIntSafe(i.innerText,4);break;case"SystemsLayout":t.systemsLayout=Tt.splitSafe(i.innerText).map((e=>Tt.parseIntSafe(e,4)));break;case"Lyrics":this.parseLyrics(s,i);break;case"Properties":this.parseTrackProperties(t,i);break;case"GeneralMidi":case"MidiConnection":case"MIDISettings":this.parseGeneralMidi(t,i);break;case"Sounds":this.parseSounds(s,t,i);break;case"PlaybackState":const r=i.innerText;t.playbackInfo.isSolo="Solo"===r,t.playbackInfo.isMute="Mute"===r;break;case"PartSounding":this.parsePartSounding(t,i);break;case"Staves":this.parseStaves(t,i);break;case"Transpose":this.parseTranspose(t,i);break;case"RSE":this.parseRSE(t,i);break;case"Automations":this.parseTrackAutomations(s,i)}this._tracksById.set(s,t)}parseTrackAutomations(e,t){const s=new Map;this._automationsPerTrackIdAndBarIndex.set(e,s);const i=new Map;this._sustainPedalsPerTrackIdAndBarIndex.set(e,i),this.parseAutomations(t,s,this._soundsByTrack.get(e),i)}parseNotationPatch(e,t){for(const s of t.childElements())switch(s.localName){case"LineCount":const t=Tt.parseIntSafe(s.innerText,5);for(const s of e.staves)s.standardNotationLineCount=t;break;case"Elements":this.parseElements(e,s)}}parseInstrumentSet(e,t){for(const s of t.childElements())switch(s.localName){case"Type":if("drumKit"===s.innerText)for(const t of e.staves)t.isPercussion=!0;break;case"Elements":this.parseElements(e,s);break;case"LineCount":const t=Tt.parseIntSafe(s.innerText,5);for(const s of e.staves)s.standardNotationLineCount=t}}parseElements(e,t){for(const s of t.childElements())if("Element"===s.localName)this.parseElement(e,s)}parseElement(e,t){const s=t.findChildElement("Type")?.innerText??"";for(const i of t.childElements())switch(i.localName){case"Name":case"Articulations":this.parseArticulations(e,i,s)}}parseArticulations(e,t,s){for(const i of t.childElements())if("Articulation"===i.localName)this.parseArticulation(e,i,s)}parseArticulation(e,t,s){const i=new Ee;i.outputMidiNumber=-1,i.elementType=s;let a="";for(const e of t.childElements()){const t=e.innerText;switch(e.localName){case"Name":a=e.innerText;break;case"OutputMidiNumber":i.outputMidiNumber=Tt.parseIntSafe(t,0);break;case"TechniqueSymbol":i.techniqueSymbol=this.parseTechniqueSymbol(t);break;case"TechniquePlacement":switch(t){case"outside":case"above":i.techniqueSymbolPlacement=oe.Bottom;break;case"inside":i.techniqueSymbolPlacement=oe.Middle;break;case"below":i.techniqueSymbolPlacement=oe.Top}break;case"Noteheads":const s=Tt.splitSafe(t);s.length>=1&&(i.noteHeadDefault=this.parseNoteHead(s[0])),s.length>=2&&(i.noteHeadHalf=this.parseNoteHead(s[1])),s.length>=3&&(i.noteHeadWhole=this.parseNoteHead(s[2])),i.noteHeadHalf===re.None&&(i.noteHeadHalf=i.noteHeadDefault),i.noteHeadWhole===re.None&&(i.noteHeadWhole=i.noteHeadDefault);break;case"StaffLine":i.staffLine=Tt.parseIntSafe(t,0)}}-1!==i.outputMidiNumber?(e.percussionArticulations.push(i),a.length>0&&this._articulationByName.set(a,i)):a.length>0&&this._articulationByName.has(a)&&(this._articulationByName.get(a).staffLine=i.staffLine)}parseTechniqueSymbol(e){switch(e){case"pictEdgeOfCymbal":return re.PictEdgeOfCymbal;case"articStaccatoAbove":return re.ArticStaccatoAbove;case"noteheadParenthesis":return re.NoteheadParenthesis;case"stringsUpBow":return re.StringsUpBow;case"stringsDownBow":return re.StringsDownBow;case"guitarGolpe":return re.GuitarGolpe;default:return re.None}}parseNoteHead(e){switch(e){case"noteheadDoubleWholeSquare":return re.NoteheadDoubleWholeSquare;case"noteheadDoubleWhole":return re.NoteheadDoubleWhole;case"noteheadWhole":return re.NoteheadWhole;case"noteheadHalf":return re.NoteheadHalf;case"noteheadBlack":return re.NoteheadBlack;case"noteheadNull":return re.NoteheadNull;case"noteheadXOrnate":return re.NoteheadXOrnate;case"noteheadTriangleUpWhole":return re.NoteheadTriangleUpWhole;case"noteheadTriangleUpHalf":return re.NoteheadTriangleUpHalf;case"noteheadTriangleUpBlack":return re.NoteheadTriangleUpBlack;case"noteheadDiamondBlackWide":return re.NoteheadDiamondBlackWide;case"noteheadDiamondWhite":return re.NoteheadDiamondWhite;case"noteheadDiamondWhiteWide":return re.NoteheadDiamondWhiteWide;case"noteheadCircleX":return re.NoteheadCircleX;case"noteheadXWhole":return re.NoteheadXWhole;case"noteheadXHalf":return re.NoteheadXHalf;case"noteheadXBlack":return re.NoteheadXBlack;case"noteheadParenthesis":return re.NoteheadParenthesis;case"noteheadSlashedBlack2":return re.NoteheadSlashedBlack2;case"noteheadCircleSlash":return re.NoteheadCircleSlash;case"noteheadHeavyX":return re.NoteheadHeavyX;case"noteheadHeavyXHat":return re.NoteheadHeavyXHat;default:return q.warning("GPIF","Unknown notehead symbol",e),re.None}}parseStaves(e,t){let s=0;for(const i of t.childElements())if("Staff"===i.localName){e.ensureStaveCount(s+1);const t=e.staves[s];this.parseStaff(t,i),s++}}parseStaff(e,t){for(const s of t.childElements())if("Properties"===s.localName)this.parseStaffProperties(e,s)}parseStaffProperties(e,t){for(const s of t.childElements())if("Property"===s.localName)this.parseStaffProperty(e,s)}parseStaffProperty(e,t){switch(t.getAttribute("name")){case"Tuning":for(const s of t.childElements())switch(s.localName){case"Pitches":const i=Tt.splitSafe(t.findChildElement("Pitches")?.innerText),a=new Array(i.length);for(let e=0;e<a.length;e++)a[a.length-1-e]=Tt.parseIntSafe(i[e],0);e.stringTuning.tunings=a;break;case"Label":e.stringTuning.name=s.innerText}e.isPercussion||(e.showTablature=!0);break;case"DiagramCollection":case"ChordCollection":this.parseDiagramCollectionForStaff(e,t);break;case"CapoFret":const s=Tt.parseIntSafe(t.findChildElement("Fret")?.innerText,0);e.capo=s}}parseLyrics(e,t){const s=[];for(const e of t.childElements())if("Line"===e.localName)s.push(this.parseLyricsLine(e));this._lyricsByTrack.set(e,s)}parseLyricsLine(e){const t=new Ke;for(const s of e.childElements())switch(s.localName){case"Offset":t.startBar=Tt.parseIntSafe(s.innerText,0);break;case"Text":t.text=s.innerText}return t}parseDiagramCollectionForTrack(e,t){const s=t.findChildElement("Items");if(s)for(const t of s.childElements())if("Item"===t.localName)this.parseDiagramItemForTrack(e,t)}parseDiagramCollectionForStaff(e,t){const s=t.findChildElement("Items");if(s)for(const t of s.childElements())if("Item"===t.localName)this.parseDiagramItemForStaff(e,t)}parseDiagramItemForTrack(e,t){const s=new je,i=t.getAttribute("id");for(const t of e.staves)t.addChord(i,s);this.parseDiagramItemForChord(s,t)}parseDiagramItemForStaff(e,t){const s=new je,i=t.getAttribute("id");e.addChord(i,s),this.parseDiagramItemForChord(s,t)}parseDiagramItemForChord(e,t){e.name=t.getAttribute("name");const s=t.findChildElement("Diagram");if(!s)return e.showDiagram=!1,void(e.showFingering=!1);const i=Tt.parseIntSafe(s.getAttribute("stringCount"),6),a=Tt.parseIntSafe(s.getAttribute("baseFret"),0);e.firstFret=a+1;for(let t=0;t<i;t++)e.strings.push(-1);for(const t of s.childElements())switch(t.localName){case"Fret":const s=Tt.parseIntSafe(t.getAttribute("string"),0);e.strings[i-s-1]=a+Tt.parseIntSafe(t.getAttribute("fret"),0);break;case"Fingering":const r=new Map;for(const s of t.childElements())if("Position"===s.localName){let t=k.Unknown;const i=a+Tt.parseIntSafe(s.getAttribute("fret"),0);switch(s.getAttribute("finger")){case"Index":t=k.IndexFinger;break;case"Middle":t=k.MiddleFinger;break;case"Rank":t=k.AnnularFinger;break;case"Pinky":t=k.LittleFinger;break;case"Thumb":t=k.Thumb}t!==k.Unknown&&(r.has(t)?e.barreFrets.push(i):r.set(t,!0))}break;case"Property":switch(t.getAttribute("name")){case"ShowName":e.showName="true"===t.getAttribute("value");break;case"ShowDiagram":e.showDiagram="true"===t.getAttribute("value");break;case"ShowFingering":e.showFingering="true"===t.getAttribute("value")}}}parseTrackProperties(e,t){for(const s of t.childElements())if("Property"===s.localName)this.parseTrackProperty(e,s)}parseTrackProperty(e,t){switch(t.getAttribute("name")){case"Tuning":const s=Tt.splitSafe(t.findChildElement("Pitches")?.innerText),i=new Array(s.length);for(let e=0;e<i.length;e++)i[i.length-1-e]=Tt.parseIntSafe(s[e],0);for(const t of e.staves)t.stringTuning.tunings=i,t.showStandardNotation=!0,t.showTablature=!0;break;case"DiagramCollection":case"ChordCollection":this.parseDiagramCollectionForTrack(e,t);break;case"CapoFret":const a=Tt.parseIntSafe(t.findChildElement("Fret")?.innerText,0);for(const t of e.staves)t.capo=a}}parseGeneralMidi(e,t){for(const s of t.childElements())switch(s.localName){case"Program":e.playbackInfo.program=Tt.parseIntSafe(s.innerText,0);break;case"Port":e.playbackInfo.port=Tt.parseIntSafe(s.innerText,0);break;case"PrimaryChannel":e.playbackInfo.primaryChannel=Tt.parseIntSafe(s.innerText,0);break;case"SecondaryChannel":e.playbackInfo.secondaryChannel=Tt.parseIntSafe(s.innerText,0)}if("Percussion"===t.getAttribute("table"))for(const t of e.staves)t.isPercussion=!0}parseSounds(e,t,s){for(const i of s.childElements())if("Sound"===i.localName)this.parseSound(e,t,i)}parseSound(e,t,s){const i=new kt;for(const e of s.childElements())switch(e.localName){case"Name":i.name=e.innerText;break;case"Path":i.path=e.innerText;break;case"Role":i.role=e.innerText;break;case"MIDI":this.parseSoundMidi(i,e)}"Factory"!==i.role&&0!==t.playbackInfo.program||(t.playbackInfo.program=i.program),this._soundsByTrack.has(e)||this._soundsByTrack.set(e,new Map),this._soundsByTrack.get(e).set(i.uniqueId,i)}parseSoundMidi(e,t){for(const s of t.childElements())if("Program"===s.localName)e.program=Tt.parseIntSafe(s.innerText,0)}parsePartSounding(e,t){for(const s of t.childElements())if("TranspositionPitch"===s.localName)for(const t of e.staves)t.displayTranspositionPitch=Tt.parseIntSafe(s.innerText,0)}parseTranspose(e,t){let s=0,i=0;for(const e of t.childElements())switch(e.localName){case"Chromatic":i=Tt.parseIntSafe(e.innerText,0);break;case"Octave":s=Tt.parseIntSafe(e.innerText,0)}for(const t of e.staves)t.displayTranspositionPitch=12*s+i}parseRSE(e,t){for(const s of t.childElements())if("ChannelStrip"===s.localName)this.parseChannelStrip(e,s)}parseChannelStrip(e,t){for(const s of t.childElements())if("Parameters"===s.localName)this.parseChannelStripParameters(e,s)}parseChannelStripParameters(e,t){if(t.firstChild&&t.firstChild.value){const s=Tt.splitSafe(t.firstChild.value);s.length>=12&&(e.playbackInfo.balance=Math.floor(16*Tt.parseFloatSafe(s[11],.5)),e.playbackInfo.volume=Math.floor(16*Tt.parseFloatSafe(s[12],.9)))}}parseMasterBarsNode(e){for(const t of e.childElements())if("MasterBar"===t.localName)this.parseMasterBar(t)}parseMasterBar(e){const t=new j;0===this._masterBars.length&&this._hasAnacrusis&&(t.isAnacrusis=!0);for(const s of e.childElements())switch(s.localName){case"Time":const e=s.innerText.split("/");t.timeSignatureNumerator=Tt.parseIntSafe(e[0],4),t.timeSignatureDenominator=Tt.parseIntSafe(e[1],4);break;case"FreeTime":t.isFreeTime=!0;break;case"DoubleBar":t.isDoubleBar=!0,this._doubleBars.add(t);break;case"Section":t.section=new Qe,t.section.marker=s.findChildElement("Letter")?.innerText??"",t.section.text=s.findChildElement("Text")?.innerText??"";break;case"Repeat":"true"===s.getAttribute("start").toLowerCase()&&(t.isRepeatStart=!0),"true"===s.getAttribute("end").toLowerCase()&&s.getAttribute("count")&&(t.repeatCount=Tt.parseIntSafe(s.getAttribute("count"),1));break;case"AlternateEndings":const i=Tt.splitSafe(s.innerText);let a=0;for(let e=0;e<i.length;e++)a|=1<<-1+Tt.parseIntSafe(i[e],0);t.alternateEndings=a;break;case"Bars":this._barsOfMasterBar.push(Tt.splitSafe(s.innerText));break;case"TripletFeel":switch(s.innerText){case"NoTripletFeel":t.tripletFeel=M.NoTripletFeel;break;case"Triplet8th":t.tripletFeel=M.Triplet8th;break;case"Triplet16th":t.tripletFeel=M.Triplet16th;break;case"Dotted8th":t.tripletFeel=M.Dotted8th;break;case"Dotted16th":t.tripletFeel=M.Dotted16th;break;case"Scottish8th":t.tripletFeel=M.Scottish8th;break;case"Scottish16th":t.tripletFeel=M.Scottish16th}break;case"Key":const r=Tt.parseIntSafe(s.findChildElement("AccidentalCount")?.innerText,0),n=s.findChildElement("Mode");let o=c.Major;if(n)switch(n.innerText.toLowerCase()){case"major":o=c.Major;break;case"minor":o=c.Minor}this._keySignatures.set(this._masterBars.length,[r,o]);break;case"Fermatas":this.parseFermatas(t,s);break;case"XProperties":this.parseMasterBarXProperties(t,s);break;case"Directions":this.parseDirections(t,s)}this._masterBars.push(t)}parseDirections(e,t){for(const s of t.childElements())switch(s.localName){case"Target":switch(s.innerText){case"Coda":e.addDirection(Be.TargetCoda);break;case"DoubleCoda":e.addDirection(Be.TargetDoubleCoda);break;case"Segno":e.addDirection(Be.TargetSegno);break;case"SegnoSegno":e.addDirection(Be.TargetSegnoSegno);break;case"Fine":e.addDirection(Be.TargetFine)}break;case"Jump":switch(s.innerText){case"DaCapo":e.addDirection(Be.JumpDaCapo);break;case"DaCapoAlCoda":e.addDirection(Be.JumpDaCapoAlCoda);break;case"DaCapoAlDoubleCoda":e.addDirection(Be.JumpDaCapoAlDoubleCoda);break;case"DaCapoAlFine":e.addDirection(Be.JumpDaCapoAlFine);break;case"DaSegno":e.addDirection(Be.JumpDalSegno);break;case"DaSegnoAlCoda":e.addDirection(Be.JumpDalSegnoAlCoda);break;case"DaSegnoAlDoubleCoda":e.addDirection(Be.JumpDalSegnoAlDoubleCoda);break;case"DaSegnoAlFine":e.addDirection(Be.JumpDalSegnoAlFine);break;case"DaSegnoSegno":e.addDirection(Be.JumpDalSegnoSegno);break;case"DaSegnoSegnoAlCoda":e.addDirection(Be.JumpDalSegnoSegnoAlCoda);break;case"DaSegnoSegnoAlDoubleCoda":e.addDirection(Be.JumpDalSegnoSegnoAlDoubleCoda);break;case"DaSegnoSegnoAlFine":e.addDirection(Be.JumpDalSegnoSegnoAlFine);break;case"DaCoda":e.addDirection(Be.JumpDaCoda);break;case"DaDoubleCoda":e.addDirection(Be.JumpDaDoubleCoda)}}}parseFermatas(e,t){for(const s of t.childElements())if("Fermata"===s.localName)this.parseFermata(e,s)}parseFermata(e,t){let s=0;const i=new lt;for(const e of t.childElements())switch(e.localName){case"Type":switch(e.innerText){case"Short":i.type=ke.Short;break;case"Medium":i.type=ke.Medium;break;case"Long":i.type=ke.Long}break;case"Length":i.length=Tt.parseFloatSafe(e.innerText,0);break;case"Offset":const t=e.innerText.split("/");if(2===t.length){s=Tt.parseIntSafe(t[0],4)/Tt.parseIntSafe(t[1],4)*z.QuarterTime|0}}e.addFermata(s,i)}parseBars(e){for(const t of e.childElements())if("Bar"===t.localName)this.parseBar(t)}parseBar(e){const t=new G,s=e.getAttribute("id");for(const i of e.childElements())switch(i.localName){case"Voices":this._voicesOfBar.set(s,Tt.splitSafe(i.innerText));break;case"Clef":switch(i.innerText){case"Neutral":t.clef=n.Neutral;break;case"G2":t.clef=n.G2;break;case"F4":t.clef=n.F4;break;case"C4":t.clef=n.C4;break;case"C3":t.clef=n.C3}break;case"Ottavia":switch(i.innerText){case"8va":t.clefOttava=o._8va;break;case"15ma":t.clefOttava=o._15ma;break;case"8vb":t.clefOttava=o._8vb;break;case"15mb":t.clefOttava=o._15mb}break;case"SimileMark":switch(i.innerText){case"Simple":t.simileMark=h.Simple;break;case"FirstOfDouble":t.simileMark=h.FirstOfDouble;break;case"SecondOfDouble":t.simileMark=h.SecondOfDouble}break;case"XProperties":this.parseBarXProperties(i,t)}this._barsById.set(s,t)}parseVoices(e){for(const t of e.childElements())if("Voice"===t.localName)this.parseVoice(t)}parseVoice(e){const t=new ee,s=e.getAttribute("id");for(const t of e.childElements())if("Beats"===t.localName)this._beatsOfVoice.set(s,Tt.splitSafe(t.innerText));this._voiceById.set(s,t)}parseBeats(e){for(const t of e.childElements())if("Beat"===t.localName)this.parseBeat(t)}parseBeat(e){const t=new ze,s=e.getAttribute("id");for(const i of e.childElements())switch(i.localName){case"Notes":this._notesOfBeat.set(s,Tt.splitSafe(i.innerText));break;case"Rhythm":this._rhythmOfBeat.set(s,i.getAttribute("ref"));break;case"Fadding":switch(i.innerText){case"FadeIn":t.fade=ue.FadeIn;break;case"FadeOut":t.fade=ue.FadeOut;break;case"VolumeSwell":t.fade=ue.VolumeSwell}break;case"Tremolo":switch(i.innerText){case"1/2":t.tremoloSpeed=_.Eighth;break;case"1/4":t.tremoloSpeed=_.Sixteenth;break;case"1/8":t.tremoloSpeed=_.ThirtySecond}break;case"Chord":t.chordId=i.innerText;break;case"Hairpin":switch(i.innerText){case"Crescendo":t.crescendo=S.Crescendo;break;case"Decrescendo":t.crescendo=S.Decrescendo}break;case"Arpeggio":"Up"===i.innerText?t.brushType=b.ArpeggioUp:t.brushType=b.ArpeggioDown;break;case"Properties":this.parseBeatProperties(i,t);break;case"XProperties":this.parseBeatXProperties(i,t);break;case"FreeText":t.text=i.innerText;break;case"TransposedPitchStemOrientation":switch(i.innerText){case"Upward":t.preferredBeamDirection=Te.Up;break;case"Downward":t.preferredBeamDirection=Te.Down}break;case"Dynamic":switch(i.innerText){case"PPP":t.dynamics=g.PPP;break;case"PP":t.dynamics=g.PP;break;case"P":t.dynamics=g.P;break;case"MP":t.dynamics=g.MP;break;case"MF":t.dynamics=g.MF;break;case"F":t.dynamics=g.F;break;case"FF":t.dynamics=g.FF;break;case"FFF":t.dynamics=g.FFF}break;case"GraceNotes":switch(i.innerText){case"OnBeat":t.graceType=w.OnBeat;break;case"BeforeBeat":t.graceType=w.BeforeBeat}break;case"Legato":"true"===i.getAttribute("origin")&&(t.isLegatoOrigin=!0);break;case"Whammy":const e=new X(0,0);e.value=this.toBendValue(Tt.parseFloatSafe(i.getAttribute("originValue"),0)),e.offset=this.toBendOffset(Tt.parseFloatSafe(i.getAttribute("originOffset"),0)),t.addWhammyBarPoint(e);const a=new X(0,0);a.value=this.toBendValue(Tt.parseFloatSafe(i.getAttribute("middleValue"),0)),a.offset=this.toBendOffset(Tt.parseFloatSafe(i.getAttribute("middleOffset1"),0)),t.addWhammyBarPoint(a);const r=new X(0,0);r.value=this.toBendValue(Tt.parseFloatSafe(i.getAttribute("middleValue"),0)),r.offset=this.toBendOffset(Tt.parseFloatSafe(i.getAttribute("middleOffset2"),0)),t.addWhammyBarPoint(r);const n=new X(0,0);n.value=this.toBendValue(Tt.parseFloatSafe(i.getAttribute("destinationValue"),0)),n.offset=this.toBendOffset(Tt.parseFloatSafe(i.getAttribute("destinationOffset"),0)),t.addWhammyBarPoint(n);break;case"Ottavia":switch(i.innerText){case"8va":t.ottava=o._8va;break;case"8vb":t.ottava=o._8vb;break;case"15ma":t.ottava=o._15ma;break;case"15mb":t.ottava=o._15mb}break;case"Lyrics":t.lyrics=this.parseBeatLyrics(i),this._skipApplyLyrics=!0;break;case"Slashed":t.slashed=!0;break;case"DeadSlapped":t.deadSlapped=!0;break;case"Golpe":switch(i.innerText){case"Finger":t.golpe=de.Finger;break;case"Thumb":t.golpe=de.Thumb}break;case"Wah":switch(i.innerText){case"Open":t.wahPedal=pe.Open;break;case"Closed":t.wahPedal=pe.Closed}break;case"UserTransposedPitchStemOrientation":switch(i.innerText){case"Downward":t.preferredBeamDirection=Te.Down;break;case"Upward":t.preferredBeamDirection=Te.Up}break;case"Timer":t.showTimer=!0,t.timer=Tt.parseIntSafe(i.innerText,-1),t.timer<0&&(t.timer=null)}this._beatById.set(s,t)}parseBeatLyrics(e){const t=[];for(const s of e.childElements())if("Line"===s.localName)t.push(s.innerText);return t}parseBeatXProperties(e,t){for(const s of e.childElements())if("XProperty"===s.localName){let e=0;switch(s.getAttribute("id")){case"1124204546":switch(e=Tt.parseIntSafe(s.findChildElement("Int")?.innerText,0),e){case 1:t.beamingMode=fe.ForceMergeWithNext;break;case 2:t.beamingMode=fe.ForceSplitToNext}break;case"1124204552":if(e=Tt.parseIntSafe(s.findChildElement("Int")?.innerText,0),1===e)t.beamingMode!==fe.ForceSplitToNext&&(t.beamingMode=fe.ForceSplitOnSecondaryToNext);break;case"1124204545":e=Tt.parseIntSafe(s.findChildElement("Int")?.innerText,0),t.invertBeamDirection=1===e;break;case"687935489":e=Tt.parseIntSafe(s.findChildElement("Int")?.innerText,0),t.brushDuration=e}}}parseBarXProperties(e,t){for(const s of e.childElements())if("XProperty"===s.localName){if("1124139520"===s.getAttribute("id")){const e=s.findChildElement("Double")??s.findChildElement("Float");t.displayScale=Tt.parseFloatSafe(e?.innerText,1)}}}parseMasterBarXProperties(e,t){for(const s of t.childElements())if("XProperty"===s.localName){if("1124073984"===s.getAttribute("id"))e.displayScale=Tt.parseFloatSafe(s.findChildElement("Double")?.innerText,1)}}parseBeatProperties(e,t){let s=!1,i=null,a=null,r=null,n=null,o=null;for(const h of e.childElements())if("Property"===h.localName){switch(h.getAttribute("name")){case"Brush":"Up"===h.findChildElement("Direction")?.innerText?t.brushType=b.BrushUp:t.brushType=b.BrushDown;break;case"PickStroke":"Up"===h.findChildElement("Direction")?.innerText?t.pickStroke=ae.Up:t.pickStroke=ae.Down;break;case"Slapped":h.findChildElement("Enable")&&(t.slap=!0);break;case"Popped":h.findChildElement("Enable")&&(t.pop=!0);break;case"VibratoWTremBar":switch(h.findChildElement("Strength")?.innerText){case"Wide":t.vibrato=P.Wide;break;case"Slight":t.vibrato=P.Slight}break;case"WhammyBar":s=!0;break;case"WhammyBarExtend":break;case"WhammyBarOriginValue":i||(i=new X(0,0)),i.value=this.toBendValue(Tt.parseFloatSafe(h.findChildElement("Float")?.innerText,0));break;case"WhammyBarOriginOffset":i||(i=new X(0,0)),i.offset=this.toBendOffset(Tt.parseFloatSafe(h.findChildElement("Float")?.innerText,0));break;case"WhammyBarMiddleValue":a=this.toBendValue(Tt.parseFloatSafe(h.findChildElement("Float")?.innerText,0));break;case"WhammyBarMiddleOffset1":r=this.toBendOffset(Tt.parseFloatSafe(h.findChildElement("Float")?.innerText,0));break;case"WhammyBarMiddleOffset2":n=this.toBendOffset(Tt.parseFloatSafe(h.findChildElement("Float")?.innerText,0));break;case"WhammyBarDestinationValue":o||(o=new X(X.MaxPosition,0)),o.value=this.toBendValue(Tt.parseFloatSafe(h.findChildElement("Float")?.innerText,0));break;case"WhammyBarDestinationOffset":o||(o=new X(0,0)),o.offset=this.toBendOffset(Tt.parseFloatSafe(h.findChildElement("Float")?.innerText,0));break;case"BarreFret":t.barreFret=Tt.parseIntSafe(h.findChildElement("Fret")?.innerText,0);break;case"BarreString":switch(h.findChildElement("String")?.innerText){case"0":t.barreShape=ge.Full;break;case"1":t.barreShape=ge.Half}break;case"Rasgueado":switch(h.findChildElement("Rasgueado")?.innerText){case"ii_1":t.rasgueado=me.Ii;break;case"mi_1":t.rasgueado=me.Mi;break;case"mii_1":t.rasgueado=me.MiiTriplet;break;case"mii_2":t.rasgueado=me.MiiAnapaest;break;case"pmp_1":t.rasgueado=me.PmpTriplet;break;case"pmp_2":t.rasgueado=me.PmpAnapaest;break;case"pei_1":t.rasgueado=me.PeiTriplet;break;case"pei_2":t.rasgueado=me.PeiAnapaest;break;case"pai_1":t.rasgueado=me.PaiTriplet;break;case"pai_2":t.rasgueado=me.PaiAnapaest;break;case"ami_1":t.rasgueado=me.AmiTriplet;break;case"ami_2":t.rasgueado=me.AmiAnapaest;break;case"ppp_1":t.rasgueado=me.Ppp;break;case"amii_1":t.rasgueado=me.Amii;break;case"amip_1":t.rasgueado=me.Amip;break;case"eami_1":t.rasgueado=me.Eami;break;case"eamii_1":t.rasgueado=me.Eamii;break;case"peami_1":t.rasgueado=me.Peami}}}s&&(i||(i=new X(0,0)),o||(o=new X(X.MaxPosition,0)),t.addWhammyBarPoint(i),r&&a&&t.addWhammyBarPoint(new X(r,a)),n&&a&&t.addWhammyBarPoint(new X(n,a)),r||n||!a||t.addWhammyBarPoint(new X(X.MaxPosition/2|0,a)),t.addWhammyBarPoint(o))}parseNotes(e){for(const t of e.childElements())if("Note"===t.localName)this.parseNote(t)}parseNote(e){const t=new Ae,s=e.getAttribute("id");for(const i of e.childElements())switch(i.localName){case"Properties":this.parseNoteProperties(i,t,s);break;case"AntiAccent":"normal"===i.innerText.toLowerCase()&&(t.isGhost=!0);break;case"LetRing":t.isLetRing=!0;break;case"Trill":t.trillValue=Tt.parseIntSafe(i.innerText,-1),t.trillSpeed=_.Sixteenth;break;case"Accent":const e=Tt.parseIntSafe(i.innerText,0);1&e&&(t.isStaccato=!0),4&e&&(t.accentuated=B.Heavy),8&e&&(t.accentuated=B.Normal),16&e&&(t.accentuated=B.Tenuto);break;case"Tie":"true"===i.getAttribute("destination").toLowerCase()&&(t.isTieDestination=!0);break;case"Vibrato":switch(i.innerText){case"Slight":t.vibrato=P.Slight;break;case"Wide":t.vibrato=P.Wide}break;case"LeftFingering":switch(i.innerText){case"P":t.leftHandFinger=k.Thumb;break;case"I":t.leftHandFinger=k.IndexFinger;break;case"M":t.leftHandFinger=k.MiddleFinger;break;case"A":t.leftHandFinger=k.AnnularFinger;break;case"C":t.leftHandFinger=k.LittleFinger}break;case"RightFingering":switch(i.innerText){case"P":t.rightHandFinger=k.Thumb;break;case"I":t.rightHandFinger=k.IndexFinger;break;case"M":t.rightHandFinger=k.MiddleFinger;break;case"A":t.rightHandFinger=k.AnnularFinger;break;case"C":t.rightHandFinger=k.LittleFinger}break;case"InstrumentArticulation":t.percussionArticulation=Tt.parseIntSafe(i.innerText,0);break;case"Ornament":switch(i.innerText){case"Turn":t.ornament=he.Turn;break;case"InvertedTurn":t.ornament=he.InvertedTurn;break;case"UpperMordent":t.ornament=he.UpperMordent;break;case"LowerMordent":t.ornament=he.LowerMordent}}this._noteById.set(s,t)}parseNoteProperties(e,t,s){let i=!1,a=null,r=null,n=null,o=null,h=null,l=-1,c=-1;for(const d of e.childElements())if("Property"===d.localName){switch(d.getAttribute("name")){case"ShowStringNumber":d.findChildElement("Enable")&&(t.showStringNumber=!0);break;case"String":t.string=Tt.parseIntSafe(d.findChildElement("String")?.innerText,0)+1;break;case"Fret":t.fret=Tt.parseIntSafe(d.findChildElement("Fret")?.innerText,0);break;case"Element":l=Tt.parseIntSafe(d.findChildElement("Element")?.innerText,0);break;case"Variation":c=Tt.parseIntSafe(d.findChildElement("Variation")?.innerText,0);break;case"Tapped":this._tappedNotes.set(s,!0);break;case"HarmonicType":const e=d.findChildElement("HType");if(e)switch(e.innerText){case"NoHarmonic":t.harmonicType=T.None;break;case"Natural":t.harmonicType=T.Natural;break;case"Artificial":t.harmonicType=T.Artificial;break;case"Pinch":t.harmonicType=T.Pinch;break;case"Tap":t.harmonicType=T.Tap;break;case"Semi":t.harmonicType=T.Semi;break;case"Feedback":t.harmonicType=T.Feedback}break;case"HarmonicFret":const u=d.findChildElement("HFret");u&&(t.harmonicValue=Tt.parseFloatSafe(u.innerText,0));break;case"Muted":d.findChildElement("Enable")&&(t.isDead=!0);break;case"PalmMuted":d.findChildElement("Enable")&&(t.isPalmMute=!0);break;case"Octave":t.octave=Tt.parseIntSafe(d.findChildElement("Number")?.innerText,0),-1===t.tone&&(t.tone=0);break;case"Tone":t.tone=Tt.parseIntSafe(d.findChildElement("Step")?.innerText,0);break;case"ConcertPitch":this.parseConcertPitch(d,t);break;case"Bended":i=!0;break;case"BendOriginValue":a||(a=new X(0,0)),a.value=this.toBendValue(Tt.parseFloatSafe(d.findChildElement("Float")?.innerText,0));break;case"BendOriginOffset":a||(a=new X(0,0)),a.offset=this.toBendOffset(Tt.parseFloatSafe(d.findChildElement("Float")?.innerText,0));break;case"BendMiddleValue":r=this.toBendValue(Tt.parseFloatSafe(d.findChildElement("Float")?.innerText,0));break;case"BendMiddleOffset1":n=this.toBendOffset(Tt.parseFloatSafe(d.findChildElement("Float")?.innerText,0));break;case"BendMiddleOffset2":o=this.toBendOffset(Tt.parseFloatSafe(d.findChildElement("Float")?.innerText,0));break;case"BendDestinationValue":h||(h=new X(X.MaxPosition,0)),h.value=this.toBendValue(Tt.parseFloatSafe(d.findChildElement("Float")?.innerText,0));break;case"BendDestinationOffset":h||(h=new X(0,0)),h.offset=this.toBendOffset(Tt.parseFloatSafe(d.findChildElement("Float")?.innerText,0));break;case"HopoOrigin":d.findChildElement("Enable")&&(t.isHammerPullOrigin=!0);break;case"HopoDestination":break;case"LeftHandTapped":t.isLeftHandTapped=!0;break;case"Slide":const p=Tt.parseIntSafe(d.findChildElement("Flags")?.innerText,0);1&p?t.slideOutType=v.Shift:2&p?t.slideOutType=v.Legato:4&p?t.slideOutType=v.OutDown:8&p&&(t.slideOutType=v.OutUp),16&p?t.slideInType=x.IntoFromBelow:32&p&&(t.slideInType=x.IntoFromAbove),64&p?t.slideOutType=v.PickSlideDown:128&p&&(t.slideOutType=v.PickSlideUp)}}i&&(a||(a=new X(0,0)),h||(h=new X(X.MaxPosition,0)),t.addBendPoint(a),n&&r&&t.addBendPoint(new X(n,r)),o&&r&&t.addBendPoint(new X(o,r)),n||o||!r||t.addBendPoint(new X(X.MaxPosition/2|0,r)),t.addBendPoint(h)),-1!==l&&-1!==c&&(t.percussionArticulation=Le.articulationFromElementVariation(l,c))}parseConcertPitch(e,t){const s=e.findChildElement("Pitch");if(s)for(const e of s.childElements())if("Accidental"===e.localName)switch(e.innerText){case"x":t.accidentalMode=N.ForceDoubleSharp;break;case"#":t.accidentalMode=N.ForceSharp;break;case"b":t.accidentalMode=N.ForceFlat;break;case"bb":t.accidentalMode=N.ForceDoubleFlat}}toBendValue(e){return e*Tt.BendPointValueFactor|0}toBendOffset(e){return e*Tt.BendPointPositionFactor}parseRhythms(e){for(const t of e.childElements())if("Rhythm"===t.localName)this.parseRhythm(t)}parseRhythm(e){const t=new Bt,s=e.getAttribute("id");t.id=s;for(const s of e.childElements())switch(s.localName){case"NoteValue":switch(s.innerText){case"Long":t.value=_.QuadrupleWhole;break;case"DoubleWhole":t.value=_.DoubleWhole;break;case"Whole":t.value=_.Whole;break;case"Half":t.value=_.Half;break;case"Quarter":t.value=_.Quarter;break;case"Eighth":t.value=_.Eighth;break;case"16th":t.value=_.Sixteenth;break;case"32nd":t.value=_.ThirtySecond;break;case"64th":t.value=_.SixtyFourth;break;case"128th":t.value=_.OneHundredTwentyEighth;break;case"256th":t.value=_.TwoHundredFiftySixth}break;case"PrimaryTuplet":t.tupletNumerator=Tt.parseIntSafe(s.getAttribute("num"),-1),t.tupletDenominator=Tt.parseIntSafe(s.getAttribute("den"),-1);break;case"AugmentationDot":t.dots=Tt.parseIntSafe(s.getAttribute("count"),0)}this._rhythmById.set(s,t)}buildModel(){for(let e=0,t=this._masterBars.length;e<t;e++){const t=this._masterBars[e];this.score.addMasterBar(t)}const e=this._masterBars[this._masterBars.length-1];this._doubleBars.has(e)&&(this._doubleBars.delete(e),e.isDoubleBar=!1);for(const e of this._tracksMapping){if(!e)continue;const t=this._tracksById.get(e);this.score.addTrack(t)}let t;for(const e of this._barsOfMasterBar){let s=0;t=[l.C,c.Major];for(let i=0,a=0;i<e.length&&a<this.score.tracks.length;i++){const r=e[i];if(r!==Tt.InvalidId){const e=this._barsById.get(r),i=this.score.tracks[a],n=i.staves[s];n.addBar(e);const o=n.bars.length-1;if(this._keySignatures.has(o)&&(t=this._keySignatures.get(o)),e.keySignature=t[0],e.keySignatureType=t[1],this._doubleBars.has(e.masterBar)&&(e.barLineRight=p.LightLight),this._voicesOfBar.has(r))for(const t of this._voicesOfBar.get(r))if(t!==Tt.InvalidId){const s=this._voiceById.get(t);if(e.addVoice(s),this._beatsOfVoice.has(t))for(const e of this._beatsOfVoice.get(t))if(e!==Tt.InvalidId){const t=Ve.clone(this._beatById.get(e));s.addBeat(t);const i=this._rhythmOfBeat.get(e),a=this._rhythmById.get(i);if(t.duration=a.value,t.dots=a.dots,t.tupletNumerator=a.tupletNumerator,t.tupletDenominator=a.tupletDenominator,this._notesOfBeat.has(e))for(const s of this._notesOfBeat.get(e))if(s!==Tt.InvalidId){const e=He.clone(this._noteById.get(s));n.isPercussion?(e.fret=-1,e.string=-1):e.percussionArticulation=-1,t.addNote(e),this._tappedNotes.has(s)&&(t.tap=!0)}}}else{const t=new ee;e.addVoice(t);const s=new ze;s.isEmpty=!0,s.duration=_.Quarter,t.addBeat(s)}s===i.staves.length-1?(a++,s=0,t=[l.C,c.Major]):(s++,t=[l.C,c.Major])}else a++}}for(const e of this._tracksMapping){if(!e)continue;const t=this._tracksById.get(e);let s=!1;for(const e of t.staves)if(e.isPercussion){s=!0;break}if(s||(t.percussionArticulations=[]),this._automationsPerTrackIdAndBarIndex.has(e)){const s=this._automationsPerTrackIdAndBarIndex.get(e);for(const[e,i]of s)if(t.staves.length>0&&e<t.staves[0].bars.length){const s=t.staves[0].bars[e];if(s.voices.length>0&&s.voices[0].beats.length>0){const e=s.voices[0].beats[0];for(const t of i)e.automations.push(t)}}}if(this._sustainPedalsPerTrackIdAndBarIndex.has(e)){const s=this._sustainPedalsPerTrackIdAndBarIndex.get(e);for(const[e,i]of s)if(t.staves.length>0&&e<t.staves[0].bars.length){t.staves[0].bars[e].sustainPedals=i}}}for(const[e,t]of this._masterTrackAutomations){const s=this.score.masterBars[e];for(let i=0,a=t.length;i<a;i++){const a=t[i];a.type===m.Tempo&&(0===e&&(this.score.tempo=0|a.value,a.text&&(this.score.tempoLabel=a.text)),s.tempoAutomations.push(a))}}}}Tt.InvalidId="-1",Tt.BendPointPositionFactor=X.MaxPosition/100,Tt.BendPointValueFactor=.04;class Nt{constructor(){this.isMultiRest=!1,this.trackViewGroups=[]}}class xt{constructor(){this.showNumbered=!1,this.showSlash=!1,this.showStandardNotation=!1,this.showTablature=!1}}class vt{apply(e){if(this.scoreViews.length>0){let t=0;e.stylesheet.multiTrackMultiBarRest=this.scoreViews[0].isMultiRest;for(const s of this.scoreViews[0].trackViewGroups){if(t<e.tracks.length){const i=e.tracks[t];for(const e of i.staves)e.showTablature=s.showTablature,e.showStandardNotation=s.showStandardNotation,e.showSlash=s.showSlash,e.showNumbered=s.showNumbered}t++}for(let s=1;s<this.scoreViews.length;s++)this.scoreViews[s].isMultiRest&&(e.stylesheet.perTrackMultiBarRest||(e.stylesheet.perTrackMultiBarRest=new Set),t=s-1,e.stylesheet.perTrackMultiBarRest.add(t))}}constructor(e){this.scoreViews=[];const t=ht.fromBuffer(e),s=ot.readInt32BE(t);for(let e=0;e<s;e++){const e=new Nt;this.scoreViews.push(e),e.isMultiRest=pt.gpReadBool(t);const s=ot.readInt32BE(t);for(let i=0;i<s;i++){let s=t.readByte();0===s&&(s=1);const i=new xt;i.showStandardNotation=!!(1&s),i.showTablature=!!(2&s),i.showSlash=!!(4&s),i.showNumbered=!!(8&s),e.trackViewGroups.push(i)}}}static writeForScore(e){const t=ht.withCapacity(128),s=[new Nt];s[0].isMultiRest=e.stylesheet.multiTrackMultiBarRest;for(const t of e.tracks){const i=new xt;i.showStandardNotation=t.staves[0].showStandardNotation,i.showTablature=t.staves[0].showTablature,i.showSlash=t.staves[0].showSlash,i.showNumbered=t.staves[0].showNumbered,s[0].trackViewGroups.push(i);const a=new Nt;a.isMultiRest=!0===e.stylesheet.perTrackMultiBarRest?.has(t.index),a.trackViewGroups.push(i),s.push(a)}ot.writeInt32BE(t,s.length);for(const e of s){t.writeByte(e.isMultiRest?1:0),ot.writeInt32BE(t,e.trackViewGroups.length);for(const s of e.trackViewGroups){let e=0;s.showStandardNotation&&(e|=1),s.showTablature&&(e|=2),s.showSlash&&(e|=4),s.showNumbered&&(e|=8),t.writeByte(e)}}return ot.writeInt32BE(t,1),t.toArray()}}let Pt=class{};class Ft extends Pt{constructor(e){super(),this.n=e}}class Ct extends Pt{constructor(e,t){super(),this.left=e,this.right=t}}class Dt extends Pt{constructor(e,t){super(),this.n=e,this.table=t}}class Et{static make(e,t,s,i){const a=[],r=[];if(i>32)throw new Ze("Invalid huffman");for(let e=0;e<i;e++)a.push(0),r.push(0);for(let r=0;r<s;r++){const s=e[r+t];if(s>=i)throw new Ze("Invalid huffman");a[s]++}let n=0;for(let e=1;e<i-1;e++)n=n+a[e]<<1,r[e]=n;const o=new Map;for(let i=0;i<s;i++){const s=e[i+t];if(0!==s){const e=r[s-1];r[s-1]=e+1,o.set(e<<5|s,i)}}return Et.treeCompress(new Ct(Et.treeMake(o,i,0,1),Et.treeMake(o,i,1,1)))}static treeMake(e,t,s,i){if(i>t)throw new Ze("Invalid huffman");const a=s<<5|i;return e.has(a)?new Ft(e.get(a)):(s<<=1,i+=1,new Ct(Et.treeMake(e,t,s,i),Et.treeMake(e,t,1|s,i)))}static treeCompress(e){const t=Et.treeDepth(e);if(0===t)return e;if(1===t){if(e instanceof Ct)return new Ct(Et.treeCompress(e.left),Et.treeCompress(e.right));throw new Ze("assert")}const s=1<<t,i=[];for(let e=0;e<s;e++)i.push(new Ft(-1));return Et.treeWalk(i,0,0,t,e),new Dt(t,i)}static treeWalk(e,t,s,i,a){a instanceof Ct&&i>0?(Et.treeWalk(e,t,s+1,i-1,a.left),Et.treeWalk(e,t|1<<s,s+1,i-1,a.right)):e[t]=Et.treeCompress(a)}static treeDepth(e){if(e instanceof Ft)return 0;if(e instanceof Dt)throw new Ze("assert");if(e instanceof Ct){const t=Et.treeDepth(e.left),s=Et.treeDepth(e.right);return 1+(t<s?t:s)}return 0}}var Lt,Mt,It,At,Rt,Ot,Ht,Wt,Vt,Gt,zt,Ut,Xt,Jt,Yt,$t,qt,jt,Kt,Qt,Zt,es,ts,ss,is,as,rs,ns,os;!function(e){e[e.Head=0]="Head",e[e.Block=1]="Block",e[e.CData=2]="CData",e[e.Flat=3]="Flat",e[e.Crc=4]="Crc",e[e.Dist=5]="Dist",e[e.DistOne=6]="DistOne",e[e.Done=7]="Done"}(Lt||(Lt={}));class hs{constructor(){this.buffer=new Uint8Array(hs.BufferSize),this.pos=0}slide(){const e=new Uint8Array(hs.BufferSize);this.pos-=hs.Size,e.set(this.buffer.subarray(hs.Size,hs.Size+this.pos),0),this.buffer=e}addBytes(e,t,s){this.pos+s>hs.BufferSize&&this.slide(),this.buffer.set(e.subarray(t,t+s),this.pos),this.pos+=s}addByte(e){this.pos===hs.BufferSize&&this.slide(),this.buffer[this.pos]=e,this.pos++}getLastChar(){return this.buffer[this.pos-1]}available(){return this.pos}}hs.Size=32768,hs.BufferSize=65536;class ls{static buildFixedHuffman(){const e=[];for(let t=0;t<288;t++)e.push(t<=143?8:t<=255?9:t<=279?7:8);return Et.make(e,0,288,10)}constructor(e){this._nbits=0,this._bits=0,this._state=Lt.Block,this._isFinal=!1,this._huffman=ls._fixedHuffman,this._huffdist=null,this._len=0,this._dist=0,this._needed=0,this._output=null,this._outpos=0,this._lengths=[],this._window=new hs,this._input=e;for(let e=0;e<19;e++)this._lengths.push(-1)}readBytes(e,t,s){if(this._needed=s,this._outpos=t,this._output=e,s>0)for(;this.inflateLoop(););return s-this._needed}inflateLoop(){switch(this._state){case Lt.Head:const e=this._input.readByte();if(8!==(15&e))throw new Ze("Invalid data");const t=this._input.readByte(),s=!!(32&t);if(((e<<8)+t)%31!=0)throw new Ze("Invalid data");if(s)throw new Ze("Unsupported dictionary");return this._state=Lt.Block,!0;case Lt.Crc:return this._state=Lt.Done,!0;case Lt.Done:return!1;case Lt.Block:switch(this._isFinal=this.getBit(),this.getBits(2)){case 0:this._len=ot.readUInt16LE(this._input);if(ot.readUInt16LE(this._input)!==65535-this._len)throw new Ze("Invalid data");this._state=Lt.Flat;const e=this.inflateLoop();return this.resetBits(),e;case 1:return this._huffman=ls._fixedHuffman,this._huffdist=null,this._state=Lt.CData,!0;case 2:const t=this.getBits(5)+257,s=this.getBits(5)+1,i=this.getBits(4)+4;for(let e=0;e<i;e++)this._lengths[ls.CodeLengthsPos[e]]=this.getBits(3);for(let e=i;e<19;e++)this._lengths[ls.CodeLengthsPos[e]]=0;this._huffman=Et.make(this._lengths,0,19,8);const a=[];for(let e=0;e<t+s;e++)a.push(0);return this.inflateLengths(a,t+s),this._huffdist=Et.make(a,t,s,16),this._huffman=Et.make(a,0,t,16),this._state=Lt.CData,!0;default:throw new Ze("Invalid data")}case Lt.Flat:{const e=this._len<this._needed?this._len:this._needed,t=ot.readByteArray(this._input,e);return this._len-=e,this.addBytes(t,0,e),0===this._len&&(this._state=this._isFinal?Lt.Crc:Lt.Block),this._needed>0}case Lt.DistOne:{const e=this._len<this._needed?this._len:this._needed;return this.addDistOne(e),this._len-=e,0===this._len&&(this._state=Lt.CData),this._needed>0}case Lt.Dist:for(;this._len>0&&this._needed>0;){const e=this._len<this._dist?this._len:this._dist,t=this._needed<e?this._needed:e;this.addDist(this._dist,t),this._len-=t}return 0===this._len&&(this._state=Lt.CData),this._needed>0;case Lt.CData:let i=this.applyHuffman(this._huffman);if(i<256)return this.addByte(i),this._needed>0;if(256===i)return this._state=this._isFinal?Lt.Crc:Lt.Block,!0;i=i-257&255;let a=ls.LenExtraBitsTbl[i];if(-1===a)throw new Ze("Invalid data");this._len=ls.LenBaseValTbl[i]+this.getBits(a);const r=this._huffdist,n=r?this.applyHuffman(r):this.getRevBits(5);if(a=ls.DistExtraBitsTbl[n],-1===a)throw new Ze("Invalid data");if(this._dist=ls.DistBaseValTbl[n]+this.getBits(a),this._dist>this._window.available())throw new Ze("Invalid data");return this._state=1===this._dist?Lt.DistOne:Lt.Dist,!0}return!1}addDistOne(e){const t=this._window.getLastChar();for(let s=0;s<e;s++)this.addByte(t)}addByte(e){this._window.addByte(e),this._output[this._outpos]=e,this._needed--,this._outpos++}addDist(e,t){this.addBytes(this._window.buffer,this._window.pos-e,t)}getBit(){0===this._nbits&&(this._nbits=8,this._bits=this._input.readByte());const e=!(1&~this._bits);return this._nbits--,this._bits=this._bits>>1,e}getBits(e){for(;this._nbits<e;)this._bits=this._bits|this._input.readByte()<<this._nbits,this._nbits+=8;const t=this._bits&(1<<e)-1;return this._nbits-=e,this._bits=this._bits>>e,t}getRevBits(e){return 0===e?0:this.getBit()?1<<e-1|this.getRevBits(e-1):this.getRevBits(e-1)}resetBits(){this._bits=0,this._nbits=0}addBytes(e,t,s){this._window.addBytes(e,t,s),this._output.set(e.subarray(t,t+s),this._outpos),this._needed-=s,this._outpos+=s}inflateLengths(e,t){let s=0,i=0;for(;s<t;){const a=this.applyHuffman(this._huffman);switch(a){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:case 8:case 9:case 10:case 11:case 12:case 13:case 14:case 15:i=a,e[s]=a,s++;break;case 16:const r=s+3+this.getBits(2);if(r>t)throw new Ze("Invalid data");for(;s<r;)e[s]=i,s++;break;case 17:if(s+=3+this.getBits(3),s>t)throw new Ze("Invalid data");break;case 18:if(s+=11+this.getBits(7),s>t)throw new Ze("Invalid data");break;default:throw new Ze("Invalid data")}}}applyHuffman(e){if(e instanceof Ft)return e.n;if(e instanceof Ct)return this.applyHuffman(this.getBit()?e.right:e.left);if(e instanceof Dt)return this.applyHuffman(e.table[this.getBits(e.n)]);throw new Ze("Invalid data")}}ls.LenExtraBitsTbl=[0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,-1,-1],ls.LenBaseValTbl=[3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258],ls.DistExtraBitsTbl=[0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,-1,-1],ls.DistBaseValTbl=[1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577],ls.CodeLengthsPos=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15],ls._fixedHuffman=ls.buildFixedHuffman();class cs{constructor(e,t){this.fullName=e;const s=e.lastIndexOf("/");this.fileName=-1===s||s===e.length-1?this.fullName:e.substr(s+1),this.data=t}}cs.OptionalDataDescriptorSignature=134695760,cs.CompressionMethodDeflate=8,cs.LocalFileHeaderSignature=67324752,cs.CentralFileHeaderSignature=33639248,cs.EndOfCentralDirSignature=101010256;class ds{constructor(e){this._readable=e}read(){const e=[];for(;;){const t=this.readEntry();if(!t)break;e.push(t)}return e}readEntry(){const e=this._readable;if(ot.readInt32LE(e)!==cs.LocalFileHeaderSignature)return null;ot.readUInt16LE(e);const t=ot.readUInt16LE(e),s=ot.readUInt16LE(e),i=0!==s;if(i&&s!==cs.CompressionMethodDeflate)return null;ot.readInt16LE(this._readable),ot.readInt16LE(this._readable),ot.readInt32LE(e),ot.readInt32LE(e);const a=ot.readInt32LE(e),r=ot.readInt16LE(e),n=ot.readInt16LE(e),o=ot.toString(ot.readByteArray(e,r),"utf-8");let h;if(e.skip(n),i){const e=ht.empty(),t=new ls(this._readable),s=new Uint8Array(65536);for(;;){const i=t.readBytes(s,0,s.length);if(e.write(s,0,i),i<s.length)break}h=e.toArray()}else h=ot.readByteArray(this._readable,a);if(8&t){ot.readInt32LE(this._readable)===cs.OptionalDataDescriptorSignature&&ot.readInt32LE(this._readable),ot.readInt32LE(this._readable),ot.readInt32LE(this._readable)}return new cs(o,h)}}class us{constructor(){this.trackViewGroups=[]}}class ps{constructor(){this.isVisible=!1}}!function(e){e[e.PageVertical=0]="PageVertical",e[e.PageGrid=1]="PageGrid",e[e.PageParchment=2]="PageParchment",e[e.ScreenVertical=3]="ScreenVertical",e[e.ScreenHorizontal=4]="ScreenHorizontal",e[e.PageHorizontal=5]="PageHorizontal"}(Mt||(Mt={}));class gs{constructor(e,t){this.zoomLevel=4,this.view=Mt.PageVertical,this.muiltiVoiceCursor=!1,this.scoreViews=[];const s=ht.fromBuffer(t);this.zoomLevel=ot.readInt32BE(s),this.view=s.readByte(),this.muiltiVoiceCursor=0!==s.readByte();const i=e.scoreViews.length;for(let t=0;t<i;t++){const i=new us;this.scoreViews.push(i);const a=e.scoreViews[t];for(let e=0;e<a.trackViewGroups.length;e++){const e=new ps;e.isVisible=0!==s.readByte(),i.trackViewGroups.push(e)}}}apply(e){if(this.scoreViews.length>0){let t=0;for(const s of this.scoreViews[0].trackViewGroups){if(t<e.tracks.length){e.tracks[t].isVisibleOnMultiTrack=s.isVisible}t++}}}static writeForScore(e){const t=ht.withCapacity(128);ot.writeInt32BE(t,4),t.writeByte(0);const s=e.tracks.length>0&&e.tracks[0].staves[0].bars[0].isMultiVoice;t.writeByte(s?255:0);for(const s of e.tracks)t.writeByte(s.isVisibleOnMultiTrack?255:0);for(const s of e.tracks)t.writeByte(255);return t.toArray()}}class ms extends Ye{get name(){return"Guitar Pro 7-8"}readScore(){q.debug(this.name,"Loading ZIP entries");const e=new ds(this.data);let t;try{t=e.read()}catch(e){throw new qe("No Zip archive",e)}q.debug(this.name,"Zip entries loaded");let s=null,i=null,a=null,r=null;for(const e of t)switch(e.fileName){case"score.gpif":s=ot.toString(e.data,this.settings.importer.encoding);break;case"BinaryStylesheet":i=e.data;break;case"PartConfiguration":a=e.data;break;case"LayoutConfiguration":r=e.data}if(!s)throw new qe("No score.gpif found in zip archive");q.debug(this.name,"Start Parsing score.gpif");const n=new Tt;n.parseXml(s,this.settings),q.debug(this.name,"score.gpif parsed");const o=n.score;if(i){q.debug(this.name,"Start Parsing BinaryStylesheet");new ft(i).apply(o),q.debug(this.name,"BinaryStylesheet parsed")}let h=null;if(a&&(q.debug(this.name,"Start Parsing Part Configuration"),h=new vt(a),h.apply(o),q.debug(this.name,"Part Configuration parsed")),r&&null!=h){q.debug(this.name,"Start Parsing Layout Configuration");new gs(h,r).apply(o),q.debug(this.name,"Layout Configuration parsed")}return o}}class fs extends $e{constructor(){super(Se.Format,"Unexpected end of data within reader"),Object.setPrototypeOf(this,fs.prototype)}}class ys{constructor(e){this._currentByte=0,this._position=ys.ByteSize,this._source=e}readByte(){return this.readBits(8)}readBytes(e){const t=new Uint8Array(e);for(let s=0;s<e;s++)t[s]=255&this.readByte();return t}readBits(e){let t=0,s=e-1;for(;s>=0;)t|=this.readBit()<<s,s--;return t}readBitsReversed(e){let t=0;for(let s=0;s<e;s++)t|=this.readBit()<<s;return t}readBit(){if(this._position>=8){if(this._currentByte=this._source.readByte(),-1===this._currentByte)throw new fs;this._position=0}const e=this._currentByte>>ys.ByteSize-this._position-1&1;return this._position++,e}readAll(){const e=ht.empty();try{for(;;)e.writeByte(255&this.readByte())}catch(e){if(!(e instanceof fs))throw e}return e.toArray()}}ys.ByteSize=8;class bs{constructor(){this.fileName="",this.fileSize=0,this.data=null}}class Ss{constructor(){this.files=[],this.files=[],this.fileFilter=e=>!0}load(e){const t=new ys(e);this.readBlock(t)}readHeader(e){return this.getString(e.readBytes(4),0,4)}decompress(e,t=!1){const s=ht.empty();let i;const a=this.getInteger(e.readBytes(4),0);try{for(;s.length<a;){if(1===e.readBits(1)){const t=e.readBits(4),a=e.readBitsReversed(t),r=e.readBitsReversed(t),n=s.length-a,o=Math.min(a,r);i=s.getBuffer(),s.write(i,n,o)}else{const t=e.readBitsReversed(2);for(let i=0;i<t;i++)s.writeByte(e.readByte())}}}catch(e){if(!(e instanceof fs))throw e}i=s.getBuffer();const r=t?4:0,n=s.length-r,o=new Uint8Array(n),h=n;return o.set(i.subarray(r,r+h),0),o}readBlock(e){const t=this.readHeader(e);if("BCFZ"===t)this.readUncompressedBlock(this.decompress(e,!0));else{if("BCFS"!==t)throw new qe("Unsupported format");this.readUncompressedBlock(e.readAll())}}readUncompressedBlock(e){const t=4096;let s=t;for(;s+3<e.length;){if(2===this.getInteger(e,s)){const i=new bs;i.fileName=this.getString(e,s+4,127),i.fileSize=this.getInteger(e,s+140);const a=!this.fileFilter||this.fileFilter(i.fileName);a&&this.files.push(i);const r=s+148;let n=0,o=0;const h=a?ht.withCapacity(i.fileSize):null;for(;n=this.getInteger(e,r+4*o++),0!==n;)s=n*t,a&&h.write(e,s,t);if(a){i.data=new Uint8Array(Math.min(i.fileSize,h.length));const e=h.toArray();i.data.set(e.subarray(0,0+i.data.length),0)}}s+=t}}getString(e,t,s){let i="";for(let a=0;a<s;a++){const s=255&e[t+a];if(0===s)break;i+=String.fromCharCode(s)}return i}getInteger(e,t){return e[t+3]<<24|e[t+2]<<16|e[t+1]<<8|e[t]}}Ss.HeaderBcFs="BCFS",Ss.HeaderBcFz="BCFZ";class _s extends Ye{get name(){return"Guitar Pro 6"}readScore(){q.debug(this.name,"Loading GPX filesystem");const e=new Ss;e.fileFilter=e=>e.endsWith("score.gpif")||e.endsWith("BinaryStylesheet")||e.endsWith("PartConfiguration")||e.endsWith("LayoutConfiguration"),e.load(this.data),q.debug(this.name,"GPX filesystem loaded");let t=null,s=null,i=null,a=null;for(const r of e.files)switch(r.fileName){case"score.gpif":t=ot.toString(r.data,this.settings.importer.encoding);break;case"BinaryStylesheet":s=r.data;break;case"PartConfiguration":i=r.data;break;case"LayoutConfiguration":a=r.data}if(!t)throw new qe("No score.gpif found in GPX");q.debug(this.name,"Start Parsing score.gpif");const r=new Tt;r.parseXml(t,this.settings),q.debug(this.name,"score.gpif parsed");const n=r.score;if(s){q.debug(this.name,"Start Parsing BinaryStylesheet");new ft(s).apply(n),q.debug(this.name,"BinaryStylesheet parsed")}let o=null;if(i&&(q.debug(this.name,"Start Parsing Part Configuration"),o=new vt(i),o.apply(n),q.debug(this.name,"Part Configuration parsed")),a&&null!=o){q.debug(this.name,"Start Parsing Layout Configuration");new gs(o,a).apply(n),q.debug(this.name,"Layout Configuration parsed")}return n}}!function(e){e[e.None=0]="None",e[e.Natural=1]="Natural",e[e.Sharp=2]="Sharp",e[e.Flat=3]="Flat",e[e.NaturalQuarterNoteUp=4]="NaturalQuarterNoteUp",e[e.SharpQuarterNoteUp=5]="SharpQuarterNoteUp",e[e.FlatQuarterNoteUp=6]="FlatQuarterNoteUp",e[e.DoubleSharp=7]="DoubleSharp",e[e.DoubleFlat=8]="DoubleFlat"}(It||(It={}));class ws{constructor(){this.maxLine=-1e3,this.minLine=-1e3}}class Bs{constructor(e){this._registeredAccidentals=new Map,this._appliedScoreLines=new Map,this._appliedScoreLinesByValue=new Map,this._notesByValue=new Map,this._beatLines=new Map,this.maxLineBeat=null,this.minLineBeat=null,this.maxLine=-1e3,this.minLine=-1e3,this._barRenderer=e,this._bar=e.bar}static getPercussionLine(e,t){return t<e.staff.track.percussionArticulations.length?e.staff.track.percussionArticulations[t].staffLine:Le.getArticulationByInputMidiNumber(t)?.staffLine??0}static getNoteValue(e){if(e.isPercussion)return e.percussionArticulation;let t=e.displayValue;switch(e.accidentalMode){case N.ForceDoubleFlat:t+=2;break;case N.ForceDoubleSharp:t-=2;break;case N.ForceFlat:t+=1;break;case N.ForceSharp:t-=1}return t}applyAccidental(e){const t=Bs.getNoteValue(e),s=e.hasQuarterToneOffset;return this.getAccidental(t,s,e.beat,!1,e)}applyAccidentalForValue(e,t,s,i){return this.getAccidental(t,s,e,i,null)}static computeLineWithoutAccidentals(e,t){let s=0;const i=Bs.getNoteValue(t);return s=t.isPercussion?Bs.getPercussionLine(e,i):Bs.calculateNoteSteps(e.keySignature,e.clef,i),s}static computeAccidental(e,t,s,i,a=null){const r=e+7,n=s%12,o=r<7?It.Flat:It.Sharp,h=Bs.KeySignatureLookup[r][n],l=Bs.AccidentalNotes[n];let c=It.None;if(i)switch(c=l?o:It.Natural,c){case It.Natural:c=It.NaturalQuarterNoteUp;break;case It.Sharp:c=It.SharpQuarterNoteUp;break;case It.Flat:c=It.FlatQuarterNoteUp}else{switch(t){case N.ForceSharp:c=It.Sharp;break;case N.ForceDoubleSharp:c=It.DoubleSharp;break;case N.ForceFlat:c=It.Flat;break;case N.ForceDoubleFlat:c=It.DoubleFlat;break;default:l?c=o:h&&(c=It.Natural)}c!==It.None?null!=a?a===c&&(c=It.None):h&&c===o&&(c=It.None):null!==a&&(c=a===It.Natural?It.None:It.Natural)}return c}getAccidental(e,t,s,i,a=null){let r=0,n=It.None;if(null!=a?a.isPercussion:this._bar.staff.isPercussion)r=Bs.getPercussionLine(this._bar,e);else{const s=a?a.accidentalMode:N.Default;r=Bs.calculateNoteSteps(this._bar.keySignature,this._bar.clef,e);const i=this._registeredAccidentals.has(r)?this._registeredAccidentals.get(r):null;n=Bs.computeAccidental(this._bar.keySignature,s,e,t,i);let o=!1;switch(n){case It.NaturalQuarterNoteUp:case It.SharpQuarterNoteUp:case It.FlatQuarterNoteUp:break;default:if(a&&a.isTieDestination&&0===a.beat.index){const e=this._barRenderer.scoreRenderer.layout?.getRendererForBar(this._barRenderer.staff.staffId,a.tieOrigin.beat.voice.bar);if(e&&e.staff===this._barRenderer.staff){e.accidentalHelper.getNoteLine(a.tieOrigin)===r&&(o=!0)}}o?n=It.None:n!==It.None&&this._registeredAccidentals.set(r,n)}}return a?(this._appliedScoreLines.set(a.id,r),this._notesByValue.set(e,a)):this._appliedScoreLinesByValue.set(e,r),(-1e3===this.minLine||this.minLine<r)&&(this.minLine=r,this.minLineBeat=s),(-1e3===this.maxLine||this.maxLine>r)&&(this.maxLine=r,this.maxLineBeat=s),i||this.registerLine(s,r),n}registerLine(e,t){let s;this._beatLines.has(e.id)?s=this._beatLines.get(e.id):(s=new ws,this._beatLines.set(e.id,s)),(-1e3===s.minLine||t<s.minLine)&&(s.minLine=t),(-1e3===s.minLine||t>s.maxLine)&&(s.maxLine=t)}getMaxLine(e){return this._beatLines.has(e.id)?this._beatLines.get(e.id).maxLine:0}getMinLine(e){return this._beatLines.has(e.id)?this._beatLines.get(e.id).minLine:0}static calculateNoteSteps(e,t,s){const i=e,a=t,r=s%12,n=(s/12|0)-1;let o=Bs.OctaveSteps[a];o-=n*Bs.StepsPerOctave;return o-=(ie.keySignatureIsSharp(i)||ie.keySignatureIsNatural(i)?Bs.SharpNoteSteps:Bs.FlatNoteSteps)[r],o}getNoteLine(e){return this._appliedScoreLines.get(e.id)}getNoteLineForValue(e,t=!1){return this._appliedScoreLinesByValue.has(e)?this._appliedScoreLinesByValue.get(e):t&&this._notesByValue.has(e)?this.getNoteLine(this._notesByValue.get(e)):0}}Bs.KeySignatureLookup=[[!0,!0,!0,!0,!0,!0,!0,!0,!0,!0,!0,!0],[!0,!0,!0,!0,!0,!1,!0,!0,!0,!0,!0,!0],[!1,!0,!0,!0,!0,!1,!0,!0,!0,!0,!0,!0],[!1,!0,!0,!0,!0,!1,!1,!1,!0,!0,!0,!0],[!1,!1,!1,!0,!0,!1,!1,!1,!0,!0,!0,!0],[!1,!1,!1,!0,!0,!1,!1,!1,!1,!1,!0,!0],[!1,!1,!1,!1,!1,!1,!1,!1,!1,!1,!0,!0],[!1,!1,!1,!1,!1,!1,!1,!1,!1,!1,!1,!1],[!1,!1,!1,!1,!1,!0,!0,!1,!1,!1,!1,!1],[!0,!0,!1,!1,!1,!0,!0,!1,!1,!1,!1,!1],[!0,!0,!1,!1,!1,!0,!0,!0,!0,!1,!1,!1],[!0,!0,!0,!0,!1,!0,!0,!0,!0,!1,!1,!1],[!0,!0,!0,!0,!1,!0,!0,!0,!0,!0,!0,!1],[!0,!0,!0,!0,!0,!0,!0,!0,!0,!0,!0,!1],[!0,!0,!0,!0,!0,!0,!0,!0,!0,!0,!0,!0]],Bs.AccidentalNotes=[!1,!0,!1,!0,!1,!1,!0,!1,!0,!1,!0,!1],Bs.StepsPerOctave=7,Bs.OctaveSteps=[38,32,30,26,38],Bs.SharpNoteSteps=[0,0,1,1,2,3,3,4,4,5,5,6],Bs.FlatNoteSteps=[0,1,1,2,2,3,4,4,5,5,6,6];class ks{constructor(){this.currentDynamics=g.F,this.slideOrigins=new Map,this.transpose=0,this.isExplicitlyBeamed=!1,this.tieStarts=new Set,this.tieStartIds=new Map,this.slideOrigins=new Map,this.slurStarts=new Map}}class Ts extends Ee{constructor(){super(...arguments),this.outputMidiChannel=-1,this.outputMidiProgram=-1,this.outputVolume=-1,this.outputBalance=-1}}class Ns{constructor(e){this.instruments=new Map,this._instrumentIdToArticulationIndex=new Map,this._lyricsLine=0,this._lyricsLines=new Map,this.track=e}getLyricLine(e){if(this._lyricsLines.has(e))return this._lyricsLines.get(e);const t=this._lyricsLine;return this._lyricsLines.set(e,t),this._lyricsLine++,t}getOrCreateArticulation(e,t){const s=12*t.octave+t.tone,i=`${e}_${s}`;if(this._instrumentIdToArticulationIndex.has(i))return this._instrumentIdToArticulationIndex.get(i);let a;a=this.instruments.has(e)?this.instruments.get(e):Ns.defaultNoteArticulation;const r=this.track.percussionArticulations.length,n=t.beat.voice.bar;let o;o=0===s?4:Bs.calculateNoteSteps(n.keySignature,n.clef,s);const h=o-(9-(2*t.beat.voice.bar.staff.standardNotationLineCount-1)),l=new Ee(a.elementType,h,a.outputMidiNumber,a.noteHeadDefault,a.noteHeadHalf,a.noteHeadWhole,a.techniqueSymbol,a.techniqueSymbolPlacement);return this._instrumentIdToArticulationIndex.set(i,r),this.track.percussionArticulations.push(l),r}}Ns.defaultNoteArticulation=new Ee("Default",0,0,re.NoteheadBlack,re.NoteheadHalf,re.NoteheadWhole);class xs extends Ye{constructor(){super(...arguments),this._idToTrackInfo=new Map,this._indexToTrackInfo=new Map,this._staffToContext=new Map,this._divisionsPerQuarterNote=1,this._currentDynamics=g.F,this._musicalPosition=0,this._lastBeat=null,this._nextMasterBarRepeatEnding=0,this._nextBeatAutomations=null,this._nextBeatChord=null,this._nextBeatCrescendo=null,this._nextBeatLetRing=!1,this._nextBeatPalmMute=!1,this._nextBeatOttavia=null,this._nextBeatText=null,this._simileMarkAllStaves=null,this._simileMarkPerStaff=null,this._isBeatSlash=!1,this._keyAllStaves=null,this._currentTrillStep=-1}get name(){return"MusicXML"}readScore(){const e=this.extractMusicXml(),t=new wt;try{t.parse(e)}catch(e){throw new qe("Unsupported format",e)}return this._score=new Je,this._score.tempo=120,this._score.stylesheet.hideDynamics=!0,this.parseDom(t),ie.consolidate(this._score),this._score.finish(this.settings),this._score.rebuildRepeatGroups(),this._score}extractMusicXml(){const e=new ds(this.data);let t;try{t=e.read()}catch(e){t=[]}if(0===t.length)return this.data.reset(),ot.toString(this.data.readAll(),this.settings.importer.encoding);const s=t.find((e=>"META-INF/container.xml"===e.fullName));if(!s)throw new qe("No compressed MusicXML");const i=new wt;try{i.parse(ot.toString(s.data,this.settings.importer.encoding))}catch(e){throw new qe("Malformed container.xml, could not parse as XML",e)}const a=i.firstElement;if(!a||"container"!==a.localName)throw new qe("Malformed container.xml, root element not 'container'");const r=a.findChildElement("rootfiles");if(!r)throw new qe("Malformed container.xml, 'container/rootfiles' not found");let n="";for(const e of r.childElements())if("rootfile"===e.localName){n=e.getAttribute("full-path");break}if(!n)throw new qe("Unsupported compressed MusicXML, missing rootfile");const o=t.find((e=>e.fullName===n));if(!o)throw new qe(`Malformed container.xml, '${n}' not contained in zip`);return ot.toString(o.data,this.settings.importer.encoding)}parseDom(e){const t=e.firstElement;if(!t)throw new qe("Unsupported format");switch(t.localName){case"score-partwise":this.parsePartwise(t);break;case"score-timewise":this.parseTimewise(t);break;default:throw new qe("Unsupported format")}}parsePartwise(e){for(const t of e.childElements())switch(t.localName){case"credit":this.parseCredit(t);break;case"identification":this.parseIdentification(t);break;case"movement-title":this.parseMovementTitle(t);break;case"part":this.parsePartwisePart(t);break;case"part-list":this.parsePartList(t);break;case"work":this.parseWork(t)}}parseTimewise(e){let t=0;for(const s of e.childElements())switch(s.localName){case"credit":this.parseCredit(s);break;case"identification":this.parseIdentification(s);break;case"movement-title":this.parseMovementTitle(s);break;case"part-list":this.parsePartList(s);break;case"work":this.parseWork(s);break;case"measure":this.parseTimewiseMeasure(s,t),t++}}parseCredit(e){if("1"!==e.getAttribute("page","1"))return;const t=[];let s=null,i="";for(const a of e.childElements())switch(a.localName){case"credit-type":t.push(a.innerText);break;case"credit-words":null===s&&(s=a),i+=a.innerText}if(t.length>0)for(const e of t)switch(e){case"title":this._score.title=xs.sanitizeDisplay(i);break;case"subtitle":this._score.subTitle=xs.sanitizeDisplay(i);break;case"composer":case"arranger":this._score.artist=xs.sanitizeDisplay(i);break;case"lyricist":this._score.words=xs.sanitizeDisplay(i);break;case"rights":this._score.copyright=xs.sanitizeDisplay(i)}else if(s){const e=s.getAttribute("font-size","0"),t=s.getAttribute("font-size","top"),a=s.getAttribute("halign","left");if("top"===t){if(i.includes("copyright")||i.includes("Copyright")||i.includes("©")||i.includes("(c)")||i.includes("(C)"))return void(this._score.copyright=xs.sanitizeDisplay(i));if("center"===a||"center"===e){if(0===this._score.title.length)return void(this._score.title=xs.sanitizeDisplay(i));if(0===this._score.subTitle.length)return void(this._score.subTitle=xs.sanitizeDisplay(i));if(0===this._score.album.length)return void(this._score.album=xs.sanitizeDisplay(i))}else if(("right"===a||"right"===e)&&0===this._score.music.length)return void(this._score.music=xs.sanitizeDisplay(i));if(0===this._score.artist.length)return void(this._score.artist=xs.sanitizeDisplay(i));if(0===this._score.words.length)return void(this._score.words=xs.sanitizeDisplay(i))}}}static sanitizeDisplay(e){return e.replaceAll("\r","").replaceAll("\n"," ").replaceAll("\t","  ").replaceAll(" "," ")}parseIdentification(e){for(const t of e.childElements())switch(t.localName){case"creator":if(t.attributes.has("type"))switch(t.attributes.get("type")){case"composer":this._score.artist=xs.sanitizeDisplay(t.innerText);break;case"lyricist":this._score.words=xs.sanitizeDisplay(t.innerText);break;case"arranger":this._score.music=xs.sanitizeDisplay(t.innerText)}else this._score.artist=xs.sanitizeDisplay(t.innerText);break;case"rights":this._score.copyright.length>0&&(this._score.copyright+=", "),this._score.copyright+=t.innerText,t.attributes.has("type")&&(this._score.copyright+=` (${t.attributes.get("type")})`);break;case"encoding":this.parseEncoding(t)}}parseEncoding(e){for(const t of e.childElements())switch(t.localName){case"encoder":this._score.tab.length>0&&(this._score.tab+=", "),this._score.tab+=t.innerText,t.attributes.has("type")&&(this._score.tab+=` (${t.attributes.get("type")})`);break;case"encoding-description":this._score.notices+=xs.sanitizeDisplay(t.innerText)}}parseMovementTitle(e){0===this._score.title.length?this._score.title=xs.sanitizeDisplay(e.innerText):this._score.subTitle=xs.sanitizeDisplay(e.innerText)}parsePartList(e){for(const t of e.childElements())if("score-part"===t.localName)this.parseScorePart(t)}parseScorePart(e){const t=new rt;t.ensureStaveCount(1),this._score.addTrack(t);const s=e.attributes.get("id"),i=new Ns(t);this._idToTrackInfo.set(s,i),this._indexToTrackInfo.set(t.index,i);for(const s of e.childElements())switch(s.localName){case"part-name":t.name=xs.sanitizeDisplay(s.innerText);break;case"part-name-display":t.name=this.parsePartDisplayAsText(s);break;case"part-abbreviation":t.shortName=xs.sanitizeDisplay(s.innerText);break;case"part-abbreviation-display":t.shortName=this.parsePartDisplayAsText(s);break;case"score-instrument":this.parseScoreInstrument(s,i);break;case"midi-device":s.attributes.has("port")&&(t.playbackInfo.port=Number.parseInt(s.attributes.get("port"),10));break;case"midi-instrument":this.parseScorePartMidiInstrument(s,i)}i.firstArticulation&&(i.firstArticulation.outputMidiProgram>=0&&(t.playbackInfo.program=i.firstArticulation.outputMidiProgram),i.firstArticulation.outputBalance>=0&&(t.playbackInfo.balance=i.firstArticulation.outputBalance),i.firstArticulation.outputVolume>=0&&(t.playbackInfo.volume=i.firstArticulation.outputVolume),i.firstArticulation.outputMidiChannel>=0&&(t.playbackInfo.primaryChannel=i.firstArticulation.outputMidiChannel,t.playbackInfo.secondaryChannel=i.firstArticulation.outputMidiChannel))}parseScoreInstrument(e,t){const s=new Ts;t.firstArticulation||(t.firstArticulation=s),t.instruments.set(e.getAttribute("id",""),s)}parseScorePartMidiInstrument(e,t){const s=e.getAttribute("id","");if(!t.instruments.has(s))return;const i=t.instruments.get(s);for(const t of e.childElements())switch(t.localName){case"midi-channel":i.outputMidiChannel=Number.parseInt(t.innerText)-1;break;case"midi-program":i.outputMidiProgram=Number.parseInt(t.innerText)-1;break;case"midi-unpitched":i.outputMidiNumber=Number.parseInt(t.innerText)-1;break;case"volume":i.outputVolume=xs.interpolatePercent(Number.parseFloat(t.innerText));break;case"pan":i.outputBalance=xs.interpolatePan(Number.parseFloat(t.innerText))}}static interpolatePercent(e){return 0|xs.interpolate(0,100,0,16,e)}static interpolatePan(e){return 0|xs.interpolate(-90,90,0,16,e)}static interpolate(e,t,s,i,a){return s+(i-s)*((a-e)/(t-e))}parsePartDisplayAsText(e){let t="";for(const s of e.childElements())switch(s.localName){case"display-text":t+=s.innerText;break;case"accidental-text":switch(s.innerText){case"sharp":t+="♯";break;case"natural":t+="♮";break;case"flat":t+="♭";break;case"double-sharp":t+="𝄪";break;case"sharp-sharp":t+="♯♯";break;case"flat-flat":t+="𝄫";break;case"natural-sharp":t+="♮♯";break;case"natural-flat":t+="♮♭";break;case"sharp-down":t+="𝄱";break;case"sharp-up":t+="𝄰";break;case"natural-down":t+="𝄯";break;case"natural-up":t+="𝄮";break;case"flat-down":t+="𝄭";break;case"flat-up":t+="𝄬";break;case"arrow-down":t+="↓";break;case"arrow-up":t+="↑";break;case"triple-sharp":t+="♯𝄪";break;case"triple-flat":t+="𝄬𝄬𝄬";break;case"sharp-1":t+="♯¹";break;case"sharp-2":t+="♯²";break;case"sharp-3":t+="♯³";break;case"sharp-4":t+="♯⁴";break;case"sharp-5":t+="♯⁵";break;case"flat-1":t+="♭¹";break;case"flat-2":t+="♭²";break;case"flat-3":t+="♭³";break;case"flat-4":t+="♭⁴";break;case"flat-5":t+="♭⁵"}}return xs.sanitizeDisplay(t)}parseWork(e){for(const t of e.childElements())if("work-title"===t.localName)this._score.title=xs.sanitizeDisplay(t.innerText)}parsePartwisePart(e){const t=e.attributes.get("id");if(!t||!this._idToTrackInfo.has(t))return;const s=this._idToTrackInfo.get(t).track;let i=0;for(const t of e.childElements())if("measure"===t.localName)this.parsePartwiseMeasure(t,s,i),i++}parsePartwiseMeasure(e,t,s){const i=this.getOrCreateMasterBar(e,s);this.parsePartMeasure(e,i,t)}parseTimewiseMeasure(e,t){const s=this.getOrCreateMasterBar(e,t);for(const t of e.childElements())if("part"===t.localName)this.parseTimewisePart(t,s)}getOrCreateMasterBar(e,t){const s="yes"===e.attributes.get("implicit");for(;this._score.masterBars.length<=t;){const e=new j;s&&(e.isAnacrusis=!0),this._score.addMasterBar(e),e.index>0&&(e.timeSignatureDenominator=e.previousMasterBar.timeSignatureDenominator,e.timeSignatureNumerator=e.previousMasterBar.timeSignatureNumerator,e.tripletFeel=e.previousMasterBar.tripletFeel)}return this._score.masterBars[t]}parseTimewisePart(e,t){const s=e.attributes.get("id");if(!s||!this._idToTrackInfo.has(s))return;const i=this._idToTrackInfo.get(s).track;this.parsePartMeasure(e,t,i)}parsePartMeasure(e,t,s){this._musicalPosition=0,this._lastBeat=null,t.alternateEndings=this._nextMasterBarRepeatEnding;const i=[];for(const a of e.childElements())switch(a.localName){case"note":this.parseNote(a,t,s);break;case"backup":this.parseBackup(a);break;case"forward":this.parseForward(a);break;case"direction":this.parseDirection(a,t,s);break;case"attributes":this.parseAttributes(a,t,s);break;case"harmony":this.parseHarmony(a,s);break;case"print":this.parsePrint(a,t,s);break;case"sound":this.parseSound(a,t,s);break;case"barline":i.push(a)}for(const e of i)this.parseBarLine(e,t,s);this.applySimileMarks(t,s);const a=this.getOrCreateStaff(s,0);this.getOrCreateBar(a,t),this._keyAllStaves=null}parsePrint(e,t,s){("yes"===e.getAttribute("new-system","no")||"yes"===e.getAttribute("new-page","no"))&&s.addLineBreaks(t.index)}applySimileMarks(e,t){if(null!==this._simileMarkAllStaves){for(const s of t.staves){const t=this.getOrCreateBar(s,e);t.simileMark=this._simileMarkAllStaves,t.simileMark!==h.None&&this.clearBar(t)}this._simileMarkAllStaves===h.FirstOfDouble?this._simileMarkAllStaves=h.SecondOfDouble:this._simileMarkAllStaves=null}if(null!==this._simileMarkPerStaff){const s=Array.from(this._simileMarkPerStaff.keys());for(const i of s){const s=this.getOrCreateStaff(t,i),a=this.getOrCreateBar(s,e);a.simileMark=this._simileMarkPerStaff.get(i),a.simileMark!==h.None&&this.clearBar(a),a.simileMark===h.FirstOfDouble?this._simileMarkPerStaff.set(i,h.SecondOfDouble):this._simileMarkPerStaff.delete(i)}0===this._simileMarkPerStaff.size&&(this._simileMarkPerStaff=null)}}clearBar(e){for(const t of e.voices){const e=new ze;e.isEmpty=!0,t.addBeat(e)}}parseBarLine(e,t,s){for(const i of e.childElements())switch(i.localName){case"bar-style":this.parseBarStyle(i,t,s,e.getAttribute("location","right"));break;case"ending":this.parseEnding(i,t);break;case"repeat":this.parseRepeat(i,t)}}parseRepeat(e,t){const s=e.getAttribute("direction");let i=Number.parseInt(e.getAttribute("times"));(i<0||Number.isNaN(i))&&(i=2),"backward"===s?t.repeatCount=i:"forward"===s&&(t.isRepeatStart=!0)}parseEnding(e,t){const s=e.getAttribute("number").split(",").map((e=>Number.parseInt(e)));let i=0;for(const e of s)i|=1<<e-1&255;switch(t.alternateEndings=i,e.getAttribute("type","")){case"start":this._nextMasterBarRepeatEnding=this._nextMasterBarRepeatEnding|i;break;case"stop":case"discontinue":this._nextMasterBarRepeatEnding=this._nextMasterBarRepeatEnding&~i}}parseBarStyle(e,t,s,i){let a=p.Automatic;switch(e.innerText){case"dashed":a=p.Dashed;break;case"dotted":a=p.Dotted;break;case"heavy":a=p.Heavy;break;case"heavy-heavy":a=p.HeavyHeavy;break;case"heavy-light":a=p.HeavyLight;break;case"light-heavy":a=p.LightHeavy;break;case"light-light":a=p.LightLight;break;case"none":a=p.None;break;case"regular":a=p.Regular;break;case"short":a=p.Short;break;case"tick":a=p.Tick}for(const e of s.staves){const s=this.getOrCreateBar(e,t);switch(i){case"left":s.barLineLeft=a;break;case"right":s.barLineRight=a}}}parseSound(e,t,s){for(const s of e.childElements())switch(s.localName){case"midi-instrument":this.parseSoundMidiInstrument(s,t);break;case"swing":this.parseSwing(s,t)}if(e.attributes.has("coda")&&t.addDirection(Be.TargetCoda),e.attributes.has("tocoda")&&t.addDirection(Be.JumpDaCoda),e.attributes.has("dacapo")&&t.addDirection(Be.JumpDaCapo),e.attributes.has("dalsegno")&&t.addDirection(Be.JumpDalSegno),e.attributes.has("fine")&&t.addDirection(Be.TargetFine),e.attributes.has("segno")&&t.addDirection(Be.TargetSegno),e.attributes.has("pan")){this._nextBeatAutomations||(this._nextBeatAutomations=[]);const t=new U;t.type=m.Balance,t.value=xs.interpolatePan(Number.parseFloat(e.attributes.get("pan"))),this._nextBeatAutomations.push(t)}if(e.attributes.has("tempo")){this._nextBeatAutomations||(this._nextBeatAutomations=[]);const t=new U;t.type=m.Tempo,t.value=xs.interpolatePercent(Number.parseFloat(e.attributes.get("tempo"))),this._nextBeatAutomations.push(t)}}parseSwing(e,t){let s=0,i=0,a=null;for(const r of e.childElements())switch(r.localName){case"straight":return void(t.tripletFeel=M.NoTripletFeel);case"first":s=Number.parseInt(r.innerText);break;case"second":i=Number.parseInt(r.innerText);break;case"swing-type":a=this.parseBeatDuration(r)}a||(a=_.Eighth),a===_.Eighth?2===s&&1===i?t.tripletFeel=M.Triplet8th:3===s&&1===i?t.tripletFeel=M.Dotted8th:1===s&&3===i&&(t.tripletFeel=M.Scottish8th):a===_.Sixteenth&&(2===s&&1===i?t.tripletFeel=M.Triplet16th:3===s&&1===i?t.tripletFeel=M.Dotted16th:1===s&&3===i&&(t.tripletFeel=M.Scottish16th))}parseSoundMidiInstrument(e,t){let s;for(const t of e.childElements())switch(t.localName){case"midi-program":this._nextBeatAutomations||(this._nextBeatAutomations=[]),s=new U,s.type=m.Instrument,s.value=Number.parseInt(t.innerText)-1,this._nextBeatAutomations.push(s);break;case"volume":this._nextBeatAutomations||(this._nextBeatAutomations=[]),s=new U,s.type=m.Volume,s.value=xs.interpolatePercent(Number.parseFloat(t.innerText)),this._nextBeatAutomations.push(s);break;case"pan":this._nextBeatAutomations||(this._nextBeatAutomations=[]),s=new U,s.type=m.Balance,s.value=xs.interpolatePan(Number.parseFloat(t.innerText)),this._nextBeatAutomations.push(s)}}parseHarmony(e,t){const s=new je;let i=!1,a="";for(const t of e.childElements())switch(t.localName){case"root":s.name=this.parseHarmonyRoot(t);break;case"kind":s.name=s.name+this.parseHarmonyKind(t),"yes"===t.getAttribute("parentheses-degrees","no")&&(i=!0);break;case"frame":this.parseHarmonyFrame(t,s);break;case"degree":a+=this.parseDegree(t)}a&&(s.name+=i?`(${a})`:a),null===this._nextBeatChord&&(this._nextBeatChord=s)}parseDegree(e){let t="",s="",i="";for(const a of e.childElements())switch(a.localName){case"degree-value":t=a.innerText;break;case"degree-alter":switch(a.innerText){case"-1":s="♭";break;case"1":s="♯"}break;case"degree-type":i+=a.getAttribute("text","")}return`${i}${s}${t}`}parseHarmonyRoot(e){let t="",s="";for(const i of e.childElements())switch(i.localName){case"root-step":t=i.innerText;break;case"root-alter":switch(Number.parseFloat(i.innerText)){case-2:s="bb";break;case-1:s="b";break;case 0:s="";break;case 1:s="#";break;case 2:s="##"}}return t+s}parseHarmonyKind(e){const t=e.getAttribute("text");let s="";if(t)s=t;else{const t=e.innerText;switch(t){case"major":s="";break;case"minor":s="m";break;case"augmented":s="+";break;case"diminished":s="○";break;case"dominant":s="7";break;case"major-seventh":s="7M";break;case"minor-seventh":s="m7";break;case"diminished-seventh":s="○7";break;case"augmented-seventh":s="+7";break;case"half-diminished":s="⍉";break;case"major-minor":s="mMaj";break;case"major-sixth":s="maj6";break;case"minor-sixth":s="m6";break;case"dominant-ninth":s="9";break;case"major-ninth":s="maj9";break;case"minor-ninth":s="m9";break;case"dominant-11th":s="11";break;case"major-11th":s="maj11";break;case"minor-11th":s="m11";break;case"dominant-13th":s="13";break;case"major-13th":s="maj13";break;case"minor-13th":s="m13";break;case"suspended-second":s="sus2";break;case"suspended-fourth":s="sus4";break;case"Neapolitan":s="♭II";break;case"Italian":s="It⁺⁶";break;case"French":case"German":s="Fr⁺⁶";break;default:s=t}}return s}parseHarmonyFrame(e,t){for(const s of e.childElements())switch(s.localName){case"frame-strings":const e=Number.parseInt(s.innerText);t.strings=new Array(e);for(let s=0;s<e;s++)t.strings[s]=-1;break;case"first-fret":t.firstFret=Number.parseInt(s.innerText);break;case"frame-note":let i=null,a=null;for(const e of s.childElements())switch(e.localName){case"string":i=Number.parseInt(e.innerText);break;case"fret":a=Number.parseInt(e.innerText),i&&a>=0&&(t.strings[i-1]=a);break;case"barre":i&&a&&"start"===e.getAttribute("type")&&t.barreFrets.push(a)}}}parseAttributes(e,t,s){let i,a,r;if(null==this._lastBeat)for(const n of e.childElements())switch(n.localName){case"divisions":this._divisionsPerQuarterNote=Number.parseFloat(n.innerText);break;case"key":this.parseKey(n,t,s);break;case"time":this.parseTime(n,t);break;case"staves":s.ensureStaveCount(Number.parseInt(n.innerText));break;case"clef":i=Number.parseInt(n.getAttribute("number","1"))-1,a=this.getOrCreateStaff(s,i),r=this.getOrCreateBar(a,t),this.parseClef(n,r);break;case"staff-details":i=Number.parseInt(n.getAttribute("number","1"))-1,a=this.getOrCreateStaff(s,i),this.parseStaffDetails(n,a);break;case"transpose":this.parseTranspose(n,s);break;case"measure-style":this.parseMeasureStyle(n,s,!1)}else for(const t of e.childElements())switch(t.localName){case"divisions":this._divisionsPerQuarterNote=Number.parseFloat(t.innerText);break;case"measure-style":this.parseMeasureStyle(t,s,!0)}}parseMeasureStyle(e,t,s){for(const t of e.childElements())switch(t.localName){case"measure-repeat":if(!s){let s=null;switch(t.getAttribute("type")){case"start":switch(Number.parseInt(t.getAttribute("slashes","1"))){case 1:s=h.Simple;break;case 2:s=h.FirstOfDouble}break;case"stop":s=null}if(e.attributes.has("number")){this._simileMarkPerStaff=this._simileMarkPerStaff??new Map;const t=Number.parseInt(e.attributes.get("number"))-1;null==s?this._simileMarkPerStaff.delete(t):this._simileMarkPerStaff.set(t,s)}else this._simileMarkAllStaves=s}break;case"slash":switch(t.getAttribute("type")){case"start":this._isBeatSlash=!0;break;case"stop":this._isBeatSlash=!1}}}parseTranspose(e,t){let s=0;for(const t of e.childElements())switch(t.localName){case"chromatic":s+=Number.parseFloat(t.innerText);break;case"octave-change":s+=12*Number.parseFloat(t.innerText)}if(e.attributes.has("number")){const i=this.getOrCreateStaff(t,Number.parseInt(e.attributes.get("number"))-1);this.getStaffContext(i).transpose=s,i.displayTranspositionPitch=s}else for(const e of t.staves)this.getStaffContext(e).transpose=s,e.displayTranspositionPitch=s}parseStaffDetails(e,t){for(const s of e.childElements())switch(s.localName){case"staff-lines":t.standardNotationLineCount=Number.parseInt(s.innerText);break;case"staff-tuning":this.parseStaffTuning(s,t);break;case"capo":t.capo=Number.parseInt(s.innerText)}}parseStaffTuning(e,t){0===t.stringTuning.tunings.length&&(t.showTablature=!0,t.showStandardNotation=!1,t.stringTuning.tunings=new Array(t.standardNotationLineCount).fill(0));const s=Number.parseInt(e.getAttribute("line"));let i="C",a="",r=0;for(const t of e.childElements())switch(t.localName){case"tuning-step":i=t.innerText;break;case"tuning-alter":r=Number.parseFloat(t.innerText);break;case"tuning-octave":a=t.innerText}const n=ie.getTuningForText(i+a)+r;t.tuning[t.tuning.length-s]=n}parseClef(e,t){let s="s",i=0;for(const a of e.childElements())switch(a.localName){case"sign":s=a.innerText.toLowerCase();break;case"line":i=Number.parseInt(a.innerText);break;case"clef-octave-change":switch(Number.parseInt(a.innerText)){case-2:t.clefOttava=o._15mb;break;case-1:t.clefOttava=o._8vb;break;case 1:t.clefOttava=o._8va;break;case 2:t.clefOttava=o._15mb}}switch(s){case"g":default:t.clef=n.G2;break;case"f":t.clef=n.F4;break;case"c":t.clef=3===i?n.C3:n.C4;break;case"percussion":t.clef=n.Neutral,t.staff.isPercussion=!0;break;case"tab":t.clef=n.G2,t.staff.showTablature=!0}}parseTime(e,t){let s=!1,i=!1;for(const a of e.childElements()){const e=a.innerText;switch(a.localName){case"beats":s||(-1===e.indexOf("+")?t.timeSignatureNumerator=Number.parseInt(e):t.timeSignatureNumerator=e.split("+").map((e=>Number.parseInt(e))).reduce(((e,t)=>t+e),0),s=!0);break;case"beat-type":i||(-1===e.indexOf("+")?t.timeSignatureDenominator=Number.parseInt(e):t.timeSignatureDenominator=e.split("+").map((e=>Number.parseInt(e))).reduce(((e,t)=>t+e),0),i=!0)}}switch(e.getAttribute("symbol","")){case"common":case"cut":t.timeSignatureCommon=!0}}parseKey(e,t,s){let i,a,r=-l.C,n="";for(const t of e.childElements())switch(t.localName){case"fifths":r=Number.parseInt(t.innerText);break;case"mode":n=t.innerText}if(i=-7<=r&&r<=7?r:l.C,a="minor"===n?c.Minor:c.Major,e.attributes.has("number")){const r=this.getOrCreateStaff(s,Number.parseInt(e.attributes.get("number"))-1),n=this.getOrCreateBar(r,t);n.keySignature=i,n.keySignatureType=a}else{this._keyAllStaves=[i,a];for(const e of s.staves)e.bars.length>t.index&&(e.bars[t.index].keySignature=i,e.bars[t.index].keySignatureType=a)}}parseDirection(e,t,s){const i=[];let a=null,r=-1,n=-1;for(const t of e.childElements())switch(t.localName){case"direction-type":i.push(t.firstElement);break;case"offset":a=Number.parseFloat(t.innerText);break;case"voice":break;case"staff":r=Number.parseInt(t.innerText)-1;break;case"sound":t.attributes.has("tempo")&&(n=Number.parseFloat(t.attributes.get("tempo")))}let o=null;o=r>=0?this.getOrCreateStaff(s,r):null!==this._lastBeat?this._lastBeat.voice.bar.staff:this.getOrCreateStaff(s,0);const h=o?this.getOrCreateBar(o,t):null,l=()=>{let e=this._musicalPosition;null!==a&&(e+=a);return e/t.calculateDuration(!1)};if(n>0){const e=new U;e.type=m.Tempo,e.value=n,e.ratioPosition=l(),this.hasSameTempo(t,e)||(t.tempoAutomations.push(e),0===t.index&&(t.score.tempo=e.value))}let c="";for(const e of i)switch(e.localName){case"rehearsal":t.section=new Qe,t.section.marker=e.innerText;break;case"segno":t.addDirection(Be.TargetSegno);break;case"coda":t.addDirection(Be.TargetCoda);break;case"words":c=e.innerText;break;case"wedge":switch(e.getAttribute("type")){case"crescendo":this._nextBeatCrescendo=S.Crescendo;break;case"diminuendo":this._nextBeatCrescendo=S.Decrescendo;break;case"stop":this._nextBeatCrescendo=null}break;case"dynamics":const s=this.parseDynamics(e);null!==s&&(this._currentDynamics=s,this._score.stylesheet.hideDynamics=!1);break;case"dashes":const i=e.getAttribute("type","start");switch(c){case"LetRing":this._nextBeatLetRing="start"===i||"continue"===i;break;case"P.M.":this._nextBeatPalmMute="start"===i||"continue"===i}c="";break;case"pedal":const a=this.parsePedal(e);if(a&&h){a.ratioPosition=l();const e=h.sustainPedals.length>0&&h.sustainPedals[h.sustainPedals.length-1].pedalType!==d.Up;(a.pedalType!==d.Up||e)&&h.sustainPedals.push(a)}break;case"metronome":this.parseMetronome(e,t,l());break;case"octave-shift":this._nextBeatOttavia=this.parseOctaveShift(e)}c&&(this._nextBeatText=c)}parseOctaveShift(e){const t=e.getAttribute("type");switch(Number.parseInt(e.getAttribute("size","8"))){case 15:switch(t){case"up":return o._15mb;case"down":return o._15ma;case"stop":return o.Regular;case"continue":return this._nextBeatOttavia}break;case 8:switch(t){case"up":return o._8vb;case"down":return o._8va;case"stop":return o.Regular;case"continue":return this._nextBeatOttavia}}return null}parseMetronome(e,t,s){let i=null,a=-1;for(const t of e.childElements())switch(t.localName){case"beat-unit":i=this.parseBeatDuration(t);break;case"per-minute":a=Number.parseFloat(t.innerText)}if(null!==i&&a>0){const e=new U;e.type=m.Tempo,e.value=a*(i/4)|0,e.ratioPosition=s,this.hasSameTempo(t,e)||(t.tempoAutomations.push(e),0===t.index&&(t.score.tempo=e.value))}}hasSameTempo(e,t){for(const s of e.tempoAutomations)if(t.ratioPosition===s.ratioPosition&&t.value===s.value)return!0;return!1}parsePedal(e){const t=new W;switch(e.getAttribute("type")){case"start":t.pedalType=d.Down;break;case"stop":t.pedalType=d.Up;break;case"continue":t.pedalType=d.Hold;break;default:return null}return t}parseDynamics(e){for(const t of e.childElements()){const e=t.localName.toUpperCase();switch(e){case"PPP":case"PP":case"P":case"MP":case"MF":case"F":case"FF":case"FFF":case"PPPP":case"PPPPP":case"PPPPPP":case"FFFF":case"FFFFF":case"FFFFFF":case"SF":case"SFP":case"SFPP":case"FP":case"RF":case"RFZ":case"SFZ":case"SFFZ":case"FZ":case"N":case"PF":case"SFZP":return g[e]}}return null}parseForward(e){for(const t of e.childElements())if("duration"===t.localName)this._musicalPosition+=this.musicXmlDivisionsToAlphaTabTicks(Number.parseFloat(t.innerText))}parseBackup(e){for(const t of e.childElements())if("duration"===t.localName){if(this._lastBeat){let e=this._musicalPosition;e-=this.musicXmlDivisionsToAlphaTabTicks(Number.parseFloat(t.innerText)),e<0&&(e=0),this._musicalPosition=e}}}getOrCreateStaff(e,t){for(;e.staves.length<=t;){const t=new it;e.addStaff(t),this._score.masterBars.length>0&&this.getOrCreateBar(t,this._score.masterBars[this._score.masterBars.length-1])}return e.staves[t]}getOrCreateBar(e,t){const s=0===e.bars.length?1:e.bars[0].voices.length;for(;e.bars.length<=t.index;){const t=new G;e.addBar(t),t.previousBar&&(t.clef=t.previousBar.clef,t.clefOttava=t.previousBar.clefOttava,t.keySignature=t.previousBar.keySignature,t.keySignatureType=t.previousBar.keySignatureType),null!=this._keyAllStaves&&(t.keySignature=this._keyAllStaves[0],t.keySignatureType=this._keyAllStaves[1]);for(let e=0;e<s;e++){const e=new ee;t.addVoice(e)}}return e.bars[t.index]}getOrCreateVoice(e,t){let s=!1;for(;e.voices.length<=t;)e.addVoice(new ee),s=!0;if(s)for(const s of e.staff.bars)for(;s.voices.length<=t;)s.addVoice(new ee);return e.voices[t]}parseNote(e,t,s){let i=null,a=w.None,r=0,n=null,o=!1,h=0,l=0,c=-1,d=null,u=0,p=-1,g=-1,m=null,f=null,y=!1,b=null;const S="no"!==e.getAttribute("print-object","yes"),B=()=>{if(null!==i)return;o&&!this._lastBeat&&(q.warning("MusicXML","Malformed MusicXML, <chord /> cannot be set on the first note of a measure"),o=!1),o&&!f&&(q.warning("MusicXML","Cannot mix <chord /> and <rest />"),o=!1);const e=this.getOrCreateStaff(s,h);if(o)return i=this._lastBeat,void i.addNote(f);const B=this.getOrCreateBar(e,t),k=this.getOrCreateVoice(B,l),T=0===k.beats.length?0:k.beats[k.beats.length-1].displayEnd;let N=this._musicalPosition-T;if(N>0){if(this._lastBeat&&this._lastBeat.beamingMode===fe.ForceMergeWithNext&&this._lastBeat.voice.bar.staff.index!==h&&k.beats.length>0&&k.beats[k.beats.length-1].beamingMode===fe.ForceMergeWithNext){const e=k.beats[k.beats.length-1].duration;for(;N>0;){const t=this.createRestForGap(N,e);if(null===t)break;this.insertBeatToVoice(t,k),N-=t.playbackDuration}}if(N>0){const e=new ze;e.dynamics=this._currentDynamics,e.isEmpty=!0,e.duration=_.TwoHundredFiftySixth,e.overrideDisplayDuration=N,e.updateDurations(),this.insertBeatToVoice(e,k)}}else N<0&&q.error("MusicXML","Unsupported forward/backup detected. Cannot fill new beats into already filled area of voice");c<0&&null!==d&&(c=z.toTicks(d),u>0&&(c=z.applyDot(c,2===u)));const x=new ze;i=x,null===n?x.beamingMode=this.getStaffContext(e).isExplicitlyBeamed?fe.ForceSplitToNext:fe.Auto:(x.beamingMode=n,this.getStaffContext(e).isExplicitlyBeamed=!0),x.isEmpty=!1,x.dynamics=this._currentDynamics,this._isBeatSlash&&(x.slashed=!0);const v=this._nextBeatAutomations;if(this._nextBeatAutomations=null,null!==v)for(const e of v)x.automations.push(e);const P=this._nextBeatChord;this._nextBeatChord=null,null!==P&&(x.chordId=P.uniqueId,k.bar.staff.hasChord(P.uniqueId)||k.bar.staff.addChord(x.chordId,P));const F=this._nextBeatCrescendo;null!==F&&(x.crescendo=F);const C=this._nextBeatOttavia;if(null!==C&&(x.ottava=C),x.isLetRing=this._nextBeatLetRing,x.isPalmMute=this._nextBeatPalmMute,this._nextBeatText&&(x.text=this._nextBeatText,this._nextBeatText=null),null!==f&&x.addNote(f),this.insertBeatToVoice(x,k),null!==f){f.isVisible=S;const e=this._indexToTrackInfo.get(s.index);null!==b?f.percussionArticulation=e.getOrCreateArticulation(b,f):y||(f.percussionArticulation=e.getOrCreateArticulation("",f))}a!==w.None?(x.graceType=a,this.applyBeatDurationFromTicks(x,r,null,!1)):(x.tupletNumerator=p,x.tupletDenominator=g,x.dots=u,x.preferredBeamDirection=m,this.applyBeatDurationFromTicks(x,c,d,!0)),this._musicalPosition=x.displayEnd,this._lastBeat=x};for(const t of e.childElements())switch(t.localName){case"grace":const e=Number.parseFloat(t.getAttribute("make-time","-1"));e>=0?(r=this.musicXmlDivisionsToAlphaTabTicks(e),a=w.BeforeBeat):a=w.OnBeat,"yes"===t.getAttribute("slash")&&(a=w.BeforeBeat);break;case"chord":o=!0;break;case"cue":return;case"pitch":f=this.parsePitch(t),y=!0;break;case"unpitched":f=this.parseUnpitched(t,s);break;case"rest":f=null,null===d&&(d=_.Whole);break;case"duration":c=this.parseDuration(t);break;case"instrument":b=t.getAttribute("id","");break;case"voice":l=Number.parseInt(t.innerText),Number.isNaN(l)?(q.warning("MusicXML","Voices need to be specified as numbers"),l=0):l-=1;break;case"type":d=this.parseBeatDuration(t);break;case"dot":u++;break;case"accidental":null===f?q.warning("MusicXML","Malformed MusicXML, missing pitch or unpitched for note"):this.parseAccidental(t,f);break;case"time-modification":for(const e of t.childElements())switch(e.localName){case"actual-notes":p=Number.parseInt(e.innerText);break;case"normal-notes":g=Number.parseInt(e.innerText)}break;case"stem":m=this.parseStem(t);break;case"notehead":null===f?q.warning("MusicXML","Malformed MusicXML, missing pitch or unpitched for note"):this.parseNoteHead(t,f,d??_.Quarter,m??this.estimateBeamDirection(f));break;case"staff":h=Number.parseInt(t.innerText)-1;break;case"beam":if("1"===t.getAttribute("number","1"))switch(t.innerText){case"begin":case"continue":n=fe.ForceMergeWithNext;break;case"end":n=fe.ForceSplitToNext}break;case"notations":B(),this.parseNotations(t,f,i);break;case"lyric":B(),this.parseLyric(t,i,s);break;case"play":this.parsePlay(t,f)}if(y){const e=this.getOrCreateStaff(s,h),t=this.getStaffContext(e).transpose;if(0!==t){const e=12*f.octave+f.tone+t;f.octave=e/12|0,f.tone=e-12*f.octave}}B()}parsePlay(e,t){for(const s of e.childElements())if("mute"===s.localName)t&&"palm"===s.innerText&&(t.isPalmMute=!0)}estimateBeamDirection(e){return e.calculateRealValue(!1,!1)<xs.B4Value?Te.Down:Te.Up}parseNoteHead(e,t,s,i){"yes"===e.getAttribute("parentheses","no")&&(t.isGhost=!0);const a=e.getAttribute("filled","");let r;switch("yes"===a?r=!0:"no"===a&&(r=!1),t.style=new Ie,e.innerText){case"arrow down":t.style.noteHeadCenterOnStem=!0,this.applyNoteHead(t,s,r,re.NoteheadTriangleDownDoubleWhole,re.NoteheadTriangleDownWhole,re.NoteheadTriangleDownHalf,re.NoteheadTriangleDownBlack);break;case"arrow up":t.style.noteHeadCenterOnStem=!0,this.applyNoteHead(t,s,r,re.NoteheadTriangleUpDoubleWhole,re.NoteheadTriangleUpWhole,re.NoteheadTriangleUpHalf,re.NoteheadTriangleUpBlack);break;case"back slashed":this.applyNoteHead(t,s,r,re.NoteheadSlashedDoubleWhole2,re.NoteheadSlashedWhole2,re.NoteheadSlashedHalf2,re.NoteheadSlashedBlack2);break;case"circle dot":t.style.noteHead=re.NoteheadRoundWhiteWithDot;break;case"circle-x":this.applyNoteHead(t,s,r,re.NoteheadCircleXDoubleWhole,re.NoteheadCircleXWhole,re.NoteheadCircleXHalf,re.NoteheadCircleX);break;case"circled":this.applyNoteHead(t,s,r,re.NoteheadCircledDoubleWhole,re.NoteheadCircledWhole,re.NoteheadCircledHalf,re.NoteheadCircledBlack);break;case"cluster":this.applyNoteHead(t,s,r,re.NoteheadClusterDoubleWhole3rd,re.NoteheadClusterWhole3rd,re.NoteheadClusterHalf3rd,re.NoteheadClusterQuarter3rd);break;case"cross":this.applyNoteHead(t,s,r,re.NoteheadPlusDoubleWhole,re.NoteheadPlusWhole,re.NoteheadPlusHalf,re.NoteheadPlusBlack);break;case"diamond":this.applyNoteHead(t,s,r,re.NoteheadDiamondDoubleWhole,re.NoteheadDiamondWhole,re.NoteheadDiamondHalf,re.NoteheadDiamondBlack);break;case"do":this.applyNoteHead(t,s,r,re.NoteShapeTriangleUpWhite,re.NoteShapeTriangleUpWhite,re.NoteShapeTriangleUpWhite,re.NoteShapeTriangleUpBlack);break;case"fa":i===Te.Up?this.applyNoteHead(t,s,r,re.NoteShapeTriangleRightWhite,re.NoteShapeTriangleRightWhite,re.NoteShapeTriangleRightWhite,re.NoteShapeTriangleRightBlack):this.applyNoteHead(t,s,r,re.NoteShapeTriangleLeftWhite,re.NoteShapeTriangleLeftWhite,re.NoteShapeTriangleLeftWhite,re.NoteShapeTriangleLeftBlack);break;case"fa up":this.applyNoteHead(t,s,r,re.NoteShapeTriangleLeftWhite,re.NoteShapeTriangleLeftWhite,re.NoteShapeTriangleLeftWhite,re.NoteShapeTriangleLeftBlack);break;case"inverted triangle":this.applyNoteHead(t,s,r,re.NoteheadTriangleDownDoubleWhole,re.NoteheadTriangleDownWhole,re.NoteheadTriangleDownHalf,re.NoteheadTriangleDownBlack);break;case"la":case"square":this.applyNoteHead(t,s,r,re.NoteShapeSquareWhite,re.NoteShapeSquareWhite,re.NoteShapeSquareWhite,re.NoteShapeSquareBlack);break;case"left triangle":this.applyNoteHead(t,s,r,re.NoteheadTriangleRightWhite,re.NoteheadTriangleRightWhite,re.NoteheadTriangleRightWhite,re.NoteheadTriangleRightBlack);break;case"mi":this.applyNoteHead(t,s,r,re.NoteShapeDiamondWhite,re.NoteShapeDiamondWhite,re.NoteShapeDiamondWhite,re.NoteShapeDiamondBlack);break;case"none":t.style.noteHead=re.NoteheadNull;break;case"normal":this.applyNoteHead(t,s,r,re.NoteheadDoubleWhole,re.NoteheadWhole,re.NoteheadHalf,re.NoteheadBlack);break;case"re":this.applyNoteHead(t,s,r,re.NoteShapeMoonWhite,re.NoteShapeMoonWhite,re.NoteShapeMoonWhite,re.NoteShapeMoonBlack);break;case"rectangle":this.applyNoteHead(t,s,r,re.NoteheadSquareWhite,re.NoteheadSquareWhite,re.NoteheadSquareWhite,re.NoteheadSquareBlack);break;case"slash":this.applyNoteHead(t,s,r,re.NoteheadSlashWhiteWhole,re.NoteheadSlashWhiteWhole,re.NoteheadSlashWhiteHalf,re.NoteheadSlashVerticalEnds);break;case"slashed":this.applyNoteHead(t,s,r,re.NoteheadSlashedDoubleWhole1,re.NoteheadSlashedWhole1,re.NoteheadSlashedHalf1,re.NoteheadSlashedBlack1);break;case"so":this.applyNoteHead(t,s,r,re.NoteShapeRoundWhite,re.NoteShapeRoundWhite,re.NoteShapeRoundWhite,re.NoteShapeRoundBlack);break;case"ti":this.applyNoteHead(t,s,r,re.NoteShapeTriangleRoundWhite,re.NoteShapeTriangleRoundWhite,re.NoteShapeTriangleRoundWhite,re.NoteShapeTriangleRoundBlack);break;case"triangle":this.applyNoteHead(t,s,r,re.NoteheadTriangleUpDoubleWhole,re.NoteheadTriangleUpWhole,re.NoteheadTriangleUpHalf,re.NoteheadTriangleUpBlack);break;case"x":this.applyNoteHead(t,s,r,re.NoteheadXDoubleWhole,re.NoteheadXWhole,re.NoteheadXHalf,re.NoteheadXBlack)}}createRestForGap(e,t){let s=z.toTicks(t);for(;s>e;){if(t===_.TwoHundredFiftySixth)return null;t*=2,s=z.toTicks(t)}const i=new ze;return i.dynamics=this._currentDynamics,i.isEmpty=!1,i.duration=t,i.overrideDisplayDuration=s,i.updateDurations(),i}insertBeatToVoice(e,t){if(t.beats.length>0){const s=t.beats[t.beats.length-1];s.nextBeat=e,e.previousBeat=s;let i=s;for(;null!==i&&i.graceType!==w.None;)i=i.index>0?i.previousBeat:null;null!==i&&(e.displayStart=i.displayEnd)}t.addBeat(e)}musicXmlDivisionsToAlphaTabTicks(e){return e*z.QuarterTime/this._divisionsPerQuarterNote}parseBeatDuration(e){switch(e.innerText){case"1024th":case"512th":case"256th":return _.TwoHundredFiftySixth;case"128th":return _.OneHundredTwentyEighth;case"64th":return _.SixtyFourth;case"32nd":return _.ThirtySecond;case"16th":return _.Sixteenth;case"eighth":return _.Eighth;case"quarter":return _.Quarter;case"half":return _.Half;case"whole":return _.Whole;case"breve":return _.DoubleWhole;case"long":return _.QuadrupleWhole}return null}applyBeatDurationFromTicks(e,t,s,i){if(!s)for(let e=0;e<xs.allDurations.length;e++){if(!(t>=xs.allDurationTicks[e]))break;s=xs.allDurations[e]}e.duration=s??_.Sixteenth,i&&(e.overrideDisplayDuration=t),e.updateDurations()}parseLyric(e,t,s){const i=this._indexToTrackInfo.get(s.index).getLyricLine(e.getAttribute("number",""));for(null===t.lyrics&&(t.lyrics=[]);t.lyrics.length<=i;)t.lyrics.push("");for(const s of e.childElements())switch(s.localName){case"text":t.lyrics[i]?t.lyrics[i]+=` ${s.innerText}`:t.lyrics[i]=s.innerText;break;case"elision":t.lyrics[i]+=s.innerText}}parseNotations(e,t,s){for(const i of e.childElements())switch(i.localName){case"tied":t&&this.parseTied(i,t,s.voice.bar.staff);break;case"slur":t&&this.parseSlur(i,t);break;case"glissando":t&&this.parseGlissando(i,t);break;case"slide":t&&this.parseSlide(i,t);break;case"ornaments":t&&this.parseOrnaments(i,t);break;case"technical":this.parseTechnical(i,t,s);break;case"articulations":t&&this.parseArticulations(i,t);break;case"dynamics":const e=this.parseDynamics(i);null!==e&&(s.dynamics=e,this._currentDynamics=e);break;case"fermata":this.parseFermata(i,s);break;case"arpeggiate":this.parseArpeggiate(i,s)}}getStaffContext(e){if(!this._staffToContext.has(e)){const t=new ks;return this._staffToContext.set(e,t),t}return this._staffToContext.get(e)}parseGlissando(e,t){const s=e.getAttribute("type"),i=e.getAttribute("number","1"),a=this.getStaffContext(t.beat.voice.bar.staff);switch(s){case"start":a.slideOrigins.set(i,t);break;case"stop":if(a.slideOrigins.has(i)){const e=a.slideOrigins.get(i);e.slideTarget=t,t.slideOrigin=e,e.slideOutType=v.Shift}}}parseSlur(e,t){const s=e.getAttribute("number","1"),i=this.getStaffContext(t.beat.voice.bar.staff);switch(e.getAttribute("type")){case"start":i.slurStarts.set(s,t);break;case"stop":if(i.slurStarts.has(s)){t.isSlurDestination=!0;const e=i.slurStarts.get(s);e.slurDestination=t,t.slurOrigin=e,i.slurStarts.delete(s)}}}parseArpeggiate(e,t){switch(e.getAttribute("direction","down")){case"down":t.brushType=b.ArpeggioDown;break;case"up":t.brushType=b.ArpeggioUp}}parseFermata(e,t){let s;switch(e.innerText){case"normal":default:s=ke.Medium;break;case"angled":s=ke.Short;break;case"square":s=ke.Long}t.fermata=new lt,t.fermata.type=s}parseArticulations(e,t){for(const s of e.childElements())switch(s.localName){case"accent":t.accentuated=B.Normal;break;case"strong-accent":t.accentuated=B.Heavy;break;case"staccato":t.isStaccato=!0;break;case"tenuto":t.accentuated=B.Tenuto}}parseTechnical(e,t,s){const i=[];for(const a of e.childElements())switch(a.localName){case"up-bow":s.pickStroke=ae.Up;break;case"down-bow":s.pickStroke=ae.Down;break;case"harmonic":break;case"fingering":t&&(t.leftHandFinger=this.parseFingering(a));break;case"pluck":t&&(t.rightHandFinger=this.parseFingering(a));break;case"fret":t&&(t.fret=Number.parseInt(a.innerText));break;case"string":t&&(t.string=s.voice.bar.staff.tuning.length-Number.parseInt(a.innerText)+1);break;case"hammer-on":case"pull-off":t&&(t.isHammerPullOrigin=!0);break;case"bend":i.push(a);break;case"tap":s.tap=!0;break;case"smear":t&&(t.vibrato=P.Slight);break;case"golpe":switch(a.getAttribute("placement","above")){case"above":s.golpe=de.Finger;break;case"below":s.golpe=de.Thumb}}t&&i.length>0&&this.parseBends(i,t)}parseBends(e,t){const s=X.MaxPosition/e.length;let i=0,a=0,r=!0;for(const n of e){const e=n.findChildElement("bend-alter");if(e){const o=Math.round(2*Math.abs(Number.parseFloat(e.innerText)));n.findChildElement("pre-bend")?r?(i+=o,t.addBendPoint(new X(a,i)),a+=s,t.addBendPoint(new X(a,i)),r=!1):a+=s:n.findChildElement("release")?(r&&(i+=o),t.addBendPoint(new X(a,i)),a+=s,i-=o,t.addBendPoint(new X(a,i)),r=!1):(t.addBendPoint(new X(a,i)),i+=o,a+=s,t.addBendPoint(new X(a,i)),r=!1)}}}parseFingering(e){switch(e.innerText){case"0":return k.NoOrDead;case"1":case"p":case"t":return k.Thumb;case"2":case"i":return k.IndexFinger;case"3":case"m":return k.MiddleFinger;case"4":case"a":return k.AnnularFinger;case"5":case"c":return k.LittleFinger}return k.Unknown}parseOrnaments(e,t){let s=-1;for(const i of e.childElements())switch(i.localName){case"trill-mark":s=Number.parseInt(i.getAttribute("trill-step","2")),t.isStringed?t.trillValue=t.stringTuning+s:t.isPercussion||(t.trillValue=t.calculateRealValue(!1,!1)+s);break;case"turn":t.ornament=he.Turn;break;case"inverted-turn":t.ornament=he.InvertedTurn;break;case"wavy-line":s>0?"start"===i.getAttribute("type")&&(this._currentTrillStep=s):this._currentTrillStep>0?"stop"===i.getAttribute("type")?this._currentTrillStep=-1:t.isStringed?t.trillValue=t.stringTuning+this._currentTrillStep:t.isPercussion||(t.trillValue=t.calculateRealValue(!1,!1)+this._currentTrillStep):t.vibrato=P.Slight;break;case"mordent":t.ornament=he.LowerMordent;break;case"inverted-mordent":t.ornament=he.UpperMordent;break;case"tremolo":switch(i.innerText){case"1":t.beat.tremoloSpeed=_.Eighth;break;case"2":t.beat.tremoloSpeed=_.Sixteenth;break;case"3":t.beat.tremoloSpeed=_.ThirtySecond}}}parseSlide(e,t){const s=e.getAttribute("type"),i=e.getAttribute("number","1"),a=this.getStaffContext(t.beat.voice.bar.staff);switch(s){case"start":a.slideOrigins.set(i,t);break;case"stop":if(a.slideOrigins.has(i)){const e=a.slideOrigins.get(i);e.slideTarget=t,t.slideOrigin=e,e.slideOutType=v.Shift}}}parseTied(e,t,s){const i=e.getAttribute("type"),a=e.getAttribute("number",""),r=this.getStaffContext(s);if("start"===i){if(a){if(r.tieStartIds.has(a)){const e=r.tieStartIds.get(a);r.tieStarts.delete(e)}r.tieStartIds.set(a,t)}r.tieStarts.add(t)}else if("stop"===i&&!t.isTieDestination){let e=null;if(a){if(!r.tieStartIds.has(a))return;e=r.tieStartIds.get(a),r.tieStartIds.delete(a),r.tieStarts.delete(t)}else{const s=this.calculatePitchedNoteValue(t);for(const t of r.tieStarts)if(this.calculatePitchedNoteValue(t)===s){e=t,r.tieStarts.delete(e);break}}if(!e)return;t.isTieDestination=!0,t.tieOrigin=e}}parseStem(e){switch(e.innerText){case"down":return Te.Down;case"up":return Te.Up;default:return null}}parseAccidental(e,t){switch(e.innerText){case"sharp":t.accidentalMode=N.ForceSharp;break;case"natural":t.accidentalMode=N.ForceNatural;break;case"flat":t.accidentalMode=N.ForceFlat;break;case"double-sharp":t.accidentalMode=N.ForceDoubleSharp;break;case"flat-flat":t.accidentalMode=N.ForceDoubleFlat}}calculatePitchedNoteValue(e){return 12*e.octave+e.tone}parseDuration(e){return this.musicXmlDivisionsToAlphaTabTicks(Number.parseFloat(e.innerText))}parseUnpitched(e,t){let s="",i=0;for(const t of e.childElements())switch(t.localName){case"display-step":s=t.innerText;break;case"display-octave":i=Number.parseInt(t.innerText)+1}const a=new Ae;if(""===s)a.octave=0,a.tone=0;else{const e=12*i+ie.getToneForText(s).noteValue;a.octave=e/12|0,a.tone=e-12*a.octave}return a}parsePitch(e){let t="",s=0,i=0;for(const a of e.childElements())switch(a.localName){case"step":t=a.innerText;break;case"alter":s=Number.parseFloat(a.innerText),Number.isNaN(s)&&(s=0);break;case"octave":i=Number.parseInt(a.innerText)+1}s|=0;const a=12*i+ie.getToneForText(t).noteValue+s,r=new Ae;return r.octave=a/12|0,r.tone=a-12*r.octave,r}applyNoteHead(e,t,s,i,a,r,n){if(void 0===s)switch(t){case _.QuadrupleWhole:case _.DoubleWhole:e.style.noteHead=i;break;case _.Whole:e.style.noteHead=a;break;case _.Half:e.style.noteHead=r;break;default:e.style.noteHead=n}else if(!0===s)e.style.noteHead=n;else switch(t){case _.QuadrupleWhole:case _.DoubleWhole:e.style.noteHead=i;break;case _.Whole:e.style.noteHead=a;break;case _.Half:default:e.style.noteHead=r}}}xs.B4Value=71,xs.allDurations=[_.TwoHundredFiftySixth,_.OneHundredTwentyEighth,_.SixtyFourth,_.ThirtySecond,_.Sixteenth,_.Eighth,_.Quarter,_.Half,_.Whole,_.DoubleWhole,_.QuadrupleWhole],xs.allDurationTicks=xs.allDurations.map((e=>z.toTicks(e))),function(e){e[e.SingleTrackMultiChannel=0]="SingleTrackMultiChannel",e[e.MultiTrack=1]="MultiTrack"}(At||(At={}));class vs{constructor(){this.events=[]}addEvent(e){if(0===this.events.length||e.tick>=this.events[this.events.length-1].tick)this.events.push(e);else{let t=this.events.length;for(;t>0;){if(!(this.events[t-1].tick>e.tick))break;t--}this.events.splice(t,0,e)}}writeTo(e){const t=ht.empty();let s=0;for(const e of this.events){const i=e.tick-s;Ps.writeVariableInt(t,i),e.writeTo(t),s=e.tick}const i=new Uint8Array([77,84,114,107]);e.write(i,0,i.length);const a=t.toArray();ot.writeInt32BE(e,a.length),e.write(a,0,a.length)}}class Ps{constructor(){this.format=At.SingleTrackMultiChannel,this.division=z.QuarterTime,this.tracks=[]}get events(){if(1===this.tracks.length)return this.tracks[0].events;const e=[];for(const e of this.tracks)this.events.push(...e.events);return e.sort(((e,t)=>e.tick-t.tick)),e}ensureTracks(e){for(;this.tracks.length<e;)this.tracks.push(new vs)}addEvent(e){this.format===At.SingleTrackMultiChannel?(this.ensureTracks(1),this.tracks[0].addEvent(e)):(this.ensureTracks(e.track+1),this.tracks[e.track].addEvent(e))}toBinary(){const e=ht.empty();return this.writeTo(e),e.toArray()}writeTo(e){const t=new Uint8Array([77,84,104,100]);e.write(t,0,t.length),ot.writeInt32BE(e,6),ot.writeInt16BE(e,this.format),ot.writeInt16BE(e,this.tracks.length),ot.writeInt16BE(e,this.division);for(const t of this.tracks)t.writeTo(e)}static writeVariableInt(e,t){const s=new Uint8Array(4);let i=0;do{s[i++]=127&t,t>>=7}while(t>0);for(;i>0;)i--,i>0?e.writeByte(128|s[i]):e.writeByte(s[i])}}!function(e){e[e.TimeSignature=88]="TimeSignature",e[e.NoteOn=128]="NoteOn",e[e.NoteOff=144]="NoteOff",e[e.ControlChange=176]="ControlChange",e[e.ProgramChange=192]="ProgramChange",e[e.TempoChange=81]="TempoChange",e[e.PitchBend=224]="PitchBend",e[e.PerNotePitchBend=96]="PerNotePitchBend",e[e.EndOfTrack=47]="EndOfTrack",e[e.AlphaTabRest=241]="AlphaTabRest",e[e.AlphaTabMetronome=242]="AlphaTabMetronome",e[e.SystemExclusive=240]="SystemExclusive",e[e.SystemExclusive2=247]="SystemExclusive2",e[e.Meta=255]="Meta"}(Rt||(Rt={}));class Fs{constructor(e,t,s){this.track=e,this.tick=t,this.type=s}get command(){return this.type}get message(){return 0}get data1(){return 0}get data2(){return 0}}class Cs extends Fs{constructor(e,t,s,i,a,r){super(e,t,Rt.TimeSignature),this.track=e,this.tick=t,this.numerator=s,this.denominatorIndex=i,this.midiClocksPerMetronomeClick=a,this.thirtySecondNodesInQuarter=r}writeTo(e){e.writeByte(255),e.writeByte(88),Ps.writeVariableInt(e,4),e.writeByte(255&this.numerator),e.writeByte(255&this.denominatorIndex),e.writeByte(255&this.midiClocksPerMetronomeClick),e.writeByte(255&this.thirtySecondNodesInQuarter)}}class Ds extends Fs{writeTo(e){e.writeByte(240);const t=ht.withCapacity(16);t.writeByte(Ds.AlphaTabManufacturerId),this.writeEventData(t),t.writeByte(247),Ps.writeVariableInt(e,t.length),t.copyTo(e)}}Ds.AlphaTabManufacturerId=125,Ds.MetronomeEventId=0,Ds.RestEventId=1;class Es extends Ds{constructor(e,t,s,i,a){super(e,t,Rt.AlphaTabMetronome),this.isMetronome=!0,this.metronomeNumerator=s,this.metronomeDurationInMilliseconds=a,this.metronomeDurationInTicks=i}writeEventData(e){e.writeByte(Ds.MetronomeEventId),e.writeByte(this.metronomeNumerator),ot.writeInt32LE(e,this.metronomeDurationInTicks),ot.writeInt32LE(e,this.metronomeDurationInMilliseconds)}}class Ls extends Ds{constructor(e,t,s){super(e,t,Rt.AlphaTabRest),this.channel=s}writeEventData(e){e.writeByte(Ds.RestEventId),e.writeByte(this.channel)}}class Ms extends Fs{constructor(e,t,s,i,a,r){super(e,t,s),this.channel=i,this.noteKey=a,this.noteVelocity=r}get data1(){return this.noteKey}get data2(){return this.noteVelocity}}class Is extends Ms{constructor(e,t,s,i,a){super(e,t,Rt.NoteOn,s,i,a)}writeTo(e){e.writeByte(15&this.channel|144),e.writeByte(255&this.noteKey),e.writeByte(255&this.noteVelocity)}}class As extends Ms{constructor(e,t,s,i,a){super(e,t,Rt.NoteOff,s,i,a)}writeTo(e){e.writeByte(15&this.channel|128),e.writeByte(255&this.noteKey),e.writeByte(255&this.noteVelocity)}}class Rs extends Fs{constructor(e,t,s,i,a){super(e,t,Rt.ControlChange),this.channel=s,this.controller=i,this.value=a}writeTo(e){e.writeByte(15&this.channel|176),e.writeByte(255&this.controller),e.writeByte(255&this.value)}get data1(){return this.controller}get data2(){return this.value}}class Os extends Fs{constructor(e,t,s,i){super(e,t,Rt.ProgramChange),this.channel=s,this.program=i}writeTo(e){e.writeByte(15&this.channel|192),e.writeByte(255&this.program)}get data1(){return this.program}}class Hs extends Fs{constructor(e,t){super(0,e,Rt.TempoChange),this.microSecondsPerQuarterNote=t}writeTo(e){e.writeByte(255),e.writeByte(81),e.writeByte(3),e.writeByte(this.microSecondsPerQuarterNote>>16&255),e.writeByte(this.microSecondsPerQuarterNote>>8&255),e.writeByte(255&this.microSecondsPerQuarterNote)}}class Ws extends Fs{constructor(e,t,s,i){super(e,t,Rt.PitchBend),this.channel=s,this.value=i}writeTo(e){e.writeByte(15&this.channel|224),e.writeByte(127&this.value),e.writeByte(this.value>>7&127)}get data1(){return 127&this.value}get data2(){return this.value>>7&127}}class Vs extends Fs{constructor(e,t,s,i,a){super(e,t,Rt.PerNotePitchBend),this.channel=s,this.noteKey=i,this.value=a}writeTo(e){throw new $e(Se.General,"Note Bend (Midi2.0) events cannot be exported to SMF1.0")}}class Gs extends Fs{constructor(e,t){super(e,t,Rt.EndOfTrack)}writeTo(e){e.writeByte(255),e.writeByte(47),e.writeByte(0)}}class zs{constructor(e,t){this.time=0,this.eventIndex=e,this.event=t,this.isMetronome=this.event.type===Rt.AlphaTabMetronome}static newMetronomeEvent(e,t,s,i,a){const r=new Es(0,t,s,i,a);return new zs(e,r)}}class Us{constructor(e,t,s){this.bpm=e,this.ticks=t,this.time=s}}class Xs{constructor(){this.tempoChanges=[],this.firstProgramEventPerChannel=new Map,this.firstTimeSignatureNumerator=0,this.firstTimeSignatureDenominator=0,this.synthData=[],this.division=z.QuarterTime,this.eventIndex=0,this.currentTime=0,this.playbackRange=null,this.playbackRangeStartTime=0,this.playbackRangeEndTime=0,this.endTick=0,this.endTime=0}}class Js{get isPlayingMain(){return this._currentState===this._mainState}get isPlayingOneTimeMidi(){return this._currentState===this._oneTimeState}get isPlayingCountIn(){return this._currentState===this._countInState}constructor(e){this._oneTimeState=null,this._countInState=null,this.isLooping=!1,this.playbackSpeed=1,this.instrumentPrograms=new Set,this.percussionKeys=new Set,this._synthesizer=e,this._mainState=new Xs,this._currentState=this._mainState}get mainPlaybackRange(){return this._mainState.playbackRange}set mainPlaybackRange(e){this._mainState.playbackRange=e,e&&(this._mainState.playbackRangeStartTime=this.tickPositionToTimePositionWithSpeed(this._mainState,e.startTick,1),this._mainState.playbackRangeEndTime=this.tickPositionToTimePositionWithSpeed(this._mainState,e.endTick,1))}get currentTime(){return this._currentState.currentTime/this.playbackSpeed}get currentEndTick(){return this._currentState.endTick}get currentEndTime(){return this._currentState.endTime/this.playbackSpeed}mainSeek(e){if(e*=this.playbackSpeed,this.mainPlaybackRange&&(e<this._mainState.playbackRangeStartTime?e=this._mainState.playbackRangeStartTime:e>this._mainState.playbackRangeEndTime&&(e=this._mainState.playbackRangeEndTime)),e>this._mainState.currentTime)this.mainSilentProcess(e-this._mainState.currentTime);else if(e<this._mainState.currentTime){if(this._mainState.currentTime=0,this._mainState.eventIndex=0,this.isPlayingMain){const e=this._synthesizer.metronomeVolume;this._synthesizer.noteOffAll(!0),this._synthesizer.resetSoft(),this._synthesizer.setupMetronomeChannel(e)}this.mainSilentProcess(e)}}mainSilentProcess(e){if(e<=0)return;const t=Date.now(),s=this._mainState.currentTime+e;if(this.isPlayingMain)for(;this._mainState.currentTime<s;)this.fillMidiEventQueueLimited(s-this._mainState.currentTime)&&this._synthesizer.synthesizeSilent(K.MicroBufferSize);this._mainState.currentTime=s;const i=Date.now()-t;q.debug("Sequencer",`Silent seek finished in ${i}ms (main)`)}loadOneTimeMidi(e){this._oneTimeState=this.createStateFromFile(e),this._currentState=this._oneTimeState}loadMidi(e){this.instrumentPrograms.clear(),this.percussionKeys.clear(),this._mainState=this.createStateFromFile(e),this._currentState=this._mainState}createStateFromFile(e){const t=new Xs;this.percussionKeys.add(K.MetronomeKey),t.tempoChanges=[],t.division=e.division,t.eventIndex=0,t.currentTime=0,t.synthData=[];let s=120,i=0,a=0,r=0,n=0,o=0,h=0,l=0,c=0;for(const d of e.events){const u=new zs(t.synthData.length,d);t.synthData.push(u);const p=d.tick-c;if(i+=p,a+=p*(6e4/(s*e.division)),u.time=a,c=d.tick,n>0)for(;h<i;){const e=zs.newMetronomeEvent(t.synthData.length,h,Math.floor(h/n)%r,n,o);t.synthData.push(e),e.time=l,h+=n,l+=o}if(d.type===Rt.TempoChange){s=6e7/d.microSecondsPerQuarterNote,t.tempoChanges.push(new Us(s,i,a)),o=n*(6e4/(s*e.division))}else if(d.type===Rt.TimeSignature){const i=d,a=Math.pow(2,i.denominatorIndex);r=i.numerator,n=t.division*(4/a)|0,o=n*(6e4/(s*e.division)),0===t.firstTimeSignatureDenominator&&(t.firstTimeSignatureNumerator=i.numerator,t.firstTimeSignatureDenominator=a)}else if(d.type===Rt.ProgramChange){const e=d,s=e.channel;t.firstProgramEventPerChannel.has(s)||t.firstProgramEventPerChannel.set(s,u);s===K.PercussionChannel||this.instrumentPrograms.add(e.program)}else if(d.type===Rt.NoteOn){const e=d;e.channel===K.PercussionChannel&&this.percussionKeys.add(e.noteKey)}}return t.synthData.sort(((e,t)=>e.time>t.time?1:e.time<t.time?-1:e.eventIndex-t.eventIndex)),t.endTime=a,t.endTick=i,t}fillMidiEventQueue(){return this.fillMidiEventQueueLimited(-1)}fillMidiEventQueueLimited(e){let t=K.MicroBufferSize/this._synthesizer.outSampleRate*1e3*this.playbackSpeed,s=this.internalEndTime;e>0&&(e<t&&(t=e),s=Math.min(this.internalEndTime,this._currentState.currentTime+e));let i=!1;for(this._currentState.currentTime+=t;this._currentState.eventIndex<this._currentState.synthData.length&&this._currentState.synthData[this._currentState.eventIndex].time<this._currentState.currentTime&&this._currentState.currentTime<s;)this._synthesizer.dispatchEvent(this._currentState.synthData[this._currentState.eventIndex]),this._currentState.eventIndex++,i=!0;return i}mainTickPositionToTimePosition(e){return this.tickPositionToTimePositionWithSpeed(this._mainState,e,this.playbackSpeed)}mainTimePositionToTickPosition(e){return this.timePositionToTickPositionWithSpeed(this._mainState,e,this.playbackSpeed)}currentTimePositionToTickPosition(e){return this.timePositionToTickPositionWithSpeed(this._currentState,e,this.playbackSpeed)}tickPositionToTimePositionWithSpeed(e,t,s){let i=0,a=120,r=0;for(const s of e.tempoChanges){if(t<s.ticks)break;i=s.time,a=s.bpm,r=s.ticks}return i+=(t-=r)*(6e4/(a*e.division)),i/s}timePositionToTickPositionWithSpeed(e,t,s){t*=s;let i=0,a=120,r=0;for(const s of e.tempoChanges){if(t<s.time)break;i=s.ticks,a=s.bpm,r=s.time}return i+=(t-=r)/(6e4/(a*e.division))|0,i+1}get internalEndTime(){return this.isPlayingMain&&this.mainPlaybackRange?this._currentState.playbackRangeEndTime:this._currentState.endTime}get isFinished(){return this._currentState.currentTime>=this.internalEndTime}stop(){this.isPlayingMain&&this.mainPlaybackRange?this._currentState.currentTime=this.mainPlaybackRange.startTick:this._currentState.currentTime=0,this._currentState.eventIndex=0}resetOneTimeMidi(){this._oneTimeState=null,this._currentState=this._mainState}resetCountIn(){this._countInState=null,this._currentState=this._mainState}startCountIn(){this.generateCountInMidi(),this._currentState=this._countInState,this.stop(),this._synthesizer.noteOffAll(!0)}generateCountInMidi(){const e=new Xs;e.division=this._mainState.division;let t=120,s=4,i=4;0===this._mainState.eventIndex?(t=this._mainState.tempoChanges[0].bpm,s=this._mainState.firstTimeSignatureNumerator,i=this._mainState.firstTimeSignatureDenominator):(t=this._synthesizer.currentTempo,s=this._synthesizer.timeSignatureNumerator,i=this._synthesizer.timeSignatureDenominator),e.tempoChanges.push(new Us(t,0,0));const a=e.division*(4/i)|0,r=a*(6e4/(t*this._mainState.division));let n=0,o=0;for(let t=0;t<s;t++){const s=zs.newMetronomeEvent(e.synthData.length,n,t,a,r);e.synthData.push(s),s.time=o,n+=a,o+=r}e.synthData.sort(((e,t)=>e.time>t.time?1:e.time<t.time?-1:e.eventIndex-t.eventIndex)),e.endTime=o,e.endTick=n,this._countInState=e}}!function(e){e[e.Paused=0]="Paused",e[e.Playing=1]="Playing"}(Ot||(Ot={}));class Ys{constructor(e,t){this.state=e,this.stopped=t}}class $s{constructor(e,t,s,i,a){this.currentTime=e,this.endTime=t,this.currentTick=s,this.endTick=i,this.isSeek=a}}class qs{constructor(){this.id="",this.size=0}static load(e,t,s){if(e&&qs.HeaderSize>e.size)return!1;if(s.position+qs.HeaderSize>=s.length)return!1;if(t.id=ot.read8BitStringLength(s,4),t.id.charCodeAt(0)<=32||t.id.charCodeAt(0)>=122)return!1;if(t.size=ot.readUInt32LE(s),e&&qs.HeaderSize+t.size>e.size)return!1;e&&(e.size-=qs.HeaderSize+t.size);const i="RIFF"===t.id,a="LIST"===t.id;return(!i||!e)&&(!i&&!a||(t.id=ot.read8BitStringLength(s,4),!(t.id.charCodeAt(0)<=32||t.id.charCodeAt(0)>=122)&&(t.size-=4,!0)))}}qs.HeaderSize=8;class js{constructor(e,t,s,i){this.packetData=e,this.isBeginningOfStream=t,this.isEndOfStream=s,this.granulePosition=s?i:null}addData(e){const t=this.packetData,s=new Uint8Array(t.length+e.length);s.set(t,0),s.set(e,t.length)}}!function(e){e[e.ContinuesPacket=1]="ContinuesPacket",e[e.BeginningOfStream=2]="BeginningOfStream",e[e.EndOfStream=4]="EndOfStream"}(Ht||(Ht={}));class Ks{constructor(e){this._readable=e}read(){const e=[];for(;this.findAndReadPage(e););return e}findAndReadPage(e){return!!this.seekPageHeader()&&this.readPage(e)}seekPageHeader(){for(let e=0;e<65536;e++){if(1399285583===ot.readInt32LE(this._readable))return!0;this._readable.position-=3}return!1}readPage(e){const t=this._readable.readByte();if(-1===t||0!==t)return!1;const s=this._readable.readByte(),i=ot.readInt64LE(this._readable);this._readable.skip(4),this._readable.skip(4),this._readable.skip(4);const a=this._readable.readByte();if(-1===a)return!1;const r=[];let n=0;for(let e=0;e<a;e++){const e=this._readable.readByte();n===r.length&&r.push(0),r[n]+=e,e<255&&n++}for(let t=0;t<r.length;t++){const a=new Uint8Array(r[t]);if(this._readable.read(a,0,a.length)!==a.length)return!1;if(s&Ht.ContinuesPacket){if(0===e.length)throw new $e(Se.Format,"OGG: Continuation page without any previous packets");e[e.length-1].addData(a)}else{const n=new js(a,!!(s&Ht.BeginningOfStream)&&0===t,!!(s&Ht.EndOfStream)&&t===r.length-1,i);e.push(n)}}return!0}}class Qs{constructor(){this.audioChannels=0,this.audioSampleRate=0,this.samples=new Float32Array(0),this.bitrateMaximum=0,this.bitrateNominal=0,this.bitrateMinimum=0,this.blocksize0=0,this.blocksize1=0}}class Zs{constructor(){this.value=0,this.bitsRead=0}}class ei{constructor(e){this._bitBucket=0n,this._bitCount=0n,this._overflowBits=0n,this._source=e}readByte(){return this.readBits(ei.ByteSize)}readBit(){return 1===this.readBits(1)}readBytes(e){const t=new Uint8Array(e);for(let s=0;s<e;s++)t[s]=255&this.readByte();return t}readBits(e){if(0===e)return 0;const t=this.tryPeekBits(e);return this.skipBits(e),t.value}tryPeekBits(e){if(e<0||e>32)throw new $e(Se.General,"IO: Cannot read more than 32 bits in one go");if(0===e)return new Zs;const t=new Zs;for(;this._bitCount<e;){const e=BigInt(this._source.readByte());if(-1n===e)return t.bitsRead=Number(this._bitCount),t.value=Number(this._bitBucket),this._bitBucket=0n,this._bitCount=0n,t;this._bitBucket=(0xffn&e)<<this._bitCount|this._bitBucket,this._bitCount+=8n,this._bitCount>32&&(this._overflowBits=e>>40n-this._bitCount&0xffn)}let s=this._bitBucket;return e<64&&(s&=(1n<<BigInt(e))-1n),t.value=Number(s),t.bitsRead=e,t}skipBits(e){let t=BigInt(e);if(0===e);else if(this._bitCount>t){if(this._bitBucket=e>31?0n:this._bitBucket>>t,this._bitCount>32){const s=this._bitCount-32n;this._bitBucket=this._bitBucket|this._overflowBits<<this._bitCount-t-s,s>e&&(this._overflowBits=this._overflowBits>>t&0xffn)}this._bitCount-=t}else if(this._bitCount===t)this._bitBucket=0n,this._bitCount=0n;else{for(t-=this._bitCount,this._bitCount=0n,this._bitBucket=0n;t>8;){if(-1===this._source.readByte()){t=0n;break}t-=8n}if(t>0){const e=BigInt(this._source.readByte());-1n===e||(this._bitBucket=e>>t,this._bitCount=8n-t)}}}}ei.ByteSize=8;class ti{constructor(){this.codebooks=[],this.timeDomainTransforms=[],this.floors=[],this.residues=[],this.mappings=[],this.modes=[]}}class si{static ilog(e){let t=0;for(;e>0;)++t,e>>=1;return t}static bitReverse(e,t=32){let s=BigInt(e);s=(s&BigInt(2863311530))>>1n|(s&BigInt(1431655765))<<1n,s=(s&BigInt(3435973836))>>2n|(s&BigInt(858993459))<<2n,s=(s&BigInt(4042322160))>>4n|(s&BigInt(252645135))<<4n,s=(s&BigInt(4278255360))>>8n|(s&BigInt(16711935))<<8n,s=(s>>16n|s<<16n)>>32n-BigInt(t);return Number(BigInt.asUintN(32,s))}static convertFromVorbisFloat32(e){const t=BigInt(e);let s=t&BigInt(2097151);const i=t&BigInt(2147483648),a=(t&BigInt(2145386496))>>21n;return 0n!==i&&(s=-s),Number(s)*Math.pow(2,Number(a)-788)}}class ii{constructor(e){this._data=e}get(e){return this._data[e]}}class ai{get(e){return e}}ai.instance=new ai;class ri{constructor(e,t){this._maxBits=0,this._overflowList=null,this._prefixList=null,this._prefixBitLength=0,this.dimensions=0,this.entries=0,this.mapType=0;if(5653314!==e.readBits(24))throw new $e(Se.Format,"Vorbis: Book header had invalid signature!");this.dimensions=e.readBits(16),this.entries=e.readBits(24),this._lengths=new Int32Array(this.entries),this.initTree(e,t),this.initLookupTable(e)}get(e,t){return this._lookupTable[e*this.dimensions+t]}decodeScalar(e){let t=e.tryPeekBits(this._prefixBitLength);if(0===t.bitsRead)return-1;let s=this._prefixList[t.value];if(null!=s)return e.skipBits(s.length),s.value;if(t=e.tryPeekBits(this._maxBits),null!==this._overflowList)for(let i=0;i<this._overflowList.length;i++){s=this._overflowList[i];const a=t.value&s.mask;if(s.bits===a)return e.skipBits(s.length),s.value}return-1}initTree(e,t){let s,i,a=0;if(e.readBit()){let t=e.readBits(5)+1;for(let s=0;s<this.entries;){let i=e.readBits(si.ilog(this.entries-s));for(;--i>=0;)this._lengths[s++]=t;++t}a=0,s=!1,i=t}else{i=-1,s=e.readBit();for(let t=0;t<this.entries;t++)!s||e.readBit()?(this._lengths[t]=e.readBits(5)+1,++a):this._lengths[t]=-1,this._lengths[t]>i&&(i=this._lengths[t])}if(this._maxBits=i,i>-1){let e,i=null;s&&a>=this.entries>>2&&(i=new Int32Array(this.entries),i.set(this._lengths.subarray(0,this.entries),0),s=!1),e=s?a:0;let r=null,n=null;if(s?0!==e&&(i=new Int32Array(e),n=new Int32Array(e),r=new Int32Array(e)):n=new Int32Array(this.entries),!this.computeCodewords(s,n,i,this._lengths,this.entries,r))throw new $e(Se.Format,"Vorbis: Failed to compute codewords");const o=null==r?ai.instance:new ii(r);t.generateTable(o,i??this._lengths,n),this._prefixList=t.prefixTree,this._prefixBitLength=t.tableBits,this._overflowList=t.overflowList}}computeCodewords(e,t,s,i,a,r){const n=new Uint32Array(32);let o=0,h=0;for(o=0;o<a&&!(i[o]>0);++o);if(o===a)return!0;this.addEntry(e,t,s,0,o,h++,i[o],r);for(let e=1;e<=i[o];++e)n[e]=1<<32-e;for(let l=o+1;l<a;++l){let a=i[l];if(a<=0)continue;for(;a>0&&0===n[a];)--a;if(0===a)return!1;const o=n[a];if(n[a]=0,this.addEntry(e,t,s,si.bitReverse(o),l,h++,i[l],r),a!==i[l])for(let e=i[l];e>a;--e)n[e]=o+(1<<32-e)}return!0}addEntry(e,t,s,i,a,r,n,o){e?(t[r]=i,s[r]=n,o[r]=a):t[a]=i}initLookupTable(e){if(this.mapType=e.readBits(4),0===this.mapType)return;const t=si.convertFromVorbisFloat32(e.readBits(32)),s=si.convertFromVorbisFloat32(e.readBits(32)),i=e.readBits(4)+1,a=e.readBit();let r=this.entries*this.dimensions;const n=new Float32Array(r);1===this.mapType&&(r=this.lookup1Values());const o=new Uint32Array(r);for(let t=0;t<r;t++)o[t]=e.readBits(i);if(1===this.mapType)for(let e=0;e<this.entries;e++){let i=0,h=1;for(let l=0;l<this.dimensions;l++){const c=o[e/h%r|0]*s+t+i;n[e*this.dimensions+l]=c,a&&(i=c),h*=r}}else for(let e=0;e<this.entries;e++){let i=0,r=e*this.dimensions;for(let h=0;h<this.dimensions;h++){const l=o[r]*s+t+i;n[e*this.dimensions+h]=l,a&&(i=l),++r}}this._lookupTable=n}lookup1Values(){let e=Math.floor(Math.exp(Math.log(this.entries)/this.dimensions));return Math.floor(Math.pow(e+1,this.dimensions))<=this.entries&&++e,e}}class ni{constructor(){this.value=0,this.length=0,this.bits=0,this.mask=0}}class oi{constructor(){this.tableBits=0,this.prefixTree=[],this.overflowList=null}generateTable(e,t,s){const i=new Array(t.length);let a=0;for(let r=0;r<i.length;r++){const n=new ni;n.value=e.get(r),n.length=t[r]<=0?99999:t[r],n.bits=s[r],n.mask=(1<<t[r])-1,i[r]=n,t[r]>0&&a<t[r]&&(a=t[r])}i.sort(((e,t)=>{const s=e.length-t.length;return 0===s?e.bits-t.bits:s}));const r=a>oi.MAX_TABLE_BITS?oi.MAX_TABLE_BITS:a,n=[];let o=null;for(let e=0;e<i.length&&i[e].length<99999;e++){const t=i[e].length;if(t>r)for(o=[];e<i.length&&i[e].length<99999;e++)o.push(i[e]);else{const s=1<<r-t,a=i[e];for(let e=0;e<s;e++){const s=e<<t|a.bits;for(;n.length<=s;)n.push(null);n[s]=a}}}for(;n.length<1<<r;)n.push(null);this.tableBits=r,this.prefixTree=n,this.overflowList=o}}oi.MAX_TABLE_BITS=10;class hi{constructor(e){e.readBits(16)}}class li{get executeChannel(){return(this.forceEnergy||this.amp>0)&&!this.forceNoEnergy}constructor(e){this.amp=0,this.forceEnergy=!1,this.forceNoEnergy=!1,this.coeff=e}}class ci{constructor(e,t,s,i){if(this._order=e.readBits(8),this._rate=e.readBits(16),this._bark_map_size=e.readBits(16),this._ampBits=e.readBits(6),this._ampOfs=e.readBits(8),this._books=new Array(e.readBits(4)+1),this._order<1||this._rate<1||this._bark_map_size<1||0===this._books.length)throw new $e(Se.Format,"Vorbis: Invalid Floor0 Data");this._ampDiv=(1<<this._ampBits)-1;for(let t=0;t<this._books.length;t++){const s=e.readBits(8);if(s<0||s>=i.length)throw new $e(Se.Format,"Vorbis: Invalid Floor0 Data");const a=i[s];if(0===a.mapType||a.dimensions<1)throw new $e(Se.Format,"Vorbis: Invalid Floor0 Data");this._books[t]=a}this._bookBits=si.ilog(this._books.length),this._barkMaps=new Map([[t,this.synthesizeBarkCurve(t/2)],[s,this.synthesizeBarkCurve(s/2)]]),this._wMap=new Map([[t,this.synthesizeWDelMap(t/2)],[s,this.synthesizeWDelMap(s/2)]])}synthesizeBarkCurve(e){const t=this._bark_map_size/ci.toBARK(this._rate/2),s=new Int32Array(e+1);for(let i=0;i<e-1;i++)s[i]=Math.min(this._bark_map_size-1,Math.floor(ci.toBARK(this._rate/2/e*i)*t));return s[e]=-1,s}static toBARK(e){return 13.1*Math.atan(74e-5*e)+2.24*Math.atan(1.85e-8*e*e)+1e-4*e}synthesizeWDelMap(e){const t=Math.PI/this._bark_map_size,s=new Float32Array(e);for(let i=0;i<e;i++)s[i]=2*Math.cos(t*i);return s}unpack(e,t,s){const i=new li(new Float32Array(this._order+1));if(i.amp=e.readBits(this._ampBits),i.amp>0){i.amp=i.amp/this._ampDiv*this._ampOfs;const t=e.readBits(this._bookBits);if(t>=this._books.length)return i.amp=0,i;const s=this._books[t];for(let t=0;t<this._order;){const a=s.decodeScalar(e);if(-1===a)return i.amp=0,i;for(let e=0;t<this._order&&e<s.dimensions;e++,t++)i.coeff[t]=s.get(a,e)}let a=0;for(let e=0;e<this._order;){for(let t=0;e<this._order&&t<s.dimensions;e++,t++)i.coeff[e]+=a;a=i.coeff[e-1]}}return i}apply(e,t,s){const i=e,a=t/2;if(i.amp>0){const e=this._barkMaps.get(t),r=this._wMap.get(t);let n=0;for(n=0;n<this._order;n++)i.coeff[n]=2*Math.cos(i.coeff[n]);for(n=0;n<a;){let t=0;const a=e[n];let o=.5,h=.5;const l=r[a];for(t=1;t<this._order;t+=2)h*=l-i.coeff[t-1],o*=l-i.coeff[t];for(t===this._order?(h*=l-i.coeff[t-1],o*=o*(4-l*l),h*=h):(o*=o*(2-l),h*=h*(2+l)),h=i.amp/Math.sqrt(o+h)-this._ampOfs,h=Math.exp(.11512925*h),s[n]*=h;e[++n]===a;)s[n]*=h}}else s.fill(0,0,a)}}class di{constructor(){this.posts=new Int32Array(64),this.postCount=0,this.forceEnergy=!1,this.forceNoEnergy=!1}get executeChannel(){return(this.forceEnergy||this.postCount>0)&&!this.forceNoEnergy}}class ui{constructor(e,t){let s=-1;this._partitionClass=new Int32Array(e.readBits(5));for(let t=0;t<this._partitionClass.length;t++)this._partitionClass[t]=e.readBits(4),this._partitionClass[t]>s&&(s=this._partitionClass[t]);++s,this._classDimensions=new Int32Array(s),this._classSubclasses=new Int32Array(s),this._classMasterbooks=new Array(s),this._classMasterBookIndex=new Int32Array(s),this._subclassBooks=new Array(s),this._subclassBookIndex=new Array(s);for(let i=0;i<s;i++){this._classDimensions[i]=e.readBits(3)+1,this._classSubclasses[i]=e.readBits(2),this._classSubclasses[i]>0&&(this._classMasterBookIndex[i]=e.readBits(8),this._classMasterbooks[i]=t[this._classMasterBookIndex[i]]),this._subclassBooks[i]=new Array(1<<this._classSubclasses[i]),this._subclassBookIndex[i]=new Int32Array(this._subclassBooks[i].length);for(let s=0;s<this._subclassBooks[i].length;s++){const a=e.readBits(8)-1;a>=0&&(this._subclassBooks[i][s]=t[a]),this._subclassBookIndex[i][s]=a}}this._multiplier=e.readBits(2),this._range=ui._rangeLookup[this._multiplier],this._yBits=ui._yBitsLookup[this._multiplier],++this._multiplier;const i=e.readBits(4),a=[];a.push(0),a.push(1<<i);for(let t=0;t<this._partitionClass.length;t++){const s=this._partitionClass[t];for(let t=0;t<this._classDimensions[s];t++)a.push(e.readBits(i))}this._xList=new Int32Array(a),this._lNeigh=new Int32Array(a.length),this._hNeigh=new Int32Array(a.length),this._sortIdx=new Int32Array(a.length),this._sortIdx[0]=0,this._sortIdx[1]=1;for(let e=2;e<this._lNeigh.length;e++){this._lNeigh[e]=0,this._hNeigh[e]=1,this._sortIdx[e]=e;for(let t=2;t<e;t++){const s=this._xList[t];s<this._xList[e]?s>this._xList[this._lNeigh[e]]&&(this._lNeigh[e]=t):s<this._xList[this._hNeigh[e]]&&(this._hNeigh[e]=t)}}for(let e=0;e<this._sortIdx.length-1;e++)for(let t=e+1;t<this._sortIdx.length;t++){if(this._xList[e]===this._xList[t])throw new $e(Se.Format,"Vorbis: Invalid Floor1 Data");if(this._xList[this._sortIdx[e]]>this._xList[this._sortIdx[t]]){const s=this._sortIdx[e];this._sortIdx[e]=this._sortIdx[t],this._sortIdx[t]=s}}}unpack(e,t,s){const i=new di;if(e.readBit()){let t=2;i.posts[0]=e.readBits(this._yBits),i.posts[1]=e.readBits(this._yBits);for(let s=0;s<this._partitionClass.length;s++){const a=this._partitionClass[s],r=this._classDimensions[a],n=this._classSubclasses[a],o=(1<<n)-1;let h=0;if(n>0&&(h=this._classMasterbooks[a].decodeScalar(e),-1===h)){t=0;break}for(let l=0;l<r;l++){const r=this._subclassBooks[a][h&o];if(h>>=n,null!=r&&(i.posts[t]=r.decodeScalar(e),-1===i.posts[t])){t=0,s=this._partitionClass.length;break}++t}}i.postCount=t}return i}apply(e,t,s){const i=e,a=t/2;if(i.postCount>0){const e=this.unwrapPosts(i);let t=0,r=i.posts[0]*this._multiplier;for(let n=1;n<i.postCount;n++){const o=this._sortIdx[n];if(e[o]){const e=this._xList[o],n=i.posts[o]*this._multiplier;t<a&&this.renderLineMulti(t,r,Math.min(e,a),n,s),t=e,r=n}if(t>=a)break}t<a&&this.renderLineMulti(t,r,a,r,s)}else s.fill(0,0,a)}unwrapPosts(e){const t=new Array(64);t.fill(!1),t[0]=!0,t[1]=!0;const s=new Int32Array(64);s[0]=e.posts[0],s[1]=e.posts[1];for(let i=2;i<e.postCount;i++){const a=this._lNeigh[i],r=this._hNeigh[i],n=this.renderPoint(this._xList[a],s[a],this._xList[r],s[r],this._xList[i]),o=e.posts[i],h=this._range-n,l=n;let c;c=h<l?2*h:2*l,0!==o?(t[a]=!0,t[r]=!0,t[i]=!0,s[i]=o>=c?h>l?o-l+n:n-o+h-1:o%2==1?n-(o+1)/2:n+o/2):(t[i]=!1,s[i]=n)}for(let t=0;t<e.postCount;t++)e.posts[t]=s[t];return t}renderPoint(e,t,s,i,a){const r=i-t,n=s-e,o=Math.abs(r)*(a-e)/n|0;return r<0?t-o:t+o}renderLineMulti(e,t,s,i,a){const r=i-t,n=s-e;let o=Math.abs(r);const h=1-2*(r>>31&1),l=r/n|0;let c=e,d=t,u=-n;for(a[e]*=ui.inverse_dB_table[t],o-=Math.abs(l)*n;++c<s;)d+=l,u+=o,u>=0&&(u-=n,d+=h),a[c]*=ui.inverse_dB_table[d]}}ui._rangeLookup=[256,128,86,64],ui._yBitsLookup=[8,7,7,6],ui.inverse_dB_table=new Float32Array([1.0649863e-7,1.1341951e-7,1.2079015e-7,1.2863978e-7,1.3699951e-7,1.4590251e-7,1.5538408e-7,1.6548181e-7,1.7623575e-7,1.8768855e-7,1.9988561e-7,2.128753e-7,2.2670913e-7,2.4144197e-7,2.5713223e-7,2.7384213e-7,2.9163793e-7,3.1059021e-7,3.3077411e-7,3.5226968e-7,3.7516214e-7,3.9954229e-7,4.255068e-7,4.5315863e-7,4.8260743e-7,5.1396998e-7,5.4737065e-7,5.8294187e-7,6.2082472e-7,6.6116941e-7,7.0413592e-7,7.4989464e-7,7.9862701e-7,8.505263e-7,9.0579828e-7,9.6466216e-7,10273513e-13,10941144e-13,11652161e-13,12409384e-13,13215816e-13,14074654e-13,14989305e-13,15963394e-13,17000785e-13,18105592e-13,19282195e-13,20535261e-13,21869758e-13,23290978e-13,24804557e-13,26416497e-13,2813319e-12,29961443e-13,31908506e-13,33982101e-13,36190449e-13,38542308e-13,41047004e-13,4371447e-12,46555282e-13,49580707e-13,5280274e-12,5623416e-12,59888572e-13,63780469e-13,67925283e-13,72339451e-13,77040476e-13,82047e-10,87378876e-13,93057248e-13,99104632e-13,10554501e-12,11240392e-12,11970856e-12,12748789e-12,13577278e-12,14459606e-12,15399272e-12,16400004e-12,17465768e-12,18600792e-12,19809576e-12,21096914e-12,22467911e-12,23928002e-12,25482978e-12,27139006e-12,28902651e-12,30780908e-12,32781225e-12,34911534e-12,37180282e-12,39596466e-12,42169667e-12,4491009e-11,47828601e-12,50936773e-12,54246931e-12,57772202e-12,61526565e-12,65524908e-12,69783085e-12,74317983e-12,79147585e-12,8429104e-11,89768747e-12,95602426e-12,.00010181521,.00010843174,.00011547824,.00012298267,.00013097477,.00013948625,.00014855085,.00015820453,.00016848555,.00017943469,.00019109536,.00020351382,.00021673929,.00023082423,.00024582449,.00026179955,.00027881276,.00029693158,.00031622787,.00033677814,.00035866388,.00038197188,.00040679456,.00043323036,.00046138411,.00049136745,.00052329927,.00055730621,.00059352311,.00063209358,.00067317058,716917e-9,.0007635063,.00081312324,.00086596457,.00092223983,.00098217216,.0010459992,.0011139742,.0011863665,.0012634633,.0013455702,.0014330129,.0015261382,.0016253153,.0017309374,.0018434235,.0019632195,.0020908006,.0022266726,.0023713743,.0025254795,.0026895994,.0028643847,.0030505286,.0032487691,.0034598925,.0036847358,.0039241906,.0041792066,.004450795,.0047400328,.0050480668,.0053761186,.0057254891,.0060975636,.0064938176,.0069158225,.0073652516,.0078438871,.0083536271,.0088964928,.009474637,.010090352,.01074608,.011444421,.012188144,.012980198,.013823725,.014722068,.015678791,.016697687,.017782797,.018938423,.020169149,.021479854,.022875735,.02436233,.025945531,.027631618,.029427276,.031339626,.033376252,.035545228,.037855157,.040315199,.042935108,.045725273,.048696758,.051861348,.055231591,.05882085,.062643361,.066714279,.071049749,.075666962,.080584227,.085821044,.091398179,.097337747,.1036633,.11039993,.11757434,.12521498,.13335215,.14201813,.15124727,.16107617,.1715438,.18269168,.19456402,.20720788,.22067342,.23501402,.25028656,.26655159,.28387361,.30232132,.32196786,.34289114,.36517414,.38890521,.41417847,.44109412,.4697589,.50028648,.53279791,.56742212,.6042964,.64356699,.68538959,.72993007,.77736504,.8278826,.88168307,.9389798,1]);class pi{constructor(e,t,s,i){const a=e.readBits(16);switch(a){case 0:this.floor=new ci(e,t,s,i);break;case 1:this.floor=new ui(e,i);break;default:throw new $e(Se.Format,`Vorbis: Invalid Floor type: ${a}`)}}apply(e,t,s){this.floor.apply(e,t,s)}unpack(e,t,s){return this.floor.unpack(e,t,s)}}class gi{constructor(e,t,s){this._begin=e.readBits(24),this._end=e.readBits(24),this._partitionSize=e.readBits(24)+1,this._classifications=e.readBits(6)+1,this._classBook=s[e.readBits(8)],this._cascade=new Int32Array(this._classifications);let i=0;for(let t=0;t<this._classifications;t++){const s=e.readBits(3);e.readBit()?this._cascade[t]=e.readBits(5)<<3|s:this._cascade[t]=s,i+=gi.icount(this._cascade[t])}const a=new Int32Array(i);for(let t=0;t<i;t++)if(a[t]=e.readBits(8),0===s[a[t]].mapType)throw new $e(Se.Format,"Vorbis: Invalid Residue 0");const r=this._classBook.entries;let n=this._classBook.dimensions,o=1;for(;n>0;){if(o*=this._classifications,o>r)throw new $e(Se.Format,"Vorbis: Invalid Residue 0");--n}this._books=new Array(this._classifications),i=0;let h,l=0;for(let e=0;e<this._classifications;e++)if(h=si.ilog(this._cascade[e]),this._books[e]=new Array(h),h>0){l=Math.max(l,h);for(let t=0;t<h;t++)(this._cascade[e]&1<<t)>0&&(this._books[e][t]=s[a[i++]])}this._maxStages=l,this._decodeMap=new Array(o);for(let e=0;e<o;e++){let t=e,s=o/this._classifications|0;this._decodeMap[e]=new Int32Array(this._classBook.dimensions);for(let i=0;i<this._classBook.dimensions;i++){const a=t/s|0;t-=a*s,s=s/this._classifications|0,this._decodeMap[e][i]=a}}this._channels=t}static icount(e){let t=0;for(;0!==e;)t+=1&e,e>>=1;return t}decode(e,t,s,i){const a=(this._end<s/2?this._end:s/2)-this._begin;if(a>0&&-1!==t.indexOf(!1)){const t=a/this._partitionSize,s=(t+this._classBook.dimensions-1)/this._classBook.dimensions|0,r=[];for(let e=0;e<this._channels;e++)r.push(new Array(s));for(let s=0;s<this._maxStages;s++)for(let a=0,n=0;a<t;n++){if(0===s)for(let i=0;i<this._channels;i++){const o=this._classBook.decodeScalar(e);if(!(o>=0&&o<this._decodeMap.length)){a=t,s=this._maxStages;break}r[i][n]=this._decodeMap[o]}for(let o=0;a<t&&o<this._classBook.dimensions;o++,a++){const h=this._begin+a*this._partitionSize;for(let l=0;l<this._channels;l++){const c=r[l][n][o];if(this._cascade[c]&1<<s){const r=this._books[c][s];if(r&&this.writeVectors(r,e,i,l,h,this._partitionSize)){a=t,s=this._maxStages;break}}}}}}}writeVectors(e,t,s,i,a,r){const n=s[i],o=r/e.dimensions,h=new Int32Array(o);for(let s=0;s<o;s++)if(h[s]=e.decodeScalar(t),-1===h[s])return!0;for(let t=0;t<e.dimensions;t++)for(let s=0;s<o;s++,a++)n[a]+=e.get(h[s],t);return!1}}class mi extends gi{writeVectors(e,t,s,i,a,r){const n=s[i];for(let s=0;s<r;){const i=e.decodeScalar(t);if(-1===i)return!0;for(let t=0;t<e.dimensions;s++,t++)n[a+s]+=e.get(i,t)}return!1}}class fi extends gi{constructor(e,t,s){super(e,1,s),this._realChannels=t}decode(e,t,s,i){super.decode(e,t,s*this._realChannels,i)}writeVectors(e,t,s,i,a,r){let n=0;a/=this._realChannels;for(let i=0;i<r;){const r=e.decodeScalar(t);if(-1===r)return!0;for(let t=0;t<e.dimensions;t++,i++)s[n][a]+=e.get(r,t),++n===this._realChannels&&(n=0,a++)}return!1}}class yi{constructor(e,t,s){const i=e.readBits(16);switch(i){case 0:this.residue=new gi(e,t,s);break;case 1:this.residue=new mi(e,t,s);break;case 2:this.residue=new fi(e,t,s);break;default:throw new $e(Se.Format,`Vorbis: Invalid Residue type: ${i}`)}}decode(e,t,s,i){this.residue.decode(e,t,s,i)}}class bi{constructor(e,t,s,i,a){if(0!==e.readBits(16))throw new $e(Se.Format,"Vorbis: Invalid mapping type!");let r=1;e.readBit()&&(r+=e.readBits(4));let n=0;e.readBit()&&(n=e.readBits(8)+1);const o=si.ilog(t-1);this._couplingAngle=new Int32Array(n),this._couplingMangitude=new Int32Array(n);for(let s=0;s<n;s++){const i=e.readBits(o),a=e.readBits(o);if(i===a||i>t-1||a>t-1)throw new $e(Se.Format,"Vorbis: Invalid magnitude or angle in mapping header!");this._couplingAngle[s]=a,this._couplingMangitude[s]=i}if(0!==e.readBits(2))throw new $e(Se.Format,"Vorbis: Reserved bits not 0 in mapping header.");const h=new Int32Array(t);if(r>1)for(let s=0;s<t;s++)if(h[s]=e.readBits(4),h[s]>r)throw new $e(Se.Format,"Vorbis: Invalid channel mux submap index in mapping header!");this._submapFloor=new Array(r),this._submapResidue=new Array(r);for(let t=0;t<r;t++){e.skipBits(8);const a=e.readBits(8);if(a>=s.length)throw new $e(Se.Format,"Vorbis: Invalid floor number in mapping header!");const r=e.readBits(8);if(r>=i.length)throw new $e(Se.Format,"Vorbis: Invalid residue number in mapping header!");this._submapFloor[t]=s[a],this._submapResidue[t]=i[r]}this._channelFloor=new Array(t),this._channelResidue=new Array(t);for(let e=0;e<t;e++)this._channelFloor[e]=this._submapFloor[h[e]],this._channelResidue[e]=this._submapResidue[h[e]];this._mdct=a}decodePacket(e,t,s){const i=t>>1,a=new Array(this._channelFloor.length),r=new Array(this._channelFloor.length);r.fill(!1);for(let n=0;n<this._channelFloor.length;n++)a[n]=this._channelFloor[n].unpack(e,t,n),r[n]=!a[n].executeChannel,s[n].fill(0,0,i);for(let e=0;e<this._couplingAngle.length;e++)(a[this._couplingAngle[e]].executeChannel||a[this._couplingMangitude[e]].executeChannel)&&(a[this._couplingAngle[e]].forceEnergy=!0,a[this._couplingMangitude[e]].forceEnergy=!0);for(let i=0;i<this._submapFloor.length;i++){for(let e=0;e<this._channelFloor.length;e++)this._submapFloor[i]===this._channelFloor[e]&&this._submapResidue[i]===this._channelResidue[e]||(a[e].forceNoEnergy=!0);this._submapResidue[i].decode(e,r,t,s)}for(let e=this._couplingAngle.length-1;e>=0;e--)if(a[this._couplingAngle[e]].executeChannel||a[this._couplingMangitude[e]].executeChannel){const t=s[this._couplingMangitude[e]],a=s[this._couplingAngle[e]];for(let e=0;e<i;e++){let s,i;const r=t[e],n=a[e];r>0?n>0?(s=r,i=r-n):(i=r,s=r+n):n>0?(s=r,i=r+n):(i=r,s=r-n),t[e]=s,a[e]=i}}for(let e=0;e<this._channelFloor.length;e++)a[e].executeChannel?(this._channelFloor[e].apply(a[e],t,s[e]),this._mdct.reverse(s[e],t)):s[e].fill(0,i,2*i)}}class Si{constructor(){this.packetStartIndex=0,this.packetTotalLength=0,this.packetValidLength=0}}class _i{constructor(){this.overlapInfo=new Si,this.windowIndex=0}}class wi{constructor(e=null){this.samplePosition=null,this.samplePosition=e}}class Bi{constructor(e,t,s,i,a){if(this._overlapInfo=null,this._channels=t,this._blockFlag=e.readBit(),0!==e.readBits(32))throw new $e(Se.Format,"Vorbis: Mode header had invalid window or transform type!");const r=e.readBits(8);if(r>=a.length)throw new $e(Se.Format,"Vorbis: Mode header had invalid mapping index!");this._mapping=a[r],this._blockFlag?(this._blockSize=i,this._windows=[Bi.calcWindow(s,i,s),Bi.calcWindow(i,i,s),Bi.calcWindow(s,i,i),Bi.calcWindow(i,i,i)],this._overlapInfo=[Bi.calcOverlap(s,i,s),Bi.calcOverlap(i,i,s),Bi.calcOverlap(s,i,i),Bi.calcOverlap(i,i,i)]):(this._blockSize=s,this._windows=[Bi.calcWindow(s,s,s)])}decode(e,t){const s=this.getPacketInfo(e);this._mapping.decodePacket(e,this._blockSize,t);const i=this._windows[s.windowIndex];for(let e=0;e<this._blockSize;e++)for(let s=0;s<this._channels;s++)t[s][e]*=i[e];return s.overlapInfo}getPacketInfo(e){const t=new _i;if(this._blockFlag){const s=e.readBit(),i=e.readBit();t.windowIndex=(s?1:0)+(i?2:0);const a=this._overlapInfo[t.windowIndex];t.overlapInfo.packetStartIndex=a.packetStartIndex,t.overlapInfo.packetValidLength=a.packetValidLength,t.overlapInfo.packetTotalLength=a.packetTotalLength}else t.windowIndex=0,t.overlapInfo.packetStartIndex=0,t.overlapInfo.packetValidLength=this._blockSize/2,t.overlapInfo.packetTotalLength=this._blockSize;return t}static calcWindow(e,t,s){const i=new Float32Array(t),a=e/2,r=s/2,n=t/4-a/2,o=t-t/4-r/2;for(let e=0;e<a;e++){let t=Math.sin((e+.5)/a*Bi.M_PI2);t*=t,i[n+e]=Math.sin(t*Bi.M_PI2)}for(let e=n+a;e<o;e++)i[e]=1;for(let e=0;e<r;e++){let t=Math.sin((r-e-.5)/r*Bi.M_PI2);t*=t,i[o+e]=Math.sin(t*Bi.M_PI2)}return i}static calcOverlap(e,t,s){const i=s/4,a=t/4-e/4,r=t/4*3+i,n=r-2*i,o=new Si;return o.packetStartIndex=a,o.packetValidLength=n,o.packetTotalLength=r,o}}Bi.M_PI2=1.57079632695;class ki{constructor(e){this._n=e,this._n2=e>>1,this._n4=this._n2>>1,this._n8=this._n4>>1,this._ld=si.ilog(e)-1,this._a=new Float32Array(this._n2),this._b=new Float32Array(this._n2),this._c=new Float32Array(this._n4);let t=0,s=0;for(;t<this._n4;++t,s+=2)this._a[s]=Math.cos(4*t*ki.M_PI/e),this._a[s+1]=-Math.sin(4*t*ki.M_PI/e),this._b[s]=.5*Math.cos((s+1)*ki.M_PI/e/2),this._b[s+1]=.5*Math.sin((s+1)*ki.M_PI/e/2);for(t=0,s=0;t<this._n8;++t,s+=2)this._c[s]=Math.cos(2*(s+1)*ki.M_PI/e),this._c[s+1]=-Math.sin(2*(s+1)*ki.M_PI/e);this._bitrev=new Uint16Array(this._n8);for(let e=0;e<this._n8;++e)this._bitrev[e]=nt.int32ToUint16(si.bitReverse(e,this._ld-3)<<2)}calcReverse(e){let t,s;const i=new Float32Array(this._n2);{let t=this._n2-2,s=0,a=0;const r=this._n2;for(;a!==r;)i[t+1]=e[a]*this._a[s]-e[a+2]*this._a[s+1],i[t]=e[a]*this._a[s+1]+e[a+2]*this._a[s],t-=2,s+=2,a+=4;for(a=this._n2-3;t>=0;)i[t+1]=-e[a+2]*this._a[s]- -e[a]*this._a[s+1],i[t]=-e[a+2]*this._a[s+1]+-e[a]*this._a[s],t-=2,s+=2,a-=4}t=e,s=i;{let e=this._n2-8,i=this._n4,a=0,r=this._n4,n=0;for(;e>=0;){let o,h;h=s[i+1]-s[a+1],o=s[i]-s[a],t[r+1]=s[i+1]+s[a+1],t[r]=s[i]+s[a],t[n+1]=h*this._a[e+4]-o*this._a[e+5],t[n]=o*this._a[e+4]+h*this._a[e+5],h=s[i+3]-s[a+3],o=s[i+2]-s[a+2],t[r+3]=s[i+3]+s[a+3],t[r+2]=s[i+2]+s[a+2],t[n+3]=h*this._a[e]-o*this._a[e+1],t[n+2]=o*this._a[e]+h*this._a[e+1],e-=8,r+=4,n+=4,i+=4,a+=4}}this.step3_iter0_loop(this._n>>4,t,this._n2-1-0*this._n4,-this._n8),this.step3_iter0_loop(this._n>>4,t,this._n2-1-1*this._n4,-this._n8),this.step3_inner_r_loop(this._n>>5,t,this._n2-1-0*this._n8,-(this._n>>4),16),this.step3_inner_r_loop(this._n>>5,t,this._n2-1-1*this._n8,-(this._n>>4),16),this.step3_inner_r_loop(this._n>>5,t,this._n2-1-2*this._n8,-(this._n>>4),16),this.step3_inner_r_loop(this._n>>5,t,this._n2-1-3*this._n8,-(this._n>>4),16);let a=2;for(;a<this._ld-3>>1;++a){const e=this._n>>a+2,s=e>>1,i=1<<a+1;for(let r=0;r<i;++r)this.step3_inner_r_loop(this._n>>a+4,t,this._n2-1-e*r,-s,1<<a+3)}for(;a<this._ld-6;++a){const e=this._n>>a+2,s=1<<a+3,i=e>>1,r=this._n>>a+6,n=1<<a+1;let o=this._n2-1,h=0;for(let a=r;a>0;--a)this.step3_inner_s_loop(n,t,o,-i,h,s,e),h+=4*s,o-=8}this.step3_inner_s_loop_ld654(this._n>>5,t,this._n2-1,this._n);{let e=0,i=this._n4-4,a=this._n2-4;for(;i>=0;){let r;r=this._bitrev[e],s[a+3]=t[r],s[a+2]=t[r+1],s[i+3]=t[r+2],s[i+2]=t[r+3],r=this._bitrev[e+1],s[a+1]=t[r],s[a]=t[r+1],s[i+1]=t[r+2],s[i]=t[r+3],i-=4,a-=4,e+=2}}{let e=0,t=0,i=this._n2-4;for(;t<i;){let a,r,n,o,h,l;a=s[t]-s[i+2],r=s[t+1]+s[i+3],n=this._c[e+1]*a+this._c[e]*r,o=this._c[e+1]*r-this._c[e]*a,h=s[t]+s[i+2],l=s[t+1]-s[i+3],s[t]=h+n,s[t+1]=l+o,s[i+2]=h-n,s[i+3]=o-l,a=s[t+2]-s[i],r=s[t+3]+s[i+1],n=this._c[e+3]*a+this._c[e+2]*r,o=this._c[e+3]*r-this._c[e+2]*a,h=s[t+2]+s[i],l=s[t+3]-s[i+1],s[t+2]=h+n,s[t+3]=l+o,s[i]=h-n,s[i+1]=o-l,e+=4,t+=4,i-=4}}{let t=this._n2-8,s=this._n2-8,a=0,r=this._n2-4,n=this._n2,o=this._n-4;for(;s>=0;){let h,l,c,d;d=i[s+6]*this._b[t+7]-i[s+7]*this._b[t+6],c=-i[s+6]*this._b[t+6]-i[s+7]*this._b[t+7],e[a]=d,e[r+3]=-d,e[n]=c,e[o+3]=c,l=i[s+4]*this._b[t+5]-i[s+5]*this._b[t+4],h=-i[s+4]*this._b[t+4]-i[s+5]*this._b[t+5],e[a+1]=l,e[r+2]=-l,e[n+1]=h,e[o+2]=h,d=i[s+2]*this._b[t+3]-i[s+3]*this._b[t+2],c=-i[s+2]*this._b[t+2]-i[s+3]*this._b[t+3],e[a+2]=d,e[r+1]=-d,e[n+2]=c,e[o+1]=c,l=i[s]*this._b[t+1]-i[s+1]*this._b[t],h=-i[s]*this._b[t]-i[s+1]*this._b[t+1],e[a+3]=l,e[r]=-l,e[n+3]=h,e[o]=h,t-=8,s-=8,a+=4,n+=4,r-=4,o-=4}}}step3_inner_r_loop(e,t,s,i,a){let r,n,o=s,h=o+i,l=0;for(let s=e>>2;s>0;--s)r=t[o]-t[h],n=t[o-1]-t[h-1],t[o]+=t[h],t[o-1]+=t[h-1],t[h]=r*this._a[l]-n*this._a[l+1],t[h-1]=n*this._a[l]+r*this._a[l+1],l+=a,r=t[o-2]-t[h-2],n=t[o-3]-t[h-3],t[o-2]+=t[h-2],t[o-3]+=t[h-3],t[h-2]=r*this._a[l]-n*this._a[l+1],t[h-3]=n*this._a[l]+r*this._a[l+1],l+=a,r=t[o-4]-t[h-4],n=t[o-5]-t[h-5],t[o-4]+=t[h-4],t[o-5]+=t[h-5],t[h-4]=r*this._a[l]-n*this._a[l+1],t[h-5]=n*this._a[l]+r*this._a[l+1],l+=a,r=t[o-6]-t[h-6],n=t[o-7]-t[h-7],t[o-6]+=t[h-6],t[o-7]+=t[h-7],t[h-6]=r*this._a[l]-n*this._a[l+1],t[h-7]=n*this._a[l]+r*this._a[l+1],l+=a,o-=8,h-=8}step3_iter0_loop(e,t,s,i){let a=s,r=a+i,n=0;for(let s=e>>2;s>0;--s){let e,s;e=t[a]-t[r],s=t[a-1]-t[r-1],t[a]+=t[r],t[a-1]+=t[r-1],t[r]=e*this._a[n]-s*this._a[n+1],t[r-1]=s*this._a[n]+e*this._a[n+1],n+=8,e=t[a-2]-t[r-2],s=t[a-3]-t[r-3],t[a-2]+=t[r-2],t[a-3]+=t[r-3],t[r-2]=e*this._a[n]-s*this._a[n+1],t[r-3]=s*this._a[n]+e*this._a[n+1],n+=8,e=t[a-4]-t[r-4],s=t[a-5]-t[r-5],t[a-4]+=t[r-4],t[a-5]+=t[r-5],t[r-4]=e*this._a[n]-s*this._a[n+1],t[r-5]=s*this._a[n]+e*this._a[n+1],n+=8,e=t[a-6]-t[r-6],s=t[a-7]-t[r-7],t[a-6]+=t[r-6],t[a-7]+=t[r-7],t[r-6]=e*this._a[n]-s*this._a[n+1],t[r-7]=s*this._a[n]+e*this._a[n+1],n+=8,a-=8,r-=8}}step3_inner_s_loop(e,t,s,i,a,r,n){const o=this._a[a],h=this._a[a+1],l=this._a[a+r],c=this._a[a+r+1],d=this._a[a+2*r],u=this._a[a+2*r+1],p=this._a[a+3*r],g=this._a[a+3*r+1];let m,f,y=s,b=y+i;for(let s=e;s>0;--s)m=t[y]-t[b],f=t[y-1]-t[b-1],t[y]+=t[b],t[y-1]+=t[b-1],t[b]=m*o-f*h,t[b-1]=f*o+m*h,m=t[y-2]-t[b-2],f=t[y-3]-t[b-3],t[y-2]+=t[b-2],t[y-3]+=t[b-3],t[b-2]=m*l-f*c,t[b-3]=f*l+m*c,m=t[y-4]-t[b-4],f=t[y-5]-t[b-5],t[y-4]+=t[b-4],t[y-5]+=t[b-5],t[b-4]=m*d-f*u,t[b-5]=f*d+m*u,m=t[y-6]-t[b-6],f=t[y-7]-t[b-7],t[y-6]+=t[b-6],t[y-7]+=t[b-7],t[b-6]=m*p-f*g,t[b-7]=f*p+m*g,y-=n,b-=n}step3_inner_s_loop_ld654(e,t,s,i){const a=i>>3,r=this._a[a];let n=s;const o=n-16*e;for(;n>o;){let e,s;e=t[n]-t[n-8],s=t[n-1]-t[n-9],t[n]+=t[n-8],t[n-1]+=t[n-9],t[n-8]=e,t[n-9]=s,e=t[n-2]-t[n-10],s=t[n-3]-t[n-11],t[n-2]+=t[n-10],t[n-3]+=t[n-11],t[n-10]=(e+s)*r,t[n-11]=(s-e)*r,e=t[n-12]-t[n-4],s=t[n-5]-t[n-13],t[n-4]+=t[n-12],t[n-5]+=t[n-13],t[n-12]=s,t[n-13]=e,e=t[n-14]-t[n-6],s=t[n-7]-t[n-15],t[n-6]+=t[n-14],t[n-7]+=t[n-15],t[n-14]=(e+s)*r,t[n-15]=(e-s)*r,this.iter_54(t,n),this.iter_54(t,n-8),n-=16}}iter_54(e,t){const s=e[t]-e[t-4],i=e[t]+e[t-4],a=e[t-2]+e[t-6],r=e[t-2]-e[t-6];e[t]=i+a,e[t-2]=i-a;const n=e[t-3]-e[t-7];e[t-4]=s+n,e[t-6]=s-n;const o=e[t-1]-e[t-5],h=e[t-1]+e[t-5],l=e[t-3]+e[t-7];e[t-1]=h+l,e[t-3]=h-l,e[t-5]=o-r,e[t-7]=o+r}}ki.M_PI=3.141592653589793;class Ti{constructor(){this._setupCache=new Map}reverse(e,t){let s;this._setupCache.has(t)?s=this._setupCache.get(t):(s=new ki(t),this._setupCache.set(t,s)),s.calcReverse(e)}}class Ni{constructor(e,t,s){this._packetIndex=0,this._stream=e,this._setup=t,this._packets=s,this._currentPosition=0,this._prevPacketBuf=null,this._prevPacketStart=0,this._prevPacketEnd=0,this._prevPacketStop=0,this._nextPacketBuf=null,this._eosFound=!1,this._hasPosition=!1,this._modeFieldBits=si.ilog(t.modes.length-1)}decode(){let e=new Float32Array(this._packets[this._packets.length-1].granulePosition*this._stream.audioChannels);const t=new Float32Array(.2*this._stream.audioSampleRate*this._stream.audioChannels);let s=0,i=0;for(;s=this.read(t,0,t.length),0!==s;){if(i+s>=e.length){const s=new Float32Array(e.length+t.length);s.set(e,0),e=s}e.set(t.subarray(0,s),i),i+=s}return e.subarray(0,i)}read(e,t,s){if(0===s)return 0;let i=t;const a=t+s;for(;i<a;){if(this._prevPacketStart===this._prevPacketEnd){if(this._eosFound){this._nextPacketBuf=null,this._prevPacketBuf=null;break}const e=this.readNextPacket((i-t)/this._stream.audioChannels);null===e&&(this._prevPacketEnd=this._prevPacketStop),null===e||null===e.samplePosition||this._hasPosition||(this._hasPosition=!0,this._currentPosition=e.samplePosition-(this._prevPacketEnd-this._prevPacketStart)-(i-t)/this._stream.audioChannels)}const s=Math.min((a-i)/this._stream.audioChannels,this._prevPacketEnd-this._prevPacketStart);s>0&&(i+=this.copyBuffer(e,i,s))}return s=i-t,this._currentPosition+=s/this._stream.audioChannels,s}copyBuffer(e,t,s){let i=t;for(;s>0;this._prevPacketStart++,s--)for(let t=0;t<this._stream.audioChannels;t++)e[i++]=this._prevPacketBuf[t][this._prevPacketStart];return i-t}readNextPacket(e){const t=this.decodeNextPacket();if(this._eosFound=this._eosFound||t.isEndOfStream,null==t.curPacket)return null;if(null!==t.samplePosition&&t.isEndOfStream){const s=this._currentPosition+e+t.validLen-t.startIndex,i=t.samplePosition-s;i<0&&(t.validLen+=i,t.validLen<0&&(t.validLen=0))}return this._prevPacketEnd>0?(Ni.overlapBuffers(this._prevPacketBuf,t.curPacket,this._prevPacketStart,this._prevPacketStop,t.startIndex,this._stream.audioChannels),this._prevPacketStart=t.startIndex):null==this._prevPacketBuf&&(this._prevPacketStart=t.validLen),this._nextPacketBuf=this._prevPacketBuf,this._prevPacketEnd=t.validLen,this._prevPacketStop=t.totalLen,this._prevPacketBuf=t.curPacket,new wi(t.samplePosition)}static overlapBuffers(e,t,s,i,a,r){for(;s<i;s++,a++)for(let i=0;i<r;i++)t[i][a]+=e[i][s]}decodeNextPacket(){const e=new xi;let t=null;if(this._packetIndex>=this._packets.length)e.isEndOfStream=!0;else{t=this._packets[this._packetIndex++];const s=new ei(ht.fromBuffer(t.packetData));if(e.isEndOfStream=t.isEndOfStream,!s.readBit()){const i=this._setup.modes[s.readBits(this._modeFieldBits)];if(null==this._nextPacketBuf){this._nextPacketBuf=new Array(this._stream.audioChannels);for(let e=0;e<this._stream.audioChannels;e++)this._nextPacketBuf[e]=new Float32Array(this._stream.blocksize1)}const a=i.decode(s,this._nextPacketBuf);return e.startIndex=a.packetStartIndex,e.validLen=a.packetValidLength,e.totalLen=a.packetTotalLength,e.samplePosition=t.granulePosition,e.curPacket=this._nextPacketBuf,e}}return e}}class xi{constructor(){this.curPacket=null,this.startIndex=0,this.validLen=0,this.totalLen=0,this.isEndOfStream=!1,this.samplePosition=null}}!function(e){e[e.IdentificationHeader=1]="IdentificationHeader",e[e.Comment=3]="Comment",e[e.SetupHeader=5]="SetupHeader"}(Wt||(Wt={}));class vi{constructor(e){this._packetIndex=-1,this._packets=e}read(){let e;for(;;){if(e=this.nextPacket(),null==e)return null;if(e.isBeginningOfStream){const t=this.readStream(e);if(null!=t)return t}}}nextPacket(){return this._packetIndex++,this._packetIndex<this._packets.length?this._packets[this._packetIndex]:null}readStream(e){const t=new Qs;if(!this.readIdentificationHeader(t,e))return null;if(!this.readComments(this.nextPacket()))return null;const s=new ti;if(!this.readSetupHeader(t,s,this.nextPacket()))return null;const i=[];let a;for(;a=this.nextPacket(),null!=a&&(i.push(a),!a.isEndOfStream););const r=new Ni(t,s,i);return t.samples=r.decode(),t}comonHeaderDecode(e,t){const s=new Uint8Array(7);if(t.read(s,0,s.length),s[0]!==e)return!1;for(let e=0;e<vi.VorbisHeaderMarker.length;e++)if(s[1+e]!==vi.VorbisHeaderMarker[e])return!1;return!0}comonHeaderDecodeBit(e,t){const s=t.readBytes(7);if(s[0]!==e)return!1;for(let e=0;e<vi.VorbisHeaderMarker.length;e++)if(s[1+e]!==vi.VorbisHeaderMarker[e])return!1;return!0}readIdentificationHeader(e,t){const s=ht.fromBuffer(t.packetData);if(!this.comonHeaderDecode(Wt.IdentificationHeader,s))return!1;if(0!==ot.readUInt32LE(s))return!1;if(e.audioChannels=s.readByte(),e.audioSampleRate=ot.readUInt32LE(s),e.audioChannels<=0||e.audioSampleRate<=0)return!1;e.bitrateMaximum=ot.readInt32LE(s),e.bitrateNominal=ot.readInt32LE(s),e.bitrateMinimum=ot.readInt32LE(s);const i=s.readByte();if(e.blocksize0=1<<(15&i),e.blocksize1=1<<(i>>4),e.blocksize0>e.blocksize1||!vi.isAllowedBlockSize(e.blocksize0)||!vi.isAllowedBlockSize(e.blocksize0))return!1;return 0!==s.readByte()}static isAllowedBlockSize(e){switch(e){case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:return!0;default:return!1}}readComments(e){if(null==e)return!1;const t=ht.fromBuffer(e.packetData);if(!this.comonHeaderDecode(Wt.Comment,t))return!1;const s=ot.readUInt32LE(t);t.skip(s);const i=ot.readUInt32LE(t);for(let e=0;e<i;e++){const e=ot.readUInt32LE(t);t.skip(e)}return 0!==t.readByte()}readSetupHeader(e,t,s){if(null==s)return!1;const i=new ei(ht.fromBuffer(s.packetData)),a=new Ti,r=new oi;if(!this.comonHeaderDecodeBit(Wt.SetupHeader,i))return!1;let n=i.readByte()+1;for(let e=0;e<n;e++)t.codebooks.push(new ri(i,r));n=i.readBits(6)+1;for(let e=0;e<n;e++)t.timeDomainTransforms.push(new hi(i));n=i.readBits(6)+1;for(let s=0;s<n;s++)t.floors.push(new pi(i,e.blocksize0,e.blocksize1,t.codebooks));n=i.readBits(6)+1;for(let s=0;s<n;s++)t.residues.push(new yi(i,e.audioChannels,t.codebooks));n=i.readBits(6)+1;for(let s=0;s<n;s++)t.mappings.push(new bi(i,e.audioChannels,t.floors,t.residues,a));n=i.readBits(6)+1;for(let s=0;s<n;s++)t.modes.push(new Bi(i,e.audioChannels,e.blocksize0,e.blocksize1,t.mappings));return!!i.readBit()}}vi.VorbisHeaderMarker=new Uint8Array(["v".charCodeAt(0),"o".charCodeAt(0),"r".charCodeAt(0),"b".charCodeAt(0),"i".charCodeAt(0),"s".charCodeAt(0)]);class Pi{constructor(e){this.streams=[];const t=new Ks(e).read(),s=new vi(t);for(;;){const e=s.read();if(null==e)break;this.streams.push(e)}}}class Fi{constructor(){this.phdrs=[],this.pbags=[],this.pmods=[],this.pgens=[],this.insts=[],this.ibags=[],this.imods=[],this.igens=[],this.sHdrs=[],this.sampleData=new Uint8Array(0),this._sampleCache=new Map}decodeSamples(e,t,s){const i=`${e}_${t}_${s}`;if(!this._sampleCache.has(i)){let a;const r=this.sampleData.slice(e,t);if(s){a=new Pi(ht.fromBuffer(r)).streams[0].samples}else{const e=new DataView(r.buffer,r.byteOffset,r.length);a=new Float32Array(r.length/2);for(let t=0;t<a.length;t++)a[t]=e.getInt16(2*t,!0)/32767}return this._sampleCache.set(i,a),a}return this._sampleCache.get(i)}load(e){const t=new qs,s=new qs;if(!qs.load(null,t,e)||"sfbk"!==t.id)throw new Ze("Soundfont is not a valid Soundfont2 file");for(;qs.load(t,s,e);){const t=new qs;if("pdta"===s.id)for(;qs.load(s,t,e);)switch(t.id){case"phdr":for(let s=0,i=t.size/Ai.SizeInFile|0;s<i;s++)this.phdrs.push(new Ai(e));break;case"pbag":for(let s=0,i=t.size/Mi.SizeInFile|0;s<i;s++)this.pbags.push(new Mi(e));break;case"pmod":for(let s=0,i=t.size/Ri.SizeInFile|0;s<i;s++)this.pmods.push(new Ri(e));break;case"pgen":for(let s=0,i=t.size/Ii.SizeInFile|0;s<i;s++)this.pgens.push(new Ii(e));break;case"inst":for(let s=0,i=t.size/Li.SizeInFile|0;s<i;s++)this.insts.push(new Li(e));break;case"ibag":for(let s=0,i=t.size/Ci.SizeInFile|0;s<i;s++)this.ibags.push(new Ci(e));break;case"imod":for(let s=0,i=t.size/Di.SizeInFile|0;s<i;s++)this.imods.push(new Di(e));break;case"igen":for(let s=0,i=t.size/Ei.SizeInFile|0;s<i;s++)this.igens.push(new Ei(e));break;case"shdr":for(let s=0,i=t.size/Oi.SizeInFile|0;s<i;s++)this.sHdrs.push(new Oi(e));break;default:e.position+=t.size}else if("sdta"===s.id)for(;qs.load(s,t,e);)if("smpl"===t.id)this.sampleData=new Uint8Array(t.size),e.read(this.sampleData,0,t.size);else e.position+=t.size;else e.position+=s.size}}}class Ci{constructor(e){this.instGenNdx=ot.readUInt16LE(e),this.instModNdx=ot.readUInt16LE(e)}}Ci.SizeInFile=4;class Di{constructor(e){this.modSrcOper=ot.readUInt16LE(e),this.modDestOper=ot.readUInt16LE(e),this.modAmount=ot.readInt16LE(e),this.modAmtSrcOper=ot.readUInt16LE(e),this.modTransOper=ot.readUInt16LE(e)}}Di.SizeInFile=10;class Ei{constructor(e){this.genOper=ot.readUInt16LE(e),this.genAmount=new Hi(e)}}Ei.SizeInFile=4;class Li{constructor(e){this.instName=ot.read8BitStringLength(e,20),this.instBagNdx=ot.readUInt16LE(e)}}Li.SizeInFile=22;class Mi{constructor(e){this.genNdx=ot.readUInt16LE(e),this.modNdx=ot.readUInt16LE(e)}}Mi.SizeInFile=4;class Ii{constructor(e){this.genOper=ot.readUInt16LE(e),this.genAmount=new Hi(e)}}Ii.SizeInFile=4,Ii.GenInstrument=41,Ii.GenKeyRange=43,Ii.GenVelRange=44,Ii.GenSampleId=53;class Ai{constructor(e){this.presetName=ot.read8BitStringLength(e,20),this.preset=ot.readUInt16LE(e),this.bank=ot.readUInt16LE(e),this.presetBagNdx=ot.readUInt16LE(e),this.library=ot.readUInt32LE(e),this.genre=ot.readUInt32LE(e),this.morphology=ot.readUInt32LE(e)}}Ai.SizeInFile=38;class Ri{constructor(e){this.modSrcOper=ot.readUInt16LE(e),this.modDestOper=ot.readUInt16LE(e),this.modAmount=ot.readUInt16LE(e),this.modAmtSrcOper=ot.readUInt16LE(e),this.modTransOper=ot.readUInt16LE(e)}}Ri.SizeInFile=10;class Oi{constructor(e){this.sampleName=ot.read8BitStringLength(e,20),this.start=ot.readUInt32LE(e),this.end=ot.readUInt32LE(e),this.startLoop=ot.readUInt32LE(e),this.endLoop=ot.readUInt32LE(e),this.sampleRate=ot.readUInt32LE(e),this.originalPitch=e.readByte(),this.pitchCorrection=ot.readSInt8(e),this.sampleLink=ot.readUInt16LE(e),this.sampleType=ot.readUInt16LE(e)}}Oi.SizeInFile=46;class Hi{get shortAmount(){return nt.uint16ToInt16(this.wordAmount)}get lowByteAmount(){return 255&this.wordAmount}get highByteAmount(){return(65280&this.wordAmount)>>8&255}constructor(e){this.wordAmount=ot.readUInt16LE(e)}}class Wi{constructor(){this.presetIndex=0,this.bank=0,this.pitchWheel=0,this.perNotePitchWheel=new Map,this.midiPan=0,this.midiVolume=0,this.midiExpression=0,this.midiRpn=0,this.midiData=0,this.panOffset=0,this.gainDb=0,this.pitchRange=0,this.tuning=0,this.mixVolume=0,this.mute=!1,this.solo=!1}}class Vi{constructor(){this.activeChannel=0,this.channelList=[]}setupVoice(e,t){const s=this.channelList[this.activeChannel],i=t.region.pan+s.panOffset;t.playingChannel=this.activeChannel,t.mixVolume=s.mixVolume,t.noteGainDb+=s.gainDb,t.updatePitchRatio(s,e.outSampleRate),i<=-.5?(t.panFactorLeft=1,t.panFactorRight=0):i>=.5?(t.panFactorLeft=0,t.panFactorRight=1):(t.panFactorLeft=Math.sqrt(.5-i),t.panFactorRight=Math.sqrt(.5+i))}}!function(e){e[e.None=0]="None",e[e.Continuous=1]="Continuous",e[e.Sustain=2]="Sustain"}(Vt||(Vt={})),function(e){e[e.StereoInterleaved=0]="StereoInterleaved",e[e.StereoUnweaved=1]="StereoUnweaved",e[e.Mono=2]="Mono"}(Gt||(Gt={}));class Gi{constructor(){this.name="",this.presetNumber=0,this.bank=0,this.regions=null}}class zi{static timecents2Secs(e){return Math.pow(2,e/1200)}static decibelsToGain(e){return e>-100?Math.pow(10,.05*e):0}static gainToDecibels(e){return e<=1e-5?-100:20*Math.log10(e)}static cents2Hertz(e){return 8.176*Math.pow(2,e/1200)}}class Ui{constructor(e){this.delay=0,this.attack=0,this.hold=0,this.decay=0,this.sustain=0,this.release=0,this.keynumToHold=0,this.keynumToDecay=0,e&&(this.delay=e.delay,this.attack=e.attack,this.hold=e.hold,this.decay=e.decay,this.sustain=e.sustain,this.release=e.release,this.keynumToHold=e.keynumToHold,this.keynumToDecay=e.keynumToDecay)}clear(){this.delay=0,this.attack=0,this.hold=0,this.decay=0,this.sustain=0,this.release=0,this.keynumToHold=0,this.keynumToDecay=0}envToSecs(e){this.delay=this.delay<-11950?0:zi.timecents2Secs(this.delay),this.attack=this.attack<-11950?0:zi.timecents2Secs(this.attack),this.release=this.release<-11950?0:zi.timecents2Secs(this.release),0===this.keynumToHold&&(this.hold=this.hold<-11950?0:zi.timecents2Secs(this.hold)),0===this.keynumToDecay&&(this.decay=this.decay<-11950?0:zi.timecents2Secs(this.decay)),this.sustain<0?this.sustain=0:this.sustain=e?zi.decibelsToGain(-this.sustain/10):1-this.sustain/1e3}}!function(e){e[e.StartAddrsOffset=0]="StartAddrsOffset",e[e.EndAddrsOffset=1]="EndAddrsOffset",e[e.StartloopAddrsOffset=2]="StartloopAddrsOffset",e[e.EndloopAddrsOffset=3]="EndloopAddrsOffset",e[e.StartAddrsCoarseOffset=4]="StartAddrsCoarseOffset",e[e.ModLfoToPitch=5]="ModLfoToPitch",e[e.VibLfoToPitch=6]="VibLfoToPitch",e[e.ModEnvToPitch=7]="ModEnvToPitch",e[e.InitialFilterFc=8]="InitialFilterFc",e[e.InitialFilterQ=9]="InitialFilterQ",e[e.ModLfoToFilterFc=10]="ModLfoToFilterFc",e[e.ModEnvToFilterFc=11]="ModEnvToFilterFc",e[e.EndAddrsCoarseOffset=12]="EndAddrsCoarseOffset",e[e.ModLfoToVolume=13]="ModLfoToVolume",e[e.Unused1=14]="Unused1",e[e.ChorusEffectsSend=15]="ChorusEffectsSend",e[e.ReverbEffectsSend=16]="ReverbEffectsSend",e[e.Pan=17]="Pan",e[e.Unused2=18]="Unused2",e[e.Unused3=19]="Unused3",e[e.Unused4=20]="Unused4",e[e.DelayModLFO=21]="DelayModLFO",e[e.FreqModLFO=22]="FreqModLFO",e[e.DelayVibLFO=23]="DelayVibLFO",e[e.FreqVibLFO=24]="FreqVibLFO",e[e.DelayModEnv=25]="DelayModEnv",e[e.AttackModEnv=26]="AttackModEnv",e[e.HoldModEnv=27]="HoldModEnv",e[e.DecayModEnv=28]="DecayModEnv",e[e.SustainModEnv=29]="SustainModEnv",e[e.ReleaseModEnv=30]="ReleaseModEnv",e[e.KeynumToModEnvHold=31]="KeynumToModEnvHold",e[e.KeynumToModEnvDecay=32]="KeynumToModEnvDecay",e[e.DelayVolEnv=33]="DelayVolEnv",e[e.AttackVolEnv=34]="AttackVolEnv",e[e.HoldVolEnv=35]="HoldVolEnv",e[e.DecayVolEnv=36]="DecayVolEnv",e[e.SustainVolEnv=37]="SustainVolEnv",e[e.ReleaseVolEnv=38]="ReleaseVolEnv",e[e.KeynumToVolEnvHold=39]="KeynumToVolEnvHold",e[e.KeynumToVolEnvDecay=40]="KeynumToVolEnvDecay",e[e.Instrument=41]="Instrument",e[e.Reserved1=42]="Reserved1",e[e.KeyRange=43]="KeyRange",e[e.VelRange=44]="VelRange",e[e.StartloopAddrsCoarseOffset=45]="StartloopAddrsCoarseOffset",e[e.Keynum=46]="Keynum",e[e.Velocity=47]="Velocity",e[e.InitialAttenuation=48]="InitialAttenuation",e[e.Reserved2=49]="Reserved2",e[e.EndloopAddrsCoarseOffset=50]="EndloopAddrsCoarseOffset",e[e.CoarseTune=51]="CoarseTune",e[e.FineTune=52]="FineTune",e[e.SampleID=53]="SampleID",e[e.SampleModes=54]="SampleModes",e[e.Reserved3=55]="Reserved3",e[e.ScaleTuning=56]="ScaleTuning",e[e.ExclusiveClass=57]="ExclusiveClass",e[e.OverridingRootKey=58]="OverridingRootKey",e[e.Unused5=59]="Unused5",e[e.EndOper=60]="EndOper"}(zt||(zt={}));class Xi{constructor(e){this.loopMode=Vt.None,this.samples=Xi.NoSamples,this.sampleRate=0,this.loKey=0,this.hiKey=0,this.loVel=0,this.hiVel=0,this.group=0,this.offset=0,this.end=0,this.loopStart=0,this.loopEnd=0,this.transpose=0,this.tune=0,this.pitchKeyCenter=0,this.pitchKeyTrack=0,this.attenuation=0,this.pan=0,this.ampEnv=new Ui,this.modEnv=new Ui,this.initialFilterQ=0,this.initialFilterFc=0,this.modEnvToPitch=0,this.modEnvToFilterFc=0,this.modLfoToFilterFc=0,this.modLfoToVolume=0,this.delayModLFO=0,this.freqModLFO=0,this.modLfoToPitch=0,this.delayVibLFO=0,this.freqVibLFO=0,this.vibLfoToPitch=0,e&&(this.loopMode=e.loopMode,this.samples=e.samples,this.sampleRate=e.sampleRate,this.loKey=e.loKey,this.hiKey=e.hiKey,this.loVel=e.loVel,this.hiVel=e.hiVel,this.group=e.group,this.offset=e.offset,this.end=e.end,this.loopStart=e.loopStart,this.loopEnd=e.loopEnd,this.transpose=e.transpose,this.tune=e.tune,this.pitchKeyCenter=e.pitchKeyCenter,this.pitchKeyTrack=e.pitchKeyTrack,this.attenuation=e.attenuation,this.pan=e.pan,this.ampEnv=new Ui(e.ampEnv),this.modEnv=new Ui(e.modEnv),this.initialFilterQ=e.initialFilterQ,this.initialFilterFc=e.initialFilterFc,this.modEnvToPitch=e.modEnvToPitch,this.modEnvToFilterFc=e.modEnvToFilterFc,this.modLfoToFilterFc=e.modLfoToFilterFc,this.modLfoToVolume=e.modLfoToVolume,this.delayModLFO=e.delayModLFO,this.freqModLFO=e.freqModLFO,this.modLfoToPitch=e.modLfoToPitch,this.delayVibLFO=e.delayVibLFO,this.freqVibLFO=e.freqVibLFO,this.vibLfoToPitch=e.vibLfoToPitch)}clear(e){this.loopMode=Vt.None,this.samples=Xi.NoSamples,this.sampleRate=0,this.loKey=0,this.hiKey=0,this.loVel=0,this.hiVel=0,this.group=0,this.offset=0,this.end=0,this.loopStart=0,this.loopEnd=0,this.transpose=0,this.tune=0,this.pitchKeyCenter=0,this.pitchKeyTrack=0,this.attenuation=0,this.pan=0,this.ampEnv.clear(),this.modEnv.clear(),this.initialFilterQ=0,this.initialFilterFc=0,this.modEnvToPitch=0,this.modEnvToFilterFc=0,this.modLfoToFilterFc=0,this.modLfoToVolume=0,this.delayModLFO=0,this.freqModLFO=0,this.modLfoToPitch=0,this.delayVibLFO=0,this.freqVibLFO=0,this.vibLfoToPitch=0,this.hiKey=127,this.hiVel=127,this.pitchKeyCenter=60,e||(this.pitchKeyTrack=100,this.pitchKeyCenter=-1,this.ampEnv.delay=-12e3,this.ampEnv.attack=-12e3,this.ampEnv.hold=-12e3,this.ampEnv.decay=-12e3,this.ampEnv.release=-12e3,this.modEnv.delay=-12e3,this.modEnv.attack=-12e3,this.modEnv.hold=-12e3,this.modEnv.decay=-12e3,this.modEnv.release=-12e3,this.initialFilterFc=13500,this.delayModLFO=-12e3,this.delayVibLFO=-12e3)}operator(e,t){switch(e){case zt.StartAddrsOffset:this.offset+=nt.int16ToUint32(t.shortAmount);break;case zt.EndAddrsOffset:this.end+=nt.int16ToUint32(t.shortAmount);break;case zt.StartloopAddrsOffset:this.loopStart+=nt.int16ToUint32(t.shortAmount);break;case zt.EndloopAddrsOffset:this.loopEnd+=nt.int16ToUint32(t.shortAmount);break;case zt.StartAddrsCoarseOffset:this.offset+=32768*nt.int16ToUint32(t.shortAmount);break;case zt.ModLfoToPitch:this.modLfoToPitch=t.shortAmount;break;case zt.VibLfoToPitch:this.vibLfoToPitch=t.shortAmount;break;case zt.ModEnvToPitch:this.modEnvToPitch=t.shortAmount;break;case zt.InitialFilterFc:this.initialFilterFc=t.shortAmount;break;case zt.InitialFilterQ:this.initialFilterQ=t.shortAmount;break;case zt.ModLfoToFilterFc:this.modLfoToFilterFc=t.shortAmount;break;case zt.ModEnvToFilterFc:this.modEnvToFilterFc=t.shortAmount;break;case zt.EndAddrsCoarseOffset:this.end+=32768*nt.int16ToUint32(t.shortAmount);break;case zt.ModLfoToVolume:this.modLfoToVolume=t.shortAmount;break;case zt.Pan:this.pan=t.shortAmount/1e3;break;case zt.DelayModLFO:this.delayModLFO=t.shortAmount;break;case zt.FreqModLFO:this.freqModLFO=t.shortAmount;break;case zt.DelayVibLFO:this.delayVibLFO=t.shortAmount;break;case zt.FreqVibLFO:this.freqVibLFO=t.shortAmount;break;case zt.DelayModEnv:this.modEnv.delay=t.shortAmount;break;case zt.AttackModEnv:this.modEnv.attack=t.shortAmount;break;case zt.HoldModEnv:this.modEnv.hold=t.shortAmount;break;case zt.DecayModEnv:this.modEnv.decay=t.shortAmount;break;case zt.SustainModEnv:this.modEnv.sustain=t.shortAmount;break;case zt.ReleaseModEnv:this.modEnv.release=t.shortAmount;break;case zt.KeynumToModEnvHold:this.modEnv.keynumToHold=t.shortAmount;break;case zt.KeynumToModEnvDecay:this.modEnv.keynumToDecay=t.shortAmount;break;case zt.DelayVolEnv:this.ampEnv.delay=t.shortAmount;break;case zt.AttackVolEnv:this.ampEnv.attack=t.shortAmount;break;case zt.HoldVolEnv:this.ampEnv.hold=t.shortAmount;break;case zt.DecayVolEnv:this.ampEnv.decay=t.shortAmount;break;case zt.SustainVolEnv:this.ampEnv.sustain=t.shortAmount;break;case zt.ReleaseVolEnv:this.ampEnv.release=t.shortAmount;break;case zt.KeynumToVolEnvHold:this.ampEnv.keynumToHold=t.shortAmount;break;case zt.KeynumToVolEnvDecay:this.ampEnv.keynumToDecay=t.shortAmount;break;case zt.KeyRange:this.loKey=t.lowByteAmount,this.hiKey=t.highByteAmount;break;case zt.VelRange:this.loVel=t.lowByteAmount,this.hiVel=t.highByteAmount;break;case zt.StartloopAddrsCoarseOffset:this.loopStart+=32768*nt.int16ToUint32(t.shortAmount);break;case zt.InitialAttenuation:this.attenuation+=.1*t.shortAmount;break;case zt.EndloopAddrsCoarseOffset:this.loopEnd+=32768*nt.int16ToUint32(t.shortAmount);break;case zt.CoarseTune:this.transpose+=t.shortAmount;break;case zt.FineTune:this.tune+=t.shortAmount;break;case zt.SampleModes:this.loopMode=3&~t.wordAmount?1==(3&t.wordAmount)?Vt.Continuous:Vt.None:Vt.Sustain;break;case zt.ScaleTuning:this.pitchKeyTrack=t.shortAmount;break;case zt.ExclusiveClass:this.group=t.wordAmount;break;case zt.OverridingRootKey:this.pitchKeyCenter=t.shortAmount}}}Xi.NoSamples=new Float32Array(0),function(e){e[e.None=0]="None",e[e.Delay=1]="Delay",e[e.Attack=2]="Attack",e[e.Hold=3]="Hold",e[e.Decay=4]="Decay",e[e.Sustain=5]="Sustain",e[e.Release=6]="Release",e[e.Done=7]="Done"}(Ut||(Ut={}));class Ji{constructor(){this.level=0,this.slope=0,this.samplesUntilNextSegment=0,this.segment=Ut.None,this.midiVelocity=0,this.parameters=null,this.segmentIsExponential=!1,this.isAmpEnv=!1}nextSegment(e,t){if(this.parameters)for(;;)switch(e){case Ut.None:if(this.samplesUntilNextSegment=this.parameters.delay*t|0,this.samplesUntilNextSegment>0)return this.segment=Ut.Delay,this.segmentIsExponential=!1,this.level=0,void(this.slope=0);e=Ut.Delay;break;case Ut.Delay:if(this.samplesUntilNextSegment=this.parameters.attack*t|0,this.samplesUntilNextSegment>0)return this.isAmpEnv||(this.samplesUntilNextSegment=this.parameters.attack*((145-this.midiVelocity)/144)*t|0),this.segment=Ut.Attack,this.segmentIsExponential=!1,this.level=0,void(this.slope=1/this.samplesUntilNextSegment);e=Ut.Attack;break;case Ut.Attack:if(this.samplesUntilNextSegment=this.parameters.hold*t|0,this.samplesUntilNextSegment>0)return this.segment=Ut.Hold,this.segmentIsExponential=!1,this.level=1,void(this.slope=0);e=Ut.Hold;break;case Ut.Hold:if(this.samplesUntilNextSegment=this.parameters.decay*t|0,this.samplesUntilNextSegment>0){if(this.segment=Ut.Decay,this.level=1,this.isAmpEnv){const e=-9.226/this.samplesUntilNextSegment;this.slope=Math.exp(e),this.segmentIsExponential=!0,this.parameters.sustain>0&&(this.samplesUntilNextSegment=Math.log(this.parameters.sustain)/e|0)}else this.slope=-1/this.samplesUntilNextSegment,this.samplesUntilNextSegment=this.parameters.decay*(1-this.parameters.sustain)*t|0,this.segmentIsExponential=!1;return}e=Ut.Decay;break;case Ut.Decay:return this.segment=Ut.Sustain,this.level=this.parameters.sustain,this.slope=0,this.samplesUntilNextSegment=2147483647,void(this.segmentIsExponential=!1);case Ut.Sustain:if(this.segment=Ut.Release,this.samplesUntilNextSegment=(this.parameters.release<=0?Ji.FastReleaseTime:this.parameters.release)*t|0,this.isAmpEnv){const e=-9.226/this.samplesUntilNextSegment;this.slope=Math.exp(e),this.segmentIsExponential=!0}else this.slope=-this.level/this.samplesUntilNextSegment,this.segmentIsExponential=!1;return;default:return this.segment=Ut.Done,this.segmentIsExponential=!1,this.level=0,this.slope=0,void(this.samplesUntilNextSegment=134217727)}}setup(e,t,s,i,a){this.parameters=new Ui(e),this.parameters.keynumToHold>0&&(this.parameters.hold+=this.parameters.keynumToHold*(60-t),this.parameters.hold=this.parameters.hold<-1e4?0:zi.timecents2Secs(this.parameters.hold)),this.parameters.keynumToDecay>0&&(this.parameters.decay+=this.parameters.keynumToDecay*(60-t),this.parameters.decay=this.parameters.decay<-1e4?0:zi.timecents2Secs(this.parameters.decay)),this.midiVelocity=0|s,this.isAmpEnv=i,this.nextSegment(Ut.None,a)}process(e,t){this.slope>0&&(this.segmentIsExponential?this.level*=Math.pow(this.slope,e):this.level+=this.slope*e),this.samplesUntilNextSegment-=e,this.samplesUntilNextSegment<=0&&this.nextSegment(this.segment,t)}}Ji.FastReleaseTime=.01;class Yi{constructor(){this.samplesUntil=0,this.level=0,this.delta=0}setup(e,t,s){this.samplesUntil=e*s|0,this.delta=4*zi.cents2Hertz(t)/s,this.level=0}process(e){this.samplesUntil>e?this.samplesUntil-=e:(this.level+=this.delta*e,this.level>1?(this.delta=-this.delta,this.level=2-this.level):this.level<-1&&(this.delta=-this.delta,this.level=-2-this.level))}}class $i{constructor(e){this.qInv=0,this.a0=0,this.a1=0,this.b1=0,this.b2=0,this.z1=0,this.z2=0,this.active=!1,e&&(this.qInv=e.qInv,this.a0=e.a0,this.a1=e.a1,this.b1=e.b1,this.b2=e.b2,this.z1=e.z1,this.z2=e.z2,this.active=e.active)}setup(e){const t=Math.tan(Math.PI*e),s=t*t,i=1/(1+t*this.qInv+s);this.a0=s*i,this.a1=2*this.a0,this.b1=2*(s-1)*i,this.b2=(1-t*this.qInv+s)*i}process(e){const t=e*this.a0+this.z1;return this.z1=e*this.a1+this.z2-this.b1*t,this.z2=e*this.a0-this.b2*t,t}}class qi{constructor(){this.playingPreset=0,this.playingKey=0,this.playingChannel=0,this.region=null,this.pitchInputTimecents=0,this.pitchOutputFactor=0,this.sourceSamplePosition=0,this.noteGainDb=0,this.panFactorLeft=0,this.panFactorRight=0,this.playIndex=0,this.loopStart=0,this.loopEnd=0,this.ampEnv=new Ji,this.modEnv=new Ji,this.lowPass=new $i,this.modLfo=new Yi,this.vibLfo=new Yi,this.mixVolume=0,this.mute=!1}updatePitchRatio(e,t){let s=e.pitchWheel;e.perNotePitchWheel.has(this.playingKey)&&(s+=e.perNotePitchWheel.get(this.playingKey)-8192);const i=8192===s?e.tuning:s/16383*e.pitchRange*2-e.pitchRange+e.tuning;this.calcPitchRatio(i,t)}calcPitchRatio(e,t){if(!this.region)return;const s=this.playingKey+this.region.transpose+this.region.tune/100;let i=this.region.pitchKeyCenter+(s-this.region.pitchKeyCenter)*(this.region.pitchKeyTrack/100);0!==e&&(i+=e),this.pitchInputTimecents=100*i,this.pitchOutputFactor=this.region.sampleRate/(zi.timecents2Secs(100*this.region.pitchKeyCenter)*t)}end(e){this.region&&(this.ampEnv.nextSegment(Ut.Sustain,e),this.modEnv.nextSegment(Ut.Sustain,e),this.region.loopMode===Vt.Sustain&&(this.loopEnd=this.loopStart))}endQuick(e){this.ampEnv.parameters.release=0,this.ampEnv.nextSegment(Ut.Sustain,e),this.modEnv.parameters.release=0,this.modEnv.nextSegment(Ut.Sustain,e)}render(e,t,s,i,a){if(!this.region)return;const r=this.region,n=r.samples;let o=0,h=e.outputMode===Gt.StereoUnweaved?i:-1;const l=0!==r.modEnvToPitch||0!==r.modEnvToFilterFc,c=this.modLfo.delta>0&&(0!==r.modLfoToPitch||0!==r.modLfoToFilterFc||0!==r.modLfoToVolume),d=this.vibLfo.delta>0&&0!==r.vibLfoToPitch,u=this.loopStart<this.loopEnd,p=this.loopStart,g=this.loopEnd,m=r.end,f=g+1;let y=this.sourceSamplePosition;const b=new $i(this.lowPass),S=0!==r.modLfoToFilterFc||0!==r.modEnvToFilterFc;let _=0,w=0,B=0,k=0;const T=0!==r.modLfoToPitch||0!==r.modEnvToPitch||0!==r.vibLfoToPitch;let N=0,x=0,v=0,P=0;const F=0!==r.modLfoToVolume;let C=0,D=0;for(S?(_=e.outSampleRate,w=r.initialFilterFc,B=r.modLfoToFilterFc,k=r.modEnvToFilterFc):(_=0,w=0,B=0,k=0),T?(N=0,x=r.modLfoToPitch,v=r.vibLfoToPitch,P=r.modEnvToPitch):(N=zi.timecents2Secs(this.pitchInputTimecents)*this.pitchOutputFactor,x=0,v=0,P=0),F?D=.1*r.modLfoToVolume:(C=zi.decibelsToGain(this.noteGainDb),D=0);i>0;){let r,E,L=0,M=i>qi.RenderEffectSampleBlock?qi.RenderEffectSampleBlock:i;if(i-=M,S){const e=w+this.modLfo.level*B+this.modEnv.level*k;b.active=e<=13500,b.active&&b.setup(zi.cents2Hertz(e)/_)}switch(T&&(N=zi.timecents2Secs(this.pitchInputTimecents+(this.modLfo.level*x+this.vibLfo.level*v+this.modEnv.level*P))*this.pitchOutputFactor),F&&(C=zi.decibelsToGain(this.noteGainDb+this.modLfo.level*D)),r=C*this.ampEnv.level,a?r=0:r*=this.mixVolume,this.ampEnv.process(M,e.outSampleRate),l&&this.modEnv.process(M,e.outSampleRate),c&&this.modLfo.process(M),d&&this.vibLfo.process(M),e.outputMode){case Gt.StereoInterleaved:for(E=r*this.panFactorLeft,L=r*this.panFactorRight;M-- >0&&y<m;){const e=0|y,i=e>=g&&u?p:e+1,a=y-e;let r=n[e]*(1-a)+n[i]*a;b.active&&(r=b.process(r)),t[s+o]+=r*E,o++,t[s+o]+=r*L,o++,y+=N,y>=f&&u&&(y-=g-p+1)}break;case Gt.StereoUnweaved:for(E=r*this.panFactorLeft,L=r*this.panFactorRight;M-- >0&&y<m;){const e=0|y,i=e>=g&&u?p:e+1,a=y-e;let r=n[e]*(1-a)+n[i]*a;b.active&&(r=b.process(r)),t[s+o]+=r*E,o++,t[s+h]+=r*L,h++,y+=N,y>=f&&u&&(y-=g-p+1)}break;case Gt.Mono:for(;M-- >0&&y<m;){const e=0|y,i=e>=g&&u?p:e+1,a=y-e;let h=n[e]*(1-a)+n[i]*a;b.active&&(h=b.process(h)),t[s+o]=h*r,o++,y+=N,y>=f&&u&&(y-=g-p+1)}}if(y>=m||this.ampEnv.segment===Ut.Done)return void this.kill()}this.sourceSamplePosition=y,(b.active||S)&&(this.lowPass=b)}kill(){this.playingPreset=-1}}qi.RenderEffectSampleBlock=K.MicroBufferSize;class ji{constructor(){this._items=[],this._position=0,this.isEmpty=!0}clear(){this._items=[],this._position=0,this.isEmpty=!0}enqueue(e){this.isEmpty=!1,this._items.push(e)}peek(){return this._items[this._position]}dequeue(){const e=this._items[this._position];return this._position++,this._position>=this._items.length/2&&(this._items=this._items.slice(this._position),this._position=0),this.isEmpty=0===this._items.length,e}toArray(){const e=this._items.slice(this._position);return e.reverse(),e}}!function(e){e[e.BankSelectCoarse=0]="BankSelectCoarse",e[e.ModulationCoarse=1]="ModulationCoarse",e[e.DataEntryCoarse=6]="DataEntryCoarse",e[e.VolumeCoarse=7]="VolumeCoarse",e[e.PanCoarse=10]="PanCoarse",e[e.ExpressionControllerCoarse=11]="ExpressionControllerCoarse",e[e.BankSelectFine=32]="BankSelectFine",e[e.ModulationFine=33]="ModulationFine",e[e.DataEntryFine=38]="DataEntryFine",e[e.VolumeFine=39]="VolumeFine",e[e.PanFine=42]="PanFine",e[e.ExpressionControllerFine=43]="ExpressionControllerFine",e[e.HoldPedal=64]="HoldPedal",e[e.LegatoPedal=68]="LegatoPedal",e[e.NonRegisteredParameterFine=98]="NonRegisteredParameterFine",e[e.NonRegisteredParameterCourse=99]="NonRegisteredParameterCourse",e[e.RegisteredParameterFine=100]="RegisteredParameterFine",e[e.RegisteredParameterCourse=101]="RegisteredParameterCourse",e[e.AllSoundOff=120]="AllSoundOff",e[e.ResetControllers=121]="ResetControllers",e[e.AllNotesOff=123]="AllNotesOff"}(Xt||(Xt={}));class Ki{constructor(e){this._midiEventQueue=new ji,this._mutedChannels=new Map,this._soloChannels=new Map,this._isAnySolo=!1,this._transpositionPitches=new Map,this._liveTranspositionPitches=new Map,this.currentTempo=0,this.timeSignatureNumerator=0,this.timeSignatureDenominator=0,this.presets=null,this._voices=[],this._channels=null,this._voicePlayIndex=0,this.outputMode=Gt.StereoInterleaved,this.outSampleRate=0,this.globalGainDb=0,this.outSampleRate=e}synthesize(e,t,s){return this.fillWorkingBuffer(e,t,s)}synthesizeSilent(e){this.fillWorkingBuffer(null,0,e)}channelGetMixVolume(e){return this._channels&&e<this._channels.channelList.length?this._channels.channelList[e].mixVolume:1}channelSetMixVolume(e,t){const s=this.channelInit(e);for(const s of this._voices)s.playingChannel===e&&-1!==s.playingPreset&&(s.mixVolume=t);s.mixVolume=t}channelSetMute(e,t){t?this._mutedChannels.set(e,!0):this._mutedChannels.delete(e)}channelSetSolo(e,t){t?this._soloChannels.set(e,!0):this._soloChannels.delete(e),this._isAnySolo=this._soloChannels.size>0}resetChannelStates(){this._mutedChannels=new Map,this._soloChannels=new Map,this._liveTranspositionPitches=new Map,this.applyTranspositionPitches(new Map),this._isAnySolo=!1}setChannelTranspositionPitch(e,t){let s=0;this._liveTranspositionPitches.has(e)&&(s=this._liveTranspositionPitches.get(e)),0===t?this._liveTranspositionPitches.delete(e):this._liveTranspositionPitches.set(e,t);for(const i of this._voices)if(i.playingChannel===e&&9!==i.playingChannel){let e=0;e-=s,e+=t,i.playingKey+=e,this._channels&&i.updatePitchRatio(this._channels.channelList[i.playingChannel],this.outSampleRate)}}applyTranspositionPitches(e){const t=this._transpositionPitches;for(const s of this._voices)if(s.playingChannel>=0&&9!==s.playingChannel){let i=0;t.has(s.playingChannel)&&(i-=t.get(s.playingChannel)),e.has(s.playingChannel)&&(i+=e.get(s.playingChannel)),s.playingKey+=i,this._channels&&s.updatePitchRatio(this._channels.channelList[s.playingChannel],this.outSampleRate)}this._transpositionPitches=e}dispatchEvent(e){this._midiEventQueue.enqueue(e)}fillWorkingBuffer(e,t,s){const i=this._isAnySolo,a=[];for(;!this._midiEventQueue.isEmpty;){const e=this._midiEventQueue.dequeue();e.isMetronome&&this.metronomeVolume>0?(this.channelNoteOff(K.MetronomeChannel,K.MetronomeKey),this.channelNoteOn(K.MetronomeChannel,K.MetronomeKey,95/127)):e.event&&this.processMidiMessage(e.event),a.push(e)}for(const a of this._voices)if(-1!==a.playingPreset){const r=a.playingChannel,n=this._mutedChannels.has(r)||i&&r!==K.MetronomeChannel&&!this._soloChannels.has(r);e?a.render(this,e,t,s,n):a.kill()}return a}processMidiMessage(e){q.debug("Midi",`Processing Midi message ${Rt[e.type]}/${e.tick}`);switch(e.type){case Rt.TimeSignature:const t=e;this.timeSignatureNumerator=t.numerator,this.timeSignatureDenominator=Math.pow(2,t.denominatorIndex);break;case Rt.NoteOn:const s=e;this.channelNoteOn(s.channel,s.noteKey,s.noteVelocity/127);break;case Rt.NoteOff:const i=e;this.channelNoteOff(i.channel,i.noteKey);break;case Rt.ControlChange:const a=e;this.channelMidiControl(a.channel,a.controller,a.value);break;case Rt.ProgramChange:const r=e;this.channelSetPresetNumber(r.channel,r.program,9===r.channel);break;case Rt.TempoChange:const n=e;this.currentTempo=6e7/n.microSecondsPerQuarterNote;break;case Rt.PitchBend:const o=e;this.channelSetPitchWheel(o.channel,o.value);break;case Rt.PerNotePitchBend:const h=e;let l=h.value;l=l*K.MaxPitchWheel/K.MaxPitchWheel20,this.channelSetPerNotePitchWheel(h.channel,h.noteKey,l)}}get metronomeVolume(){return this.channelGetMixVolume(K.MetronomeChannel)}set metronomeVolume(e){this.setupMetronomeChannel(e)}setupMetronomeChannel(e){this.channelSetMixVolume(K.MetronomeChannel,e),e>0&&(this.channelSetVolume(K.MetronomeChannel,1),this.channelSetPresetNumber(K.MetronomeChannel,0,!0))}get masterVolume(){return zi.decibelsToGain(this.globalGainDb)}set masterVolume(e){const t=zi.gainToDecibels(e),s=t-this.globalGainDb;if(0!==s){for(const e of this._voices)-1!==e.playingPreset&&(e.noteGainDb+=s);this.globalGainDb=t}}resetSoft(){for(const e of this._voices)-1!==e.playingPreset&&(e.ampEnv.segment<Ut.Release||0!==e.ampEnv.parameters.release)&&e.endQuick(this.outSampleRate);if(this._channels)for(const e of this._channels.channelList)e.presetIndex=0,e.bank=0,e.pitchWheel=8192,e.midiPan=8192,e.perNotePitchWheel.clear(),e.midiVolume=16383,e.midiExpression=16383,e.midiRpn=65535,e.midiData=0,e.panOffset=0,e.gainDb=0,e.pitchRange=2,e.tuning=0}get presetCount(){return this.presets?.length??0}reset(){for(const e of this._voices)-1!==e.playingPreset&&(e.ampEnv.segment<Ut.Release||0!==e.ampEnv.parameters.release)&&e.endQuick(this.outSampleRate);this._channels=null}setOutput(e,t,s){this.outputMode=e,this.outSampleRate=t>=1?t:44100,this.globalGainDb=s}noteOn(e,t,s){if(!this.presets)return;const i=127*s|0;if(e<0||e>=this.presets.length)return;if(s<=0)return void this.noteOff(e,t);const a=this._voicePlayIndex++;for(const r of this.presets[e].regions){if(t<r.loKey||t>r.hiKey||i<r.loVel||i>r.hiVel)continue;let n=null;if(0!==r.group)for(const t of this._voices)t.playingPreset===e&&t.region.group===r.group?t.endQuick(this.outSampleRate):-1!==t.playingPreset||n||(n=t);else for(const e of this._voices)-1===e.playingPreset&&(n=e);if(!n){for(let e=0;e<4;e++){const e=new qi;e.playingPreset=-1,this._voices.push(e)}n=this._voices[this._voices.length-4]}n.region=r,n.playingPreset=e,n.playingKey=t,n.playIndex=a,n.noteGainDb=this.globalGainDb-r.attenuation-zi.gainToDecibels(1/s),this._channels?this._channels.setupVoice(this,n):(n.calcPitchRatio(0,this.outSampleRate),n.panFactorLeft=Math.sqrt(.5-r.pan),n.panFactorRight=Math.sqrt(.5+r.pan)),n.sourceSamplePosition=r.offset;const o=r.loopMode!==Vt.None&&r.loopStart<r.loopEnd;n.loopStart=o?r.loopStart:0,n.loopEnd=o?r.loopEnd:0,n.ampEnv.setup(r.ampEnv,t,i,!0,this.outSampleRate),n.modEnv.setup(r.modEnv,t,i,!1,this.outSampleRate);const h=r.initialFilterQ/10;n.lowPass.qInv=1/Math.pow(10,h/20),n.lowPass.z1=0,n.lowPass.z2=0,n.lowPass.active=r.initialFilterFc<=13500,n.lowPass.active&&n.lowPass.setup(zi.cents2Hertz(r.initialFilterFc)/this.outSampleRate),n.modLfo.setup(r.delayModLFO,r.freqModLFO,this.outSampleRate),n.vibLfo.setup(r.delayVibLFO,r.freqVibLFO,this.outSampleRate)}}bankNoteOn(e,t,s,i){const a=this.getPresetIndex(e,t);return-1!==a&&(this.noteOn(a,s,i),!0)}noteOff(e,t){let s=null,i=null;const a=[];for(const r of this._voices)r.playingPreset!==e||r.playingKey!==t||r.ampEnv.segment>=Ut.Release||(!s||r.playIndex<s.playIndex?(s=r,i=r,a.push(r)):r.playIndex===s.playIndex&&(i=r,a.push(r)));if(s)for(const r of a)r!==s&&r!==i&&(r.playIndex!==s.playIndex||r.playingPreset!==e||r.playingKey!==t||r.ampEnv.segment>=Ut.Release)||r.end(this.outSampleRate)}bankNoteOff(e,t,s){const i=this.getPresetIndex(e,t);return-1!==i&&(this.noteOff(i,s),!0)}noteOffAll(e){for(const t of this._voices)-1!==t.playingPreset&&(e?t.endQuick(this.outSampleRate):t.ampEnv.segment<Ut.Release&&t.end(this.outSampleRate))}get activeVoiceCount(){let e=0;for(const t of this._voices)-1!==t.playingPreset&&e++;return e}channelInit(e){if(this._channels&&e<this._channels.channelList.length)return this._channels.channelList[e];this._channels||(this._channels=new Vi);for(let t=this._channels.channelList.length;t<=e;t++){const e=new Wi;e.presetIndex=0,e.bank=0,e.pitchWheel=8192,e.midiPan=8192,e.midiVolume=16383,e.midiExpression=16383,e.midiRpn=65535,e.midiData=0,e.panOffset=0,e.gainDb=0,e.pitchRange=2,e.tuning=0,e.mixVolume=1,this._channels.channelList.push(e)}return this._channels.channelList[e]}getPresetIndex(e,t){if(!this.presets)return-1;for(let s=this.presets.length-1;s>=0;s--){const i=this.presets[s];if(i.presetNumber===t&&i.bank===e)return s}return-1}getPresetName(e){return this.presets?e<0||e>=this.presets.length?null:this.presets[e].name:null}bankGetPresetName(e,t){return this.getPresetName(this.getPresetIndex(e,t))}channelNoteOn(e,t,s){!this._channels||e>this._channels.channelList.length||(this._transpositionPitches.has(e)&&(t+=this._transpositionPitches.get(e)),this._liveTranspositionPitches.has(e)&&(t+=this._liveTranspositionPitches.get(e)),this._channels.activeChannel=e,this.noteOn(this._channels.channelList[e].presetIndex,t,s))}channelNoteOff(e,t){this._transpositionPitches.has(e)&&(t+=this._transpositionPitches.get(e)),this._liveTranspositionPitches.has(e)&&(t+=this._liveTranspositionPitches.get(e));const s=[];let i=null,a=null;for(const r of this._voices)-1===r.playingPreset||r.playingChannel!==e||r.playingKey!==t||r.ampEnv.segment>=Ut.Release||(!i||r.playIndex<i.playIndex?(i=r,a=r,s.push(r)):r.playIndex===i.playIndex&&(a=r,s.push(r)));if(this.channelInit(e).perNotePitchWheel.delete(t),i)for(const r of s)r!==i&&r!==a&&(r.playIndex!==i.playIndex||-1===r.playingPreset||r.playingChannel!==e||r.playingKey!==t||r.ampEnv.segment>=Ut.Release)||r.end(this.outSampleRate)}channelNoteOffAll(e){this.channelInit(e).perNotePitchWheel.clear();for(const t of this._voices)-1!==t.playingPreset&&t.playingChannel===e&&t.ampEnv.segment<Ut.Release&&t.end(this.outSampleRate)}channelSoundsOffAll(e){this.channelInit(e).perNotePitchWheel.clear();for(const t of this._voices)-1!==t.playingPreset&&t.playingChannel===e&&(t.ampEnv.segment<Ut.Release||0===t.ampEnv.parameters.release)&&t.endQuick(this.outSampleRate)}channelSetPresetIndex(e,t){this.channelInit(e).presetIndex=nt.int32ToUint16(t)}channelSetPresetNumber(e,t,s=!1){const i=this.channelInit(e);let a=0;return s?(a=this.getPresetIndex(128|32767&i.bank,t),-1===a&&(a=this.getPresetIndex(128,t)),-1===a&&(a=this.getPresetIndex(128,0)),-1===a&&(a=this.getPresetIndex(2047&i.bank,t))):a=this.getPresetIndex(2047&i.bank,t),i.presetIndex=a,-1!==a}channelSetBank(e,t){this.channelInit(e).bank=nt.int32ToUint16(t)}channelSetBankPreset(e,t,s){const i=this.channelInit(e),a=this.getPresetIndex(t,s);return-1!==a&&(i.presetIndex=nt.int32ToUint16(a),i.bank=nt.int32ToUint16(t),!0)}channelSetPan(e,t){for(const s of this._voices)if(s.playingChannel===e&&-1!==s.playingPreset){const e=s.region.pan+t-.5;e<=-.5?(s.panFactorLeft=1,s.panFactorRight=0):e>=.5?(s.panFactorLeft=0,s.panFactorRight=1):(s.panFactorLeft=Math.sqrt(.5-e),s.panFactorRight=Math.sqrt(.5+e))}this.channelInit(e).panOffset=t-.5}channelSetVolume(e,t){const s=this.channelInit(e),i=zi.gainToDecibels(t),a=i-s.gainDb;if(0!==a){for(const t of this._voices)t.playingChannel===e&&-1!==t.playingPreset&&(t.noteGainDb+=a);s.gainDb=i}}channelSetPitchWheel(e,t){const s=this.channelInit(e);s.pitchWheel!==t&&(s.pitchWheel=nt.int32ToUint16(t),this.channelApplyPitch(e,s))}channelSetPerNotePitchWheel(e,t,s){this._transpositionPitches.has(e)&&(t+=this._transpositionPitches.get(e)),this._liveTranspositionPitches.has(e)&&(t+=this._liveTranspositionPitches.get(e));const i=this.channelInit(e);i.perNotePitchWheel.has(t)&&i.perNotePitchWheel.get(t)===s||(i.perNotePitchWheel.set(t,s),this.channelApplyPitch(e,i,t))}channelApplyPitch(e,t,s=-1){for(const i of this._voices)i.playingChannel!==e||-1===i.playingPreset||-1!==s&&i.playingKey!==s||i.updatePitchRatio(t,this.outSampleRate)}channelSetPitchRange(e,t){const s=this.channelInit(e);s.pitchRange!==t&&(s.pitchRange=t,8192!==s.pitchWheel&&this.channelApplyPitch(e,s))}channelSetTuning(e,t){const s=this.channelInit(e);s.tuning!==t&&(s.tuning=t,this.channelApplyPitch(e,s))}channelMidiControl(e,t,s){const i=this.channelInit(e);switch(t){case Xt.DataEntryFine:return i.midiData=nt.int32ToUint16(16256&i.midiData|s),void(0===i.midiRpn?this.channelSetPitchRange(e,(i.midiData>>7)+.01*(127&i.midiData)):1===i.midiRpn?this.channelSetTuning(e,(0|i.tuning)+(i.midiData-8192)/8192):2===i.midiRpn&&this.channelSetTuning(e,s-64+(i.tuning-(0|i.tuning))));case Xt.VolumeCoarse:return i.midiVolume=nt.int32ToUint16(127&i.midiVolume|s<<7),void this.channelSetVolume(e,Math.pow(i.midiVolume/16383*(i.midiExpression/16383),3));case Xt.VolumeFine:return i.midiVolume=nt.int32ToUint16(16256&i.midiVolume|s),void this.channelSetVolume(e,Math.pow(i.midiVolume/16383*(i.midiExpression/16383),3));case Xt.ExpressionControllerCoarse:return i.midiExpression=nt.int32ToUint16(127&i.midiExpression|s<<7),void this.channelSetVolume(e,Math.pow(i.midiVolume/16383*(i.midiExpression/16383),3));case Xt.ExpressionControllerFine:return i.midiExpression=nt.int32ToUint16(16256&i.midiExpression|s),void this.channelSetVolume(e,Math.pow(i.midiVolume/16383*(i.midiExpression/16383),3));case Xt.PanCoarse:return i.midiPan=nt.int32ToUint16(127&i.midiPan|s<<7),void this.channelSetPan(e,i.midiPan/16383);case Xt.PanFine:return i.midiPan=nt.int32ToUint16(16256&i.midiPan|s),void this.channelSetPan(e,i.midiPan/16383);case Xt.DataEntryCoarse:return i.midiData=nt.int32ToUint16(127&i.midiData|s<<7),void(0===i.midiRpn?this.channelSetPitchRange(e,(i.midiData>>7)+.01*(127&i.midiData)):1===i.midiRpn?this.channelSetTuning(e,(0|i.tuning)+(i.midiData-8192)/8192):2===i.midiRpn&&t===Xt.DataEntryCoarse&&this.channelSetTuning(e,s-64+(i.tuning-(0|i.tuning))));case Xt.BankSelectCoarse:return void(i.bank=nt.int32ToUint16(32768|s));case Xt.BankSelectFine:return void(i.bank=nt.int32ToUint16((32768&i.bank?(127&i.bank)<<7:0)|s));case Xt.RegisteredParameterCourse:return void(i.midiRpn=nt.int32ToUint16(127&(65535===i.midiRpn?0:i.midiRpn)|s<<7));case Xt.RegisteredParameterFine:return void(i.midiRpn=nt.int32ToUint16(16256&(65535===i.midiRpn?0:i.midiRpn)|s));case Xt.NonRegisteredParameterFine:case Xt.NonRegisteredParameterCourse:return void(i.midiRpn=65535);case Xt.AllSoundOff:return void this.channelSoundsOffAll(e);case Xt.AllNotesOff:return void this.channelNoteOffAll(e);case Xt.ResetControllers:return i.midiVolume=16383,i.midiExpression=16383,i.midiPan=8192,i.bank=0,this.channelSetVolume(e,1),this.channelSetPan(e,.5),void this.channelSetPitchRange(e,2)}}channelGetPresetIndex(e){return this._channels&&e<this._channels.channelList.length?this._channels.channelList[e].presetIndex:0}channelGetPresetBank(e){return this._channels&&e<this._channels.channelList.length?32767&this._channels.channelList[e].bank:0}channelGetPan(e){return this._channels&&e<this._channels.channelList.length?this._channels.channelList[e].panOffset-.5:.5}channelGetVolume(e){return this._channels&&e<this._channels.channelList.length?zi.decibelsToGain(this._channels.channelList[e].gainDb):1}channelGetPitchWheel(e){return this._channels&&e<this._channels.channelList.length?this._channels.channelList[e].pitchWheel:8192}channelGetPitchRange(e){return this._channels&&e<this._channels.channelList.length?this._channels.channelList[e].pitchRange:2}channelGetTuning(e){return this._channels&&e<this._channels.channelList.length?this._channels.channelList[e].tuning:0}resetPresets(){this.presets=[]}loadPresets(e,t,s,i){const a=[];for(let i=0;i<e.phdrs.length-1;i++){const r=e.phdrs[i];let n=0;const o=new Gi;a.push(o),o.name=r.presetName,o.bank=r.bank,o.presetNumber=r.preset;let h=0;for(let t=r.presetBagNdx;t<e.phdrs[i+1].presetBagNdx;t++){let s=0,i=127,a=0,r=127;for(let n=e.pbags[t].genNdx;n<e.pbags[t+1].genNdx;n++){const t=e.pgens[n];if(t.genOper===Ii.GenKeyRange){s=t.genAmount.lowByteAmount,i=t.genAmount.highByteAmount;continue}if(t.genOper===Ii.GenVelRange){a=t.genAmount.lowByteAmount,r=t.genAmount.highByteAmount;continue}if(t.genOper!==Ii.GenInstrument)continue;if(t.genAmount.wordAmount>=e.insts.length)continue;for(let n=e.insts[t.genAmount.wordAmount].instBagNdx;n<e.insts[t.genAmount.wordAmount+1].instBagNdx;n++){let t=0,o=127,l=0,c=127;for(let d=e.ibags[n].instGenNdx;d<e.ibags[n+1].instGenNdx;d++){const n=e.igens[d];n.genOper!==Ii.GenKeyRange?n.genOper!==Ii.GenVelRange?53===n.genOper&&o>=s&&t<=i&&c>=a&&l<=r&&h++:(l=n.genAmount.lowByteAmount,c=n.genAmount.highByteAmount):(t=n.genAmount.lowByteAmount,o=n.genAmount.highByteAmount)}}}}o.regions=new Array(h);let l=new Xi;l.clear(!0);for(let a=r.presetBagNdx;a<e.phdrs[i+1].presetBagNdx;a++){const i=e.pbags[a],h=new Xi(l);let c=!1;for(let l=i.genNdx;l<e.pbags[a+1].genNdx;l++){const i=e.pgens[l];if(i.genOper===Ii.GenInstrument){const a=i.genAmount.wordAmount;if(a>=e.insts.length)continue;let l=new Xi;l.clear(!1);const d=e.insts[a];for(let i=d.instBagNdx;i<e.insts[a+1].instBagNdx;i++){const a=e.ibags[i],c=new Xi(l);let u=!1;for(let l=a.instGenNdx;l<e.ibags[i+1].instGenNdx;l++){const i=e.igens[l];if(i.genOper===Ii.GenSampleId){if(c.hiKey<h.loKey||c.loKey>h.hiKey)continue;if(c.hiVel<h.loVel||c.loVel>h.hiVel)continue;h.loKey>c.loKey&&(c.loKey=h.loKey),h.hiKey<c.hiKey&&(c.hiKey=h.hiKey),h.loVel>c.loVel&&(c.loVel=h.loVel),h.hiVel<c.hiVel&&(c.hiVel=h.hiVel),c.offset+=h.offset,c.end+=h.end,c.loopStart+=h.loopStart,c.loopEnd+=h.loopEnd,c.transpose+=h.transpose,c.tune+=h.tune,c.pitchKeyTrack+=h.pitchKeyTrack,c.attenuation+=h.attenuation,c.pan+=h.pan,c.ampEnv.delay+=h.ampEnv.delay,c.ampEnv.attack+=h.ampEnv.attack,c.ampEnv.hold+=h.ampEnv.hold,c.ampEnv.decay+=h.ampEnv.decay,c.ampEnv.sustain+=h.ampEnv.sustain,c.ampEnv.release+=h.ampEnv.release,c.modEnv.delay+=h.modEnv.delay,c.modEnv.attack+=h.modEnv.attack,c.modEnv.hold+=h.modEnv.hold,c.modEnv.decay+=h.modEnv.decay,c.modEnv.sustain+=h.modEnv.sustain,c.modEnv.release+=h.modEnv.release,c.initialFilterQ+=h.initialFilterQ,c.initialFilterFc+=h.initialFilterFc,c.modEnvToPitch+=h.modEnvToPitch,c.modEnvToFilterFc+=h.modEnvToFilterFc,c.delayModLFO+=h.delayModLFO,c.freqModLFO+=h.freqModLFO,c.modLfoToPitch+=h.modLfoToPitch,c.modLfoToFilterFc+=h.modLfoToFilterFc,c.modLfoToVolume+=h.modLfoToVolume,c.delayVibLFO+=h.delayVibLFO,c.freqVibLFO+=h.freqVibLFO,c.vibLfoToPitch+=h.vibLfoToPitch,c.ampEnv.envToSecs(!0),c.modEnv.envToSecs(!1),c.delayModLFO=c.delayModLFO<-11950?0:zi.timecents2Secs(c.delayModLFO),c.delayVibLFO=c.delayVibLFO<-11950?0:zi.timecents2Secs(c.delayVibLFO),c.pan<-.5?c.pan=-.5:c.pan>.5&&(c.pan=.5),(c.initialFilterQ<1500||c.initialFilterQ>13500)&&(c.initialFilterQ=0);const a=e.sHdrs[i.genAmount.wordAmount];c.offset+=a.start,c.end+=a.end,c.loopStart+=a.startLoop,c.loopEnd+=a.endLoop,a.endLoop>0&&(c.loopEnd-=1),-1===c.pitchKeyCenter&&(c.pitchKeyCenter=a.originalPitch),c.tune+=a.pitchCorrection,c.sampleRate=a.sampleRate;const l=r.bank===K.PercussionBank;if(l&&Ki.setContainsRange(s,c.loKey,c.hiKey)||!l&&t.has(r.preset))if(1&a.sampleType){q.debug("AlphaSynth",`Loading of used sample ${a.sampleName} for preset ${r.presetName} (bank ${o.bank} program ${o.presetNumber})`);!!(16&a.sampleType)?c.samples=e.decodeSamples(a.start,a.end,!0):(c.samples=e.decodeSamples(2*c.offset,2*c.end,!1),c.loopStart>0&&(c.loopStart-=c.offset),c.loopEnd>0&&(c.loopEnd-=c.offset)),c.offset=0,c.end=c.samples.length-1}else q.warning("AlphaSynth",`Skipping load of unsupported sample ${a.sampleName} for preset ${r.presetName}, sample type ${a.sampleType} is not supported (bank ${o.bank} program ${o.presetNumber})`),c.samples=new Float32Array(0);else q.debug("AlphaSynth",`Skipping load of unused sample ${a.sampleName} for preset ${r.presetName} (bank ${o.bank} program ${o.presetNumber})`),c.samples=new Float32Array(0);o.regions[n]=new Xi(c),n++,u=!0}else c.operator(i.genOper,i.genAmount)}a!==e.ibags[d.instBagNdx]||u||(l=new Xi(c))}c=!0}else h.operator(i.genOper,i.genAmount)}i!==e.pbags[r.presetBagNdx]||c||(l=h)}}if(i&&this.presets)for(const e of a)this.presets.push(e);else this.presets=a}static setContainsRange(e,t,s){for(let i=t;i<=s;i++)if(e.has(i))return!0;return!1}hasSamplesForProgram(e){const t=this.presets;if(!t)return!1;for(const s of t)if(s.presetNumber===e)for(const e of s.regions)if(e.samples.length>0)return!0;return!1}hasSamplesForPercussion(e){const t=this.presets;if(!t)return!1;for(const s of t)if(s.bank===K.PercussionBank)for(const t of s.regions)if(t.loKey>=e&&t.hiKey<=e&&t.samples.length>0)return!0;return!1}}class Qi{constructor(){this._listeners=[]}on(e){this._listeners.push(e)}off(e){this._listeners=this._listeners.filter((t=>t!==e))}trigger(){for(const e of this._listeners)e()}}class Zi{constructor(){this._listeners=[]}on(e){this._listeners.push(e)}off(e){this._listeners=this._listeners.filter((t=>t!==e))}trigger(e){for(const t of this._listeners)t(e)}}class ea{constructor(e){this.events=e}}class ta{constructor(e){this.playbackRange=e}}class sa{get output(){return this._output}get isReadyForPlayback(){return this.isReady&&this._isSoundFontLoaded&&this._isMidiLoaded}get logLevel(){return q.logLevel}set logLevel(e){q.logLevel=e}get masterVolume(){return this._synthesizer.masterVolume}set masterVolume(e){e=Math.max(e,K.MinVolume),this._synthesizer.masterVolume=e}get metronomeVolume(){return this._metronomeVolume}set metronomeVolume(e){e=Math.max(e,K.MinVolume),this._metronomeVolume=e,this._synthesizer.metronomeVolume=e}get countInVolume(){return this._countInVolume}set countInVolume(e){e=Math.max(e,K.MinVolume),this._countInVolume=e}get midiEventsPlayedFilter(){return Array.from(this._midiEventsPlayedFilter)}set midiEventsPlayedFilter(e){this._midiEventsPlayedFilter=new Set(e)}get playbackSpeed(){return this._sequencer.playbackSpeed}set playbackSpeed(e){e=ie.clamp(e,K.MinPlaybackSpeed,K.MaxPlaybackSpeed);const t=this._sequencer.playbackSpeed;this._sequencer.playbackSpeed=e,this.timePosition=this.timePosition*(t/e)}get tickPosition(){return this._tickPosition}set tickPosition(e){this.timePosition=this._sequencer.mainTickPositionToTimePosition(e)}get timePosition(){return this._timePosition}set timePosition(e){q.debug("AlphaSynth",`Seeking to position ${e}ms (main)`),this._sequencer.mainSeek(e),this.updateTimePosition(e,!0),this._sequencer.isPlayingMain&&(this._notPlayedSamples=0,this.output.resetSamples())}get playbackRange(){return this._sequencer.mainPlaybackRange}set playbackRange(e){this._sequencer.mainPlaybackRange=e,e&&(this.tickPosition=e.startTick),this.playbackRangeChanged.trigger(new ta(e))}get isLooping(){return this._sequencer.isLooping}set isLooping(e){this._sequencer.isLooping=e}destroy(){q.debug("AlphaSynth","Destroying player"),this.stop(),this.output.destroy()}constructor(e,t){this._isSoundFontLoaded=!1,this._isMidiLoaded=!1,this._tickPosition=0,this._timePosition=0,this._metronomeVolume=0,this._countInVolume=0,this._playedEventsQueue=new ji,this._midiEventsPlayedFilter=new Set,this._notPlayedSamples=0,this._synthStopping=!1,this.isReady=!1,this.state=Ot.Paused,this._loadedSoundFonts=[],this.ready=new Qi,this.readyForPlayback=new Qi,this.finished=new Qi,this.soundFontLoaded=new Qi,this.soundFontLoadFailed=new Zi,this.midiLoaded=new Zi,this.midiLoadFailed=new Zi,this.stateChanged=new Zi,this.positionChanged=new Zi,this.midiEventsPlayed=new Zi,this.playbackRangeChanged=new Zi,q.debug("AlphaSynth","Initializing player"),this.state=Ot.Paused,q.debug("AlphaSynth","Creating output"),this._output=e,q.debug("AlphaSynth","Creating synthesizer"),this._synthesizer=new Ki(this.output.sampleRate),this._sequencer=new Js(this._synthesizer),q.debug("AlphaSynth","Opening output"),this.output.ready.on((()=>{this.isReady=!0,this.ready.trigger(),this.checkReadyForPlayback()})),this.output.sampleRequest.on((()=>{if(this.state===Ot.Playing&&(!this._sequencer.isFinished||this._synthesizer.activeVoiceCount>0)){let e=new Float32Array(K.MicroBufferSize*K.MicroBufferCount*K.AudioChannels),t=0;for(let s=0;s<K.MicroBufferCount;s++){this._sequencer.fillMidiEventQueue();const s=this._synthesizer.synthesize(e,t,K.MicroBufferSize);t+=K.MicroBufferSize*K.AudioChannels;for(const e of s)this._midiEventsPlayedFilter.has(e.event.type)&&this._playedEventsQueue.enqueue(e);if(this._sequencer.isFinished)break}t<e.length&&(e=e.subarray(0,t)),this._notPlayedSamples+=e.length,this.output.addSamples(e)}else{const e=new Float32Array(0);this.output.addSamples(e)}})),this.output.samplesPlayed.on(this.onSamplesPlayed.bind(this)),this.output.open(t)}play(){return!(this.state!==Ot.Paused||!this._isMidiLoaded)&&(this.output.activate(),this.playInternal(),this._countInVolume>0&&(q.debug("AlphaSynth","Starting countin"),this._sequencer.startCountIn(),this._synthesizer.setupMetronomeChannel(this._countInVolume),this.updateTimePosition(0,!0)),this.output.play(),!0)}playInternal(){this._sequencer.isPlayingOneTimeMidi&&(q.debug("AlphaSynth","Cancelling one time midi"),this.stopOneTimeMidi()),q.debug("AlphaSynth","Starting playback"),this._synthesizer.setupMetronomeChannel(this.metronomeVolume),this._synthStopping=!1,this.state=Ot.Playing,this.stateChanged.trigger(new Ys(this.state,!1))}pause(){this.state!==Ot.Paused&&this._isMidiLoaded&&(q.debug("AlphaSynth","Pausing playback"),this.state=Ot.Paused,this.stateChanged.trigger(new Ys(this.state,!1)),this.output.pause(),this._synthesizer.noteOffAll(!1))}playPause(){this.state===Ot.Paused&&this._isMidiLoaded?this.play():this.pause()}stop(){this._isMidiLoaded&&(q.debug("AlphaSynth","Stopping playback"),this.state=Ot.Paused,this.output.pause(),this._notPlayedSamples=0,this._sequencer.stop(),this._synthesizer.noteOffAll(!0),this.tickPosition=this._sequencer.mainPlaybackRange?this._sequencer.mainPlaybackRange.startTick:0,this.stateChanged.trigger(new Ys(this.state,!0)))}playOneTimeMidiFile(e){this._sequencer.isPlayingOneTimeMidi?this.stopOneTimeMidi():this.pause(),this._sequencer.loadOneTimeMidi(e),this._synthesizer.noteOffAll(!0),this.updateTimePosition(0,!0),this._notPlayedSamples=0,this.output.resetSamples(),this.output.play()}resetSoundFonts(){this.stop(),this._synthesizer.resetPresets(),this._loadedSoundFonts=[],this._isSoundFontLoaded=!1,this.soundFontLoaded.trigger()}loadSoundFont(e,t){this.pause();const s=ht.fromBuffer(e);try{q.debug("AlphaSynth","Loading soundfont from bytes");const e=new Fi;e.load(s),t||(this._loadedSoundFonts=[]),this._loadedSoundFonts.push(e),this._isSoundFontLoaded=!0,this.soundFontLoaded.trigger(),q.debug("AlphaSynth","soundFont successfully loaded"),this.checkReadyForPlayback()}catch(e){q.error("AlphaSynth",`Could not load soundfont from bytes ${e}`),this.soundFontLoadFailed.trigger(e)}}checkReadyForPlayback(){if(this.isReadyForPlayback){this._synthesizer.setupMetronomeChannel(this.metronomeVolume);const e=this._sequencer.instrumentPrograms,t=this._sequencer.percussionKeys;let s=!1;for(const i of this._loadedSoundFonts)this._synthesizer.loadPresets(i,e,t,s),s=!0;this.readyForPlayback.trigger()}}loadMidiFile(e){this.stop();try{q.debug("AlphaSynth","Loading midi from model"),this._sequencer.loadMidi(e),this._isMidiLoaded=!0,this.midiLoaded.trigger(new $s(0,this._sequencer.currentEndTime,0,this._sequencer.currentEndTick,!1)),q.debug("AlphaSynth","Midi successfully loaded"),this.checkReadyForPlayback(),this.tickPosition=0}catch(e){q.error("AlphaSynth",`Could not load midi from model ${e}`),this.midiLoadFailed.trigger(e)}}applyTranspositionPitches(e){this._synthesizer.applyTranspositionPitches(e)}setChannelTranspositionPitch(e,t){this._synthesizer.setChannelTranspositionPitch(e,t)}setChannelMute(e,t){this._synthesizer.channelSetMute(e,t)}resetChannelStates(){this._synthesizer.resetChannelStates()}setChannelSolo(e,t){this._synthesizer.channelSetSolo(e,t)}setChannelVolume(e,t){t=Math.max(t,K.MinVolume),this._synthesizer.channelSetMixVolume(e,t)}onSamplesPlayed(e){if(0===e)return;const t=e/this._synthesizer.outSampleRate*1e3;this._notPlayedSamples-=e*K.AudioChannels,this.updateTimePosition(this._timePosition+t,!1),this.checkForFinish()}checkForFinish(){let e=0,t=0;this.playbackRange&&this._sequencer.isPlayingMain?(e=this.playbackRange.startTick,t=this.playbackRange.endTick):t=this._sequencer.currentEndTick,this._tickPosition>=t&&this._notPlayedSamples<=0&&(this._notPlayedSamples=0,this._sequencer.isPlayingCountIn?(q.debug("AlphaSynth","Finished playback (count-in)"),this._sequencer.resetCountIn(),this.timePosition=this._sequencer.currentTime,this.playInternal(),this.output.resetSamples()):this._sequencer.isPlayingOneTimeMidi?(q.debug("AlphaSynth","Finished playback (one time)"),this.output.resetSamples(),this.state=Ot.Paused,this.stopOneTimeMidi()):this.isLooping?(q.debug("AlphaSynth","Finished playback (main looping)"),this.finished.trigger(),this.tickPosition=e,this._synthStopping=!1):this._synthesizer.activeVoiceCount>0?this._synthStopping||(this._synthesizer.noteOffAll(!0),this._synthStopping=!0):(this._synthStopping=!1,q.debug("AlphaSynth","Finished playback (main)"),this.finished.trigger(),this.stop()))}stopOneTimeMidi(){this.output.pause(),this._synthesizer.noteOffAll(!0),this._sequencer.resetOneTimeMidi(),this.timePosition=this._sequencer.currentTime}updateTimePosition(e,t){let s=e;this._timePosition=s;let i=this._sequencer.currentTimePositionToTickPosition(s);this._tickPosition=i;const a=this._sequencer.currentEndTime,r=this._sequencer.currentEndTick;s>a&&(s=a,i=r);const n=this._sequencer.isPlayingMain?"main":this._sequencer.isPlayingCountIn?"count-in":"one-time";if(q.debug("AlphaSynth",`Position changed: (time: ${s}/${a}, tick: ${i}/${r}, Active Voices: ${this._synthesizer.activeVoiceCount} (${n})`),this._sequencer.isPlayingMain&&this.positionChanged.trigger(new $s(s,a,i,r,t)),t)this._playedEventsQueue.clear();else{const e=new ji;for(;!this._playedEventsQueue.isEmpty&&this._playedEventsQueue.peek().time<s;){const t=this._playedEventsQueue.dequeue();e.enqueue(t.event)}e.isEmpty||this.midiEventsPlayed.trigger(new ea(e.toArray()))}}hasSamplesForProgram(e){return this._synthesizer.hasSamplesForProgram(e)}hasSamplesForPercussion(e){return this._synthesizer.hasSamplesForPercussion(e)}}class ia{static parseEnum(e,t){switch(typeof e){case"string":const s=Number.parseInt(e);return Number.isNaN(s)?t[Object.keys(t).find((t=>t.toLowerCase()===e.toLowerCase()))]:s;case"number":return e;case"undefined":case"object":return}throw new $e(Se.Format,`Could not parse enum value '${e}'`)}static forEach(e,t){if(e instanceof Map)e.forEach(t);else if("object"==typeof e)for(const s in e)t(e[s],s)}static getValue(e,t){return e instanceof Map?e.get(t):"object"==typeof e?e[t]:null}}class aa{constructor(e,t,s){this.text=e,this.startPos=t,this.endPos=s}}class ra{constructor(e){this.style="normal",this.variant="normal",this.weight="normal",this.stretch="normal",this.lineHeight="normal",this.size="1rem",this.families=[],this.parseOnlyFamilies=!1,this._currentTokenIndex=-1,this._input="",this._currentToken=null,this._input=e,this._tokens=this.splitToTokens(e)}splitToTokens(e){const t=[];let s=0;for(;s<e.length;){let i=s;for(;i<e.length&&" "!==e.charAt(i);)i++;i>s&&t.push(new aa(e.substring(s,i),s,i)),s=i+1}return t}parse(){if(this.reset(),1===this._tokens.length)switch(this._currentToken?.text){case"caption":case"icon":case"menu":case"message-box":case"small-caption":case"status-bar":case"inherit":return}this.parseOnlyFamilies||(this.fontStyleVariantWeight(),this.fontSizeLineHeight()),this.fontFamily()}static parseFamilies(e){const t=new ra(e);return t.parseOnlyFamilies=!0,t.parse(),t.families}fontFamily(){if(!this._currentToken){if(this.parseOnlyFamilies)return;throw new Error("Missing font list")}const e=this._input.substr(this._currentToken.startPos).trim();let t=0;for(;t<e.length;){const s=e.charAt(t);if(" "===s||","===s)t++;else if('"'===s||"'"===s){const i=this.findEndOfQuote(e,t+1,s);this.families.push(e.substring(t+1,i).split(`\\${s}`).join(s)),t=i+1}else{const s=this.findEndOfQuote(e,t+1,",");this.families.push(e.substring(t,s).trim()),t=s+1}}}findEndOfQuote(e,t,s){let i=!1;for(;t<e.length;){const a=e.charAt(t);if(!i&&a===s)return t;i=!i&&"\\"===a,t+=1}return e.length}fontSizeLineHeight(){if(!this._currentToken)throw new Error("Missing font size");const e=this._currentToken.text.split("/");if(e.length>=3)throw new Error(`Invalid font size '${this._currentToken}' specified`);if(this.nextToken(),e.length>=2)if("/"===e[1]){if(!this._currentToken)throw new Error("Missing line-height after font size");this.lineHeight=this._currentToken.text,this.nextToken()}else this.size=e[0],this.lineHeight=e[1];else{if(!(e.length>=1))throw new Error("Missing font size");if(this.size=e[0],this._currentToken&&0===this._currentToken.text.indexOf("/"))if("/"===this._currentToken.text){if(this.nextToken(),!this._currentToken)throw new Error("Missing line-height after font size");this.lineHeight=this._currentToken.text,this.nextToken()}else this.lineHeight=this._currentToken.text.substr(1),this.nextToken()}}nextToken(){this._currentTokenIndex++,this._currentTokenIndex<this._tokens.length?this._currentToken=this._tokens[this._currentTokenIndex]:this._currentToken=null}fontStyleVariantWeight(){let e=!1,t=!1,s=!1,i=3;const a=[];for(;;){if(!this._currentToken)return;const r=this._currentToken.text;switch(r){case"normal":case"inherit":a.push(r),i--,this.nextToken();break;case"italic":case"oblique":this.style=r,e=!0,i--,this.nextToken();break;case"small-caps":this.variant=r,t=!0,i--,this.nextToken();break;case"bold":case"bolder":case"lighter":case"100":case"200":case"300":case"400":case"500":case"600":case"700":case"800":case"900":this.weight=r,s=!0,i--,this.nextToken();break;default:return}if(0===i)break}for(;a.length>0;){const i=a.pop();s?t?e||(this.style=i):this.variant=i:this.weight=i}}reset(){this._currentTokenIndex=-1,this.nextToken()}static quoteFont(e){if(-1===e.indexOf(" "))return e;return`"${e.replaceAll('"','\\"')}"`}}!function(e){e[e.Plain=0]="Plain",e[e.Italic=1]="Italic"}(Jt||(Jt={})),function(e){e[e.Regular=0]="Regular",e[e.Bold=1]="Bold"}(Yt||(Yt={}));class na{reset(){this._cssScale=0,this._css=this.toCssString()}get family(){return this._families[0]}set family(e){this.families=ra.parseFamilies(e)}get families(){return this._families}set families(e){this._families=e,this.reset()}get size(){return this._size}set size(e){this._size=e,this.reset()}get style(){return this._style}set style(e){this._style=e,this.reset()}get weight(){return this._weight}set weight(e){this._weight=e,this.reset()}get isBold(){return this.weight===Yt.Bold}get isItalic(){return this.style===Jt.Italic}constructor(e,t,s=Jt.Plain,i=Yt.Regular){this._cssScale=0,this._families=ra.parseFamilies(e),this._size=t,this._style=s,this._weight=i,this._css=this.toCssString()}withSize(e){return na.withFamilyList(this._families,e,this._style,this._weight)}static withFamilyList(e,t,s=Jt.Plain,i=Yt.Regular){const a=new na("",t,s,i);return a.families=e,a}toCssString(e=1){if(!(this._css&&Math.abs(e-this._cssScale)<.01)){let t="";this.isBold&&(t+="bold "),this.isItalic&&(t+="italic "),t+=this.size*e,t+="px ",t+=this.families.map((e=>ra.quoteFont(e))).join(", "),this._css=t,this._cssScale=e}return this._css}static fromJson(e){if(e instanceof na)return e;switch(typeof e){case"undefined":default:return null;case"object":{const t=e,s=t.get("families"),i=t.get("size"),a=ia.parseEnum(t.get("style"),Jt),r=ia.parseEnum(t.get("weight"),Yt);return na.withFamilyList(s,i,a,r)}case"string":{const t=new ra(e);t.parse();const s=t.families,i=t.size.toLowerCase();let a=0;switch(i){case"xx-small":a=7;break;case"x-small":a=10;break;case"small":case"smaller":a=13;break;case"medium":a=16;break;case"large":case"larger":a=18;break;case"x-large":a=24;break;case"xx-large":a=32;break;default:try{a=i.endsWith("em")?16*Number.parseFloat(i.substr(0,i.length-2)):i.endsWith("pt")?16*Number.parseFloat(i.substr(0,i.length-2))/12:i.endsWith("px")?Number.parseFloat(i.substr(0,i.length-2)):12}catch(e){a=12}}let r=Jt.Plain;"italic"===t.style&&(r=Jt.Italic);let n=Yt.Regular;switch(t.weight.toLowerCase()){case"normal":case"lighter":break;default:n=Yt.Bold}return na.withFamilyList(s,a,r,n)}}}static toJson(e){const t=new Map;return t.set("families",e.families),t.set("size",e.size),t.set("style",e.style),t.set("weight",e.weight),t}}class oa{constructor(){this.copyrightFont=new na(oa.sansFont,12,Jt.Plain,Yt.Bold),this.titleFont=new na(oa.serifFont,32,Jt.Plain),this.subTitleFont=new na(oa.serifFont,20,Jt.Plain),this.wordsFont=new na(oa.serifFont,15,Jt.Plain),this.effectFont=new na(oa.serifFont,12,Jt.Italic),this.timerFont=new na(oa.serifFont,12,Jt.Plain),this.directionsFont=new na(oa.serifFont,14,Jt.Plain),this.fretboardNumberFont=new na(oa.sansFont,11,Jt.Plain),this.numberedNotationFont=new na(oa.sansFont,16,Jt.Plain),this.numberedNotationGraceFont=new na(oa.sansFont,14,Jt.Plain),this.tablatureFont=new na(oa.sansFont,13,Jt.Plain),this.graceFont=new na(oa.sansFont,11,Jt.Plain),this.staffLineColor=new et(165,165,165,255),this.barSeparatorColor=new et(34,34,17,255),this.barNumberFont=new na(oa.sansFont,11,Jt.Plain),this.barNumberColor=new et(200,0,0,255),this.fingeringFont=new na(oa.serifFont,14,Jt.Plain),this.inlineFingeringFont=new na(oa.serifFont,12,Jt.Plain),this.markerFont=new na(oa.serifFont,14,Jt.Plain,Yt.Bold),this.mainGlyphColor=new et(0,0,0,255),this.secondaryGlyphColor=new et(0,0,0,100),this.scoreInfoColor=new et(0,0,0,255)}getFontForElement(e){switch(e){case be.Title:return this.titleFont;case be.SubTitle:case be.Artist:case be.Album:return this.subTitleFont;case be.Words:case be.Music:case be.WordsAndMusic:case be.Transcriber:return this.wordsFont;case be.Copyright:case be.CopyrightSecondLine:return this.copyrightFont}return this.wordsFont}}oa.sansFont="Arial, sans-serif",oa.serifFont="Georgia, serif",function(e){e[e.Automatic=0]="Automatic",e[e.UseModelLayout=1]="UseModelLayout"}($t||($t={}));class ha{constructor(){this.scale=1,this.stretchForce=1,this.layoutMode=e.Page,this.staveProfile=t.Default,this.barsPerRow=-1,this.startBar=1,this.barCount=-1,this.barCountPerPartial=10,this.justifyLastSystem=!1,this.resources=new oa,this.padding=[35,35],this.firstSystemPaddingTop=5,this.systemPaddingTop=10,this.systemPaddingBottom=20,this.lastSystemPaddingBottom=0,this.systemLabelPaddingLeft=0,this.systemLabelPaddingRight=3,this.accoladeBarPaddingRight=3,this.notationStaffPaddingTop=5,this.notationStaffPaddingBottom=5,this.effectStaffPaddingTop=0,this.effectStaffPaddingBottom=0,this.firstStaffPaddingLeft=6,this.staffPaddingLeft=2,this.systemsLayoutMode=$t.Automatic}}class la{constructor(){this.encoding="utf-8",this.mergePartGroupsInMusicXml=!1,this.beatTextAsLyrics=!1}}!function(e){e[e.Off=0]="Off",e[e.Continuous=1]="Continuous",e[e.OffScreen=2]="OffScreen"}(qt||(qt={}));class ca{constructor(){this.noteWideLength=240,this.noteWideAmplitude=1,this.noteSlightLength=360,this.noteSlightAmplitude=.5,this.beatWideLength=480,this.beatWideAmplitude=2,this.beatSlightLength=480,this.beatSlightAmplitude=2}}class da{constructor(){this.simpleSlidePitchOffset=6,this.simpleSlideDurationRatio=.25,this.shiftSlideDurationRatio=.5}}!function(e){e[e.WebAudioAudioWorklets=0]="WebAudioAudioWorklets",e[e.WebAudioScriptProcessor=1]="WebAudioScriptProcessor"}(jt||(jt={}));class ua{constructor(){this.soundFont=null,this.scrollElement="html,body",this.outputMode=jt.WebAudioAudioWorklets,this.enablePlayer=!1,this.enableCursor=!0,this.enableAnimatedBeatCursor=!0,this.enableElementHighlighting=!0,this.enableUserInteraction=!0,this.scrollOffsetX=0,this.scrollOffsetY=0,this.scrollMode=qt.Continuous,this.scrollSpeed=300,this.nativeBrowserSmoothScroll=!0,this.songBookBendDuration=75,this.songBookDipDuration=150,this.vibrato=new ca,this.slide=new da,this.playTripletFeel=!0,this.bufferTimeInMilliseconds=500}}class pa{static fromJson(e,t){t&&ia.forEach(t,((t,s)=>pa.setProperty(e,s.toLowerCase(),t)))}static toJson(e){if(!e)return null;const t=new Map;return t.set("scriptfile",e.scriptFile),t.set("fontdirectory",e.fontDirectory),t.set("file",e.file),t.set("tex",e.tex),t.set("tracks",e.tracks),t.set("enablelazyloading",e.enableLazyLoading),t.set("engine",e.engine),t.set("loglevel",e.logLevel),t.set("useworkers",e.useWorkers),t.set("includenotebounds",e.includeNoteBounds),t}static setProperty(e,t,s){switch(t){case"scriptfile":return e.scriptFile=s,!0;case"fontdirectory":return e.fontDirectory=s,!0;case"file":return e.file=s,!0;case"tex":return e.tex=s,!0;case"tracks":return e.tracks=s,!0;case"enablelazyloading":return e.enableLazyLoading=s,!0;case"engine":return e.engine=s,!0;case"loglevel":return e.logLevel=ia.parseEnum(s,L),!0;case"useworkers":return e.useWorkers=s,!0;case"includenotebounds":return e.includeNoteBounds=s,!0}return!1}}class ga{static fromJson(e,t){t&&ia.forEach(t,((t,s)=>ga.setProperty(e,s.toLowerCase(),t)))}static toJson(e){if(!e)return null;const t=new Map;return t.set("copyrightfont",na.toJson(e.copyrightFont)),t.set("titlefont",na.toJson(e.titleFont)),t.set("subtitlefont",na.toJson(e.subTitleFont)),t.set("wordsfont",na.toJson(e.wordsFont)),t.set("effectfont",na.toJson(e.effectFont)),t.set("timerfont",na.toJson(e.timerFont)),t.set("directionsfont",na.toJson(e.directionsFont)),t.set("fretboardnumberfont",na.toJson(e.fretboardNumberFont)),t.set("numberednotationfont",na.toJson(e.numberedNotationFont)),t.set("numberednotationgracefont",na.toJson(e.numberedNotationGraceFont)),t.set("tablaturefont",na.toJson(e.tablatureFont)),t.set("gracefont",na.toJson(e.graceFont)),t.set("stafflinecolor",et.toJson(e.staffLineColor)),t.set("barseparatorcolor",et.toJson(e.barSeparatorColor)),t.set("barnumberfont",na.toJson(e.barNumberFont)),t.set("barnumbercolor",et.toJson(e.barNumberColor)),t.set("fingeringfont",na.toJson(e.fingeringFont)),t.set("inlinefingeringfont",na.toJson(e.inlineFingeringFont)),t.set("markerfont",na.toJson(e.markerFont)),t.set("mainglyphcolor",et.toJson(e.mainGlyphColor)),t.set("secondaryglyphcolor",et.toJson(e.secondaryGlyphColor)),t.set("scoreinfocolor",et.toJson(e.scoreInfoColor)),t}static setProperty(e,t,s){switch(t){case"copyrightfont":return e.copyrightFont=na.fromJson(s),!0;case"titlefont":return e.titleFont=na.fromJson(s),!0;case"subtitlefont":return e.subTitleFont=na.fromJson(s),!0;case"wordsfont":return e.wordsFont=na.fromJson(s),!0;case"effectfont":return e.effectFont=na.fromJson(s),!0;case"timerfont":return e.timerFont=na.fromJson(s),!0;case"directionsfont":return e.directionsFont=na.fromJson(s),!0;case"fretboardnumberfont":return e.fretboardNumberFont=na.fromJson(s),!0;case"numberednotationfont":return e.numberedNotationFont=na.fromJson(s),!0;case"numberednotationgracefont":return e.numberedNotationGraceFont=na.fromJson(s),!0;case"tablaturefont":return e.tablatureFont=na.fromJson(s),!0;case"gracefont":return e.graceFont=na.fromJson(s),!0;case"stafflinecolor":return e.staffLineColor=et.fromJson(s),!0;case"barseparatorcolor":return e.barSeparatorColor=et.fromJson(s),!0;case"barnumberfont":return e.barNumberFont=na.fromJson(s),!0;case"barnumbercolor":return e.barNumberColor=et.fromJson(s),!0;case"fingeringfont":return e.fingeringFont=na.fromJson(s),!0;case"inlinefingeringfont":return e.inlineFingeringFont=na.fromJson(s),!0;case"markerfont":return e.markerFont=na.fromJson(s),!0;case"mainglyphcolor":return e.mainGlyphColor=et.fromJson(s),!0;case"secondaryglyphcolor":return e.secondaryGlyphColor=et.fromJson(s),!0;case"scoreinfocolor":return e.scoreInfoColor=et.fromJson(s),!0}return!1}}class ma{static fromJson(e,t){t&&ia.forEach(t,((t,s)=>ma.setProperty(e,s.toLowerCase(),t)))}static toJson(e){if(!e)return null;const t=new Map;return t.set("scale",e.scale),t.set("stretchforce",e.stretchForce),t.set("layoutmode",e.layoutMode),t.set("staveprofile",e.staveProfile),t.set("barsperrow",e.barsPerRow),t.set("startbar",e.startBar),t.set("barcount",e.barCount),t.set("barcountperpartial",e.barCountPerPartial),t.set("justifylastsystem",e.justifyLastSystem),t.set("resources",ga.toJson(e.resources)),t.set("padding",e.padding),t.set("firstsystempaddingtop",e.firstSystemPaddingTop),t.set("systempaddingtop",e.systemPaddingTop),t.set("systempaddingbottom",e.systemPaddingBottom),t.set("lastsystempaddingbottom",e.lastSystemPaddingBottom),t.set("systemlabelpaddingleft",e.systemLabelPaddingLeft),t.set("systemlabelpaddingright",e.systemLabelPaddingRight),t.set("accoladebarpaddingright",e.accoladeBarPaddingRight),t.set("notationstaffpaddingtop",e.notationStaffPaddingTop),t.set("notationstaffpaddingbottom",e.notationStaffPaddingBottom),t.set("effectstaffpaddingtop",e.effectStaffPaddingTop),t.set("effectstaffpaddingbottom",e.effectStaffPaddingBottom),t.set("firststaffpaddingleft",e.firstStaffPaddingLeft),t.set("staffpaddingleft",e.staffPaddingLeft),t.set("systemslayoutmode",e.systemsLayoutMode),t}static setProperty(s,i,a){switch(i){case"scale":return s.scale=a,!0;case"stretchforce":return s.stretchForce=a,!0;case"layoutmode":return s.layoutMode=ia.parseEnum(a,e),!0;case"staveprofile":return s.staveProfile=ia.parseEnum(a,t),!0;case"barsperrow":return s.barsPerRow=a,!0;case"startbar":return s.startBar=a,!0;case"barcount":return s.barCount=a,!0;case"barcountperpartial":return s.barCountPerPartial=a,!0;case"justifylastsystem":return s.justifyLastSystem=a,!0;case"padding":return s.padding=a,!0;case"firstsystempaddingtop":return s.firstSystemPaddingTop=a,!0;case"systempaddingtop":return s.systemPaddingTop=a,!0;case"systempaddingbottom":return s.systemPaddingBottom=a,!0;case"lastsystempaddingbottom":return s.lastSystemPaddingBottom=a,!0;case"systemlabelpaddingleft":return s.systemLabelPaddingLeft=a,!0;case"systemlabelpaddingright":return s.systemLabelPaddingRight=a,!0;case"accoladebarpaddingright":return s.accoladeBarPaddingRight=a,!0;case"notationstaffpaddingtop":return s.notationStaffPaddingTop=a,!0;case"notationstaffpaddingbottom":return s.notationStaffPaddingBottom=a,!0;case"effectstaffpaddingtop":return s.effectStaffPaddingTop=a,!0;case"effectstaffpaddingbottom":return s.effectStaffPaddingBottom=a,!0;case"firststaffpaddingleft":return s.firstStaffPaddingLeft=a,!0;case"staffpaddingleft":return s.staffPaddingLeft=a,!0;case"systemslayoutmode":return s.systemsLayoutMode=ia.parseEnum(a,$t),!0}if(["resources"].indexOf(i)>=0)return ga.fromJson(s.resources,a),!0;for(const e of["resources"])if(0===i.indexOf(e)&&ga.setProperty(s.resources,i.substring(e.length),a))return!0;return!1}}class fa{static fromJson(e,t){t&&ia.forEach(t,((t,s)=>fa.setProperty(e,s.toLowerCase(),t)))}static toJson(e){if(!e)return null;const t=new Map;t.set("notationmode",e.notationMode),t.set("fingeringmode",e.fingeringMode);{const s=new Map;t.set("elements",s);for(const[t,i]of e.elements)s.set(t.toString(),i)}return t.set("rhythmmode",e.rhythmMode),t.set("rhythmheight",e.rhythmHeight),t.set("transpositionpitches",e.transpositionPitches),t.set("displaytranspositionpitches",e.displayTranspositionPitches),t.set("smallgracetabnotes",e.smallGraceTabNotes),t.set("extendbendarrowsontiednotes",e.extendBendArrowsOnTiedNotes),t.set("extendlineeffectstobeatend",e.extendLineEffectsToBeatEnd),t.set("slurheight",e.slurHeight),t}static setProperty(e,t,s){switch(t){case"notationmode":return e.notationMode=ia.parseEnum(s,D),!0;case"fingeringmode":return e.fingeringMode=ia.parseEnum(s,C),!0;case"elements":return e.elements=new Map,ia.forEach(s,((t,s)=>{e.elements.set(ia.parseEnum(s,E),t)})),!0;case"rhythmmode":return e.rhythmMode=ia.parseEnum(s,F),!0;case"rhythmheight":return e.rhythmHeight=s,!0;case"transpositionpitches":return e.transpositionPitches=s,!0;case"displaytranspositionpitches":return e.displayTranspositionPitches=s,!0;case"smallgracetabnotes":return e.smallGraceTabNotes=s,!0;case"extendbendarrowsontiednotes":return e.extendBendArrowsOnTiedNotes=s,!0;case"extendlineeffectstobeatend":return e.extendLineEffectsToBeatEnd=s,!0;case"slurheight":return e.slurHeight=s,!0}return!1}}class ya{static fromJson(e,t){t&&ia.forEach(t,((t,s)=>ya.setProperty(e,s.toLowerCase(),t)))}static toJson(e){if(!e)return null;const t=new Map;return t.set("encoding",e.encoding),t.set("mergepartgroupsinmusicxml",e.mergePartGroupsInMusicXml),t.set("beattextaslyrics",e.beatTextAsLyrics),t}static setProperty(e,t,s){switch(t){case"encoding":return e.encoding=s,!0;case"mergepartgroupsinmusicxml":return e.mergePartGroupsInMusicXml=s,!0;case"beattextaslyrics":return e.beatTextAsLyrics=s,!0}return!1}}class ba{static fromJson(e,t){t&&ia.forEach(t,((t,s)=>ba.setProperty(e,s.toLowerCase(),t)))}static toJson(e){if(!e)return null;const t=new Map;return t.set("notewidelength",e.noteWideLength),t.set("notewideamplitude",e.noteWideAmplitude),t.set("noteslightlength",e.noteSlightLength),t.set("noteslightamplitude",e.noteSlightAmplitude),t.set("beatwidelength",e.beatWideLength),t.set("beatwideamplitude",e.beatWideAmplitude),t.set("beatslightlength",e.beatSlightLength),t.set("beatslightamplitude",e.beatSlightAmplitude),t}static setProperty(e,t,s){switch(t){case"notewidelength":return e.noteWideLength=s,!0;case"notewideamplitude":return e.noteWideAmplitude=s,!0;case"noteslightlength":return e.noteSlightLength=s,!0;case"noteslightamplitude":return e.noteSlightAmplitude=s,!0;case"beatwidelength":return e.beatWideLength=s,!0;case"beatwideamplitude":return e.beatWideAmplitude=s,!0;case"beatslightlength":return e.beatSlightLength=s,!0;case"beatslightamplitude":return e.beatSlightAmplitude=s,!0}return!1}}class Sa{static fromJson(e,t){t&&ia.forEach(t,((t,s)=>Sa.setProperty(e,s.toLowerCase(),t)))}static toJson(e){if(!e)return null;const t=new Map;return t.set("simpleslidepitchoffset",e.simpleSlidePitchOffset),t.set("simpleslidedurationratio",e.simpleSlideDurationRatio),t.set("shiftslidedurationratio",e.shiftSlideDurationRatio),t}static setProperty(e,t,s){switch(t){case"simpleslidepitchoffset":return e.simpleSlidePitchOffset=s,!0;case"simpleslidedurationratio":return e.simpleSlideDurationRatio=s,!0;case"shiftslidedurationratio":return e.shiftSlideDurationRatio=s,!0}return!1}}class _a{static fromJson(e,t){t&&ia.forEach(t,((t,s)=>_a.setProperty(e,s.toLowerCase(),t)))}static toJson(e){if(!e)return null;const t=new Map;return t.set("soundfont",e.soundFont),t.set("outputmode",e.outputMode),t.set("enableplayer",e.enablePlayer),t.set("enablecursor",e.enableCursor),t.set("enableanimatedbeatcursor",e.enableAnimatedBeatCursor),t.set("enableelementhighlighting",e.enableElementHighlighting),t.set("enableuserinteraction",e.enableUserInteraction),t.set("scrolloffsetx",e.scrollOffsetX),t.set("scrolloffsety",e.scrollOffsetY),t.set("scrollmode",e.scrollMode),t.set("scrollspeed",e.scrollSpeed),t.set("nativebrowsersmoothscroll",e.nativeBrowserSmoothScroll),t.set("songbookbendduration",e.songBookBendDuration),t.set("songbookdipduration",e.songBookDipDuration),t.set("vibrato",ba.toJson(e.vibrato)),t.set("slide",Sa.toJson(e.slide)),t.set("playtripletfeel",e.playTripletFeel),t.set("buffertimeinmilliseconds",e.bufferTimeInMilliseconds),t}static setProperty(e,t,s){switch(t){case"soundfont":return e.soundFont=s,!0;case"scrollelement":return e.scrollElement=s,!0;case"outputmode":return e.outputMode=ia.parseEnum(s,jt),!0;case"enableplayer":return e.enablePlayer=s,!0;case"enablecursor":return e.enableCursor=s,!0;case"enableanimatedbeatcursor":return e.enableAnimatedBeatCursor=s,!0;case"enableelementhighlighting":return e.enableElementHighlighting=s,!0;case"enableuserinteraction":return e.enableUserInteraction=s,!0;case"scrolloffsetx":return e.scrollOffsetX=s,!0;case"scrolloffsety":return e.scrollOffsetY=s,!0;case"scrollmode":return e.scrollMode=ia.parseEnum(s,qt),!0;case"scrollspeed":return e.scrollSpeed=s,!0;case"nativebrowsersmoothscroll":return e.nativeBrowserSmoothScroll=s,!0;case"songbookbendduration":return e.songBookBendDuration=s,!0;case"songbookdipduration":return e.songBookDipDuration=s,!0;case"playtripletfeel":return e.playTripletFeel=s,!0;case"buffertimeinmilliseconds":return e.bufferTimeInMilliseconds=s,!0}if(["vibrato"].indexOf(t)>=0)return ba.fromJson(e.vibrato,s),!0;for(const i of["vibrato"])if(0===t.indexOf(i)&&ba.setProperty(e.vibrato,t.substring(i.length),s))return!0;if(["slide"].indexOf(t)>=0)return Sa.fromJson(e.slide,s),!0;for(const i of["slide"])if(0===t.indexOf(i)&&Sa.setProperty(e.slide,t.substring(i.length),s))return!0;return!1}}class wa{static fromJson(e,t){t&&ia.forEach(t,((t,s)=>wa.setProperty(e,s.toLowerCase(),t)))}static toJson(e){if(!e)return null;const t=new Map;return t.set("core",pa.toJson(e.core)),t.set("display",ma.toJson(e.display)),t.set("notation",fa.toJson(e.notation)),t.set("importer",ya.toJson(e.importer)),t.set("player",_a.toJson(e.player)),t}static setProperty(e,t,s){if(["core",""].indexOf(t)>=0)return pa.fromJson(e.core,s),!0;for(const i of["core",""])if(0===t.indexOf(i)&&pa.setProperty(e.core,t.substring(i.length),s))return!0;if(["display",""].indexOf(t)>=0)return ma.fromJson(e.display,s),!0;for(const i of["display",""])if(0===t.indexOf(i)&&ma.setProperty(e.display,t.substring(i.length),s))return!0;if(["notation"].indexOf(t)>=0)return fa.fromJson(e.notation,s),!0;for(const i of["notation"])if(0===t.indexOf(i)&&fa.setProperty(e.notation,t.substring(i.length),s))return!0;if(["importer"].indexOf(t)>=0)return ya.fromJson(e.importer,s),!0;for(const i of["importer"])if(0===t.indexOf(i)&&ya.setProperty(e.importer,t.substring(i.length),s))return!0;if(["player"].indexOf(t)>=0)return _a.fromJson(e.player,s),!0;for(const i of["player"])if(0===t.indexOf(i)&&_a.setProperty(e.player,t.substring(i.length),s))return!0;return!1}}class Ba{constructor(){this.core=new nc,this.display=new ha,this.notation=new J,this.importer=new la,this.player=new ua}setSongBookModeSettings(){this.notation.notationMode=D.SongBook,this.notation.smallGraceTabNotes=!1,this.notation.fingeringMode=C.SingleNoteEffectBand,this.notation.extendBendArrowsOnTiedNotes=!1,this.notation.elements.set(E.ParenthesisOnTiedBends,!1),this.notation.elements.set(E.TabNotesOnTiedBends,!1),this.notation.elements.set(E.ZerosOnDiveWhammys,!0)}static get songBook(){const e=new Ba;return e.setSongBookModeSettings(),e}fillFromJson(e){wa.fromJson(this,e)}}class ka{static fromJson(e,t){t&&ia.forEach(t,((t,s)=>ka.setProperty(e,s,t)))}static toJson(e){if(!e)return null;const t=new Map;return t.set("marker",e.marker),t.set("text",e.text),t}static setProperty(e,t,s){switch(t){case"marker":return e.marker=s,!0;case"text":return e.text=s,!0}return!1}}class Ta{static fromJson(e,t){t&&ia.forEach(t,((t,s)=>Ta.setProperty(e,s,t)))}static toJson(e){if(!e)return null;const t=new Map;return t.set("islinear",e.isLinear),t.set("type",e.type),t.set("value",e.value),t.set("ratioposition",e.ratioPosition),t.set("text",e.text),t}static setProperty(e,t,s){switch(t){case"islinear":return e.isLinear=s,!0;case"type":return e.type=ia.parseEnum(s,m),!0;case"value":return e.value=s,!0;case"ratioposition":return e.ratioPosition=s,!0;case"text":return e.text=s,!0}return!1}}class Na{static fromJson(e,t){t&&ia.forEach(t,((t,s)=>Na.setProperty(e,s,t)))}static toJson(e){if(!e)return null;const t=new Map;return t.set("type",e.type),t.set("length",e.length),t}static setProperty(e,t,s){switch(t){case"type":return e.type=ia.parseEnum(s,ke),!0;case"length":return e.length=s,!0}return!1}}class xa{static fromJson(e,t){t&&ia.forEach(t,((t,s)=>xa.setProperty(e,s,t)))}static toJson(e){if(!e)return null;const t=new Map;if(t.set("alternateendings",e.alternateEndings),t.set("isdoublebar",e.isDoubleBar),t.set("isrepeatstart",e.isRepeatStart),t.set("repeatcount",e.repeatCount),t.set("timesignaturenumerator",e.timeSignatureNumerator),t.set("timesignaturedenominator",e.timeSignatureDenominator),t.set("timesignaturecommon",e.timeSignatureCommon),t.set("isfreetime",e.isFreeTime),t.set("tripletfeel",e.tripletFeel),e.section&&t.set("section",ka.toJson(e.section)),t.set("tempoautomations",e.tempoAutomations.map((e=>Ta.toJson(e)))),null!==e.fermata){const s=new Map;t.set("fermata",s);for(const[t,i]of e.fermata)s.set(t.toString(),Na.toJson(i))}if(t.set("start",e.start),t.set("isanacrusis",e.isAnacrusis),t.set("displayscale",e.displayScale),t.set("displaywidth",e.displayWidth),null!==e.directions){const s=[];t.set("directions",s);for(const t of e.directions)s.push(t)}return t}static setProperty(e,t,s){switch(t){case"alternateendings":return e.alternateEndings=s,!0;case"isdoublebar":return e.isDoubleBar=s,!0;case"isrepeatstart":return e.isRepeatStart=s,!0;case"repeatcount":return e.repeatCount=s,!0;case"timesignaturenumerator":return e.timeSignatureNumerator=s,!0;case"timesignaturedenominator":return e.timeSignatureDenominator=s,!0;case"timesignaturecommon":return e.timeSignatureCommon=s,!0;case"isfreetime":return e.isFreeTime=s,!0;case"tripletfeel":return e.tripletFeel=ia.parseEnum(s,M),!0;case"section":return s?(e.section=new Qe,ka.fromJson(e.section,s)):e.section=null,!0;case"tempoautomations":e.tempoAutomations=[];for(const t of s){const s=new U;Ta.fromJson(s,t),e.tempoAutomations.push(s)}return!0;case"fermata":return e.fermata=new Map,ia.forEach(s,((t,s)=>{const i=new lt;Na.fromJson(i,t),e.addFermata(Number.parseInt(s),i)})),!0;case"start":return e.start=s,!0;case"isanacrusis":return e.isAnacrusis=s,!0;case"displayscale":return e.displayScale=s,!0;case"displaywidth":return e.displayWidth=s,!0;case"directions":for(const t of s)e.addDirection(ia.parseEnum(t,Be));return!0}return!1}}class va{static fromJson(e,t){t&&ia.forEach(t,((t,s)=>va.setProperty(e,s,t)))}static toJson(e){if(!e)return null;const t=new Map;return t.set("offset",e.offset),t.set("value",e.value),t}static setProperty(e,t,s){switch(t){case"offset":return e.offset=s,!0;case"value":return e.value=s,!0}return!1}}class Pa{static fromJson(e,t){t&&ia.forEach(t,((t,s)=>Pa.setProperty(e,s,t)))}static toJson(e){if(!e)return null;const t=new Map;t.set("notehead",e.noteHead),t.set("noteheadcenteronstem",e.noteHeadCenterOnStem);{const s=new Map;t.set("colors",s);for(const[t,i]of e.colors)s.set(t.toString(),et.toJson(i))}return t}static setProperty(e,t,s){switch(t){case"notehead":return e.noteHead=ia.parseEnum(s,re),!0;case"noteheadcenteronstem":return e.noteHeadCenterOnStem=s,!0;case"colors":return e.colors=new Map,ia.forEach(s,((t,s)=>{e.colors.set(ia.parseEnum(s,le),et.fromJson(t))})),!0}return!1}}class Fa{static fromJson(e,t){t&&ia.forEach(t,((t,s)=>Fa.setProperty(e,s,t)))}static toJson(e){if(!e)return null;const t=new Map;return t.set("id",e.id),t.set("accentuated",e.accentuated),t.set("bendtype",e.bendType),t.set("bendstyle",e.bendStyle),t.set("iscontinuedbend",e.isContinuedBend),null!==e.bendPoints&&t.set("bendpoints",e.bendPoints?.map((e=>va.toJson(e)))),t.set("fret",e.fret),t.set("string",e.string),t.set("showstringnumber",e.showStringNumber),t.set("octave",e.octave),t.set("tone",e.tone),t.set("percussionarticulation",e.percussionArticulation),t.set("isvisible",e.isVisible),t.set("islefthandtapped",e.isLeftHandTapped),t.set("ishammerpullorigin",e.isHammerPullOrigin),t.set("isslurdestination",e.isSlurDestination),t.set("harmonictype",e.harmonicType),t.set("harmonicvalue",e.harmonicValue),t.set("isghost",e.isGhost),t.set("isletring",e.isLetRing),t.set("ispalmmute",e.isPalmMute),t.set("isdead",e.isDead),t.set("isstaccato",e.isStaccato),t.set("slideintype",e.slideInType),t.set("slideouttype",e.slideOutType),t.set("vibrato",e.vibrato),t.set("istiedestination",e.isTieDestination),t.set("lefthandfinger",e.leftHandFinger),t.set("righthandfinger",e.rightHandFinger),t.set("trillvalue",e.trillValue),t.set("trillspeed",e.trillSpeed),t.set("durationpercent",e.durationPercent),t.set("accidentalmode",e.accidentalMode),t.set("dynamics",e.dynamics),t.set("ornament",e.ornament),e.style&&t.set("style",Pa.toJson(e.style)),e.toJson(t),t}static setProperty(e,t,s){switch(t){case"id":return e.id=s,!0;case"accentuated":return e.accentuated=ia.parseEnum(s,B),!0;case"bendtype":return e.bendType=ia.parseEnum(s,y),!0;case"bendstyle":return e.bendStyle=ia.parseEnum(s,f),!0;case"iscontinuedbend":return e.isContinuedBend=s,!0;case"bendpoints":if(s){e.bendPoints=[];for(const t of s){const s=new X;va.fromJson(s,t),e.addBendPoint(s)}}return!0;case"fret":return e.fret=s,!0;case"string":return e.string=s,!0;case"showstringnumber":return e.showStringNumber=s,!0;case"octave":return e.octave=s,!0;case"tone":return e.tone=s,!0;case"percussionarticulation":return e.percussionArticulation=s,!0;case"isvisible":return e.isVisible=s,!0;case"islefthandtapped":return e.isLeftHandTapped=s,!0;case"ishammerpullorigin":return e.isHammerPullOrigin=s,!0;case"isslurdestination":return e.isSlurDestination=s,!0;case"harmonictype":return e.harmonicType=ia.parseEnum(s,T),!0;case"harmonicvalue":return e.harmonicValue=s,!0;case"isghost":return e.isGhost=s,!0;case"isletring":return e.isLetRing=s,!0;case"ispalmmute":return e.isPalmMute=s,!0;case"isdead":return e.isDead=s,!0;case"isstaccato":return e.isStaccato=s,!0;case"slideintype":return e.slideInType=ia.parseEnum(s,x),!0;case"slideouttype":return e.slideOutType=ia.parseEnum(s,v),!0;case"vibrato":return e.vibrato=ia.parseEnum(s,P),!0;case"istiedestination":return e.isTieDestination=s,!0;case"lefthandfinger":return e.leftHandFinger=ia.parseEnum(s,k),!0;case"righthandfinger":return e.rightHandFinger=ia.parseEnum(s,k),!0;case"trillvalue":return e.trillValue=s,!0;case"trillspeed":return e.trillSpeed=ia.parseEnum(s,_),!0;case"durationpercent":return e.durationPercent=s,!0;case"accidentalmode":return e.accidentalMode=ia.parseEnum(s,N),!0;case"dynamics":return e.dynamics=ia.parseEnum(s,g),!0;case"ornament":return e.ornament=ia.parseEnum(s,he),!0;case"style":return s?(e.style=new Ie,Pa.fromJson(e.style,s)):e.style=void 0,!0}return e.setProperty(t,s)}}class Ca{static fromJson(e,t){t&&ia.forEach(t,((t,s)=>Ca.setProperty(e,s,t)))}static toJson(e){if(!e)return null;const t=new Map;{const s=new Map;t.set("colors",s);for(const[t,i]of e.colors)s.set(t.toString(),et.toJson(i))}return t}static setProperty(e,t,s){return"colors"===t&&(e.colors=new Map,ia.forEach(s,((t,s)=>{e.colors.set(ia.parseEnum(s,ye),et.fromJson(t))})),!0)}}class Da{static fromJson(e,t){t&&ia.forEach(t,((t,s)=>Da.setProperty(e,s,t)))}static toJson(e){if(!e)return null;const t=new Map;return t.set("id",e.id),t.set("notes",e.notes.map((e=>Fa.toJson(e)))),t.set("isempty",e.isEmpty),t.set("whammystyle",e.whammyStyle),t.set("ottava",e.ottava),t.set("islegatoorigin",e.isLegatoOrigin),t.set("duration",e.duration),t.set("automations",e.automations.map((e=>Ta.toJson(e)))),t.set("dots",e.dots),t.set("fade",e.fade),t.set("lyrics",e.lyrics),t.set("pop",e.pop),t.set("slap",e.slap),t.set("tap",e.tap),t.set("text",e.text),t.set("slashed",e.slashed),t.set("deadslapped",e.deadSlapped),t.set("brushtype",e.brushType),t.set("brushduration",e.brushDuration),t.set("tupletdenominator",e.tupletDenominator),t.set("tupletnumerator",e.tupletNumerator),t.set("iscontinuedwhammy",e.isContinuedWhammy),t.set("whammybartype",e.whammyBarType),null!==e.whammyBarPoints&&t.set("whammybarpoints",e.whammyBarPoints?.map((e=>va.toJson(e)))),t.set("vibrato",e.vibrato),t.set("chordid",e.chordId),t.set("gracetype",e.graceType),t.set("pickstroke",e.pickStroke),t.set("tremolospeed",e.tremoloSpeed),t.set("crescendo",e.crescendo),t.set("displaystart",e.displayStart),t.set("playbackstart",e.playbackStart),t.set("displayduration",e.displayDuration),t.set("playbackduration",e.playbackDuration),t.set("overridedisplayduration",e.overrideDisplayDuration),t.set("golpe",e.golpe),t.set("dynamics",e.dynamics),t.set("invertbeamdirection",e.invertBeamDirection),t.set("preferredbeamdirection",e.preferredBeamDirection),t.set("beamingmode",e.beamingMode),t.set("wahpedal",e.wahPedal),t.set("barrefret",e.barreFret),t.set("barreshape",e.barreShape),t.set("rasgueado",e.rasgueado),t.set("showtimer",e.showTimer),t.set("timer",e.timer),e.style&&t.set("style",Ca.toJson(e.style)),t}static setProperty(e,t,s){switch(t){case"id":return e.id=s,!0;case"notes":e.notes=[];for(const t of s){const s=new Ae;Fa.fromJson(s,t),e.addNote(s)}return!0;case"isempty":return e.isEmpty=s,!0;case"whammystyle":return e.whammyStyle=ia.parseEnum(s,f),!0;case"ottava":return e.ottava=ia.parseEnum(s,o),!0;case"islegatoorigin":return e.isLegatoOrigin=s,!0;case"duration":return e.duration=ia.parseEnum(s,_),!0;case"automations":e.automations=[];for(const t of s){const s=new U;Ta.fromJson(s,t),e.automations.push(s)}return!0;case"dots":return e.dots=s,!0;case"fade":return e.fade=ia.parseEnum(s,ue),!0;case"lyrics":return e.lyrics=s,!0;case"pop":return e.pop=s,!0;case"slap":return e.slap=s,!0;case"tap":return e.tap=s,!0;case"text":return e.text=s,!0;case"slashed":return e.slashed=s,!0;case"deadslapped":return e.deadSlapped=s,!0;case"brushtype":return e.brushType=ia.parseEnum(s,b),!0;case"brushduration":return e.brushDuration=s,!0;case"tupletdenominator":return e.tupletDenominator=s,!0;case"tupletnumerator":return e.tupletNumerator=s,!0;case"iscontinuedwhammy":return e.isContinuedWhammy=s,!0;case"whammybartype":return e.whammyBarType=ia.parseEnum(s,ce),!0;case"whammybarpoints":if(s){e.whammyBarPoints=[];for(const t of s){const s=new X;va.fromJson(s,t),e.addWhammyBarPoint(s)}}return!0;case"vibrato":return e.vibrato=ia.parseEnum(s,P),!0;case"chordid":return e.chordId=s,!0;case"gracetype":return e.graceType=ia.parseEnum(s,w),!0;case"pickstroke":return e.pickStroke=ia.parseEnum(s,ae),!0;case"tremolospeed":return e.tremoloSpeed=ia.parseEnum(s,_)??null,!0;case"crescendo":return e.crescendo=ia.parseEnum(s,S),!0;case"displaystart":return e.displayStart=s,!0;case"playbackstart":return e.playbackStart=s,!0;case"displayduration":return e.displayDuration=s,!0;case"playbackduration":return e.playbackDuration=s,!0;case"overridedisplayduration":return e.overrideDisplayDuration=s,!0;case"golpe":return e.golpe=ia.parseEnum(s,de),!0;case"dynamics":return e.dynamics=ia.parseEnum(s,g),!0;case"invertbeamdirection":return e.invertBeamDirection=s,!0;case"preferredbeamdirection":return e.preferredBeamDirection=ia.parseEnum(s,Te)??null,!0;case"beamingmode":return e.beamingMode=ia.parseEnum(s,fe),!0;case"wahpedal":return e.wahPedal=ia.parseEnum(s,pe),!0;case"barrefret":return e.barreFret=s,!0;case"barreshape":return e.barreShape=ia.parseEnum(s,ge),!0;case"rasgueado":return e.rasgueado=ia.parseEnum(s,me),!0;case"showtimer":return e.showTimer=s,!0;case"timer":return e.timer=s,!0;case"style":return s?(e.style=new Ge,Ca.fromJson(e.style,s)):e.style=void 0,!0}return!1}}class Ea{static fromJson(e,t){t&&ia.forEach(t,((t,s)=>Ea.setProperty(e,s,t)))}static toJson(e){if(!e)return null;const t=new Map;{const s=new Map;t.set("colors",s);for(const[t,i]of e.colors)s.set(t.toString(),et.toJson(i))}return t}static setProperty(e,t,s){return"colors"===t&&(e.colors=new Map,ia.forEach(s,((t,s)=>{e.colors.set(ia.parseEnum(s,I),et.fromJson(t))})),!0)}}class La{static fromJson(e,t){t&&ia.forEach(t,((t,s)=>La.setProperty(e,s,t)))}static toJson(e){if(!e)return null;const t=new Map;return t.set("id",e.id),t.set("beats",e.beats.map((e=>Da.toJson(e)))),e.style&&t.set("style",Ea.toJson(e.style)),t}static setProperty(e,t,s){switch(t){case"id":return e.id=s,!0;case"beats":e.beats=[];for(const t of s){const s=new ze;Da.fromJson(s,t),e.addBeat(s)}return!0;case"style":return s?(e.style=new Z,Ea.fromJson(e.style,s)):e.style=void 0,!0}return!1}}class Ma{static fromJson(e,t){t&&ia.forEach(t,((t,s)=>Ma.setProperty(e,s,t)))}static toJson(e){if(!e)return null;const t=new Map;return t.set("ratioposition",e.ratioPosition),t.set("pedaltype",e.pedalType),t}static setProperty(e,t,s){switch(t){case"ratioposition":return e.ratioPosition=s,!0;case"pedaltype":return e.pedalType=ia.parseEnum(s,d),!0}return!1}}class Ia{static fromJson(e,t){t&&ia.forEach(t,((t,s)=>Ia.setProperty(e,s,t)))}static toJson(e){if(!e)return null;const t=new Map;{const s=new Map;t.set("colors",s);for(const[t,i]of e.colors)s.set(t.toString(),et.toJson(i))}return t}static setProperty(e,t,s){return"colors"===t&&(e.colors=new Map,ia.forEach(s,((t,s)=>{e.colors.set(ia.parseEnum(s,u),et.fromJson(t))})),!0)}}class Aa{static fromJson(e,t){t&&ia.forEach(t,((t,s)=>Aa.setProperty(e,s,t)))}static toJson(e){if(!e)return null;const t=new Map;return t.set("id",e.id),t.set("clef",e.clef),t.set("clefottava",e.clefOttava),t.set("voices",e.voices.map((e=>La.toJson(e)))),t.set("similemark",e.simileMark),t.set("displayscale",e.displayScale),t.set("displaywidth",e.displayWidth),t.set("sustainpedals",e.sustainPedals.map((e=>Ma.toJson(e)))),t.set("barlineleft",e.barLineLeft),t.set("barlineright",e.barLineRight),t.set("keysignature",e.keySignature),t.set("keysignaturetype",e.keySignatureType),e.style&&t.set("style",Ia.toJson(e.style)),t}static setProperty(e,t,s){switch(t){case"id":return e.id=s,!0;case"clef":return e.clef=ia.parseEnum(s,n),!0;case"clefottava":return e.clefOttava=ia.parseEnum(s,o),!0;case"voices":e.voices=[];for(const t of s){const s=new ee;La.fromJson(s,t),e.addVoice(s)}return!0;case"similemark":return e.simileMark=ia.parseEnum(s,h),!0;case"displayscale":return e.displayScale=s,!0;case"displaywidth":return e.displayWidth=s,!0;case"sustainpedals":e.sustainPedals=[];for(const t of s){const s=new W;Ma.fromJson(s,t),e.sustainPedals.push(s)}return!0;case"barlineleft":return e.barLineLeft=ia.parseEnum(s,p),!0;case"barlineright":return e.barLineRight=ia.parseEnum(s,p),!0;case"keysignature":return e.keySignature=ia.parseEnum(s,l),!0;case"keysignaturetype":return e.keySignatureType=ia.parseEnum(s,c),!0;case"style":return s?(e.style=new V,Ia.fromJson(e.style,s)):e.style=void 0,!0}return!1}}class Ra{static fromJson(e,t){t&&ia.forEach(t,((t,s)=>Ra.setProperty(e,s,t)))}static toJson(e){if(!e)return null;const t=new Map;return t.set("name",e.name),t.set("firstfret",e.firstFret),t.set("strings",e.strings),t.set("barrefrets",e.barreFrets),t.set("showname",e.showName),t.set("showdiagram",e.showDiagram),t.set("showfingering",e.showFingering),t}static setProperty(e,t,s){switch(t){case"name":return e.name=s,!0;case"firstfret":return e.firstFret=s,!0;case"strings":return e.strings=s,!0;case"barrefrets":return e.barreFrets=s,!0;case"showname":return e.showName=s,!0;case"showdiagram":return e.showDiagram=s,!0;case"showfingering":return e.showFingering=s,!0}return!1}}class Oa{static fromJson(e,t){t&&ia.forEach(t,((t,s)=>Oa.setProperty(e,s,t)))}static toJson(e){if(!e)return null;const t=new Map;return t.set("isstandard",e.isStandard),t.set("name",e.name),t.set("tunings",e.tunings),t}static setProperty(e,t,s){switch(t){case"isstandard":return e.isStandard=s,!0;case"name":return e.name=s,!0;case"tunings":return e.tunings=s,!0}return!1}}class Ha{static fromJson(e,t){t&&ia.forEach(t,((t,s)=>Ha.setProperty(e,s,t)))}static toJson(e){if(!e)return null;const t=new Map;if(t.set("bars",e.bars.map((e=>Aa.toJson(e)))),null!==e.chords){const s=new Map;t.set("chords",s);for(const[t,i]of e.chords)s.set(t.toString(),Ra.toJson(i))}return t.set("capo",e.capo),t.set("transpositionpitch",e.transpositionPitch),t.set("displaytranspositionpitch",e.displayTranspositionPitch),t.set("stringtuning",Oa.toJson(e.stringTuning)),t.set("showslash",e.showSlash),t.set("shownumbered",e.showNumbered),t.set("showtablature",e.showTablature),t.set("showstandardnotation",e.showStandardNotation),t.set("ispercussion",e.isPercussion),t.set("standardnotationlinecount",e.standardNotationLineCount),t}static setProperty(e,t,s){switch(t){case"bars":e.bars=[];for(const t of s){const s=new G;Aa.fromJson(s,t),e.addBar(s)}return!0;case"chords":return e.chords=new Map,ia.forEach(s,((t,s)=>{const i=new je;Ra.fromJson(i,t),e.addChord(s,i)})),!0;case"capo":return e.capo=s,!0;case"transpositionpitch":return e.transpositionPitch=s,!0;case"displaytranspositionpitch":return e.displayTranspositionPitch=s,!0;case"stringtuning":return Oa.fromJson(e.stringTuning,s),!0;case"showslash":return e.showSlash=s,!0;case"shownumbered":return e.showNumbered=s,!0;case"showtablature":return e.showTablature=s,!0;case"showstandardnotation":return e.showStandardNotation=s,!0;case"ispercussion":return e.isPercussion=s,!0;case"standardnotationlinecount":return e.standardNotationLineCount=s,!0}return!1}}class Wa{static fromJson(e,t){t&&ia.forEach(t,((t,s)=>Wa.setProperty(e,s,t)))}static toJson(e){if(!e)return null;const t=new Map;return t.set("volume",e.volume),t.set("balance",e.balance),t.set("port",e.port),t.set("program",e.program),t.set("primarychannel",e.primaryChannel),t.set("secondarychannel",e.secondaryChannel),t.set("ismute",e.isMute),t.set("issolo",e.isSolo),t}static setProperty(e,t,s){switch(t){case"volume":return e.volume=s,!0;case"balance":return e.balance=s,!0;case"port":return e.port=s,!0;case"program":return e.program=s,!0;case"primarychannel":return e.primaryChannel=s,!0;case"secondarychannel":return e.secondaryChannel=s,!0;case"ismute":return e.isMute=s,!0;case"issolo":return e.isSolo=s,!0}return!1}}class Va{static fromJson(e,t){t&&ia.forEach(t,((t,s)=>Va.setProperty(e,s,t)))}static toJson(e){if(!e)return null;const t=new Map;return t.set("elementtype",e.elementType),t.set("staffline",e.staffLine),t.set("noteheaddefault",e.noteHeadDefault),t.set("noteheadhalf",e.noteHeadHalf),t.set("noteheadwhole",e.noteHeadWhole),t.set("techniquesymbol",e.techniqueSymbol),t.set("techniquesymbolplacement",e.techniqueSymbolPlacement),t.set("outputmidinumber",e.outputMidiNumber),t}static setProperty(e,t,s){switch(t){case"elementtype":return e.elementType=s,!0;case"staffline":return e.staffLine=s,!0;case"noteheaddefault":return e.noteHeadDefault=ia.parseEnum(s,re),!0;case"noteheadhalf":return e.noteHeadHalf=ia.parseEnum(s,re),!0;case"noteheadwhole":return e.noteHeadWhole=ia.parseEnum(s,re),!0;case"techniquesymbol":return e.techniqueSymbol=ia.parseEnum(s,re),!0;case"techniquesymbolplacement":return e.techniqueSymbolPlacement=ia.parseEnum(s,oe),!0;case"outputmidinumber":return e.outputMidiNumber=s,!0}return!1}}class Ga{static fromJson(e,t){t&&ia.forEach(t,((t,s)=>Ga.setProperty(e,s,t)))}static toJson(e){if(!e)return null;const t=new Map;{const s=new Map;t.set("colors",s);for(const[t,i]of e.colors)s.set(t.toString(),et.toJson(i))}return t}static setProperty(e,t,s){return"colors"===t&&(e.colors=new Map,ia.forEach(s,((t,s)=>{e.colors.set(ia.parseEnum(s,we),et.fromJson(t))})),!0)}}class za{static fromJson(e,t){t&&ia.forEach(t,((t,s)=>za.setProperty(e,s,t)))}static toJson(e){if(!e)return null;const t=new Map;if(t.set("staves",e.staves.map((e=>Ha.toJson(e)))),t.set("playbackinfo",Wa.toJson(e.playbackInfo)),t.set("color",et.toJson(e.color)),t.set("name",e.name),t.set("isvisibleonmultitrack",e.isVisibleOnMultiTrack),t.set("shortname",e.shortName),t.set("defaultsystemslayout",e.defaultSystemsLayout),t.set("systemslayout",e.systemsLayout),void 0!==e.lineBreaks){const s=[];t.set("linebreaks",s);for(const t of e.lineBreaks)s.push(t)}return t.set("percussionarticulations",e.percussionArticulations.map((e=>Va.toJson(e)))),e.style&&t.set("style",Ga.toJson(e.style)),t}static setProperty(e,t,s){switch(t){case"staves":e.staves=[];for(const t of s){const s=new it;Ha.fromJson(s,t),e.addStaff(s)}return!0;case"playbackinfo":return Wa.fromJson(e.playbackInfo,s),!0;case"color":return e.color=et.fromJson(s),!0;case"name":return e.name=s,!0;case"isvisibleonmultitrack":return e.isVisibleOnMultiTrack=s,!0;case"shortname":return e.shortName=s,!0;case"defaultsystemslayout":return e.defaultSystemsLayout=s,!0;case"systemslayout":return e.systemsLayout=s,!0;case"linebreaks":for(const t of s)e.addLineBreaks(t);return!0;case"percussionarticulations":e.percussionArticulations=[];for(const t of s){const s=new Ee;Va.fromJson(s,t),e.percussionArticulations.push(s)}return!0;case"style":return s?(e.style=new at,Ga.fromJson(e.style,s)):e.style=void 0,!0}return!1}}class Ua{static fromJson(e,t){t&&ia.forEach(t,((t,s)=>Ua.setProperty(e,s,t)))}static toJson(e){if(!e)return null;const t=new Map;if(t.set("hidedynamics",e.hideDynamics),t.set("bracketextendmode",e.bracketExtendMode),t.set("usesystemsignseparator",e.useSystemSignSeparator),t.set("globaldisplaytuning",e.globalDisplayTuning),null!==e.perTrackDisplayTuning){const s=new Map;t.set("pertrackdisplaytuning",s);for(const[t,i]of e.perTrackDisplayTuning)s.set(t.toString(),i)}if(t.set("globaldisplaychorddiagramsontop",e.globalDisplayChordDiagramsOnTop),null!==e.perTrackChordDiagramsOnTop){const s=new Map;t.set("pertrackchorddiagramsontop",s);for(const[t,i]of e.perTrackChordDiagramsOnTop)s.set(t.toString(),i)}if(t.set("singletracktracknamepolicy",e.singleTrackTrackNamePolicy),t.set("multitracktracknamepolicy",e.multiTrackTrackNamePolicy),t.set("firstsystemtracknamemode",e.firstSystemTrackNameMode),t.set("othersystemstracknamemode",e.otherSystemsTrackNameMode),t.set("firstsystemtracknameorientation",e.firstSystemTrackNameOrientation),t.set("othersystemstracknameorientation",e.otherSystemsTrackNameOrientation),t.set("multitrackmultibarrest",e.multiTrackMultiBarRest),null!==e.perTrackMultiBarRest){const s=[];t.set("pertrackmultibarrest",s);for(const t of e.perTrackMultiBarRest)s.push(t)}return t}static setProperty(e,t,n){switch(t){case"hidedynamics":return e.hideDynamics=n,!0;case"bracketextendmode":return e.bracketExtendMode=ia.parseEnum(n,s),!0;case"usesystemsignseparator":return e.useSystemSignSeparator=n,!0;case"globaldisplaytuning":return e.globalDisplayTuning=n,!0;case"pertrackdisplaytuning":return e.perTrackDisplayTuning=new Map,ia.forEach(n,((t,s)=>{e.perTrackDisplayTuning.set(Number.parseInt(s),t)})),!0;case"globaldisplaychorddiagramsontop":return e.globalDisplayChordDiagramsOnTop=n,!0;case"pertrackchorddiagramsontop":return e.perTrackChordDiagramsOnTop=new Map,ia.forEach(n,((t,s)=>{e.perTrackChordDiagramsOnTop.set(Number.parseInt(s),t)})),!0;case"singletracktracknamepolicy":return e.singleTrackTrackNamePolicy=ia.parseEnum(n,i),!0;case"multitracktracknamepolicy":return e.multiTrackTrackNamePolicy=ia.parseEnum(n,i),!0;case"firstsystemtracknamemode":return e.firstSystemTrackNameMode=ia.parseEnum(n,a),!0;case"othersystemstracknamemode":return e.otherSystemsTrackNameMode=ia.parseEnum(n,a),!0;case"firstsystemtracknameorientation":return e.firstSystemTrackNameOrientation=ia.parseEnum(n,r),!0;case"othersystemstracknameorientation":return e.otherSystemsTrackNameOrientation=ia.parseEnum(n,r),!0;case"multitrackmultibarrest":return e.multiTrackMultiBarRest=n,!0;case"pertrackmultibarrest":return e.perTrackMultiBarRest=new Set(n),!0}return!1}}class Xa{static fromJson(e,t){t&&ia.forEach(t,((t,s)=>Xa.setProperty(e,s,t)))}static toJson(e){if(!e)return null;const t=new Map;return t.set("template",e.template),t.set("isvisible",e.isVisible),t.set("textalign",e.textAlign),t}static setProperty(e,t,s){switch(t){case"template":return e.template=s,!0;case"isvisible":return e.isVisible=s,!0;case"textalign":return e.textAlign=ia.parseEnum(s,ne),!0}return!1}}class Ja{static fromJson(e,t){t&&ia.forEach(t,((t,s)=>Ja.setProperty(e,s,t)))}static toJson(e){if(!e)return null;const t=new Map;{const s=new Map;t.set("headerandfooter",s);for(const[t,i]of e.headerAndFooter)s.set(t.toString(),Xa.toJson(i))}{const s=new Map;t.set("colors",s);for(const[t,i]of e.colors)s.set(t.toString(),et.toJson(i))}return t}static setProperty(e,t,s){switch(t){case"headerandfooter":return e.headerAndFooter=new Map,ia.forEach(s,((t,s)=>{const i=new Ue;Xa.fromJson(i,t),e.headerAndFooter.set(ia.parseEnum(s,be),i)})),!0;case"colors":return e.colors=new Map,ia.forEach(s,((t,s)=>{e.colors.set(ia.parseEnum(s,be),et.fromJson(t))})),!0}return!1}}class Ya{static fromJson(e,t){t&&ia.forEach(t,((t,s)=>Ya.setProperty(e,s,t)))}static toJson(e){if(!e)return null;const t=new Map;return t.set("album",e.album),t.set("artist",e.artist),t.set("copyright",e.copyright),t.set("instructions",e.instructions),t.set("music",e.music),t.set("notices",e.notices),t.set("subtitle",e.subTitle),t.set("title",e.title),t.set("words",e.words),t.set("tab",e.tab),t.set("tempo",e.tempo),t.set("tempolabel",e.tempoLabel),t.set("masterbars",e.masterBars.map((e=>xa.toJson(e)))),t.set("tracks",e.tracks.map((e=>za.toJson(e)))),t.set("defaultsystemslayout",e.defaultSystemsLayout),t.set("systemslayout",e.systemsLayout),t.set("stylesheet",Ua.toJson(e.stylesheet)),e.style&&t.set("style",Ja.toJson(e.style)),t}static setProperty(e,t,s){switch(t){case"album":return e.album=s,!0;case"artist":return e.artist=s,!0;case"copyright":return e.copyright=s,!0;case"instructions":return e.instructions=s,!0;case"music":return e.music=s,!0;case"notices":return e.notices=s,!0;case"subtitle":return e.subTitle=s,!0;case"title":return e.title=s,!0;case"words":return e.words=s,!0;case"tab":return e.tab=s,!0;case"tempo":return e.tempo=s,!0;case"tempolabel":return e.tempoLabel=s,!0;case"masterbars":e.masterBars=[];for(const t of s){const s=new j;xa.fromJson(s,t),e.addMasterBar(s)}return!0;case"tracks":e.tracks=[];for(const t of s){const s=new rt;za.fromJson(s,t),e.addTrack(s)}return!0;case"defaultsystemslayout":return e.defaultSystemsLayout=s,!0;case"systemslayout":return e.systemsLayout=s,!0;case"stylesheet":return Ua.fromJson(e.stylesheet,s),!0;case"style":return s?(e.style=new Xe,Ja.fromJson(e.style,s)):e.style=void 0,!0}return!1}}class $a{static jsonReplacer(e,t){if(t instanceof Map){if("fromEntries"in Object)return Object.fromEntries(t);const e={};for(const[s,i]of t)e[s]=i;return e}return ArrayBuffer.isView(t)?Array.apply([],[t]):t}static scoreToJson(e){const t=$a.scoreToJsObject(e);return JSON.stringify(t,$a.jsonReplacer)}static jsonToScore(e,t){return $a.jsObjectToScore(JSON.parse(e),t)}static scoreToJsObject(e){return Ya.toJson(e)}static jsObjectToScore(e,t){const s=new Je;return Ya.fromJson(s,e),s.finish(t??new Ba),s}static settingsToJson(e){const t=$a.settingsToJsObject(e);return JSON.stringify(t,$a.jsonReplacer)}static jsonToSettings(e){return $a.jsObjectToSettings(JSON.parse(e))}static settingsToJsObject(e){return wa.toJson(e)}static jsObjectToSettings(e){const t=new Ba;return wa.fromJson(t,e),t}static jsObjectToMidiFile(e){const t=new Ps;return ia.forEach(e,((e,s)=>{switch(s){case"division":t.division=e;break;case"tracks":for(const s of e){const e=$a.jsObjectToMidiTrack(s);t.tracks.push(e)}}})),t}static jsObjectToMidiTrack(e){const t=new vs;return ia.forEach(e,((e,s)=>{if("events"===s)for(const s of e){const e=$a.jsObjectToMidiEvent(s);t.events.push(e)}})),t}static jsObjectToMidiEvent(e){const t=ia.getValue(e,"track"),s=ia.getValue(e,"tick"),i=ia.getValue(e,"type");switch(i){case Rt.TimeSignature:return new Cs(t,s,ia.getValue(e,"numerator"),ia.getValue(e,"denominatorIndex"),ia.getValue(e,"midiClocksPerMetronomeClick"),ia.getValue(e,"thirdySecondNodesInQuarter"));case Rt.AlphaTabRest:return new Ls(t,s,ia.getValue(e,"channel"));case Rt.AlphaTabMetronome:return new Es(t,s,ia.getValue(e,"metronomeNumerator"),ia.getValue(e,"metronomeDurationInTicks"),ia.getValue(e,"metronomeDurationInMilliseconds"));case Rt.NoteOn:return new Is(t,s,ia.getValue(e,"channel"),ia.getValue(e,"noteKey"),ia.getValue(e,"noteVelocity"));case Rt.NoteOff:return new As(t,s,ia.getValue(e,"channel"),ia.getValue(e,"noteKey"),ia.getValue(e,"noteVelocity"));case Rt.ControlChange:return new Rs(t,s,ia.getValue(e,"channel"),ia.getValue(e,"controller"),ia.getValue(e,"value"));case Rt.ProgramChange:return new Os(t,s,ia.getValue(e,"channel"),ia.getValue(e,"program"));case Rt.TempoChange:return new Hs(s,ia.getValue(e,"microSecondsPerQuarterNote"));case Rt.PitchBend:return new Ws(t,s,ia.getValue(e,"channel"),ia.getValue(e,"value"));case Rt.PerNotePitchBend:return new Vs(t,s,ia.getValue(e,"channel"),ia.getValue(e,"noteKey"),ia.getValue(e,"value"));case Rt.EndOfTrack:return new Gs(t,s)}throw new $e(Se.Format,`Unknown Midi Event type: ${i}`)}static midiFileToJsObject(e){const t=new Map;t.set("division",e.division);const s=[];for(const t of e.tracks)s.push($a.midiTrackToJsObject(t));return t.set("tracks",s),t}static midiTrackToJsObject(e){const t=new Map,s=[];for(const t of e.events)s.push($a.midiEventToJsObject(t));return t.set("events",s),t}static midiEventToJsObject(e){const t=new Map;switch(t.set("track",e.track),t.set("tick",e.tick),t.set("type",e.type),e.type){case Rt.TimeSignature:t.set("numerator",e.numerator),t.set("denominatorIndex",e.denominatorIndex),t.set("midiClocksPerMetronomeClick",e.midiClocksPerMetronomeClick),t.set("thirdySecondNodesInQuarter",e.thirtySecondNodesInQuarter);break;case Rt.AlphaTabRest:t.set("channel",e.channel);break;case Rt.AlphaTabMetronome:t.set("metronomeNumerator",e.metronomeNumerator),t.set("metronomeDurationInMilliseconds",e.metronomeDurationInMilliseconds),t.set("metronomeDurationInTicks",e.metronomeDurationInTicks);break;case Rt.NoteOn:case Rt.NoteOff:t.set("channel",e.channel),t.set("noteKey",e.noteKey),t.set("noteVelocity",e.noteVelocity);break;case Rt.ControlChange:t.set("channel",e.channel),t.set("controller",e.controller),t.set("value",e.value);break;case Rt.ProgramChange:t.set("channel",e.channel),t.set("program",e.program);break;case Rt.TempoChange:t.set("microSecondsPerQuarterNote",e.microSecondsPerQuarterNote);break;case Rt.PitchBend:t.set("channel",e.channel),t.set("value",e.value);break;case Rt.PerNotePitchBend:t.set("channel",e.channel),t.set("noteKey",e.noteKey),t.set("value",e.value);case Rt.EndOfTrack:}return t}}class qa{constructor(){this.ready=new Qi,this.samplesPlayed=new Zi,this.sampleRequest=new Qi}get sampleRate(){return qa.preferredSampleRate}open(){q.debug("AlphaSynth","Initializing synth worker"),this._worker=rc.globalThis,this._worker.addEventListener("message",this.handleMessage.bind(this)),this.ready.trigger()}destroy(){this._worker.postMessage({cmd:"alphaSynth.output.destroy"})}handleMessage(e){const t=e.data;switch(t.cmd){case qa.CmdOutputSampleRequest:this.sampleRequest.trigger();break;case qa.CmdOutputSamplesPlayed:this.samplesPlayed.trigger(t.samples)}}addSamples(e){this._worker.postMessage({cmd:"alphaSynth.output.addSamples",samples:e})}play(){this._worker.postMessage({cmd:"alphaSynth.output.play"})}pause(){this._worker.postMessage({cmd:"alphaSynth.output.pause"})}resetSamples(){this._worker.postMessage({cmd:"alphaSynth.output.resetSamples"})}activate(){}async enumerateOutputDevices(){return[]}async setOutputDevice(e){}async getOutputDevice(){return null}}qa.CmdOutputPrefix="alphaSynth.output.",qa.CmdOutputAddSamples=`${qa.CmdOutputPrefix}addSamples`,qa.CmdOutputPlay=`${qa.CmdOutputPrefix}play`,qa.CmdOutputPause=`${qa.CmdOutputPrefix}pause`,qa.CmdOutputResetSamples=`${qa.CmdOutputPrefix}resetSamples`,qa.CmdOutputStop=`${qa.CmdOutputPrefix}stop`,qa.CmdOutputSampleRequest=`${qa.CmdOutputPrefix}sampleRequest`,qa.CmdOutputSamplesPlayed=`${qa.CmdOutputPrefix}samplesPlayed`,qa.preferredSampleRate=0;class ja{constructor(e,t){this._main=e,this._main.addEventListener("message",this.handleMessage.bind(this)),this._player=new sa(new qa,t),this._player.positionChanged.on(this.onPositionChanged.bind(this)),this._player.stateChanged.on(this.onPlayerStateChanged.bind(this)),this._player.finished.on(this.onFinished.bind(this)),this._player.soundFontLoaded.on(this.onSoundFontLoaded.bind(this)),this._player.soundFontLoadFailed.on(this.onSoundFontLoadFailed.bind(this)),this._player.soundFontLoadFailed.on(this.onSoundFontLoadFailed.bind(this)),this._player.midiLoaded.on(this.onMidiLoaded.bind(this)),this._player.midiLoadFailed.on(this.onMidiLoadFailed.bind(this)),this._player.readyForPlayback.on(this.onReadyForPlayback.bind(this)),this._player.midiEventsPlayed.on(this.onMidiEventsPlayed.bind(this)),this._player.playbackRangeChanged.on(this.onPlaybackRangeChanged.bind(this)),this._main.postMessage({cmd:"alphaSynth.ready"})}static init(){const e=rc.globalThis;e.addEventListener("message",(t=>{const s=t.data;if("alphaSynth.initialize"===s.cmd)qa.preferredSampleRate=s.sampleRate,q.logLevel=s.logLevel,rc.globalThis.alphaSynthWebWorker=new ja(e,s.bufferTimeInMilliseconds)}))}handleMessage(e){const t=e.data;switch(t.cmd){case"alphaSynth.setLogLevel":q.logLevel=t.value;break;case"alphaSynth.setMasterVolume":this._player.masterVolume=t.value;break;case"alphaSynth.setMetronomeVolume":this._player.metronomeVolume=t.value;break;case"alphaSynth.setPlaybackSpeed":this._player.playbackSpeed=t.value;break;case"alphaSynth.setTickPosition":this._player.tickPosition=t.value;break;case"alphaSynth.setTimePosition":this._player.timePosition=t.value;break;case"alphaSynth.setPlaybackRange":this._player.playbackRange=t.value;break;case"alphaSynth.setIsLooping":this._player.isLooping=t.value;break;case"alphaSynth.setCountInVolume":this._player.countInVolume=t.value;break;case"alphaSynth.setMidiEventsPlayedFilter":this._player.midiEventsPlayedFilter=t.value;break;case"alphaSynth.play":this._player.play();break;case"alphaSynth.pause":this._player.pause();break;case"alphaSynth.playPause":this._player.playPause();break;case"alphaSynth.stop":this._player.stop();break;case"alphaSynth.playOneTimeMidiFile":this._player.playOneTimeMidiFile($a.jsObjectToMidiFile(t.midi));break;case"alphaSynth.loadSoundFontBytes":this._player.loadSoundFont(t.data,t.append);break;case"alphaSynth.resetSoundFonts":this._player.resetSoundFonts();break;case"alphaSynth.loadMidi":this._player.loadMidiFile($a.jsObjectToMidiFile(t.midi));break;case"alphaSynth.setChannelMute":this._player.setChannelMute(t.channel,t.mute);break;case"alphaSynth.setChannelTranspositionPitch":this._player.setChannelTranspositionPitch(t.channel,t.semitones);break;case"alphaSynth.setChannelSolo":this._player.setChannelSolo(t.channel,t.solo);break;case"alphaSynth.setChannelVolume":this._player.setChannelVolume(t.channel,t.volume);break;case"alphaSynth.resetChannelStates":this._player.resetChannelStates();break;case"alphaSynth.destroy":this._player.destroy(),this._main.postMessage({cmd:"alphaSynth.destroyed"});break;case"alphaSynth.applyTranspositionPitches":this._player.applyTranspositionPitches(new Map(JSON.parse(t.transpositionPitches)))}}onPositionChanged(e){this._main.postMessage({cmd:"alphaSynth.positionChanged",currentTime:e.currentTime,endTime:e.endTime,currentTick:e.currentTick,endTick:e.endTick,isSeek:e.isSeek})}onPlayerStateChanged(e){this._main.postMessage({cmd:"alphaSynth.playerStateChanged",state:e.state,stopped:e.stopped})}onFinished(){this._main.postMessage({cmd:"alphaSynth.finished"})}onSoundFontLoaded(){this._main.postMessage({cmd:"alphaSynth.soundFontLoaded"})}onSoundFontLoadFailed(e){this._main.postMessage({cmd:"alphaSynth.soundFontLoadFailed",error:this.serializeException(e)})}serializeException(e){const t=JSON.parse(JSON.stringify(e));return e.message&&(t.message=e.message),e.stack&&(t.stack=e.stack),e.constructor&&e.constructor.name&&(t.type=e.constructor.name),t}onMidiLoaded(e){this._main.postMessage({cmd:"alphaSynth.midiLoaded",currentTime:e.currentTime,endTime:e.endTime,currentTick:e.currentTick,endTick:e.endTick,isSeek:e.isSeek})}onMidiLoadFailed(e){this._main.postMessage({cmd:"alphaSynth.midiLoaded",error:this.serializeException(e)})}onReadyForPlayback(){this._main.postMessage({cmd:"alphaSynth.readyForPlayback"})}onMidiEventsPlayed(e){this._main.postMessage({cmd:"alphaSynth.midiEventsPlayed",events:e.events.map($a.midiEventToJsObject)})}onPlaybackRangeChanged(e){this._main.postMessage({cmd:"alphaSynth.playbackRangeChanged",playbackRange:e.playbackRange})}}!function(e){e[e.Browser=0]="Browser",e[e.NodeJs=1]="NodeJs",e[e.BrowserModule=2]="BrowserModule"}(Kt||(Kt={}));class Ka{constructor(e,t){this.characterWidths=e,this.fontSizeToHeight=t}}class Qa{static generateFontLookup(e){if(!Qa.FontSizeLookupTables.has(e))if(rc.isRunningInWorker||rc.webPlatform===Kt.NodeJs){const t=new Ka(new Uint8Array([8]),1.2);Qa.FontSizeLookupTables.set(e,t)}else{const t=document.createElement("canvas").getContext("2d"),s=11;t.font=`${s}px ${e}`;const i=[];let a="";for(let e=Qa.ControlChars;e<255;e++){const s=String.fromCharCode(e);a+=s;const r=t.measureText(s);i.push(r.width)}const r=t.measureText(`${a}ÄÖÜÁÈ`),n=0-Math.abs(r.fontBoundingBoxAscent),o=0+Math.abs(r.fontBoundingBoxDescent)-n,h=new Ka(new Uint8Array(i),o/s);Qa.FontSizeLookupTables.set(e,h)}}static measureString(e,t,s,i,a){let r;let n=t[0];for(let e=0;e<t.length;e++)if(Qa.FontSizeLookupTables.has(t[e])){n=t[e];break}Qa.FontSizeLookupTables.has(n)||Qa.generateFontLookup(n),r=Qa.FontSizeLookupTables.get(n);let o=1;i===Jt.Italic&&(o*=1.1),a===Yt.Bold&&(o*=1.1);let h=0;for(let t=0;t<e.length;t++){const i=Math.min(r.characterWidths.length-1,e.charCodeAt(t)-Qa.ControlChars);i>=0&&(h+=r.characterWidths[i]*s/11)}return o*=1.07,new De(h*o,s*r.fontSizeToHeight)}}Qa.FontSizeLookupTables=new Map,Qa.ControlChars=32;class Za{constructor(){this.id=ie.newGuid(),this.x=0,this.y=0,this.width=0,this.height=0,this.totalWidth=0,this.totalHeight=0,this.firstMasterBarIndex=-1,this.lastMasterBarIndex=-1,this.renderResult=null}}class er{constructor(){this.beats=[]}addBeat(e){e.barBounds=this,this.beats.push(e),this.masterBarBounds.addBeat(e)}findBeatAtPos(e){let t=null;for(const s of this.beats)if(!t||s.realBounds.x<e)t=s;else if(s.realBounds.x>e)break;return t}finish(e=1){this.realBounds.scaleWith(e),this.visualBounds.scaleWith(e),this.beats.sort(((e,t)=>e.realBounds.x-t.realBounds.x));for(const t of this.beats)t.finish(e)}}class tr{constructor(){this.onNotesX=0,this.notes=null}addNote(e){this.notes||(this.notes=[]),e.beatBounds=this,this.notes.push(e)}findNoteAtPos(e,t){const s=this.notes;if(!s)return null;for(const i of s){const s=i.noteHeadBounds.y+i.noteHeadBounds.h,a=i.noteHeadBounds.x+i.noteHeadBounds.w;if(i.noteHeadBounds.x<=e&&i.noteHeadBounds.y<=t&&e<=a&&t<=s)return i.note}return null}finish(e=1){if(this.realBounds.scaleWith(e),this.visualBounds.scaleWith(e),this.onNotesX*=e,this.notes)for(const t of this.notes)t.finish(e)}}class sr{constructor(){this.index=0,this.isFirstOfLine=!1,this.bars=[],this.staffSystemBounds=null}get staveGroupBounds(){return this.staffSystemBounds}addBar(e){e.masterBarBounds=this,this.bars.push(e)}findBeatAtPos(e,t){let s=null;for(const t of this.bars){const i=t.findBeatAtPos(e);if(i&&(!s||s.realBounds.x<i.realBounds.x)){const t=Math.abs(i.realBounds.x-e);(!s||t<1e7)&&(s=i)}}return s?s.beat:null}finish(e=1){this.realBounds.scaleWith(e),this.visualBounds.scaleWith(e),this.lineAlignedBounds.scaleWith(e),this.bars.sort(((e,t)=>e.realBounds.y<t.realBounds.y?-1:e.realBounds.y>t.realBounds.y?1:e.realBounds.x<t.realBounds.x?-1:e.realBounds.x>t.realBounds.x?1:0));for(const t of this.bars)t.finish(e)}addBeat(e){this.staffSystemBounds.boundsLookup.addBeat(e)}}class ir{finish(e=1){this.noteHeadBounds.scaleWith(e)}}class ar{constructor(){this.index=0,this.bars=[]}finish(e=1){this.realBounds.scaleWith(e),this.visualBounds.scaleWith(e);for(const t of this.bars)t.finish(e)}addBar(e){this.boundsLookup.addMasterBar(e),e.staffSystemBounds=this,this.bars.push(e)}findBarAtPos(e){let t=null;for(const s of this.bars)if(!t||s.realBounds.x<e)t=s;else if(e>s.realBounds.x+s.realBounds.w)break;return t}}class rr{constructor(){this._beatLookup=new Map,this._masterBarLookup=new Map,this._currentStaffSystem=null,this.staffSystems=[],this.isFinished=!1}toJson(){const e={},t=[];e.staffSystems=t;for(const e of this.staffSystems){const s={};s.visualBounds=this.boundsToJson(e.visualBounds),s.realBounds=this.boundsToJson(e.realBounds),s.bars=[];for(const t of e.bars){const e={};e.lineAlignedBounds=this.boundsToJson(t.lineAlignedBounds),e.visualBounds=this.boundsToJson(t.visualBounds),e.realBounds=this.boundsToJson(t.realBounds),e.index=t.index,e.bars=[];for(const s of t.bars){const t={};t.visualBounds=this.boundsToJson(s.visualBounds),t.realBounds=this.boundsToJson(s.realBounds),t.beats=[];for(const e of s.beats){const s={};s.visualBounds=this.boundsToJson(e.visualBounds),s.realBounds=this.boundsToJson(e.realBounds),s.onNotesX=e.onNotesX;const i=s;if(i.beatIndex=e.beat.index,i.voiceIndex=e.beat.voice.index,i.barIndex=e.beat.voice.bar.index,i.staffIndex=e.beat.voice.bar.staff.index,i.trackIndex=e.beat.voice.bar.staff.track.index,e.notes){const t=[];s.notes=t;for(const s of e.notes){const e={};e.index=s.note.index,e.noteHeadBounds=this.boundsToJson(s.noteHeadBounds),t.push(e)}}t.beats.push(s)}e.bars.push(t)}s.bars.push(e)}t.push(s)}return e}static fromJson(e,t){const s=new rr,i=e.staffSystems;for(const e of i){const i=new ar;i.visualBounds=rr.boundsFromJson(e.visualBounds),i.realBounds=rr.boundsFromJson(e.realBounds),s.addStaffSystem(i);for(const s of e.bars){const e=new sr;e.index=s.index,e.isFirstOfLine=s.isFirstOfLine,e.lineAlignedBounds=rr.boundsFromJson(s.lineAlignedBounds),e.visualBounds=rr.boundsFromJson(s.visualBounds),e.realBounds=rr.boundsFromJson(s.realBounds),i.addBar(e);for(const i of s.bars){const s=new er;s.visualBounds=rr.boundsFromJson(i.visualBounds),s.realBounds=rr.boundsFromJson(i.realBounds),e.addBar(s);for(const e of i.beats){const i=new tr;i.visualBounds=rr.boundsFromJson(e.visualBounds),i.realBounds=rr.boundsFromJson(e.realBounds),i.onNotesX=e.onNotesX;const a=e;if(i.beat=t.tracks[a.trackIndex].staves[a.staffIndex].bars[a.barIndex].voices[a.voiceIndex].beats[a.beatIndex],e.notes){i.notes=[];for(const t of e.notes){const e=new ir,s=t;e.note=i.beat.notes[s.index],e.noteHeadBounds=rr.boundsFromJson(t.noteHeadBounds),i.addNote(e)}}s.addBeat(i)}}}}return s}static boundsFromJson(e){const t=new mt;return t.x=e.x,t.y=e.y,t.w=e.w,t.h=e.h,t}boundsToJson(e){const t={};return t.x=e.x,t.y=e.y,t.w=e.w,t.h=e.h,t}finish(e=1){for(const t of this.staffSystems)t.finish(e);this.isFinished=!0}addStaffSystem(e){e.index=this.staffSystems.length,e.boundsLookup=this,this.staffSystems.push(e),this._currentStaffSystem=e}addMasterBar(e){e.staffSystemBounds?this._masterBarLookup.set(e.index,e):(e.staffSystemBounds=this._currentStaffSystem,this._masterBarLookup.set(e.index,e),this._currentStaffSystem.addBar(e))}addBeat(e){this._beatLookup.has(e.beat.id)||this._beatLookup.set(e.beat.id,[]),this._beatLookup.get(e.beat.id)?.push(e)}findMasterBarByIndex(e){return this._masterBarLookup.has(e)?this._masterBarLookup.get(e):null}findMasterBar(e){const t=e.index;return this._masterBarLookup.has(t)?this._masterBarLookup.get(t):null}findBeat(e){const t=this.findBeats(e);return t?t[0]:null}findBeats(e){const t=e.id;return this._beatLookup.has(t)?this._beatLookup.get(t):null}getBeatAtPos(e,t){let s=0,i=this.staffSystems.length-1,a=-1;for(;s<=i;){const e=(i+s)/2|0,r=this.staffSystems[e];if(t>=r.realBounds.y&&t<=r.realBounds.y+r.realBounds.h){a=e;break}t<r.realBounds.y?i=e-1:s=e+1}if(-1===a)return null;const r=this.staffSystems[a].findBarAtPos(e);return r?r.findBeatAtPos(e,t):null}getNoteAtPos(e,t,s){const i=this.findBeats(e);if(i)for(const e of i){const i=e.findNoteAtPos(t,s);if(i)return i}return null}}class nr{constructor(t){this._currentLayoutMode=e.Page,this._currentRenderEngine=null,this._renderedTracks=null,this.canvas=null,this.score=null,this.tracks=null,this.layout=null,this.boundsLookup=null,this.width=0,this.preRender=new Zi,this.renderFinished=new Zi,this.partialRenderFinished=new Zi,this.partialLayoutFinished=new Zi,this.postRenderFinished=new Qi,this.error=new Zi,this.settings=t,this.recreateCanvas(),this.recreateLayout()}destroy(){this.score=null,this.canvas?.destroy(),this.canvas=null,this.layout=null,this.boundsLookup=null,this.tracks=null}recreateCanvas(){return this._currentRenderEngine!==this.settings.core.engine&&(this.canvas?.destroy(),this.canvas=rc.getRenderEngineFactory(this.settings.core.engine).createCanvas(),this._currentRenderEngine=this.settings.core.engine,!0)}recreateLayout(){return(!this.layout||this._currentLayoutMode!==this.settings.display.layoutMode)&&(this.layout=rc.getLayoutEngineFactory(this.settings.display.layoutMode).createLayout(this),this._currentLayoutMode=this.settings.display.layoutMode,!0)}renderScore(e,t){try{this.score=e;let s=null;if(null!=e&&null!=t){if(t){s=[];for(const i of t)i>=0&&i<e.tracks.length&&s.push(e.tracks[i])}else s=e.tracks.slice(0);0===s.length&&e.tracks.length>0&&s.push(e.tracks[0])}this.tracks=s,this.render()}catch(e){this.error.trigger(e)}}renderTracks(e){0===e.length?this.score=null:this.score=e[0].score,this.tracks=e,this.render()}updateSettings(e){this.settings=e}renderResult(e){try{const t=this.layout;t?(q.debug("Rendering",`Request render of lazy partial ${e}`),t.renderLazyPartial(e)):q.warning("Rendering",`Request render of lazy partial ${e} ignored, no layout exists`)}catch(e){this.error.trigger(e)}}render(){if(0!==this.width)if(this.boundsLookup=new rr,this.recreateCanvas(),this.canvas.lineWidth=1,this.canvas.settings=this.settings,this.tracks&&0!==this.tracks.length&&this.score){q.debug("Rendering",`Rendering ${this.tracks.length} tracks`);for(let e=0;e<this.tracks.length;e++){const t=this.tracks[e];q.debug("Rendering",`Track ${e}: ${t.name}`)}this.preRender.trigger(!1),this.recreateLayout(),this.layoutAndRender(),q.debug("Rendering","Rendering finished")}else q.debug("Rendering","Clearing rendered tracks because no score or tracks are set"),this.preRender.trigger(!1),this._renderedTracks=null,this.onRenderFinished(),this.postRenderFinished.trigger(),q.debug("Rendering","Clearing finished");else q.warning("Rendering","AlphaTab skipped rendering because of width=0 (element invisible)",null)}resizeRender(){this.recreateLayout()||this.recreateCanvas()||this._renderedTracks!==this.tracks||!this.tracks?(q.debug("Rendering","Starting full rerendering due to layout or canvas change",null),this.render()):this.layout.supportsResize?(q.debug("Rendering","Starting optimized rerendering for resize"),this.boundsLookup=new rr,this.preRender.trigger(!0),this.canvas.settings=this.settings,this.layout.resize(),this.onRenderFinished(),this.postRenderFinished.trigger()):q.debug("Rendering","Current layout does not support dynamic resizing, nothing was done",null),q.debug("Rendering","Resize finished")}layoutAndRender(){q.debug("Rendering",`Rendering at scale ${this.settings.display.scale} with layout ${this.layout.name}`,null),this.layout.layoutAndRender(),this._renderedTracks=this.tracks,this.onRenderFinished(),this.postRenderFinished.trigger()}onRenderFinished(){this.boundsLookup?.finish(this.settings.display.scale);const e=new Za;e.totalHeight=this.layout.height,e.totalWidth=this.layout.width,e.renderResult=this.canvas.onRenderFinished(),this.renderFinished.trigger(e)}}class or{constructor(e){this._main=e,this._main.addEventListener("message",this.handleMessage.bind(this),!1)}static init(){rc.globalThis.alphaTabWebWorker=new or(rc.globalThis)}handleMessage(e){const t=e.data;switch(t?t.cmd:""){case"alphaTab.initialize":const e=$a.jsObjectToSettings(t.settings);q.logLevel=e.core.logLevel,this._renderer=new nr(e),this._renderer.partialRenderFinished.on((e=>{this._main.postMessage({cmd:"alphaTab.partialRenderFinished",result:e})})),this._renderer.partialLayoutFinished.on((e=>{this._main.postMessage({cmd:"alphaTab.partialLayoutFinished",result:e})})),this._renderer.renderFinished.on((e=>{this._main.postMessage({cmd:"alphaTab.renderFinished",result:e})})),this._renderer.postRenderFinished.on((()=>{this._main.postMessage({cmd:"alphaTab.postRenderFinished",boundsLookup:this._renderer.boundsLookup?.toJson()??null})})),this._renderer.preRender.on((e=>{this._main.postMessage({cmd:"alphaTab.preRender",resize:e})})),this._renderer.error.on(this.error.bind(this));break;case"alphaTab.invalidate":this._renderer.render();break;case"alphaTab.resizeRender":this._renderer.resizeRender();break;case"alphaTab.renderResult":this._renderer.renderResult(t.resultId);break;case"alphaTab.setWidth":this._renderer.width=t.width;break;case"alphaTab.renderScore":this.updateFontSizes(t.fontSizes);const s=null==t.score?null:$a.jsObjectToScore(t.score,this._renderer.settings);this.renderMultiple(s,t.trackIndexes);break;case"alphaTab.updateSettings":this.updateSettings(t.settings)}}updateFontSizes(e){if(!(e instanceof Map)){const t=e;e=new Map;for(const s in t)e.set(s,t[s])}if(e){Qa.FontSizeLookupTables||(Qa.FontSizeLookupTables=new Map);for(const[t,s]of e)Qa.FontSizeLookupTables.set(t,s)}}updateSettings(e){wa.fromJson(this._renderer.settings,e)}renderMultiple(e,t){try{this._renderer.renderScore(e,t)}catch(e){this.error(e)}}error(e){q.error("Worker","An unexpected error occurred in worker",e),this._main.postMessage({cmd:"alphaTab.error",error:e})}}class hr{constructor(){this._canvas=null,this._color=new et(0,0,0,255),this._font=new na("Arial",10,Jt.Plain),this._lineWidth=0;const e=document.createElement("span");e.classList.add("at"),document.body.appendChild(e);const t=window.getComputedStyle(e);let s=t.fontFamily;(s.startsWith('"')||s.startsWith("'"))&&(s=s.substr(1,s.length-2)),this._musicFont=new na(s,Number.parseFloat(t.fontSize),Jt.Plain),this._measureCanvas=document.createElement("canvas"),this._measureCanvas.width=10,this._measureCanvas.height=10,this._measureCanvas.style.width="10px",this._measureCanvas.style.height="10px",this._measureContext=this._measureCanvas.getContext("2d"),this._measureContext.textBaseline="hanging"}destroy(){}onRenderFinished(){return null}beginRender(e,t){const s=this.settings.display.scale;this._canvas=document.createElement("canvas"),this._canvas.width=e*rc.HighDpiFactor|0,this._canvas.height=t*rc.HighDpiFactor|0,this._canvas.style.width=`${e}px`,this._canvas.style.height=`${t}px`,this._context=this._canvas.getContext("2d"),this._context.textBaseline="hanging",this._context.scale(rc.HighDpiFactor*s,rc.HighDpiFactor*s),this._context.lineWidth=this._lineWidth}endRender(){const e=this._canvas;return this._canvas=null,e}get color(){return this._color}set color(e){this._color.rgba!==e.rgba&&(this._color=e,this._context.strokeStyle=e.rgba,this._context.fillStyle=e.rgba)}get lineWidth(){return this._lineWidth}set lineWidth(e){this._lineWidth=e,this._context&&(this._context.lineWidth=e)}fillRect(e,t,s,i){s>0&&this._context.fillRect(0|e,0|t,s,i)}strokeRect(e,t,s,i){const a=this.lineWidth%2==0?0:.5;this._context.strokeRect((0|e)+a,(0|t)+a,s,i)}beginPath(){this._context.beginPath()}closePath(){this._context.closePath()}moveTo(e,t){this._context.moveTo(e,t)}lineTo(e,t){this._context.lineTo(e,t)}quadraticCurveTo(e,t,s,i){this._context.quadraticCurveTo(e,t,s,i)}bezierCurveTo(e,t,s,i,a,r){this._context.bezierCurveTo(e,t,s,i,a,r)}fillCircle(e,t,s){this._context.beginPath(),this._context.arc(e,t,s,0,2*Math.PI,!0),this.fill()}strokeCircle(e,t,s){this._context.beginPath(),this._context.arc(e,t,s,0,2*Math.PI,!0),this.stroke()}fill(){this._context.fill(),this._context.beginPath()}stroke(){this._context.stroke(),this._context.beginPath()}get font(){return this._font}set font(e){this._font=e,this._context&&(this._context.font=e.toCssString(1)),this._measureContext.font=e.toCssString(1)}get textAlign(){switch(this._context.textAlign){case"left":default:return ne.Left;case"center":return ne.Center;case"right":return ne.Right}}set textAlign(e){switch(e){case ne.Left:this._context.textAlign="left";break;case ne.Center:this._context.textAlign="center";break;case ne.Right:this._context.textAlign="right"}}get textBaseline(){switch(this._context.textBaseline){case"hanging":default:return oe.Top;case"middle":return oe.Middle;case"bottom":return oe.Bottom}}set textBaseline(e){switch(e){case oe.Top:this._context.textBaseline="hanging";break;case oe.Middle:this._context.textBaseline="middle";break;case oe.Bottom:this._context.textBaseline="bottom"}}beginGroup(e){}endGroup(){}fillText(e,t,s){this._context.fillText(e,t,s)}measureText(e){const t=this._measureContext.measureText(e);return new De(t.width,t.actualBoundingBoxDescent+t.actualBoundingBoxAscent)}fillMusicFontSymbol(e,t,s,i,a=!1){i!==re.None&&this.fillMusicFontSymbolText(e,t,s,String.fromCharCode(i),a)}fillMusicFontSymbols(e,t,s,i,a=!1){let r="";for(const e of i)e!==re.None&&(r+=String.fromCharCode(e));this.fillMusicFontSymbolText(e,t,s,r,a)}fillMusicFontSymbolText(e,t,s,i,a){const r=this._context.textAlign,n=this._context.textBaseline,o=this._context.font;this._context.font=this._musicFont.toCssString(s),this._context.textBaseline="middle",this._context.textAlign=a?"center":"left",this._context.fillText(i,e,t),this._context.textBaseline=n,this._context.font=o,this._context.textAlign=r}beginRotate(e,t,s){this._context.save(),this._context.translate(e,t),this._context.rotate(s*Math.PI/180)}endRotate(){this._context.restore()}}class lr{constructor(e,t=!1){this._midiFile=e,this._smf1Mode=t}addTimeSignature(e,t,s){let i=0,a=s;for(;a>>=1,a>0;)i++;this._midiFile.addEvent(new Cs(0,e,t,i,48,8))}addRest(e,t,s){this._smf1Mode||this._midiFile.addEvent(new Ls(e,t,s))}addNote(e,t,s,i,a,r){this._midiFile.addEvent(new Is(e,t,r,lr.fixValue(i),lr.fixValue(a))),this._midiFile.addEvent(new As(e,t+s,r,lr.fixValue(i),lr.fixValue(a)))}static fixValue(e){return e>127?127:e<0?0:e}addControlChange(e,t,s,i,a){this._midiFile.addEvent(new Rs(e,t,s,i,lr.fixValue(a)))}addProgramChange(e,t,s,i){this._midiFile.addEvent(new Os(e,t,s,i))}addTempo(e,t){const s=6e7/t|0;this._midiFile.addEvent(new Hs(e,s))}addBend(e,t,s,i){i=i>=K.MaxPitchWheel?K.MaxPitchWheel:Math.floor(i),this._midiFile.addEvent(new Ws(e,t,s,i))}addNoteBend(e,t,s,i,a){this._smf1Mode?this.addBend(e,t,s,a):(a=a*K.MaxPitchWheel20/K.MaxPitchWheel,this._midiFile.addEvent(new Vs(e,t,s,i,a)))}finishTrack(e,t){this._midiFile.format!==At.MultiTrack&&0!==e||this._midiFile.addEvent(new Gs(e,t))}}class cr{constructor(e,t){this.closingIndex=0,this.group=e,this.opening=t,e.closings=e.closings.sort(((e,t)=>e.index-t.index)),this.iterations=e.closings.map((e=>0))}}!function(e){e[e.PlayingNormally=0]="PlayingNormally",e[e.DirectionJumped=1]="DirectionJumped",e[e.DirectionJumpedAlCoda=2]="DirectionJumpedAlCoda",e[e.DirectionJumpedAlDoubleCoda=3]="DirectionJumpedAlDoubleCoda",e[e.DirectionJumpedAlFine=4]="DirectionJumpedAlFine"}(Qt||(Qt={}));class dr{get finished(){return this.index>=this._score.masterBars.length}constructor(e){this._repeatStack=[],this._groupsOnStack=new Set,this._previousAlternateEndings=0,this._state=Qt.PlayingNormally,this.shouldPlay=!0,this.index=0,this.currentTick=0,this._score=e}processCurrent(){const e=this._score.masterBars[this.index];if(this._state===Qt.PlayingNormally){let t=e.alternateEndings;if(0===t&&(t=this._previousAlternateEndings),e===e.repeatGroup.opening&&e.repeatGroup.isClosed&&!this._groupsOnStack.has(e.repeatGroup)){const s=new cr(e.repeatGroup,e);this._repeatStack.push(s),this._groupsOnStack.add(e.repeatGroup),this._previousAlternateEndings=0,t=e.alternateEndings}if(0===this._repeatStack.length||0===t)this.shouldPlay=!0;else{const e=this._repeatStack[this._repeatStack.length-1],s=e.iterations[e.closingIndex];this._previousAlternateEndings=t,this.shouldPlay=!!(t&1<<s)}}else this.shouldPlay=!0;this.shouldPlay&&(this.currentTick+=e.calculateDuration())}moveNext(){this.moveNextWithDirections()||this.moveNextWithNormalRepeats()}resetRepeats(){this._groupsOnStack.clear(),this._previousAlternateEndings=0,this._repeatStack=[]}handleDaCapo(e,t,s){return!!e.has(t)&&(this.index=0,this._state=s,this.resetRepeats(),!0)}handleDalSegno(e,t,s,i){if(e.has(t)){const e=this.findJumpTarget(i,this.index,!0);return-1!==e&&(this.index=e,this._state=s,this.resetRepeats(),!0)}return!1}handleDaCoda(e,t,s){if(e.has(t)){const e=this.findJumpTarget(s,this.index,!1);return-1===e?(this.index++,!0):(this.index=e,this._state=Qt.PlayingNormally,!0)}return!1}moveNextWithDirections(){const e=this._score.masterBars[this.index],t=null!==e.directions&&e.directions.size>0;if(this._state===Qt.PlayingNormally&&!t)return!1;if(!t)return this.index++,!0;switch(this._state){case Qt.PlayingNormally:return!!(this.handleDaCapo(e.directions,Be.JumpDaCapo,Qt.DirectionJumped)||this.handleDaCapo(e.directions,Be.JumpDaCapoAlCoda,Qt.DirectionJumpedAlCoda)||this.handleDaCapo(e.directions,Be.JumpDaCapoAlDoubleCoda,Qt.DirectionJumpedAlDoubleCoda)||this.handleDaCapo(e.directions,Be.JumpDaCapoAlFine,Qt.DirectionJumpedAlFine))||(!!(this.handleDalSegno(e.directions,Be.JumpDalSegno,Qt.DirectionJumped,Be.TargetSegno)||this.handleDalSegno(e.directions,Be.JumpDalSegnoAlCoda,Qt.DirectionJumpedAlCoda,Be.TargetSegno)||this.handleDalSegno(e.directions,Be.JumpDalSegnoAlDoubleCoda,Qt.DirectionJumpedAlDoubleCoda,Be.TargetSegno)||this.handleDalSegno(e.directions,Be.JumpDalSegnoAlFine,Qt.DirectionJumpedAlFine,Be.TargetSegno))||!!(this.handleDalSegno(e.directions,Be.JumpDalSegnoSegno,Qt.DirectionJumped,Be.TargetSegnoSegno)||this.handleDalSegno(e.directions,Be.JumpDalSegnoSegnoAlCoda,Qt.DirectionJumpedAlCoda,Be.TargetSegnoSegno)||this.handleDalSegno(e.directions,Be.JumpDalSegnoSegnoAlDoubleCoda,Qt.DirectionJumpedAlDoubleCoda,Be.TargetSegnoSegno)||this.handleDalSegno(e.directions,Be.JumpDalSegnoSegnoAlFine,Qt.DirectionJumpedAlFine,Be.TargetSegnoSegno)));case Qt.DirectionJumped:return this.index++,!0;case Qt.DirectionJumpedAlCoda:return this.handleDaCoda(e.directions,Be.JumpDaCoda,Be.TargetCoda)||this.index++,!0;case Qt.DirectionJumpedAlDoubleCoda:return this.handleDaCoda(e.directions,Be.JumpDaDoubleCoda,Be.TargetDoubleCoda)||this.index++,!0;case Qt.DirectionJumpedAlFine:return e.directions.has(Be.TargetFine)?(this.index=this._score.masterBars.length,!0):(this.index++,!0)}return!0}findJumpTarget(e,t,s){let i;return s?(i=this.findJumpTargetBackwards(e,t),-1===i&&(i=this.findJumpTargetForwards(e,t)),i):(i=this.findJumpTargetForwards(e,t),-1===i&&(i=this.findJumpTargetBackwards(e,t)),i)}findJumpTargetForwards(e,t){let s=t;for(;s<this._score.masterBars.length;){const t=this._score.masterBars[s].directions;if(t&&t.has(e))return s;s++}return-1}findJumpTargetBackwards(e,t){let s=t;for(;s>=0;){const t=this._score.masterBars[s].directions;if(t&&t.has(e))return s;s--}return-1}moveNextWithNormalRepeats(){const e=this._score.masterBars[this.index].repeatCount-1;if(this._repeatStack.length>0&&e>0){const t=this._repeatStack[this._repeatStack.length-1];if(t.iterations[t.closingIndex]<e){this.index=t.opening.index,t.iterations[t.closingIndex]++;for(let e=0;e<t.closingIndex;e++)t.iterations[e]=0;t.closingIndex=0,this._previousAlternateEndings=0}else t.closingIndex<t.group.closings.length-1?(t.closingIndex++,this.index++):(this._repeatStack.pop(),this._groupsOnStack.delete(t.group),this.index++)}else this.index++}}class ur{constructor(e,t){this.beat=e,this.playbackStart=t}}class pr{get duration(){return this.end-this.start}constructor(e,t){this._highlightedBeats=new Map,this.highlightedBeats=[],this.nextBeat=null,this.previousBeat=null,this.start=e,this.end=t}highlightBeat(e,t){e.isEmpty&&!e.voice.isEmpty||this._highlightedBeats.has(e.id)||(this._highlightedBeats.set(e.id,!0),this.highlightedBeats.push(new ur(e,t)))}getVisibleBeatAtStart(e){for(const t of this.highlightedBeats)if(t.playbackStart===this.start&&e.has(t.beat.voice.bar.staff.track.index))return t.beat;return null}}class gr{constructor(e,t){this.tick=e,this.tempo=t}}class mr{constructor(){this.start=0,this.end=0,this.tempoChanges=[],this.firstBeat=null,this.lastBeat=null,this.nextMasterBar=null,this.previousMasterBar=null}get tempo(){return this.tempoChanges[0].tempo}insertAfter(e,t){null==this.firstBeat||null==e||null==this.lastBeat?(this.firstBeat=t,this.lastBeat=t):(t.nextBeat=e.nextBeat,t.previousBeat=e,e.nextBeat&&(e.nextBeat.previousBeat=t),e.nextBeat=t,e===this.lastBeat&&(this.lastBeat=t))}insertBefore(e,t){null==this.firstBeat||null==e||null==this.lastBeat?(this.firstBeat=t,this.lastBeat=t):(t.previousBeat=e.previousBeat,t.nextBeat=e,e.previousBeat&&(e.previousBeat.nextBeat=t),e.previousBeat=t,e===this.firstBeat&&(this.firstBeat=t))}addBeat(e,t,s,i){const a=s+i;if(null==this.firstBeat){const i=new pr(s,a);i.highlightBeat(e,t),this.insertAfter(this.firstBeat,i)}else if(s>=this.lastBeat.end){const s=new pr(this.lastBeat.end,a);s.highlightBeat(e,t),this.insertAfter(this.lastBeat,s)}else{let i=null;if(s<this.firstBeat.start)i=this.firstBeat;else{let e=this.firstBeat;for(;null!=e;){if(s>=e.start&&s<e.end){i=e;break}e=e.nextBeat}if(null===i)throw new $e(Se.General,"Error on building lookup, unknown variant")}if(s<i.start)if(a===i.start){const a=new pr(s,i.start);a.highlightBeat(e,t),this.insertBefore(this.firstBeat,a)}else if(a<i.end){const r=new pr(s,i.start);r.highlightBeat(e,t),this.insertBefore(i,r);const n=new pr(i.start,a);for(const e of i.highlightedBeats)n.highlightBeat(e.beat,e.playbackStart);n.highlightBeat(e,t),this.insertBefore(i,n),i.start=a}else if(a===i.end){const a=new pr(s,i.start);a.highlightBeat(e,t),i.highlightBeat(e,t),this.insertBefore(i,a)}else{const r=new pr(s,i.start);r.highlightBeat(e,t),i.highlightBeat(e,t),this.insertBefore(i,r),this.addBeat(e,t,i.end,a-i.end)}else if(s>i.start)if(a===i.end){const a=new pr(i.start,s);for(const e of i.highlightedBeats)a.highlightBeat(e.beat,e.playbackStart);i.start=s,i.highlightBeat(e,t),this.insertBefore(i,a)}else if(a<i.end){const r=new pr(i.start,s);this.insertBefore(i,r);const n=new pr(s,a);this.insertBefore(i,n);for(const e of i.highlightedBeats)r.highlightBeat(e.beat,e.playbackStart),n.highlightBeat(e.beat,e.playbackStart);n.highlightBeat(e,t),i.start=a}else{const r=new pr(i.start,s);for(const e of i.highlightedBeats)r.highlightBeat(e.beat,e.playbackStart);i.start=s,i.highlightBeat(e,t),this.insertBefore(i,r),this.addBeat(e,t,i.end,a-i.end)}else if(a===i.end)i.highlightBeat(e,t);else if(a<i.end){const s=new pr(i.start,a);for(const e of i.highlightedBeats)s.highlightBeat(e.beat,e.playbackStart);s.highlightBeat(e,t),i.start=a,this.insertBefore(i,s)}else i.highlightBeat(e,t),this.addBeat(e,t,i.end,a-i.end)}}}!function(e){e[e.Unknown=0]="Unknown",e[e.ToNextBext=1]="ToNextBext",e[e.ToEndOfBar=2]="ToEndOfBar"}(Zt||(Zt={}));class fr{get start(){return this.masterBar.start+this.beatLookup.start}get end(){return this.start+this.tickDuration}constructor(e){this.nextBeat=null,this.tickDuration=0,this.duration=0,this.cursorMode=Zt.Unknown,this.masterBar=e}calculateDuration(){if(1===this.masterBar.tempoChanges.length)this.duration=z.ticksToMillis(this.tickDuration,this.masterBar.tempoChanges[0].tempo);else{let e=0,t=this.start,s=this.masterBar.tempoChanges[0].tempo;const i=this.end;for(const a of this.masterBar.tempoChanges)if(a.tick<t)s=a.tempo;else{if(a.tick>i)break;e+=z.ticksToMillis(a.tick-t,s),s=a.tempo,t=a.tick}i>t&&(e+=z.ticksToMillis(i-t,s)),this.duration=e}}}class yr{constructor(){this._currentMasterBar=null,this.masterBarLookup=new Map,this.masterBars=[],this.multiBarRestInfo=null}findBeat(e,t,s=null){let i=null;return s&&(i=this.findBeatFast(e,s,t)),i||(i=this.findBeatSlow(e,s,t,!1)),i}findBeatFast(e,t,s){if(s>=t.start&&s<t.end)return t;if(t.nextBeat&&s>=t.nextBeat.start&&s<t.nextBeat.end){const s=t.nextBeat;return this.fillNextBeat(s,e),s}return null}fillNextBeatMultiBarRest(e,t){const s=this.multiBarRestInfo.get(e.masterBar.masterBar.index);let i=e.masterBar;for(let e=0;e<s.length&&i;e++)i=i.nextMasterBar;i?i.nextMasterBar?(e.nextBeat=this.firstBeatInMasterBar(t,i.nextMasterBar,i.nextMasterBar.start,!0),e.nextBeat?(e.tickDuration=e.nextBeat.start-e.start,e.cursorMode=Zt.ToNextBext,e.nextBeat.masterBar.masterBar.index!==i.masterBar.index+1&&(e.nextBeat.masterBar.masterBar.index!==i.masterBar.index||e.nextBeat.beat.playbackStart<=e.beat.playbackStart)&&(e.cursorMode=Zt.ToEndOfBar)):(e.tickDuration=i.nextMasterBar.end-e.start,e.cursorMode=Zt.ToEndOfBar)):(e.tickDuration=i.end-e.start,e.cursorMode=Zt.ToEndOfBar):(q.warning("Synth","MultiBar Rest Info and the nextMasterBar are out of sync, this is an unexpected error. Please report it as bug. (broken chain fill-next)"),e.tickDuration=(e.masterBar.end-e.masterBar.start)*(s.length+1),e.cursorMode=Zt.ToEndOfBar),e.calculateDuration()}fillNextBeat(e,t){this.isMultiBarRestResult(e)?this.fillNextBeatMultiBarRest(e,t):this.fillNextBeatDefault(e,t)}fillNextBeatDefault(e,t){e.nextBeat=this.findBeatInMasterBar(e.masterBar,e.beatLookup.nextBeat,e.end,t,!0),null==e.nextBeat&&(e.nextBeat=this.findBeatSlow(t,e,e.end,!0)),e.nextBeat?(e.tickDuration=e.nextBeat.start-e.start,e.cursorMode=Zt.ToNextBext,e.calculateDuration()):(e.tickDuration=e.masterBar.end-e.start,e.cursorMode=Zt.ToEndOfBar,e.calculateDuration()),e.nextBeat&&e.nextBeat.masterBar.masterBar.index!==e.masterBar.masterBar.index+1&&(e.nextBeat.masterBar.masterBar.index!==e.masterBar.masterBar.index||e.nextBeat.beat.playbackStart<=e.beat.playbackStart)&&(e.cursorMode=Zt.ToEndOfBar)}isMultiBarRestResult(e){return this.internalIsMultiBarRestResult(e.masterBar.masterBar.index,e.beat)}internalIsMultiBarRestResult(e,t){return this.multiBarRestInfo&&this.multiBarRestInfo.has(e)&&t.isRest&&t.voice.bar.isRestOnly}findBeatSlow(e,t,s,i){let a=null;return null!=t&&(t.masterBar.start<=s&&t.masterBar.end>s?a=t.masterBar:t.masterBar.nextMasterBar&&t.masterBar.nextMasterBar.start<=s&&t.masterBar.nextMasterBar.end>s&&(a=t.masterBar.nextMasterBar)),a||(a=this.findMasterBar(s)),a?this.firstBeatInMasterBar(e,a,s,i):null}firstBeatInMasterBar(e,t,s,i){let a=t;for(;a;){if(a.firstBeat){const t=this.findBeatInMasterBar(a,a.firstBeat,s,e,i);if(t)return t}a=a.nextMasterBar}return null}findBeatInMasterBar(e,t,s,i,a){if(!t)return null;let r=null,n=null;const o=s-e.start;for(;null!=t&&null==n;){if((t.start<=o||a&&o<0)&&o<t.end){if(r=t,n=t.getVisibleBeatAtStart(i),!n)if(a){let s=e;for(;null!=s&&null==n;){for(;null!=t;){if(n=t.getVisibleBeatAtStart(i),n){r=t,e=s;break}t=t.nextBeat}n&&r||(s=s.nextMasterBar,t=s?.firstBeat??null)}}else{let s=e;for(;null!=s&&null==n;){for(;null!=t;){if(n=t.getVisibleBeatAtStart(i),n){r=t,e=s;break}t=t.previousBeat}n&&r||(s=s.previousMasterBar,t=s?.firstBeat??null)}}}else if(t.end>o)break;t=t?.nextBeat??null}if(null==n)return null;return this.createResult(e,r,n,a,i)}createResult(e,t,s,i,a){const r=new fr(e);if(r.beat=s,r.beatLookup=t,r.tickDuration=t.end-t.start,i){if(this.isMultiBarRestResult(r)){const s=this.multiBarRestInfo.get(e.masterBar.index);let i=e;for(let e=0;e<s.length&&i;e++)i=i.nextMasterBar;i?i.nextMasterBar?r.tickDuration=i.nextMasterBar.start-t.start:r.tickDuration=i.end-t.start:q.warning("Synth","MultiBar Rest Info and the nextMasterBar are out of sync, this is an unexpected error. Please report it as bug. (broken chain stretch-result)")}}else this.fillNextBeat(r,a);return r.calculateDuration(),r}findMasterBar(e){const t=this.masterBars;let s=0,i=t.length-1;for(;s<=i;){const a=(i+s)/2|0,r=t[a];if(e>=r.start&&e<r.end)return r;e<r.start?i=a-1:s=a+1}return null}getMasterBar(e){if(!this.masterBarLookup.has(e.index)){const t=new mr;return t.masterBar=e,t}return this.masterBarLookup.get(e.index)}getMasterBarStart(e){return this.masterBarLookup.has(e.index)?this.masterBarLookup.get(e.index).start:0}getBeatStart(e){return this.masterBarLookup.has(e.voice.bar.index)?this.masterBarLookup.get(e.voice.bar.index).start+e.playbackStart:0}addMasterBar(e){this.masterBars.push(e),this._currentMasterBar&&(e.previousMasterBar=this._currentMasterBar,this._currentMasterBar.nextMasterBar=e),this._currentMasterBar=e,this.masterBarLookup.has(e.masterBar.index)||this.masterBarLookup.set(e.masterBar.index,e)}addBeat(e,t,s){const i=this._currentMasterBar;if(i)if(t<0&&i.previousMasterBar){const a=i.previousMasterBar.end-i.previousMasterBar.start,r=a+t,n=r+s;if(i.previousMasterBar.addBeat(e,r,r,s),n>a){const a=s+t;i.addBeat(e,t,0,a)}}else i.addBeat(e,t,t,s)}}class br{constructor(){this.noteOnly=0,this.untilTieOrSlideEnd=0,this.letRingEnd=0}}class Sr{constructor(){this.firstBeatDuration=0,this.secondBeatStartOffset=0,this.secondBeatDuration=0}}class _r{constructor(){this.durations=[],this.brushInfos=[]}}class wr{constructor(e,t,s){this._programsPerChannel=new Map,this._currentTime=0,this._calculatedBeatTimers=new Set,this.tickLookup=new yr,this.applyTranspositionPitches=!0,this.transpositionPitches=new Map,this._currentTripletFeel=null,this.vibratoResolution=16,this._score=e,this._settings=t||new Ba,this._handler=s}generate(){this.transpositionPitches.clear(),this._calculatedBeatTimers.clear(),this._currentTime=0;for(const e of this._score.tracks)this.generateTrack(e);q.debug("Midi","Begin midi generation");const e=new dr(this._score);let t=null,s=this._score.tempo;for(;!e.finished;){const i=e.index,a=this._score.masterBars[i],r=e.currentTick;if(e.processCurrent(),e.shouldPlay){this.generateMasterBar(a,t,r,s),a.tempoAutomations.length>0&&(s=a.tempoAutomations[0].value);for(const e of this._score.tracks)for(const t of e.staves)i<t.bars.length&&this.generateBar(t.bars[i],r,s);a.tempoAutomations.length>0&&(s=a.tempoAutomations[a.tempoAutomations.length-1].value)}e.moveNext(),t=a}for(const t of this._score.tracks)this._handler.finishTrack(t.index,e.currentTick);q.debug("Midi","Midi generation done")}generateTrack(e){this.generateChannel(e,e.playbackInfo.primaryChannel,e.playbackInfo),e.playbackInfo.primaryChannel!==e.playbackInfo.secondaryChannel&&this.generateChannel(e,e.playbackInfo.secondaryChannel,e.playbackInfo)}addProgramChange(e,t,s,i){this._programsPerChannel.has(s)&&this._programsPerChannel.get(s)===i||(this._handler.addProgramChange(e.index,t,s,i),this._programsPerChannel.set(s,i))}static buildTranspositionPitches(e,t){const s=new Map;for(const i of e.tracks){const e=i.index<t.notation.transpositionPitches.length?t.notation.transpositionPitches[i.index]:-i.staves[0].transpositionPitch;s.set(i.playbackInfo.primaryChannel,e),s.set(i.playbackInfo.secondaryChannel,e)}return s}generateChannel(e,t,s){const i=e.index<this._settings.notation.transpositionPitches.length?this._settings.notation.transpositionPitches[e.index]:-e.staves[0].transpositionPitch;this.transpositionPitches.set(t,i);const a=wr.toChannelShort(s.volume),r=wr.toChannelShort(s.balance);this._handler.addControlChange(e.index,0,t,Xt.VolumeCoarse,a),this._handler.addControlChange(e.index,0,t,Xt.PanCoarse,r),this._handler.addControlChange(e.index,0,t,Xt.ExpressionControllerCoarse,127),this._handler.addControlChange(e.index,0,t,Xt.RegisteredParameterFine,0),this._handler.addControlChange(e.index,0,t,Xt.RegisteredParameterCourse,0),this._handler.addControlChange(e.index,0,t,Xt.DataEntryFine,0),this._handler.addControlChange(e.index,0,t,Xt.DataEntryCoarse,wr.PitchBendRangeInSemitones),this.addProgramChange(e,0,t,s.program)}static toChannelShort(e){const t=Math.max(-32768,Math.min(32767,8*e-1));return Math.max(t,-1)+1}generateMasterBar(e,t,s,i){t&&t.timeSignatureDenominator===e.timeSignatureDenominator&&t.timeSignatureNumerator===e.timeSignatureNumerator||this._handler.addTimeSignature(s,e.timeSignatureNumerator,e.timeSignatureDenominator);const a=e.calculateDuration(),r=new mr;if(e.tempoAutomations.length>0){e.tempoAutomations[0].ratioPosition>0&&r.tempoChanges.push(new gr(s,i));for(const t of e.tempoAutomations){const e=s+a*t.ratioPosition;this._handler.addTempo(e,t.value),r.tempoChanges.push(new gr(e,t.value))}}else t?r.tempoChanges.push(new gr(s,i)):(this._handler.addTempo(s,e.score.tempo),r.tempoChanges.push(new gr(s,e.score.tempo)));r.masterBar=e,r.start=s,r.end=r.start+a,this.tickLookup.addMasterBar(r)}generateBar(e,t,s){const i=this.getPlaybackBar(e),a=this._currentTime;for(const r of i.voices)this._currentTime=a,this.generateVoice(r,t,e,s);const r=i.masterBar,n=r.calculateDuration(),o=r.tempoAutomations.slice();if(0===o.length)this._currentTime=a+z.ticksToMillis(n,s);else{this._currentTime=a;let e=t,i=s;const r=t+n;for(const t of o){const s=n*t.ratioPosition-e;s>0&&(this._currentTime+=z.ticksToMillis(s,i)),i=t.value,e+=s}const h=r-e;h>0&&(this._currentTime+=z.ticksToMillis(h,i))}i.id!==e.id&&this.tickLookup.addBeat(e.voices[0].beats[0],0,n)}getPlaybackBar(e){switch(e.simileMark){case h.Simple:e.previousBar&&(e=this.getPlaybackBar(e.previousBar));break;case h.FirstOfDouble:case h.SecondOfDouble:e.previousBar&&e.previousBar.previousBar&&(e=this.getPlaybackBar(e.previousBar.previousBar))}return e}generateVoice(e,t,s,i){if(e.isEmpty&&(!e.bar.isEmpty||0!==e.index))return;const a=s.masterBar.tempoAutomations.slice();let r=i;const n=s.masterBar.calculateDuration();for(const i of e.beats){const e=i.playbackStart/n;for(;a.length>0&&a[0].ratioPosition<=e;)r=a.shift().value;this.generateBeat(i,t,s,r)}}generateBeat(e,t,s,i){let a=e.playbackStart,r=e.playbackDuration;const n=e.voice.bar.masterBar.calculateDuration();e.voice.bar.isEmpty?r=n:e.voice.bar.masterBar.tripletFeel!==M.NoTripletFeel&&this._settings.player.playTripletFeel&&(this._currentTripletFeel?(a-=this._currentTripletFeel.secondBeatStartOffset,r=this._currentTripletFeel.secondBeatDuration,this._currentTripletFeel=null):(this._currentTripletFeel=wr.calculateTripletFeelInfo(a,r,e),this._currentTripletFeel&&(r=this._currentTripletFeel.firstBeatDuration))),e.showTimer&&!this._calculatedBeatTimers.has(e.id)&&(e.timer=this._currentTime,this._calculatedBeatTimers.add(e.id)),this._currentTime+=z.ticksToMillis(r,i),s===e.voice.bar&&this.tickLookup.addBeat(e,a,r);const o=e.voice.bar.staff.track;for(const s of e.automations)this.generateNonTempoAutomation(e,s,t);if(e.isRest)this._handler.addRest(o.index,t+a,o.playbackInfo.primaryChannel);else if(e.deadSlapped)this.generateDeadSlap(e,t+a);else{const s=this.getBrushInfo(e),n=this.getRasgueadoInfo(e,r);for(const o of e.notes)this.generateNote(o,t+a,r,i,s,n)}if(e.fade!==ue.None&&this.generateFade(e,t+a,r),e.vibrato!==P.None){let s=240,i=3;switch(e.vibrato){case P.Slight:s=this._settings.player.vibrato.beatSlightLength,i=this._settings.player.vibrato.beatSlightAmplitude;break;case P.Wide:s=this._settings.player.vibrato.beatWideLength,i=this._settings.player.vibrato.beatWideAmplitude}this.generateVibratorWithParams(t+a,e.playbackDuration,s,0,i,((t,s)=>{this._handler.addBend(e.voice.bar.staff.track.index,t,o.playbackInfo.secondaryChannel,s)}))}}static calculateTripletFeelInfo(e,t,s){let i;switch(s.voice.bar.masterBar.tripletFeel){case M.Triplet8th:case M.Dotted8th:case M.Scottish8th:i=_.Eighth;break;case M.Triplet16th:case M.Dotted16th:case M.Scottish16th:i=_.Sixteenth;break;default:return null}const a=z.toTicks(i);if(t!==a)return null;if(e%a!=0)return null;if(!s.nextBeat||s.nextBeat.voice!==s.voice||s.playbackDuration!==a)return null;const r=new Sr;switch(s.voice.bar.masterBar.tripletFeel){case M.Triplet8th:r.firstBeatDuration=z.applyTuplet(z.toTicks(_.Quarter),3,2),r.secondBeatDuration=z.applyTuplet(z.toTicks(_.Eighth),3,2);break;case M.Dotted8th:r.firstBeatDuration=z.applyDot(z.toTicks(_.Eighth),!1),r.secondBeatDuration=z.toTicks(_.Sixteenth);break;case M.Scottish8th:r.firstBeatDuration=z.toTicks(_.Sixteenth),r.secondBeatDuration=z.applyDot(z.toTicks(_.Eighth),!1);break;case M.Triplet16th:r.firstBeatDuration=z.applyTuplet(z.toTicks(_.Eighth),3,2),r.secondBeatDuration=z.applyTuplet(z.toTicks(_.Sixteenth),3,2);break;case M.Dotted16th:r.firstBeatDuration=z.applyDot(z.toTicks(_.Sixteenth),!1),r.secondBeatDuration=z.toTicks(_.ThirtySecond);break;case M.Scottish16th:r.firstBeatDuration=z.toTicks(_.ThirtySecond),r.secondBeatDuration=z.applyDot(z.toTicks(_.Sixteenth),!1)}return r.secondBeatStartOffset=t-r.firstBeatDuration,r}generateDeadSlap(e,t){const s=z.toTicks(_.SixtyFourth),i=e.voice.bar.staff;if(i.tuning.length>0)for(const e of i.tuning)this._handler.addNote(i.track.index,t,s,e,z.dynamicToVelocity(g.F),i.track.playbackInfo.primaryChannel)}needsSecondaryChannel(e){return e.hasBend||e.beat.hasWhammyBar||e.beat.vibrato!==P.None}determineChannel(e,t){if(this.needsSecondaryChannel(t))return e.playbackInfo.secondaryChannel;let s=t;for(;s.isTieDestination;)if(s=s.tieOrigin,this.needsSecondaryChannel(s))return e.playbackInfo.secondaryChannel;for(s=t;s.isTieOrigin;)if(s=s.tieDestination,this.needsSecondaryChannel(s))return e.playbackInfo.secondaryChannel;return e.playbackInfo.primaryChannel}generateNote(e,t,s,i,a,r){const n=e.beat.voice.bar.staff.track,o=e.beat.voice.bar.staff;let h=e.calculateRealValue(this.applyTranspositionPitches,!0);if(e.isPercussion){const t=Le.getArticulation(e);t&&(h=t.outputMidiNumber)}const l=null==r&&e.isStringed&&e.string<=a.length?a[e.string-1]:0,c=t+l,d=this.getNoteDuration(e,s,i);d.untilTieOrSlideEnd-=l,d.noteOnly-=l,d.letRingEnd-=l;const u=wr.getNoteVelocity(e),p=this.determineChannel(n,e);let g=0;const m=Math.max(d.untilTieOrSlideEnd,d.letRingEnd);g=e.hasBend?wr.getPitchWheel(e.bendPoints[0].value):e.beat.hasWhammyBar?wr.getPitchWheel(e.beat.whammyBarPoints[0].value):e.isTieDestination||e.slideOrigin&&e.slideOrigin.slideOutType===v.Legato?-1:wr.getPitchWheel(0),g>=0&&this._handler.addNoteBend(n.index,c,p,h,g),e.beat.hasRasgueado?this.generateRasgueado(n,e,c,h,u,p,r):e.ornament===he.None?!e.isTrill||o.isPercussion?e.beat.isTremolo?this.generateTremoloPicking(e,c,d,h,u,p):(e.hasBend?this.generateBend(e,c,d,h,p,i):e.beat.hasWhammyBar&&0===e.index?this.generateWhammy(e.beat,c,d,p,i):e.slideInType!==x.None||e.slideOutType!==v.None?this.generateSlide(e,c,d,h,p,i):(e.vibrato!==P.None||e.isTieDestination&&e.tieOrigin.vibrato!==P.None)&&this.generateVibrato(e,c,d,h,p),e.isTieDestination||e.slideOrigin&&e.slideOrigin.slideOutType===v.Legato||this._handler.addNote(n.index,c,m,h,u,p)):this.generateTrill(e,c,d,h,u,p):this.generateOrnament(n,e,c,m,h,u,p)}generateOrnament(e,t,s,i,a,r,n){let o,h;const l=a%12,c=1/3;switch(t.ornament){case he.Turn:o=[a+wr.OrnamentKeysUp[l],a,a+wr.OrnamentKeysDown[l]],h=[z.toTicks(_.Sixteenth)*c,z.toTicks(_.Sixteenth)*c,z.toTicks(_.Sixteenth)*c];break;case he.InvertedTurn:o=[a+wr.OrnamentKeysDown[l],a,a+wr.OrnamentKeysUp[l]],h=[z.toTicks(_.Sixteenth)*c,z.toTicks(_.Sixteenth)*c,z.toTicks(_.Sixteenth)*c];break;case he.UpperMordent:o=[a,a+wr.OrnamentKeysUp[l]],h=[z.toTicks(_.ThirtySecond),z.toTicks(_.ThirtySecond)];break;case he.LowerMordent:o=[a,a+wr.OrnamentKeysDown[l]],h=[z.toTicks(_.ThirtySecond),z.toTicks(_.ThirtySecond)];break;default:return}let d=1;i<z.QuarterTime&&(d=i/z.QuarterTime),r-=z.VelocityIncrement;let u=0;for(let t=0;t<o.length;t++){const i=h[t]*d;this._handler.addNote(e.index,s,i,o[t],r,n),s+=i,u+=i}const p=i-u;this._handler.addNote(e.index,s,p,a,r,n)}getNoteDuration(e,t,s){const i=new br;if(i.noteOnly=t,i.untilTieOrSlideEnd=t,i.letRingEnd=t,e.isDead)return i.noteOnly=this.applyStaticDuration(wr.DefaultDurationDead,t,s),i.untilTieOrSlideEnd=i.noteOnly,i.letRingEnd=i.noteOnly,i;if(e.isPalmMute)return i.noteOnly=this.applyStaticDuration(wr.DefaultDurationPalmMute,t,s),i.untilTieOrSlideEnd=i.noteOnly,i.letRingEnd=i.noteOnly,i;if(e.isStaccato)return i.noteOnly=t/2|0,i.untilTieOrSlideEnd=i.noteOnly,i.letRingEnd=i.noteOnly,i;if(e.isTieOrigin){const a=e.tieDestination;if(a)if(e.isTieDestination){const e=this.getNoteDuration(a,a.beat.playbackDuration,s);i.untilTieOrSlideEnd=t+e.untilTieOrSlideEnd}else{const t=e.beat.absolutePlaybackStart,r=this.getNoteDuration(a,a.beat.playbackDuration,s),n=a.beat.absolutePlaybackStart+r.untilTieOrSlideEnd;i.untilTieOrSlideEnd=n-t}}else if(e.slideOutType===v.Legato){const t=e.slideTarget;if(t){const a=e.beat.absolutePlaybackStart,r=this.getNoteDuration(t,t.beat.playbackDuration,s),n=t.beat.absolutePlaybackStart+r.untilTieOrSlideEnd;i.untilTieOrSlideEnd=n-a}}if(e.isLetRing&&this._settings.notation.notationMode===D.GuitarPro){let s=e.beat,a=0;const r=e.beat.voice.bar.masterBar.calculateDuration();for(;s.nextBeat;){const t=s.nextBeat;if(t.isRest)break;if(e.isStringed&&t.hasNoteOnString(e.string))break;if(s=s.nextBeat,a=s.absolutePlaybackStart-e.beat.absolutePlaybackStart+s.playbackDuration,a>r){a=r;break}}s===e.beat?i.letRingEnd=t:i.letRingEnd=a}else i.letRingEnd=i.untilTieOrSlideEnd;return i}applyStaticDuration(e,t,s){const i=s*e/X.MaxPosition|0;return Math.min(i,t)}static getNoteVelocity(e){let t=0;switch(!e.beat.voice.bar.staff.isPercussion&&e.hammerPullOrigin&&t--,e.isGhost&&t--,e.accentuated){case B.Normal:t++;break;case B.Heavy:t+=2}return z.dynamicToVelocity(e.dynamics,t)}generateFade(e,t,s){const i=e.voice.bar.staff.track;switch(e.fade){case ue.FadeIn:this.generateFadeSteps(i,t,s,0,wr.toChannelShort(i.playbackInfo.volume));break;case ue.FadeOut:this.generateFadeSteps(i,t,s,wr.toChannelShort(i.playbackInfo.volume),0);break;case ue.VolumeSwell:const e=s/2|0;this.generateFadeSteps(i,t,e,0,wr.toChannelShort(i.playbackInfo.volume)),this.generateFadeSteps(i,t+e,e,wr.toChannelShort(i.playbackInfo.volume),0)}}generateFadeSteps(e,t,s,i,a){const r=(a-i)/(s=.8*s|0),n=s/120+1|0,o=t+s;for(let s=0;s<n;s++){const h=s===n-1,l=h?o:t+120*s,c=h?a:Math.round(i+(l-t)*r);this._handler.addControlChange(e.index,l,e.playbackInfo.primaryChannel,Xt.VolumeCoarse,c),this._handler.addControlChange(e.index,l,e.playbackInfo.secondaryChannel,Xt.VolumeCoarse,c)}}generateVibrato(e,t,s,i,a){let r=0,n=0;switch(e.vibrato!==P.None?e.vibrato:e.isTieDestination?e.tieOrigin.vibrato:P.Slight){case P.Slight:r=this._settings.player.vibrato.noteSlightLength,n=this._settings.player.vibrato.noteSlightAmplitude;break;case P.Wide:r=this._settings.player.vibrato.noteWideLength,n=this._settings.player.vibrato.noteWideAmplitude;break;default:return}const o=e.beat.voice.bar.staff.track;let h=0;if(e.isTieDestination&&e.tieOrigin.hasBend){const t=e.tieOrigin.bendPoints;h=t[t.length-1].value}this.generateVibratorWithParams(t,s.noteOnly,r,h,n,((e,t)=>{this._handler.addNoteBend(o.index,e,a,i,t)}))}generateVibratorWithParams(e,t,s,i,a,r){const n=this.vibratoResolution,o=s/2|0,h=e+t;for(;e<h;){let t=0;const l=e+s<h?s:h-e;for(;t<l;){const s=i+a*Math.sin(t*Math.PI/o);r(e+t|0,wr.getPitchWheel(s)),t+=n}e+=s}r(0|h,wr.getPitchWheel(i))}static getPitchWheel(e){return K.DefaultPitchWheel+e/2*wr.PitchValuePerSemitone}generateSlide(e,t,s,i,a,r){const n=e.slideOutType===v.Legato?s.noteOnly:s.untilTieOrSlideEnd,o=[],h=e.beat.voice.bar.staff.track,l=this._settings.player.slide.simpleSlidePitchOffset,c=Math.floor(X.MaxPosition*this._settings.player.slide.simpleSlideDurationRatio),d=Math.floor(X.MaxPosition*this._settings.player.slide.shiftSlideDurationRatio);switch(e.slideInType){case x.IntoFromAbove:o.push(new X(0,l)),o.push(new X(c,0));break;case x.IntoFromBelow:o.push(new X(0,-l)),o.push(new X(c,0))}switch(e.slideOutType){case v.Legato:case v.Shift:o.push(new X(d,0));const t=2*(e.slideTarget.calculateRealValue(this.applyTranspositionPitches,!0)-e.calculateRealValue(this.applyTranspositionPitches,!0));o.push(new X(X.MaxPosition,t));break;case v.OutDown:o.push(new X(X.MaxPosition-c,0)),o.push(new X(X.MaxPosition,-l));break;case v.OutUp:o.push(new X(X.MaxPosition-c,0)),o.push(new X(X.MaxPosition,l))}this.generateWhammyOrBend(t,n,o,r,((e,t)=>{this._handler.addNoteBend(h.index,e,a,i,t)}))}generateBend(e,t,s,i,a,r){const n=e.bendPoints,o=e.beat.voice.bar.staff.track,h=(e,t)=>{this._handler.addNoteBend(o.index,e,a,i,t)};let l,c=null;if(e.isTieOrigin&&this._settings.notation.extendBendArrowsOnTiedNotes){let t=e;for(;t.isTieOrigin&&!t.tieDestination.hasBend&&t.tieDestination.vibrato===P.None;)t=t.tieDestination;l=t.beat.absolutePlaybackStart-e.beat.absolutePlaybackStart+this.getNoteDuration(t,t.beat.playbackDuration,r).noteOnly}else if(e.isTieOrigin&&e.beat.graceType!==w.None){switch(e.tieDestination.bendType){case y.Bend:case y.BendRelease:case y.PrebendBend:c=e.tieDestination.bendPoints[1].value;break;case y.Prebend:case y.PrebendRelease:c=e.tieDestination.bendPoints[0].value}l=Math.max(s.noteOnly,z.millisToTicks(this._settings.player.songBookBendDuration,r))}else l=s.noteOnly;n[0].value>0&&!e.isContinuedBend&&t>0&&t--;const d=Math.min(l,z.millisToTicks(this._settings.player.songBookBendDuration,r));let u=[];switch(e.bendType){case y.Custom:u=n;break;case y.Bend:case y.Release:switch(e.bendStyle){case f.Default:u=n;break;case f.Gradual:u.push(new X(0,e.bendPoints[0].value)),(!c||c<e.bendPoints[1].value)&&(c=e.bendPoints[1].value),u.push(new X(X.MaxPosition,c));break;case f.Fast:return(!c||c<e.bendPoints[1].value)&&(c=e.bendPoints[1].value),void(e.beat.graceType===w.BendGrace?this.generateSongBookWhammyOrBend(t,l,!0,[e.bendPoints[0].value,c],d,r,h):this.generateSongBookWhammyOrBend(t,l,!1,[e.bendPoints[0].value,c],d,r,h))}break;case y.BendRelease:switch(e.bendStyle){case f.Default:u=n;break;case f.Gradual:u.push(new X(0,e.bendPoints[0].value)),u.push(new X(X.MaxPosition/2|0,e.bendPoints[1].value)),u.push(new X(X.MaxPosition,e.bendPoints[2].value));break;case f.Fast:return void this.generateSongBookWhammyOrBend(t,l,!1,[e.bendPoints[0].value,e.bendPoints[1].value,e.bendPoints[2].value],d,r,h)}break;case y.Hold:case y.Prebend:u=n;break;case y.PrebendBend:switch(e.bendStyle){case f.Default:u=n;break;case f.Gradual:u.push(new X(0,e.bendPoints[0].value)),u.push(new X(X.MaxPosition,e.bendPoints[1].value));break;case f.Fast:return h(t,0|wr.getPitchWheel(e.bendPoints[0].value)),(!c||c<e.bendPoints[1].value)&&(c=e.bendPoints[1].value),void this.generateSongBookWhammyOrBend(t,l,!1,[e.bendPoints[0].value,c],d,r,h)}break;case y.PrebendRelease:switch(e.bendStyle){case f.Default:u=n;break;case f.Gradual:u.push(new X(0,e.bendPoints[0].value)),u.push(new X(X.MaxPosition,e.bendPoints[1].value));break;case f.Fast:return h(t,0|wr.getPitchWheel(e.bendPoints[0].value)),void this.generateSongBookWhammyOrBend(t,l,!1,[e.bendPoints[0].value,e.bendPoints[1].value],d,r,h)}}this.generateWhammyOrBend(t,l,u,r,h)}generateSongBookWhammyOrBend(e,t,s,i,a,r,n){const o=s?e:e+t-a,h=a/(i.length-1);for(let e=0;e<i.length-1;e++){const t=wr.getPitchWheel(i[e]),s=wr.getPitchWheel(i[e+1]),a=o+h*e;this.generateBendValues(a,h,t,s,r,n)}}generateWhammy(e,t,s,i,a){const r=e.whammyBarPoints,n=e.voice.bar.staff.track,o=s.noteOnly;r[0].value>0&&!e.isContinuedWhammy&&t--;const h=(e,t)=>{this._handler.addBend(n.index,e,i,t)};let l=[];switch(e.whammyBarType){case ce.Custom:l=r;break;case ce.Dive:switch(e.whammyStyle){case f.Default:l=r;break;case f.Gradual:l.push(new X(0,r[0].value)),l.push(new X(X.MaxPosition,r[1].value));break;case f.Fast:const e=Math.min(o,z.millisToTicks(this._settings.player.songBookBendDuration,a));return void this.generateSongBookWhammyOrBend(t,o,!1,[r[0].value,r[1].value],e,a,h)}break;case ce.Dip:switch(e.whammyStyle){case f.Default:l=r;break;case f.Gradual:l.push(new X(0,r[0].value)),l.push(new X(X.MaxPosition/2|0,r[1].value)),l.push(new X(X.MaxPosition,r[2].value));break;case f.Fast:const e=Math.min(o,z.millisToTicks(this._settings.player.songBookDipDuration,a));return void this.generateSongBookWhammyOrBend(t,o,!0,[r[0].value,r[1].value,r[2].value],e,a,h)}break;case ce.Hold:case ce.Predive:l=r;break;case ce.PrediveDive:switch(e.whammyStyle){case f.Default:l=r;break;case f.Gradual:l.push(new X(0,r[0].value)),l.push(new X(X.MaxPosition/2|0,r[0].value)),l.push(new X(X.MaxPosition,r[1].value));break;case f.Fast:const e=wr.getPitchWheel(r[0].value);this._handler.addBend(n.index,t,i,0|e);const s=Math.min(o,z.millisToTicks(this._settings.player.songBookBendDuration,a));return void this.generateSongBookWhammyOrBend(t,o,!1,[r[0].value,r[1].value],s,a,h)}}this.generateWhammyOrBend(t,o,l,a,h)}generateWhammyOrBend(e,t,s,i,a){const r=t/X.MaxPosition;for(let t=0;t<s.length-1;t++){const n=s[t],o=s[t+1],h=wr.getPitchWheel(n.value),l=wr.getPitchWheel(o.value),c=r*(o.offset-n.offset),d=e+r*n.offset;this.generateBendValues(d,c,h,l,i,a)}}generateBendValues(e,t,s,i,a,r){const n=z.ticksToMillis(t,a),o=Math.abs(i-s)/wr.PitchValuePerSemitone,h=Math.max(wr.MinBreakpointsPerSemitone*o,n/wr.MillisecondsPerBreakpoint),l=t/h,c=(i-s)/h,d=e+t;for(let t=0;t<h;t++)r(0|e,Math.round(s)),s+=c,e+=l;r(0|d,i)}generateRasgueado(e,t,s,i,a,r,n){let o=s;for(let s=0;s<n.durations.length;s++){const h=n.brushInfos[s],l=t.isStringed&&t.string<=h.length?h[t.string-1]:0,c=n.durations[s];this._handler.addNote(e.index,o+l,c-l,i,a,r),o+=c}}generateTrill(e,t,s,i,a,r){const n=e.beat.voice.bar.staff.track,o=e.stringTuning+e.trillFret;let h=z.toTicks(e.trillSpeed),l=!0,c=t;const d=t+s.untilTieOrSlideEnd;for(;c+10<d;)c+h>=d&&(h=d-c),this._handler.addNote(n.index,c,h,l?o:i,a,r),l=!l,c+=h}generateTremoloPicking(e,t,s,i,a,r){const n=e.beat.voice.bar.staff.track;let o=z.toTicks(e.beat.tremoloSpeed),h=t;const l=t+s.untilTieOrSlideEnd;for(;h+10<l;)h+o>=l&&(o=l-h),this._handler.addNote(n.index,h,o,i,a,r),h+=o}getRasgueadoInfo(e,t){if(!e.hasRasgueado)return null;const s=new _r,i=wr.RasgueadoDurations.get(e.rasgueado).reduce(((e,t)=>e+t),0);s.durations=wr.RasgueadoDurations.get(e.rasgueado).map((e=>t*e/i)),s.brushInfos=new Array(s.durations.length);const a=z.toTicks(_.Sixteenth);let r=0,n=0;for(const t of e.notes)t.isTieDestination||(r|=1<<t.string-1,n++);const o=wr.RasgueadoDirections.get(e.rasgueado);for(let t=0;t<s.durations.length;t++){const i=s.durations[t]*a/z.QuarterTime,h=new Int32Array(e.voice.bar.staff.tuning.length);s.brushInfos[t]=h;const l=o[t];l!==b.None&&this.fillBrushInfo(e,h,l===b.ArpeggioDown||l===b.BrushDown,r,n,i)}return s}getBrushInfo(e){const t=new Int32Array(e.voice.bar.staff.tuning.length);if(e.brushType){let s=0,i=0;for(const t of e.notes)t.isTieDestination||(s|=1<<t.string-1,i++);this.fillBrushInfo(e,t,e.brushType===b.ArpeggioDown||e.brushType===b.BrushDown,s,i,e.brushDuration)}return t}fillBrushInfo(e,t,s,i,a,r){if(e.notes.length>0){let n=0;const o=r/(a-1)|0;for(let a=0;a<e.voice.bar.staff.tuning.length;a++){const e=s?a:t.length-1-a;i&1<<e&&(t[e]=n,n+=o)}}return t}generateNonTempoAutomation(e,t,s){switch(t.type){case m.Instrument:this.addProgramChange(e.voice.bar.staff.track,e.playbackStart+s,e.voice.bar.staff.track.playbackInfo.primaryChannel,255&t.value),this.addProgramChange(e.voice.bar.staff.track,e.playbackStart+s,e.voice.bar.staff.track.playbackInfo.secondaryChannel,255&t.value);break;case m.Balance:const i=wr.toChannelShort(t.value);this._handler.addControlChange(e.voice.bar.staff.track.index,e.playbackStart+s,e.voice.bar.staff.track.playbackInfo.primaryChannel,Xt.PanCoarse,i),this._handler.addControlChange(e.voice.bar.staff.track.index,e.playbackStart+s,e.voice.bar.staff.track.playbackInfo.secondaryChannel,Xt.PanCoarse,i);break;case m.Volume:const a=wr.toChannelShort(t.value);this._handler.addControlChange(e.voice.bar.staff.track.index,e.playbackStart+s,e.voice.bar.staff.track.playbackInfo.primaryChannel,Xt.VolumeCoarse,a),this._handler.addControlChange(e.voice.bar.staff.track.index,e.playbackStart+s,e.voice.bar.staff.track.playbackInfo.secondaryChannel,Xt.VolumeCoarse,a)}}prepareSingleBeat(e){let t=-1,s=-1,i=e;for(;i&&(-1===t||-1===s);){for(const i of e.automations)switch(i.type){case m.Instrument:s=i.value;break;case m.Tempo:t=i.value}i=i.previousBeat}const a=e.voice.bar.staff.track,r=e.voice.bar.masterBar;-1===t&&(t=r.score.tempo);const n=e.playbackStart/r.calculateDuration();for(const e of r.tempoAutomations){if(!(e.ratioPosition<=n))break;t=e.value}-1===s&&(s=a.playbackInfo.program);const o=a.playbackInfo.volume;this.generateTrack(a),this._handler.addTimeSignature(0,r.timeSignatureNumerator,r.timeSignatureDenominator),this._handler.addTempo(0,t);const h=wr.toChannelShort(o);return this._handler.addControlChange(0,0,a.playbackInfo.primaryChannel,Xt.VolumeCoarse,h),this._handler.addControlChange(0,0,a.playbackInfo.secondaryChannel,Xt.VolumeCoarse,h),t}generateSingleBeat(e){const t=this.prepareSingleBeat(e);this.generateBeat(e,-e.playbackStart,e.voice.bar,t)}generateSingleNote(e){const t=this.prepareSingleBeat(e.beat);this.generateNote(e,0,e.beat.playbackDuration,t,new Int32Array(e.beat.voice.bar.staff.tuning.length),null)}}wr.DefaultDurationDead=30,wr.DefaultDurationPalmMute=80,wr.OrnamentKeysUp=[2,2,2,1,1,2,2,2,2,2,1,1],wr.OrnamentKeysDown=[-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1],wr.PitchBendRangeInSemitones=16,wr.PitchValuePerSemitone=K.DefaultPitchWheel/wr.PitchBendRangeInSemitones,wr.MinBreakpointsPerSemitone=6,wr.MillisecondsPerBreakpoint=150,wr.RasgueadoDirections=new Map([[me.Ii,[b.BrushDown,b.BrushUp]],[me.Mi,[b.BrushDown,b.BrushDown]],[me.MiiTriplet,[b.BrushDown,b.BrushDown,b.BrushUp]],[me.MiiAnapaest,[b.BrushDown,b.BrushDown,b.BrushUp]],[me.PmpTriplet,[b.BrushUp,b.BrushDown,b.BrushDown]],[me.PmpAnapaest,[b.BrushUp,b.BrushDown,b.BrushDown]],[me.PeiTriplet,[b.BrushUp,b.BrushDown,b.BrushDown]],[me.PeiAnapaest,[b.BrushUp,b.BrushDown,b.BrushDown]],[me.PaiTriplet,[b.BrushUp,b.BrushDown,b.BrushDown]],[me.PaiAnapaest,[b.BrushUp,b.BrushDown,b.BrushDown]],[me.AmiTriplet,[b.BrushDown,b.BrushDown,b.BrushDown]],[me.AmiAnapaest,[b.BrushDown,b.BrushDown,b.BrushDown]],[me.Ppp,[b.None,b.BrushDown,b.BrushUp]],[me.Amii,[b.BrushDown,b.BrushDown,b.BrushDown,b.BrushUp]],[me.Amip,[b.BrushDown,b.BrushDown,b.BrushDown,b.BrushUp]],[me.Eami,[b.BrushDown,b.BrushDown,b.BrushDown,b.BrushDown]],[me.Eamii,[b.BrushDown,b.BrushDown,b.BrushDown,b.BrushDown,b.BrushUp]],[me.Peami,[b.BrushDown,b.BrushDown,b.BrushDown,b.BrushDown,b.BrushUp]]]),wr.RasgueadoDurations=new Map([[me.Ii,[z.toTicks(_.Eighth),z.toTicks(_.Eighth)]],[me.Mi,[z.toTicks(_.Eighth),z.toTicks(_.Eighth)]],[me.MiiTriplet,[z.toTicks(_.Eighth)/3,z.toTicks(_.Eighth)/3,z.toTicks(_.Eighth)/3]],[me.MiiAnapaest,[z.toTicks(_.Sixteenth),z.toTicks(_.Sixteenth),z.toTicks(_.Eighth)]],[me.PmpTriplet,[z.toTicks(_.Eighth)/3,z.toTicks(_.Eighth)/3,z.toTicks(_.Eighth)/3]],[me.PmpAnapaest,[z.toTicks(_.Sixteenth)/3,z.toTicks(_.Sixteenth)/3,z.toTicks(_.Eighth)/3]],[me.PeiTriplet,[z.toTicks(_.Eighth)/3,z.toTicks(_.Eighth)/3,z.toTicks(_.Eighth)/3]],[me.PeiAnapaest,[z.toTicks(_.Sixteenth),z.toTicks(_.Sixteenth),z.toTicks(_.Eighth)]],[me.PaiTriplet,[z.toTicks(_.Eighth)/3,z.toTicks(_.Eighth)/3,z.toTicks(_.Eighth)/3]],[me.PaiAnapaest,[z.toTicks(_.Sixteenth),z.toTicks(_.Sixteenth),z.toTicks(_.Eighth)]],[me.AmiTriplet,[z.toTicks(_.Eighth)/3,z.toTicks(_.Eighth)/3,z.toTicks(_.Eighth)/3]],[me.AmiAnapaest,[z.toTicks(_.Sixteenth)/3,z.toTicks(_.Sixteenth)/3,z.toTicks(_.Eighth)/3]],[me.Ppp,[z.toTicks(_.Sixteenth)/3,z.toTicks(_.Sixteenth)/3,z.toTicks(_.Eighth)/3]],[me.Amii,[z.toTicks(_.Sixteenth)/3,z.toTicks(_.Sixteenth)/3,z.toTicks(_.Sixteenth)/3,z.toTicks(_.Eighth)]],[me.Amip,[z.toTicks(_.Sixteenth)/3,z.toTicks(_.Sixteenth)/3,z.toTicks(_.Sixteenth)/3,z.toTicks(_.Eighth)]],[me.Eami,[z.toTicks(_.Sixteenth),z.toTicks(_.Sixteenth),z.toTicks(_.Sixteenth),z.toTicks(_.Sixteenth)]],[me.Eamii,[z.toTicks(_.Sixteenth)/5,z.toTicks(_.Sixteenth)/5,z.toTicks(_.Sixteenth)/5,z.toTicks(_.Sixteenth)/5,z.toTicks(_.Sixteenth)/5]],[me.Peami,[z.toTicks(_.Sixteenth)/5,z.toTicks(_.Sixteenth)/5,z.toTicks(_.Sixteenth)/5,z.toTicks(_.Sixteenth)/5,z.toTicks(_.Sixteenth)/5]]]);class Br{constructor(){this.startTick=0,this.endTick=0}}class kr{constructor(e,t){this.width=0,this.height=0,this.x=e,this.y=t}doLayout(){}paint(e,t,s){}}class Tr extends kr{constructor(e=0,t=0){super(e,t),this.beat=null,this.nextGlyph=null,this.previousGlyph=null}}class Nr{}Nr.Widths=new Map([[re.Brace,3],[re.BracketTop,0],[re.BracketBottom,0],[re.SystemDivider,0],[re.GClef,28],[re.CClef,28],[re.FClef,28],[re.UnpitchedPercussionClef1,15],[re.SixStringTabClef,28],[re.FourStringTabClef,28],[re.TimeSig0,14],[re.TimeSig1,10],[re.TimeSig2,14],[re.TimeSig3,14],[re.TimeSig4,14],[re.TimeSig5,14],[re.TimeSig6,14],[re.TimeSig7,14],[re.TimeSig8,14],[re.TimeSig9,14],[re.TimeSigCommon,14],[re.TimeSigCutCommon,14],[re.NoteheadDoubleWholeSquare,14],[re.NoteheadDoubleWhole,14],[re.NoteheadWhole,14],[re.NoteheadHalf,9],[re.NoteheadBlack,9],[re.NoteheadNull,9],[re.NoteheadXOrnate,9],[re.NoteheadPlusDoubleWhole,16],[re.NoteheadPlusWhole,10],[re.NoteheadPlusHalf,10],[re.NoteheadPlusBlack,10],[re.NoteheadSquareWhite,11],[re.NoteheadSquareBlack,11],[re.NoteheadTriangleUpDoubleWhole,16],[re.NoteheadTriangleUpWhole,11],[re.NoteheadTriangleUpHalf,11],[re.NoteheadTriangleUpBlack,11],[re.NoteheadTriangleRightWhite,11],[re.NoteheadTriangleRightBlack,11],[re.NoteheadTriangleDownDoubleWhole,16],[re.NoteheadTriangleDownWhole,11],[re.NoteheadTriangleDownHalf,11],[re.NoteheadTriangleDownBlack,11],[re.NoteheadDiamondDoubleWhole,16],[re.NoteheadDiamondWhole,9],[re.NoteheadDiamondHalf,9],[re.NoteheadDiamondBlack,9],[re.NoteheadDiamondBlackWide,10],[re.NoteheadDiamondWhite,9],[re.NoteheadDiamondWhiteWide,9],[re.NoteheadCircleXDoubleWhole,16],[re.NoteheadCircleXWhole,9],[re.NoteheadCircleXHalf,9],[re.NoteheadCircleX,9],[re.NoteheadXDoubleWhole,16],[re.NoteheadXWhole,9],[re.NoteheadXHalf,9],[re.NoteheadXBlack,9],[re.NoteheadParenthesis,9],[re.NoteheadSlashedBlack1,9],[re.NoteheadSlashedBlack2,9],[re.NoteheadSlashedHalf1,9],[re.NoteheadSlashedHalf2,9],[re.NoteheadSlashedWhole1,9],[re.NoteheadSlashedWhole2,9],[re.NoteheadSlashedDoubleWhole1,16],[re.NoteheadSlashedDoubleWhole2,16],[re.NoteheadCircledBlack,9],[re.NoteheadCircledHalf,9],[re.NoteheadCircledWhole,9],[re.NoteheadCircledDoubleWhole,16],[re.NoteheadCircleSlash,9],[re.NoteheadHeavyX,13],[re.NoteheadHeavyXHat,13],[re.NoteheadSlashVerticalEnds,12],[re.NoteheadSlashWhiteWhole,32],[re.NoteheadSlashWhiteHalf,25],[re.NoteheadRoundWhiteWithDot,9],[re.NoteheadSquareBlackLarge,9],[re.NoteheadSquareBlackWhite,9],[re.NoteheadClusterDoubleWhole3rd,16],[re.NoteheadClusterWhole3rd,12],[re.NoteheadClusterHalf3rd,12],[re.NoteheadClusterQuarter3rd,12],[re.NoteShapeRoundWhite,9],[re.NoteShapeRoundBlack,9],[re.NoteShapeSquareWhite,12],[re.NoteShapeSquareBlack,12],[re.NoteShapeTriangleRightWhite,12],[re.NoteShapeTriangleRightBlack,12],[re.NoteShapeTriangleLeftWhite,12],[re.NoteShapeTriangleLeftBlack,12],[re.NoteShapeDiamondWhite,9],[re.NoteShapeDiamondBlack,9],[re.NoteShapeTriangleUpWhite,12],[re.NoteShapeTriangleUpBlack,12],[re.NoteShapeMoonWhite,12],[re.NoteShapeMoonBlack,12],[re.NoteShapeTriangleRoundWhite,12],[re.NoteShapeTriangleRoundBlack,12],[re.NoteQuarterUp,10],[re.NoteEighthUp,10],[re.TextBlackNoteLongStem,0],[re.TextBlackNoteFrac8thLongStem,0],[re.TextBlackNoteFrac16thLongStem,0],[re.TextBlackNoteFrac32ndLongStem,0],[re.TextCont8thBeamLongStem,0],[re.TextCont16thBeamLongStem,0],[re.TextCont32ndBeamLongStem,0],[re.TextAugmentationDot,0],[re.TextTupletBracketStartLongStem,0],[re.TextTuplet3LongStem,0],[re.TextTupletBracketEndLongStem,0],[re.Tremolo3,12],[re.Tremolo2,12],[re.Tremolo1,12],[re.FlagEighthUp,0],[re.FlagEighthDown,0],[re.FlagSixteenthUp,0],[re.FlagSixteenthDown,0],[re.FlagThirtySecondUp,0],[re.FlagThirtySecondDown,0],[re.FlagSixtyFourthUp,0],[re.FlagSixtyFourthDown,0],[re.FlagOneHundredTwentyEighthUp,0],[re.FlagOneHundredTwentyEighthDown,0],[re.FlagTwoHundredFiftySixthUp,0],[re.FlagTwoHundredFiftySixthDown,0],[re.AccidentalFlat,8],[re.AccidentalNatural,8],[re.AccidentalSharp,8],[re.AccidentalDoubleSharp,8],[re.AccidentalDoubleFlat,18],[re.AccidentalQuarterToneFlatArrowUp,8],[re.AccidentalQuarterToneSharpArrowUp,8],[re.AccidentalQuarterToneNaturalArrowUp,8],[re.Segno,0],[re.Coda,0],[re.ArticAccentAbove,9],[re.ArticAccentBelow,9],[re.ArticStaccatoAbove,9],[re.ArticStaccatoBelow,9],[re.ArticTenutoAbove,9],[re.ArticTenutoBelow,9],[re.ArticMarcatoAbove,9],[re.ArticMarcatoBelow,9],[re.FermataAbove,23],[re.FermataShortAbove,23],[re.FermataLongAbove,23],[re.RestLonga,9],[re.RestDoubleWhole,9],[re.RestWhole,9],[re.RestHalf,9],[re.RestQuarter,9],[re.RestEighth,9],[re.RestSixteenth,9],[re.RestThirtySecond,12],[re.RestSixtyFourth,14],[re.RestOneHundredTwentyEighth,14],[re.RestTwoHundredFiftySixth,14],[re.RestHBarLeft,0],[re.RestHBarMiddle,0],[re.RestHBarRight,0],[re.Repeat1Bar,0],[re.Repeat2Bars,0],[re.Ottava,0],[re.OttavaAlta,32],[re.OttavaBassaVb,29],[re.Quindicesima,23],[re.QuindicesimaAlta,46],[re.DynamicPPPPPP,0],[re.DynamicPPPPP,0],[re.DynamicPPPP,0],[re.DynamicPPP,0],[re.DynamicPP,0],[re.DynamicPiano,0],[re.DynamicMP,0],[re.DynamicMF,0],[re.DynamicPF,0],[re.DynamicForte,0],[re.DynamicFF,0],[re.DynamicFFF,0],[re.DynamicFFFF,0],[re.DynamicFFFFF,0],[re.DynamicFFFFFF,0],[re.DynamicFortePiano,0],[re.DynamicNiente,0],[re.DynamicSforzando1,0],[re.DynamicSforzandoPiano,0],[re.DynamicSforzandoPianissimo,0],[re.DynamicSforzato,0],[re.DynamicSforzatoPiano,0],[re.DynamicSforzatoFF,0],[re.DynamicRinforzando1,0],[re.DynamicRinforzando2,0],[re.DynamicForzando,0],[re.OrnamentTrill,20],[re.OrnamentTurn,26],[re.OrnamentTurnInverted,26],[re.OrnamentShortTrill,0],[re.OrnamentMordent,26],[re.StringsDownBow,9],[re.StringsUpBow,9],[re.KeyboardPedalPed,35],[re.KeyboardPedalUp,16],[re.PictEdgeOfCymbal,44],[re.GuitarString0,20],[re.GuitarString1,20],[re.GuitarString2,20],[re.GuitarString3,20],[re.GuitarString4,20],[re.GuitarString5,20],[re.GuitarString6,20],[re.GuitarString7,20],[re.GuitarString8,20],[re.GuitarString9,20],[re.GuitarOpenPedal,11],[re.GuitarClosePedal,11],[re.GuitarGolpe,13.4],[re.GuitarFadeIn,13],[re.GuitarFadeOut,13],[re.GuitarVolumeSwell,26],[re.FretboardX,0],[re.FretboardO,0],[re.WiggleTrill,9],[re.WiggleVibratoMediumFast,10],[re.OctaveBaselineM,13],[re.OctaveBaselineB,9]]),Nr.Heights=new Map([[re.Brace,34],[re.BracketTop,0],[re.BracketBottom,0],[re.SystemDivider,0],[re.GClef,0],[re.CClef,0],[re.FClef,0],[re.UnpitchedPercussionClef1,0],[re.SixStringTabClef,0],[re.FourStringTabClef,0],[re.TimeSig0,0],[re.TimeSig1,0],[re.TimeSig2,0],[re.TimeSig3,0],[re.TimeSig4,0],[re.TimeSig5,0],[re.TimeSig6,0],[re.TimeSig7,0],[re.TimeSig8,0],[re.TimeSig9,0],[re.TimeSigCommon,0],[re.TimeSigCutCommon,0],[re.NoteheadDoubleWholeSquare,8],[re.NoteheadDoubleWhole,8],[re.NoteheadWhole,8],[re.NoteheadHalf,8],[re.NoteheadBlack,8],[re.NoteheadNull,8],[re.NoteheadXOrnate,8],[re.NoteheadPlusDoubleWhole,8],[re.NoteheadPlusWhole,8],[re.NoteheadPlusHalf,8],[re.NoteheadPlusBlack,8],[re.NoteheadSquareWhite,8],[re.NoteheadSquareBlack,8],[re.NoteheadTriangleUpDoubleWhole,8],[re.NoteheadTriangleUpWhole,8],[re.NoteheadTriangleUpHalf,8],[re.NoteheadTriangleUpBlack,8],[re.NoteheadTriangleRightWhite,8],[re.NoteheadTriangleRightBlack,8],[re.NoteheadTriangleDownDoubleWhole,8],[re.NoteheadTriangleDownWhole,8],[re.NoteheadTriangleDownHalf,8],[re.NoteheadTriangleDownBlack,8],[re.NoteheadDiamondDoubleWhole,8],[re.NoteheadDiamondWhole,8],[re.NoteheadDiamondHalf,8],[re.NoteheadDiamondBlack,8],[re.NoteheadDiamondBlackWide,9],[re.NoteheadDiamondWhite,9],[re.NoteheadDiamondWhiteWide,9],[re.NoteheadCircleXDoubleWhole,8],[re.NoteheadCircleXWhole,8],[re.NoteheadCircleXHalf,8],[re.NoteheadCircleX,8],[re.NoteheadXDoubleWhole,8],[re.NoteheadXWhole,8],[re.NoteheadXHalf,8],[re.NoteheadXBlack,8],[re.NoteheadParenthesis,8],[re.NoteheadSlashedBlack1,8],[re.NoteheadSlashedBlack2,8],[re.NoteheadSlashedHalf1,8],[re.NoteheadSlashedHalf2,8],[re.NoteheadSlashedWhole1,8],[re.NoteheadSlashedWhole2,8],[re.NoteheadSlashedDoubleWhole1,8],[re.NoteheadSlashedDoubleWhole2,8],[re.NoteheadCircledBlack,8],[re.NoteheadCircledHalf,8],[re.NoteheadCircledWhole,8],[re.NoteheadCircledDoubleWhole,8],[re.NoteheadCircleSlash,8],[re.NoteheadHeavyX,8],[re.NoteheadHeavyXHat,8],[re.NoteheadSlashVerticalEnds,17],[re.NoteheadSlashWhiteWhole,17],[re.NoteheadSlashWhiteHalf,17],[re.NoteheadRoundWhiteWithDot,8],[re.NoteheadSquareBlackLarge,8],[re.NoteheadSquareBlackWhite,8],[re.NoteheadClusterDoubleWhole3rd,8],[re.NoteheadClusterWhole3rd,8],[re.NoteheadClusterHalf3rd,8],[re.NoteheadClusterQuarter3rd,8],[re.NoteShapeRoundWhite,8],[re.NoteShapeRoundBlack,8],[re.NoteShapeSquareWhite,8],[re.NoteShapeSquareBlack,8],[re.NoteShapeTriangleRightWhite,8],[re.NoteShapeTriangleRightBlack,8],[re.NoteShapeTriangleLeftWhite,8],[re.NoteShapeTriangleLeftBlack,8],[re.NoteShapeDiamondWhite,8],[re.NoteShapeDiamondBlack,8],[re.NoteShapeTriangleUpWhite,8],[re.NoteShapeTriangleUpBlack,8],[re.NoteShapeMoonWhite,8],[re.NoteShapeMoonBlack,8],[re.NoteShapeTriangleRoundWhite,8],[re.NoteShapeTriangleRoundBlack,8],[re.NoteQuarterUp,8],[re.NoteEighthUp,8],[re.TextBlackNoteLongStem,0],[re.TextBlackNoteFrac8thLongStem,0],[re.TextBlackNoteFrac16thLongStem,0],[re.TextBlackNoteFrac32ndLongStem,0],[re.TextCont8thBeamLongStem,0],[re.TextCont16thBeamLongStem,0],[re.TextCont32ndBeamLongStem,0],[re.TextAugmentationDot,0],[re.TextTupletBracketStartLongStem,0],[re.TextTuplet3LongStem,0],[re.TextTupletBracketEndLongStem,0],[re.Tremolo3,0],[re.Tremolo2,0],[re.Tremolo1,0],[re.FlagEighthUp,0],[re.FlagEighthDown,0],[re.FlagSixteenthUp,0],[re.FlagSixteenthDown,0],[re.FlagThirtySecondUp,0],[re.FlagThirtySecondDown,0],[re.FlagSixtyFourthUp,0],[re.FlagSixtyFourthDown,0],[re.FlagOneHundredTwentyEighthUp,0],[re.FlagOneHundredTwentyEighthDown,0],[re.FlagTwoHundredFiftySixthUp,0],[re.FlagTwoHundredFiftySixthDown,0],[re.AccidentalFlat,0],[re.AccidentalNatural,0],[re.AccidentalSharp,0],[re.AccidentalDoubleSharp,0],[re.AccidentalDoubleFlat,0],[re.AccidentalQuarterToneFlatArrowUp,0],[re.AccidentalQuarterToneSharpArrowUp,0],[re.AccidentalQuarterToneNaturalArrowUp,0],[re.Segno,0],[re.Coda,0],[re.ArticAccentAbove,9],[re.ArticAccentBelow,9],[re.ArticStaccatoAbove,9],[re.ArticStaccatoBelow,9],[re.ArticTenutoAbove,9],[re.ArticTenutoBelow,9],[re.ArticMarcatoAbove,9],[re.ArticMarcatoBelow,9],[re.FermataAbove,12],[re.FermataShortAbove,12],[re.FermataLongAbove,12],[re.RestLonga,0],[re.RestDoubleWhole,0],[re.RestWhole,0],[re.RestHalf,0],[re.RestQuarter,0],[re.RestEighth,0],[re.RestSixteenth,0],[re.RestThirtySecond,0],[re.RestSixtyFourth,0],[re.RestOneHundredTwentyEighth,0],[re.RestTwoHundredFiftySixth,0],[re.RestHBarLeft,0],[re.RestHBarMiddle,0],[re.RestHBarRight,0],[re.Repeat1Bar,0],[re.Repeat2Bars,0],[re.Ottava,13],[re.OttavaAlta,13],[re.OttavaBassaVb,13],[re.Quindicesima,13],[re.QuindicesimaAlta,13],[re.DynamicPPPPPP,28.4],[re.DynamicPPPPP,28.4],[re.DynamicPPPP,28.4],[re.DynamicPPP,28.4],[re.DynamicPP,28.4],[re.DynamicPiano,28.4],[re.DynamicMP,28.4],[re.DynamicMF,28.4],[re.DynamicPF,28.4],[re.DynamicForte,28.4],[re.DynamicFF,28.4],[re.DynamicFFF,28.4],[re.DynamicFFFF,28.4],[re.DynamicFFFFF,28.4],[re.DynamicFFFFFF,28.4],[re.DynamicFortePiano,28.4],[re.DynamicNiente,28.4],[re.DynamicSforzando1,28.4],[re.DynamicSforzandoPiano,28.4],[re.DynamicSforzandoPianissimo,28.4],[re.DynamicSforzato,28.4],[re.DynamicSforzatoPiano,28.4],[re.DynamicSforzatoFF,28.4],[re.DynamicRinforzando1,28.4],[re.DynamicRinforzando2,28.4],[re.DynamicForzando,28.4],[re.OrnamentTrill,24],[re.OrnamentTurn,18],[re.OrnamentTurnInverted,18],[re.OrnamentShortTrill,18],[re.OrnamentMordent,18],[re.StringsDownBow,13/.75],[re.StringsUpBow,13/.75],[re.KeyboardPedalPed,19],[re.KeyboardPedalUp,16],[re.PictEdgeOfCymbal,30],[re.GuitarString0,20],[re.GuitarString1,20],[re.GuitarString2,20],[re.GuitarString3,20],[re.GuitarString4,20],[re.GuitarString5,20],[re.GuitarString6,20],[re.GuitarString7,20],[re.GuitarString8,20],[re.GuitarString9,20],[re.GuitarOpenPedal,11],[re.GuitarClosePedal,11],[re.GuitarGolpe,13.4],[re.GuitarFadeIn,13],[re.GuitarFadeOut,13],[re.GuitarVolumeSwell,13],[re.FretboardX,0],[re.FretboardO,0],[re.WiggleTrill,6],[re.WiggleVibratoMediumFast,10],[re.OctaveBaselineM,0],[re.OctaveBaselineB,0]]);class xr extends Tr{constructor(e,t,s,i){super(e,t),this.glyphScale=0,this.center=!1,this.glyphScale=s,this.symbol=i}doLayout(){this.width=Nr.Widths.has(this.symbol)?Nr.Widths.get(this.symbol)*this.glyphScale:0,this.height=Nr.Heights.has(this.symbol)?Nr.Heights.get(this.symbol)*this.glyphScale:0}paint(e,t,s){const i=s.color;this.colorOverride&&(s.color=this.colorOverride),s.fillMusicFontSymbol(e+this.x,t+this.y,this.glyphScale,this.symbol,this.center),s.color=i}}class vr extends xr{constructor(e,t,s,i){super(e,t,i?vr.GraceScale:1,vr.getSymbol(s)),this.centerOnStem=!1,this._isGrace=i}paint(e,t,s){const i=this._isGrace?1:0;this.centerOnStem&&(this.center=!0),super.paint(e,t+i,s)}static getSymbol(e){switch(e){case _.QuadrupleWhole:return re.NoteheadDoubleWholeSquare;case _.DoubleWhole:return re.NoteheadDoubleWhole;case _.Whole:return re.NoteheadWhole;case _.Half:return re.NoteheadHalf;default:return re.NoteheadBlack}}}vr.GraceScale=.75;class Pr extends xr{constructor(e,t,s,i,a){super(e,t,a?vr.GraceScale:1,Pr.getSymbol(s,i,a))}static getSymbol(e,t,s){if(s&&(e=_.Eighth),t===Te.Up)switch(e){case _.Eighth:return re.FlagEighthUp;case _.Sixteenth:return re.FlagSixteenthUp;case _.ThirtySecond:return re.FlagThirtySecondUp;case _.SixtyFourth:return re.FlagSixtyFourthUp;case _.OneHundredTwentyEighth:return re.FlagOneHundredTwentyEighthUp;case _.TwoHundredFiftySixth:return re.FlagTwoHundredFiftySixthUp;default:return re.FlagEighthUp}switch(e){case _.Eighth:return re.FlagEighthDown;case _.Sixteenth:return re.FlagSixteenthDown;case _.ThirtySecond:return re.FlagThirtySecondDown;case _.SixtyFourth:return re.FlagSixtyFourthDown;case _.OneHundredTwentyEighth:case _.TwoHundredFiftySixth:return re.FlagOneHundredTwentyEighthDown;default:return re.FlagEighthDown}}}Pr.FlagWidth=11;class Fr extends kr{get onTimeX(){return this.onNotes.x+this.onNotes.centerX}constructor(e,t){super(0,0),this.ties=[],this.minWidth=0,this.beat=e,this.ties=[],this.voiceContainer=t}addTie(e){e.renderer=this.renderer,this.ties.push(e)}drawBeamHelperAsFlags(e){return e.hasFlag(!1,void 0)}registerLayoutingInfo(e){const t=this.preNotes.computedWidth+this.onNotes.centerX;let s=this.onNotes.computedWidth-this.onNotes.centerX;const i=this.renderer.helpers.getBeamingHelperForBeat(this.beat);this.beat.graceType!==w.None?1===this.beat.graceGroup.beats.length?s+=Pr.FlagWidth*vr.GraceScale:this.beat.graceIndex<this.beat.graceGroup.beats.length-1?s+=7:s+=Fr.GraceBeatPadding:i&&this.drawBeamHelperAsFlags(i)&&(s+=Pr.FlagWidth);for(const e of this.ties)s+=e.width;e.addBeatSpring(this.beat,t,s)}applyLayoutingInfo(e){this.onNotes.updateBeamingHelper(),this.updateWidth()}doLayout(){this.preNotes.x=0,this.preNotes.renderer=this.renderer,this.preNotes.container=this,this.preNotes.doLayout(),this.onNotes.x=this.preNotes.x+this.preNotes.width,this.onNotes.renderer=this.renderer,this.onNotes.container=this,this.onNotes.doLayout();let e=this.beat.notes.length-1;for(;e>=0;)this.createTies(this.beat.notes[e--]);this.renderer.registerTies(this.ties),this.updateWidth()}updateWidth(){if(this.minWidth=this.preNotes.width+this.onNotes.width,!this.beat.isRest)if(1===this.onNotes.beamingHelper.beats.length)this.beat.duration>=_.Eighth&&(this.minWidth+=20);else switch(this.beat.duration){case _.OneHundredTwentyEighth:case _.TwoHundredFiftySixth:this.minWidth+=10}let e=0;for(const t of this.ties)t.width>e&&(e=t.width);this.minWidth+=e,this.width=this.minWidth}scaleToWidth(e){this.onNotes.updateBeamingHelper(),this.width=e}createTies(e){}static getGroupId(e){return`b${e.id}`}paint(e,t,s){if(this.preNotes.isEmpty&&this.onNotes.isEmpty&&0===this.ties.length)return;s.beginGroup(Fr.getGroupId(this.beat)),this.preNotes.paint(e+this.x,t+this.y,s),this.onNotes.paint(e+this.x,t+this.y,s);const i=e-this.voiceContainer.x-this.renderer.x,a=t-this.voiceContainer.y-this.renderer.y;for(let e=0,t=this.ties.length;e<t;e++){const t=this.ties[e];t.renderer=this.renderer,t.paint(i,a,s)}s.endGroup()}buildBoundingsLookup(e,t,s,i){const a=new tr;if(a.beat=this.beat,this.beat.isEmpty)a.visualBounds=new mt,a.visualBounds.x=t+this.x,a.visualBounds.y=e.visualBounds.y,a.visualBounds.w=this.width,a.visualBounds.h=e.visualBounds.h,a.realBounds=new mt,a.realBounds.x=t+this.x,a.realBounds.y=e.realBounds.y,a.realBounds.w=this.width,a.realBounds.h=e.realBounds.h,a.onNotesX=t+this.x+this.onNotes.centerX;else{a.visualBounds=new mt,a.visualBounds.x=t+this.x,this.preNotes.isEmpty?this.onNotes.isEmpty?a.visualBounds.x=t+this.x:a.visualBounds.x=t+this.x+this.onNotes.x:a.visualBounds.x=t+this.x+this.preNotes.x;let s=0;s=this.onNotes.isEmpty?this.preNotes.isEmpty?t+this.x+this.width:t+this.x+this.preNotes.x+this.preNotes.width:t+this.x+this.onNotes.x+this.onNotes.width,a.visualBounds.w=s-a.visualBounds.x;const i=this.renderer.helpers.getBeamingHelperForBeat(this.beat);(i&&this.drawBeamHelperAsFlags(i)||this.beat.graceType!==w.None)&&(a.visualBounds.w+=Pr.FlagWidth*(this.beat.graceType!==w.None?vr.GraceScale:1)),a.visualBounds.y=e.visualBounds.y,a.visualBounds.h=e.visualBounds.h,a.realBounds=new mt,a.realBounds.x=t+this.x,a.realBounds.y=e.realBounds.y,a.realBounds.w=this.width,a.realBounds.h=e.realBounds.h,a.onNotesX=t+this.x+this.onNotes.x+this.onNotes.centerX}e.addBeat(a),this.renderer.settings.core.includeNoteBounds&&this.onNotes.buildBoundingsLookup(a,t+this.x,s+this.y)}}Fr.GraceBeatPadding=3;class Cr{constructor(){this.oldWidth=0,this.newWidth=0,this.settings=null}core(){return this.settings&&this.causeIssue()?this.settings.core:new nc}causeIssue(){return this.settings=null,!0}}class Dr{constructor(e){this.activeBeats=e}}class Er{constructor(e){this.bounds=null,this.beat=e}}class Lr{get score(){return this._score}get tracks(){return this._tracks}constructor(e,t){this._startTime=0,this._trackIndexes=null,this._trackIndexLookup=null,this._isDestroyed=!1,this._score=null,this._tracks=[],this._tickCache=null,this.player=null,this._cursorWrapper=null,this._barCursor=null,this._beatCursor=null,this._selectionWrapper=null,this._previousTick=0,this._playerState=Ot.Paused,this._currentBeat=null,this._currentBarBounds=null,this._previousStateForCursor=Ot.Paused,this._previousCursorCache=null,this._lastScroll=0,this.playedBeatChanged=new Zi,this.activeBeatsChanged=new Zi,this._beatMouseDown=!1,this._noteMouseDown=!1,this._selectionStart=null,this._selectionEnd=null,this.beatMouseDown=new Zi,this.beatMouseMove=new Zi,this.beatMouseUp=new Zi,this.noteMouseDown=new Zi,this.noteMouseMove=new Zi,this.noteMouseUp=new Zi,this.scoreLoaded=new Zi,this.resize=new Zi,this.renderStarted=new Zi,this.renderFinished=new Zi,this.postRenderFinished=new Qi,this.error=new Zi,this.playerReady=new Qi,this.playerFinished=new Qi,this.soundFontLoaded=new Qi,this.midiLoad=new Zi,this.midiLoaded=new Zi,this.playerStateChanged=new Zi,this.playerPositionChanged=new Zi,this.midiEventsPlayed=new Zi,this.playbackRangeChanged=new Zi,this.settingsUpdated=new Qi,this.uiFacade=e,this.container=e.rootContainer,e.initialize(this,t),q.logLevel=this.settings.core.logLevel,rc.printEnvironmentInfo(!1),this.canvasElement=e.createCanvasElement(),this.container.appendChild(this.canvasElement),this.settings.core.useWorkers&&this.uiFacade.areWorkersSupported&&rc.getRenderEngineFactory(this.settings.core.engine).supportsWorkers?this.renderer=this.uiFacade.createWorkerRenderer():this.renderer=new nr(this.settings),this.container.resize.on(rc.throttle((()=>{this._isDestroyed||this.container.width!==this.renderer.width&&this.triggerResize()}),e.resizeThrottle));const s=new Cr;s.oldWidth=this.renderer.width,s.newWidth=0|this.container.width,s.settings=this.settings,this.onResize(s),this.renderer.preRender.on(this.onRenderStarted.bind(this)),this.renderer.renderFinished.on((e=>{this.onRenderFinished(e)})),this.renderer.postRenderFinished.on((()=>{const e=Date.now()-this._startTime;q.debug("rendering",`Rendering completed in ${e}ms`),this.onPostRenderFinished()})),this.renderer.preRender.on((e=>{this._startTime=Date.now()})),this.renderer.partialLayoutFinished.on(this.appendRenderResult.bind(this)),this.renderer.partialRenderFinished.on(this.updateRenderResult.bind(this)),this.renderer.renderFinished.on((e=>{this.appendRenderResult(e),this.appendRenderResult(null)})),this.renderer.error.on(this.onError.bind(this)),this.settings.player.enablePlayer&&this.setupPlayer(),this.setupClickHandling(),this.uiFacade.beginInvoke((()=>{this.uiFacade.initialRender()}))}destroy(){this._isDestroyed=!0,this.player&&this.player.destroy(),this.uiFacade.destroy(),this.renderer.destroy()}updateSettings(){const e=this.score;e&&ie.applyPitchOffsets(this.settings,e),this.renderer.updateSettings(this.settings),this.settings.player.enablePlayer?(this.setupPlayer(),e&&this.player?.applyTranspositionPitches(wr.buildTranspositionPitches(e,this.settings))):this.destroyPlayer(),this.onSettingsUpdated()}load(e,t){try{return this.uiFacade.load(e,(e=>{this.renderScore(e,t)}),(e=>{this.onError(e)}))}catch(e){return this.onError(e),!1}}renderScore(e,t){const s=[];if(t)if(0===t.length)e.tracks.length>0&&s.push(e.tracks[0]);else if(1===t.length&&-1===t[0])for(const t of e.tracks)s.push(t);else for(const i of t)i>=0&&i<=e.tracks.length&&s.push(e.tracks[i]);else e.tracks.length>0&&s.push(e.tracks[0]);this.internalRenderTracks(e,s)}renderTracks(e){if(e.length>0){const t=e[0].score;for(const s of e)if(s.score!==t)return void this.onError(new $e(Se.General,"All rendered tracks must belong to the same score."));this.internalRenderTracks(t,e)}}internalRenderTracks(e,t){if(ie.applyPitchOffsets(this.settings,e),e!==this.score){this._score=e,this._tracks=t,this._tickCache=null,this._trackIndexes=[];for(const e of t)this._trackIndexes.push(e.index);this._trackIndexLookup=new Set(this._trackIndexes),this.onScoreLoaded(e),this.loadMidiForScore(),this.render()}else{this._tracks=t;const s=ie.computeFirstDisplayedBarIndex(e,this.settings),i=ie.computeLastDisplayedBarIndex(e,this.settings,s);this._tickCache&&(this._tickCache.multiBarRestInfo=ie.buildMultiBarRestInfo(this.tracks,s,i)),this._trackIndexes=[];for(const e of t)this._trackIndexes.push(e.index);this._trackIndexLookup=new Set(this._trackIndexes),this.render()}}triggerResize(){if(this.container.isVisible){const e=new Cr;e.oldWidth=this.renderer.width,e.newWidth=this.container.width,e.settings=this.settings,this.onResize(e),this.renderer.updateSettings(this.settings),this.renderer.width=this.container.width,this.renderer.resizeRender()}else q.warning("Rendering","AlphaTab container was invisible while autosizing, waiting for element to become visible",null),this.uiFacade.rootContainerBecameVisible.on((()=>{q.debug("Rendering","AlphaTab container became visible, doing autosizing",null),this.triggerResize()}))}appendRenderResult(e){e?(this.canvasElement.width=e.totalWidth,this.canvasElement.height=e.totalHeight,this._cursorWrapper&&(this._cursorWrapper.width=e.totalWidth,this._cursorWrapper.height=e.totalHeight),(e.width>0||e.height>0)&&this.uiFacade.beginAppendRenderResults(e)):this.uiFacade.beginAppendRenderResults(e)}updateRenderResult(e){e&&e.renderResult&&this.uiFacade.beginUpdateRenderResults(e)}tex(e,t){try{const s=new dt;s.logErrors=!0,s.initFromString(e,this.settings);const i=s.readScore();this.renderScore(i,t)}catch(e){this.onError(e)}}loadSoundFont(e,t=!1){return!!this.player&&this.uiFacade.loadSoundFont(e,t)}resetSoundFonts(){this.player&&this.player.resetSoundFonts()}render(){this.renderer&&(this.uiFacade.canRender?(this.renderer.width=this.container.width,this.renderer.renderScore(this.score,this._trackIndexes)):this.uiFacade.canRenderChanged.on((()=>this.render())))}get tickCache(){return this._tickCache}get boundsLookup(){return this.renderer.boundsLookup}get isReadyForPlayback(){return!!this.player&&this.player.isReadyForPlayback}get playerState(){return this.player?this.player.state:Ot.Paused}get masterVolume(){return this.player?this.player.masterVolume:0}set masterVolume(e){this.player&&(this.player.masterVolume=e)}get metronomeVolume(){return this.player?this.player.metronomeVolume:0}set metronomeVolume(e){this.player&&(this.player.metronomeVolume=e)}get countInVolume(){return this.player?this.player.countInVolume:0}set countInVolume(e){this.player&&(this.player.countInVolume=e)}get midiEventsPlayedFilter(){return this.player?this.player.midiEventsPlayedFilter:[]}set midiEventsPlayedFilter(e){this.player&&(this.player.midiEventsPlayedFilter=e)}get tickPosition(){return this.player?this.player.tickPosition:0}set tickPosition(e){this.player&&(this.player.tickPosition=e)}get timePosition(){return this.player?this.player.timePosition:0}set timePosition(e){this.player&&(this.player.timePosition=e)}get playbackRange(){return this.player?this.player.playbackRange:null}set playbackRange(e){this.player&&(this.player.playbackRange=e,this.settings.player.enableCursor&&this.updateSelectionCursor(e))}get playbackSpeed(){return this.player?this.player.playbackSpeed:0}set playbackSpeed(e){this.player&&(this.player.playbackSpeed=e)}get isLooping(){return!!this.player&&this.player.isLooping}set isLooping(e){this.player&&(this.player.isLooping=e)}destroyPlayer(){this.player&&(this.player.destroy(),this.player=null,this._previousTick=0,this._playerState=Ot.Paused,this.destroyCursors())}setupPlayer(){this.updateCursors(),this.player||(this.player=this.uiFacade.createWorkerPlayer(),this.player&&(this.player.ready.on((()=>{this.loadMidiForScore()})),this.player.readyForPlayback.on((()=>{if(this.onPlayerReady(),this.tracks)for(const e of this.tracks){const t=e.playbackInfo.volume/16;this.player.setChannelVolume(e.playbackInfo.primaryChannel,t),this.player.setChannelVolume(e.playbackInfo.secondaryChannel,t)}})),this.player.soundFontLoaded.on(this.onSoundFontLoaded.bind(this)),this.player.soundFontLoadFailed.on((e=>{this.onError(e)})),this.player.midiLoaded.on(this.onMidiLoaded.bind(this)),this.player.midiLoadFailed.on((e=>{this.onError(e)})),this.player.stateChanged.on(this.onPlayerStateChanged.bind(this)),this.player.positionChanged.on(this.onPlayerPositionChanged.bind(this)),this.player.midiEventsPlayed.on(this.onMidiEventsPlayed.bind(this)),this.player.playbackRangeChanged.on(this.onPlaybackRangeChanged.bind(this)),this.player.finished.on(this.onPlayerFinished.bind(this)),this.setupPlayerEvents()))}loadMidiForScore(){if(!this.score)return;const e=this.score;q.debug("AlphaTab","Generating Midi");const t=new Ps,s=new lr(t),i=new wr(e,this.settings,s),a=ie.computeFirstDisplayedBarIndex(e,this.settings),r=ie.computeLastDisplayedBarIndex(e,this.settings,a);i.tickLookup.multiBarRestInfo=ie.buildMultiBarRestInfo(this.tracks,a,r),i.applyTranspositionPitches=!1,i.generate(),this._tickCache=i.tickLookup,this.onMidiLoad(t);const n=this.player;n&&(n.loadMidiFile(t),n.applyTranspositionPitches(i.transpositionPitches))}changeTrackVolume(e,t){if(this.player)for(const s of e)this.player.setChannelVolume(s.playbackInfo.primaryChannel,t),this.player.setChannelVolume(s.playbackInfo.secondaryChannel,t)}changeTrackSolo(e,t){if(this.player)for(const s of e)this.player.setChannelSolo(s.playbackInfo.primaryChannel,t),this.player.setChannelSolo(s.playbackInfo.secondaryChannel,t)}changeTrackMute(e,t){if(this.player)for(const s of e)this.player.setChannelMute(s.playbackInfo.primaryChannel,t),this.player.setChannelMute(s.playbackInfo.secondaryChannel,t)}changeTrackTranspositionPitch(e,t){if(this.player)for(const s of e)this.player.setChannelTranspositionPitch(s.playbackInfo.primaryChannel,t),this.player.setChannelTranspositionPitch(s.playbackInfo.secondaryChannel,t)}play(){return!!this.player&&this.player.play()}pause(){this.player&&this.player.pause()}playPause(){this.player&&this.player.playPause()}stop(){this.player&&this.player.stop()}playBeat(e){if(!this.player)return;const t=new Ps,s=new lr(t);new wr(e.voice.bar.staff.track.score,this.settings,s).generateSingleBeat(e),this.player.playOneTimeMidiFile(t)}playNote(e){if(!this.player)return;const t=new Ps,s=new lr(t);new wr(e.beat.voice.bar.staff.track.score,this.settings,s).generateSingleNote(e),this.player.playOneTimeMidiFile(t)}destroyCursors(){this._cursorWrapper&&(this.uiFacade.destroyCursors(),this._cursorWrapper=null,this._barCursor=null,this._beatCursor=null,this._selectionWrapper=null)}updateCursors(){if(this.settings.player.enableCursor&&!this._cursorWrapper){const e=this.uiFacade.createCursors();e&&(this._cursorWrapper=e.cursorWrapper,this._barCursor=e.barCursor,this._beatCursor=e.beatCursor,this._selectionWrapper=e.selectionWrapper),null!==this._currentBeat&&this.cursorUpdateBeat(this._currentBeat,!1,this._previousTick>10,!0)}else!this.settings.player.enableCursor&&this._cursorWrapper&&this.destroyCursors()}setupPlayerEvents(){this._previousTick=0,this._playerState=Ot.Paused,this.renderer.postRenderFinished.on((()=>{this._currentBeat=null,this.cursorUpdateTick(this._previousTick,!1,this._previousTick>10)})),this.player&&(this.player.positionChanged.on((e=>{this._previousTick=e.currentTick,this.uiFacade.beginInvoke((()=>{this.cursorUpdateTick(e.currentTick,!1,!1,e.isSeek)}))})),this.player.stateChanged.on((e=>{if(this._playerState=e.state,!e.stopped&&e.state===Ot.Paused){const e=this._currentBeat,t=this._tickCache;e&&t&&(this.player.tickPosition=t.getBeatStart(e.beat))}})))}cursorUpdateTick(e,t,s=!1,i=!1){const a=this._tickCache;if(a){const r=this._trackIndexLookup;if(null!=r&&r.size>0){const n=a.findBeat(r,e,this._currentBeat);n&&this.cursorUpdateBeat(n,t,s,i||this.playerState===Ot.Paused)}}}cursorUpdateBeat(e,t,s,i=!1){const a=e.beat,r=e.nextBeat?.beat??null,n=e.duration,o=e.beatLookup.highlightedBeats;if(!a)return;const h=this.renderer.boundsLookup;if(!h)return;const l=this._currentBeat,c=this._previousCursorCache,d=this._previousStateForCursor;if(!i&&a===l?.beat&&h===c&&d===this._playerState&&l?.start===e.start)return;const u=h.findBeat(a);u&&(this._currentBeat=e,this._previousCursorCache=h,this._previousStateForCursor=this._playerState,this.uiFacade.beginInvoke((()=>{this.internalCursorUpdateBeat(a,r,n,t,o,h,u,s,e.cursorMode)})))}scrollToCursor(){const e=this._currentBarBounds;e&&this.internalScrollToCursor(e)}internalScrollToCursor(e){const t=this.uiFacade.getScrollContainer(),s=rc.getLayoutEngineFactory(this.settings.display.layoutMode).vertical,i=this.settings.player.scrollMode;if(s){const s=e.realBounds.y+this.settings.player.scrollOffsetY;if(s!==this._lastScroll)switch(this._lastScroll=s,i){case qt.Continuous:const i=this.uiFacade.getOffset(t,this.container);this.uiFacade.scrollToY(t,i.y+s,this.settings.player.scrollSpeed);break;case qt.OffScreen:const a=t.scrollTop+this.uiFacade.getOffset(null,t).h;if(e.visualBounds.y+e.visualBounds.h>=a||e.visualBounds.y<t.scrollTop){const s=e.realBounds.y+this.settings.player.scrollOffsetY;this.uiFacade.scrollToY(t,s,this.settings.player.scrollSpeed)}}}else{const s=e.visualBounds.x;if(s!==this._lastScroll)switch(this._lastScroll=s,i){case qt.Continuous:const s=e.realBounds.x+this.settings.player.scrollOffsetX;this._lastScroll=e.visualBounds.x,this.uiFacade.scrollToX(t,s,this.settings.player.scrollSpeed);break;case qt.OffScreen:const i=t.scrollLeft+this.uiFacade.getOffset(null,t).w;if(e.visualBounds.x+e.visualBounds.w>=i||e.visualBounds.x<t.scrollLeft){const s=e.realBounds.x+this.settings.player.scrollOffsetX;this._lastScroll=e.visualBounds.x,this.uiFacade.scrollToX(t,s,this.settings.player.scrollSpeed)}}}}internalCursorUpdateBeat(e,t,s,i,a,r,n,o,h){const l=this._barCursor,c=this._beatCursor,d=n.barBounds.masterBarBounds,u=d.visualBounds;this._currentBarBounds=d,l&&l.setBounds(u.x,u.y,u.w,u.h),c&&(this.settings.player.enableAnimatedBeatCursor&&c.stopAnimation(),c.setBounds(n.onNotesX,u.y,1,u.h)),this.settings.player.enableElementHighlighting&&this.uiFacade.removeHighlights();let p=!1;const g=this._playerState===Ot.Playing&&!i;if(g){if(this.settings.player.enableElementHighlighting)for(const t of a){const s=Fr.getGroupId(t.beat);this.uiFacade.highlightElements(s,e.voice.bar.index)}o=!i,p=!0}if(this.settings.player.enableAnimatedBeatCursor&&c){let e=d.visualBounds.x+d.visualBounds.w;if(t&&h===Zt.ToNextBext){const s=r.findBeat(t);s&&s.barBounds.masterBarBounds.staffSystemBounds===d.staffSystemBounds&&(e=s.onNotesX)}g&&this.uiFacade.beginInvoke((()=>{c.transitionToX(s/this.playbackSpeed,e)}))}o&&!this._beatMouseDown&&this.settings.player.scrollMode!==qt.Off&&this.internalScrollToCursor(d),p&&(this.onPlayedBeatChanged(e),this.onActiveBeatsChanged(new Dr(a.map((e=>e.beat)))))}onPlayedBeatChanged(e){this._isDestroyed||(this.playedBeatChanged.trigger(e),this.uiFacade.triggerEvent(this.container,"playedBeatChanged",e))}onActiveBeatsChanged(e){this._isDestroyed||(this.activeBeatsChanged.trigger(e),this.uiFacade.triggerEvent(this.container,"activeBeatsChanged",e))}onBeatMouseDown(e,t){this._isDestroyed||(this.settings.player.enablePlayer&&this.settings.player.enableCursor&&this.settings.player.enableUserInteraction&&(this._selectionStart=new Er(t),this._selectionEnd=null),this._beatMouseDown=!0,this.beatMouseDown.trigger(t),this.uiFacade.triggerEvent(this.container,"beatMouseDown",t,e))}onNoteMouseDown(e,t){this._isDestroyed||(this._noteMouseDown=!0,this.noteMouseDown.trigger(t),this.uiFacade.triggerEvent(this.container,"noteMouseDown",t,e))}onBeatMouseMove(e,t){this._isDestroyed||(this.settings.player.enableUserInteraction&&(this._selectionEnd&&this._selectionEnd.beat===t||(this._selectionEnd=new Er(t),this.cursorSelectRange(this._selectionStart,this._selectionEnd))),this.beatMouseMove.trigger(t),this.uiFacade.triggerEvent(this.container,"beatMouseMove",t,e))}onNoteMouseMove(e,t){this._isDestroyed||(this.noteMouseMove.trigger(t),this.uiFacade.triggerEvent(this.container,"noteMouseMove",t,e))}onBeatMouseUp(e,t){if(!this._isDestroyed){if(this.settings.player.enablePlayer&&this.settings.player.enableCursor&&this.settings.player.enableUserInteraction){if(this._selectionEnd){const e=this._tickCache?.getBeatStart(this._selectionStart.beat)??this._selectionStart.beat.absolutePlaybackStart;if((this._tickCache?.getBeatStart(this._selectionEnd.beat)??this._selectionEnd.beat.absolutePlaybackStart)<e){const e=this._selectionStart;this._selectionStart=this._selectionEnd,this._selectionEnd=e}}if(this._selectionStart&&this._tickCache){const e=this._tickCache,t=e.getMasterBarStart(this._selectionStart.beat.voice.bar.masterBar);if(this._currentBeat=null,this._playerState===Ot.Paused&&this.cursorUpdateTick(this._tickCache.getBeatStart(this._selectionStart.beat),!1),this.tickPosition=t+this._selectionStart.beat.playbackStart,this._selectionEnd&&this._selectionStart.beat!==this._selectionEnd.beat){const s=e.getMasterBarStart(this._selectionEnd.beat.voice.bar.masterBar),i=new Br;i.startTick=t+this._selectionStart.beat.playbackStart,i.endTick=s+this._selectionEnd.beat.playbackStart+this._selectionEnd.beat.playbackDuration-50,this.playbackRange=i}else this._selectionStart=null,this.playbackRange=null,this.cursorSelectRange(this._selectionStart,this._selectionEnd)}}this.beatMouseUp.trigger(t),this.uiFacade.triggerEvent(this.container,"beatMouseUp",t,e),this._beatMouseDown=!1}}onNoteMouseUp(e,t){this._isDestroyed||(this.noteMouseUp.trigger(t),this.uiFacade.triggerEvent(this.container,"noteMouseUp",t,e),this._noteMouseDown=!1)}updateSelectionCursor(e){if(this._tickCache)if(e){const t=this._tickCache.findBeat(this._trackIndexLookup,e.startTick),s=this._tickCache.findBeat(this._trackIndexLookup,e.endTick);if(t&&s){const e=new Er(t.beat),i=new Er(s.beat);this.cursorSelectRange(e,i)}}else this.cursorSelectRange(null,null)}setupClickHandling(){this.canvasElement.mouseDown.on((e=>{if(!e.isLeftMouseButton)return;this.settings.player.enableUserInteraction&&e.preventDefault();const t=e.getX(this.canvasElement),s=e.getY(this.canvasElement),i=this.renderer.boundsLookup?.getBeatAtPos(t,s)??null;if(i&&(this.onBeatMouseDown(e,i),this.settings.core.includeNoteBounds)){const a=this.renderer.boundsLookup?.getNoteAtPos(i,t,s);a&&this.onNoteMouseDown(e,a)}})),this.canvasElement.mouseMove.on((e=>{if(!this._beatMouseDown)return;const t=e.getX(this.canvasElement),s=e.getY(this.canvasElement),i=this.renderer.boundsLookup?.getBeatAtPos(t,s)??null;if(i&&(this.onBeatMouseMove(e,i),this._noteMouseDown)){const a=this.renderer.boundsLookup?.getNoteAtPos(i,t,s);a&&this.onNoteMouseMove(e,a)}})),this.canvasElement.mouseUp.on((e=>{if(!this._beatMouseDown)return;this.settings.player.enableUserInteraction&&e.preventDefault();const t=e.getX(this.canvasElement),s=e.getY(this.canvasElement),i=this.renderer.boundsLookup?.getBeatAtPos(t,s)??null;if(this.onBeatMouseUp(e,i),this._noteMouseDown)if(i){const a=this.renderer.boundsLookup?.getNoteAtPos(i,t,s)??null;this.onNoteMouseUp(e,a)}else this.onNoteMouseUp(e,null)})),this.renderer.postRenderFinished.on((()=>{this._selectionStart&&this.settings.player.enablePlayer&&this.settings.player.enableCursor&&this.settings.player.enableUserInteraction&&this.cursorSelectRange(this._selectionStart,this._selectionEnd)}))}cursorSelectRange(e,t){const s=this.renderer.boundsLookup;if(!s)return;const i=this._selectionWrapper;if(!i)return;if(i.clear(),!e||!t||e.beat===t.beat)return;e.bounds||(e.bounds=s.findBeat(e.beat)),t.bounds||(t.bounds=s.findBeat(t.beat));const a=this._tickCache?.getBeatStart(e.beat)??e.beat.absolutePlaybackStart;if((this._tickCache?.getBeatStart(t.beat)??t.beat.absolutePlaybackStart)<a){const s=e;e=t,t=s}const r=e.bounds.realBounds.x;let n=t.bounds.realBounds.x+t.bounds.realBounds.w;if(t.beat.index===t.beat.voice.beats.length-1&&(n=t.bounds.barBounds.masterBarBounds.realBounds.x+t.bounds.barBounds.masterBarBounds.realBounds.w),e.bounds.barBounds.masterBarBounds.staffSystemBounds!==t.bounds.barBounds.masterBarBounds.staffSystemBounds){const a=e.bounds.barBounds.masterBarBounds.staffSystemBounds.visualBounds.x,o=e.bounds.barBounds.masterBarBounds.staffSystemBounds.visualBounds.x+e.bounds.barBounds.masterBarBounds.staffSystemBounds.visualBounds.w,h=this.uiFacade.createSelectionElement();h.setBounds(r,e.bounds.barBounds.masterBarBounds.visualBounds.y,o-r,e.bounds.barBounds.masterBarBounds.visualBounds.h),i.appendChild(h);const l=e.bounds.barBounds.masterBarBounds.staffSystemBounds.index+1,c=t.bounds.barBounds.masterBarBounds.staffSystemBounds.index;for(let e=l;e<c;e++){const t=s.staffSystems[e],r=this.uiFacade.createSelectionElement();r.setBounds(a,t.visualBounds.y,o-a,t.visualBounds.h),i.appendChild(r)}const d=this.uiFacade.createSelectionElement();d.setBounds(a,t.bounds.barBounds.masterBarBounds.visualBounds.y,n-a,t.bounds.barBounds.masterBarBounds.visualBounds.h),i.appendChild(d)}else{const t=this.uiFacade.createSelectionElement();t.setBounds(r,e.bounds.barBounds.masterBarBounds.visualBounds.y,n-r,e.bounds.barBounds.masterBarBounds.visualBounds.h),i.appendChild(t)}}onScoreLoaded(e){this._isDestroyed||(this.scoreLoaded.trigger(e),this.uiFacade.triggerEvent(this.container,"scoreLoaded",e))}onResize(e){this._isDestroyed||(this.resize.trigger(e),this.uiFacade.triggerEvent(this.container,"resize",e))}onRenderStarted(e){this._isDestroyed||(this.renderStarted.trigger(e),this.uiFacade.triggerEvent(this.container,"renderStarted",e))}onRenderFinished(e){this._isDestroyed||(this.renderFinished.trigger(e),this.uiFacade.triggerEvent(this.container,"renderFinished",e))}onPostRenderFinished(){this._isDestroyed||(this.postRenderFinished.trigger(),this.uiFacade.triggerEvent(this.container,"postRenderFinished",null))}onError(e){this._isDestroyed||(q.error("API","An unexpected error occurred",e),this.error.trigger(e),this.uiFacade.triggerEvent(this.container,"error",e))}onPlayerReady(){this._isDestroyed||(this.playerReady.trigger(),this.uiFacade.triggerEvent(this.container,"playerReady",null))}onPlayerFinished(){this._isDestroyed||(this.playerFinished.trigger(),this.uiFacade.triggerEvent(this.container,"playerFinished",null))}onSoundFontLoaded(){this._isDestroyed||(this.soundFontLoaded.trigger(),this.uiFacade.triggerEvent(this.container,"soundFontLoaded",null))}onMidiLoad(e){this._isDestroyed||(this.midiLoad.trigger(e),this.uiFacade.triggerEvent(this.container,"midiLoad",e))}onMidiLoaded(e){this._isDestroyed||(this.midiLoaded.trigger(e),this.uiFacade.triggerEvent(this.container,"midiFileLoaded",e))}onPlayerStateChanged(e){this._isDestroyed||(this.playerStateChanged.trigger(e),this.uiFacade.triggerEvent(this.container,"playerStateChanged",e))}onPlayerPositionChanged(e){this._isDestroyed||null!==this.score&&this.tracks.length>0&&(this.playerPositionChanged.trigger(e),this.uiFacade.triggerEvent(this.container,"playerPositionChanged",e))}onMidiEventsPlayed(e){this._isDestroyed||(this.midiEventsPlayed.trigger(e),this.uiFacade.triggerEvent(this.container,"midiEventsPlayed",e))}onPlaybackRangeChanged(e){this._isDestroyed||(this.playbackRangeChanged.trigger(e),this.uiFacade.triggerEvent(this.container,"playbackRangeChanged",e))}onSettingsUpdated(){this._isDestroyed||(this.settingsUpdated.trigger(),this.uiFacade.triggerEvent(this.container,"settingsUpdated",null))}async enumerateOutputDevices(){return this.player?await this.player.output.enumerateOutputDevices():[]}async setOutputDevice(e){this.player&&await this.player.output.setOutputDevice(e)}async getOutputDevice(){return this.player?await this.player.output.getOutputDevice():null}}class Mr extends $e{constructor(e,t){super(Se.General,e),this.xhr=t,Object.setPrototypeOf(this,Mr.prototype)}}class Ir{static loadScoreAsync(e,t,s,i){const a=new XMLHttpRequest;a.open("GET",e,!0,null,null),a.responseType="arraybuffer",a.onreadystatechange=()=>{if(a.readyState===XMLHttpRequest.DONE){const e=a.response;if(200===a.status||0===a.status&&e)try{const e=a.response,s=new Uint8Array(e),r=Ir.loadScoreFromBytes(s,i);t(r)}catch(e){s(e)}else 0===a.status?s(new Mr("You are offline!!\n Please Check Your Network.",a)):404===a.status?s(new Mr("Requested URL not found.",a)):500===a.status?s(new Mr("Internel Server Error.",a)):"parsererror"===a.statusText?s(new Mr("Error.\nParsing JSON Request failed.",a)):"timeout"===a.statusText?s(new Mr("Request Time out.",a)):s(new Mr(`Unknow Error: ${a.responseText}`,a))}},a.send()}static loadScoreFromBytes(e,t){t||(t=new Ba);const s=rc.buildImporters();q.debug("ScoreLoader",`Loading score from ${e.length} bytes using ${s.length} importers`);let i=null;const a=ht.fromBuffer(e);for(const e of s){a.reset();try{q.debug("ScoreLoader",`Importing using importer ${e.name}`),e.init(a,t),i=e.readScore(),q.debug("ScoreLoader",`Score imported using ${e.name}`);break}catch(t){if(!(t instanceof qe))throw q.error("ScoreLoader","Score import failed due to unexpected error: ",t),t;q.debug("ScoreLoader",`${e.name} does not support the file`)}}if(i)return i;throw new qe("No compatible importer found for file")}}class Ar{get isLeftMouseButton(){return 0===this.mouseEvent.button}getX(e){const t=e.element,s=t.getBoundingClientRect().left+t.ownerDocument.defaultView.pageXOffset;return this.mouseEvent.pageX-s}getY(e){const t=e.element,s=t.getBoundingClientRect().top+t.ownerDocument.defaultView.pageYOffset;return this.mouseEvent.pageY-s}preventDefault(){this.mouseEvent.preventDefault()}constructor(e){this.mouseEvent=e}}class Rr{get width(){return this.element.offsetWidth}set width(e){this.element.style.width=`${e}px`}get scrollLeft(){return this.element.scrollLeft}set scrollLeft(e){this.element.scrollLeft=e}get scrollTop(){return this.element.scrollTop}set scrollTop(e){this.element.scrollTop=e}get height(){return this.element.offsetHeight}set height(e){this.element.style.height=e>=0?`${e}px`:"100%"}get isVisible(){return!!this.element.offsetWidth||!!this.element.offsetHeight||!!this.element.getClientRects().length}constructor(e){this._resizeListeners=0,this.lastBounds=new mt,this.element=e,this.mouseDown={on:e=>{this.element.addEventListener("mousedown",(t=>{e(new Ar(t))}),!0)},off:e=>{}},this.mouseUp={on:e=>{this.element.addEventListener("mouseup",(t=>{e(new Ar(t))}),!0)},off:e=>{}},this.mouseMove={on:e=>{this.element.addEventListener("mousemove",(t=>{e(new Ar(t))}),!0)},off:e=>{}},this.resize={on:e=>{0===this._resizeListeners&&Rr.resizeObserver.value.observe(this.element),this.element.addEventListener("resize",e,!0),this._resizeListeners++},off:e=>{this.element.removeEventListener("resize",e,!0),this._resizeListeners--,this._resizeListeners<=0&&(this._resizeListeners=0,Rr.resizeObserver.value.unobserve(this.element))}}}stopAnimation(){this.element.style.transition="none"}transitionToX(e,t){this.element.style.transition=`transform ${e}ms linear`,this.setBounds(t,Number.NaN,Number.NaN,Number.NaN)}setBounds(e,t,s,i){Number.isNaN(e)&&(e=this.lastBounds.x),Number.isNaN(t)&&(t=this.lastBounds.y),Number.isNaN(s)&&(s=this.lastBounds.w),Number.isNaN(i)&&(i=this.lastBounds.h),this.element.style.transform=`translate(${e}px, ${t}px) scale(${s}, ${i})`,this.element.style.transformOrigin="top left",this.lastBounds.x=e,this.lastBounds.y=t,this.lastBounds.w=s,this.lastBounds.h=i}appendChild(e){this.element.appendChild(e.element)}clear(){this.element.innerHTML=""}}Rr.resizeObserver=new Y((()=>new ResizeObserver((e=>{for(const t of e){const e=new CustomEvent("resize",{detail:t});t.target.dispatchEvent(e)}}))));class Or{constructor(e){this._isStarted=!1,this.isFontLoaded=!1,this.fontLoaded=new Zi,this._originalFamilies=e,this._families=e}checkForFontAvailability(){if(rc.isRunningInWorker)return void(this.isFontLoaded=!1);if(this._isStarted)return;this._isStarted=!0;let e=0;const t=window.setInterval((()=>{q.warning("Rendering",`Could not load font '${this._families[0]}' within ${5*(e+1)} seconds`,null),this._families.length>1?(this._families.shift(),e=0):e++}),5e3);q.debug("Font",`Start checking for font availablility: ${this._families.join(", ")}`);const s=e=>{this._families.length>1?(q.debug("Font",`[${this._families[0]}] Loading Failed, switching to ${this._families[1]}`,e),this._families.shift(),window.setTimeout((()=>{a()}),0)):(q.error("Font",`[${this._originalFamilies.join(",")}] Loading Failed, rendering cannot start`,e),window.clearInterval(t))},i=e=>{q.debug("Font",`[${e}] Font API signaled available`),this.isFontLoaded=!0,window.clearInterval(t),this.fontLoaded.trigger(this._families[0])},a=async()=>{for(const e of this._families)if(await this.isFontAvailable(e,!1))return void i(e);try{await document.fonts.load(`1em ${this._families[0]}`)}catch(e){s(e)}return q.debug("Font",`[${this._families[0]}] Font API signaled loaded`),await this.isFontAvailable(this._families[0],!0)?i(this._families[0]):s("Font not available"),!0};document.fonts.ready.then((()=>{a()}))}isFontAvailable(e,t){return new Promise((s=>{const i=`1em ${e}`;if(document.fonts.check(i))s(!0);else if(t){q.debug("Font",`Font ${e} not available, creating test element to trigger load`);const t=document.createElement("div");t.style.font=i,t.style.opacity="0",t.style.position="absolute",t.style.top="0",t.style.left="0",t.innerText=`Trigger ${e} load`,document.body.appendChild(t),setTimeout((()=>{document.body.removeChild(t),document.fonts.check(i)?s(!0):s(!1)}),200)}else s(!1)}))}}class Hr{constructor(e){this._writePosition=0,this._readPosition=0,this.count=0,this._buffer=new Float32Array(e)}clear(){this._readPosition=0,this._writePosition=0,this.count=0,this._buffer=new Float32Array(this._buffer.length)}write(e,t,s){let i=0;s>this._buffer.length-this.count&&(s=this._buffer.length-this.count);const a=Math.min(this._buffer.length-this._writePosition,s);return this._buffer.set(e.subarray(t,t+a),this._writePosition),this._writePosition+=a,this._writePosition%=this._buffer.length,i+=a,i<s&&(this._buffer.set(e.subarray(t+i,t+i+s-i),this._writePosition),this._writePosition+=s-i,i=s),this.count+=i,i}read(e,t,s){s>this.count&&(s=this.count);let i=0;const a=Math.min(this._buffer.length-this._readPosition,s);return e.set(this._buffer.subarray(this._readPosition,this._readPosition+a),t),i+=a,this._readPosition+=a,this._readPosition%=this._buffer.length,i<s&&(e.set(this._buffer.subarray(this._readPosition,this._readPosition+s-i),t+i),this._readPosition+=s-i,i=s),this.count-=i,i}}class Wr{constructor(e){this.isDefault=!1,this.device=e}get deviceId(){return this.device.deviceId}get label(){return this.device.label}}class Vr{constructor(){this._context=null,this._buffer=null,this._source=null,this.ready=new Qi,this.samplesPlayed=new Zi,this.sampleRequest=new Qi,this._knownDevices=[]}get sampleRate(){return this._context?this._context.sampleRate:Vr.PreferredSampleRate}activate(e){this._context||(this._context=this.createAudioContext()),"suspended"!==this._context.state&&"interrupted"!==this._context.state||(q.debug("WebAudio","Audio Context is suspended, trying resume"),this._context.resume().then((()=>{q.debug("WebAudio",`Audio Context resume success: state=${this._context?.state}, sampleRate:${this._context?.sampleRate}`),e&&e()}),(e=>{q.warning("WebAudio",`Audio Context resume failed: state=${this._context?.state}, sampleRate:${this._context?.sampleRate}, reason=${e}`)})))}patchIosSampleRate(){const e=navigator.userAgent;if(-1!==e.indexOf("iPhone")||-1!==e.indexOf("iPad")){const e=this.createAudioContext(),t=e.createBuffer(1,1,Vr.PreferredSampleRate),s=e.createBufferSource();s.buffer=t,s.connect(e.destination),s.start(0),s.disconnect(0),e.close()}}createAudioContext(){if("AudioContext"in rc.globalThis)return new AudioContext;if("webkitAudioContext"in rc.globalThis)return new webkitAudioContext;throw new $e(Se.General,"AudioContext not found")}open(e){this.patchIosSampleRate(),this._context=this.createAudioContext();"suspended"===this._context.state&&this.registerResumeHandler()}registerResumeHandler(){this._resumeHandler=(()=>{this.activate((()=>{this.unregisterResumeHandler()}))}).bind(this),document.body.addEventListener("touchend",this._resumeHandler,!1),document.body.addEventListener("click",this._resumeHandler,!1)}unregisterResumeHandler(){const e=this._resumeHandler;e&&(document.body.removeEventListener("touchend",e,!1),document.body.removeEventListener("click",e,!1))}play(){const e=this._context;this.activate(),this._buffer=e.createBuffer(2,Vr.BufferSize,e.sampleRate),this._source=e.createBufferSource(),this._source.buffer=this._buffer,this._source.loop=!0}pause(){this._source&&(this._source.stop(0),this._source.disconnect()),this._source=null}destroy(){this.pause(),this._context?.close(),this._context=null,this.unregisterResumeHandler()}onSamplesPlayed(e){this.samplesPlayed.trigger(e)}onSampleRequest(){this.sampleRequest.trigger()}onReady(){this.ready.trigger()}async checkSinkIdSupport(){return"setSinkId"in(this._context??this.createAudioContext())||(q.warning("WebAudio","Browser does not support changing the output device"),!1)}async enumerateOutputDevices(){try{if(!await this.checkSinkIdSupport())return[];try{await navigator.mediaDevices.getUserMedia({audio:!0})}catch(e){q.warning("WebAudio","Output device permission rejected",e)}const e=await navigator.mediaDevices.enumerateDevices();let t="",s="";const i=new Map;for(const a of e)"audiooutput"===a.kind&&(i.set(a.groupId,new Wr(a)),"default"!==a.deviceId&&""!==a.deviceId||(t=a.groupId,s=a.deviceId));const a=Array.from(i.values());let r=a.find((e=>e.deviceId===s));return r||(r=a.find((e=>e.device.groupId===t))),!r&&a.length>0&&(r=a[0]),r&&(r.isDefault=!0),this._knownDevices=a,a}catch(e){return q.error("WebAudio","Failed to enumerate output devices",e),[]}}async setOutputDevice(e){await this.checkSinkIdSupport()&&(e?await this._context.setSinkId(e.deviceId):await this._context.setSinkId(""))}async getOutputDevice(){if(!await this.checkSinkIdSupport())return null;const e=this._context.sinkId;if("string"!=typeof e||""===e||"default"===e)return null;let t=this._knownDevices.find((t=>t.deviceId===e));if(t)return t;const s=await this.enumerateOutputDevices();return t=s.find((t=>t.deviceId===e)),t||(q.warning("WebAudio","Could not find output device in device list",e,s),null)}}Vr.BufferSize=4096,Vr.PreferredSampleRate=44100;class Gr extends Vr{constructor(){super(...arguments),this._audioNode=null,this._bufferCount=0,this._requestedBufferCount=0,this._outputBuffer=new Float32Array(0)}open(e){super.open(e),this._bufferCount=Math.floor(e*this.sampleRate/1e3/Vr.BufferSize),this._circularBuffer=new Hr(Vr.BufferSize*this._bufferCount),this.onReady()}play(){super.play();const e=this._context;this._audioNode=e.createScriptProcessor(4096,0,2),this._audioNode.onaudioprocess=this.generateSound.bind(this),this._circularBuffer.clear(),this.requestBuffers(),this._source=e.createBufferSource(),this._source.buffer=this._buffer,this._source.loop=!0,this._source.connect(this._audioNode,0,0),this._source.start(0),this._audioNode.connect(e.destination,0,0)}pause(){super.pause(),this._audioNode&&this._audioNode.disconnect(0),this._audioNode=null}addSamples(e){this._circularBuffer.write(e,0,e.length),this._requestedBufferCount--}resetSamples(){this._circularBuffer.clear()}requestBuffers(){const e=this._bufferCount/2|0,t=e*Vr.BufferSize;if(this._circularBuffer.count+this._requestedBufferCount*Vr.BufferSize<t){for(let t=0;t<e;t++)this.onSampleRequest();this._requestedBufferCount+=e}}generateSound(e){const t=e.outputBuffer.getChannelData(0),s=e.outputBuffer.getChannelData(1),i=t.length+s.length;let a=this._outputBuffer;a.length!==i&&(a=new Float32Array(i),this._outputBuffer=a);const r=this._circularBuffer.read(a,0,Math.min(a.length,this._circularBuffer.count));let n=0;const o=Math.min(t.length,r);for(let e=0;e<o;e++)t[e]=a[n++],s[e]=a[n++];if(r<t.length)for(let e=r;e<t.length;e++)t[e]=0,s[e]=0;this.onSamplesPlayed(r/K.AudioChannels),this.requestBuffers()}}class zr{constructor(e,t){this.loaded=e,this.total=t}}class Ur{get output(){return this._output}get isReady(){return this._workerIsReady&&this._outputIsReady}get isReadyForPlayback(){return this._workerIsReadyForPlayback}get state(){return this._state}get logLevel(){return q.logLevel}set logLevel(e){q.logLevel=e,this._synth.postMessage({cmd:"alphaSynth.setLogLevel",value:e})}get masterVolume(){return this._masterVolume}set masterVolume(e){e=Math.max(e,K.MinVolume),this._masterVolume=e,this._synth.postMessage({cmd:"alphaSynth.setMasterVolume",value:e})}get metronomeVolume(){return this._metronomeVolume}set metronomeVolume(e){e=Math.max(e,K.MinVolume),this._metronomeVolume=e,this._synth.postMessage({cmd:"alphaSynth.setMetronomeVolume",value:e})}get countInVolume(){return this._countInVolume}set countInVolume(e){e=Math.max(e,K.MinVolume),this._countInVolume=e,this._synth.postMessage({cmd:"alphaSynth.setCountInVolume",value:e})}get midiEventsPlayedFilter(){return this._midiEventsPlayedFilter}set midiEventsPlayedFilter(e){this._midiEventsPlayedFilter=e,this._synth.postMessage({cmd:"alphaSynth.setMidiEventsPlayedFilter",value:e})}get playbackSpeed(){return this._playbackSpeed}set playbackSpeed(e){e=ie.clamp(e,K.MinPlaybackSpeed,K.MaxPlaybackSpeed),this._playbackSpeed=e,this._synth.postMessage({cmd:"alphaSynth.setPlaybackSpeed",value:e})}get tickPosition(){return this._tickPosition}set tickPosition(e){e<0&&(e=0),this._tickPosition=e,this._synth.postMessage({cmd:"alphaSynth.setTickPosition",value:e})}get timePosition(){return this._timePosition}set timePosition(e){e<0&&(e=0),this._timePosition=e,this._synth.postMessage({cmd:"alphaSynth.setTimePosition",value:e})}get isLooping(){return this._isLooping}set isLooping(e){this._isLooping=e,this._synth.postMessage({cmd:"alphaSynth.setIsLooping",value:e})}get playbackRange(){return this._playbackRange}set playbackRange(e){e&&(e.startTick<0&&(e.startTick=0),e.endTick<0&&(e.endTick=0)),this._playbackRange=e,this._synth.postMessage({cmd:"alphaSynth.setPlaybackRange",value:e})}constructor(e,t){this._workerIsReadyForPlayback=!1,this._workerIsReady=!1,this._outputIsReady=!1,this._state=Ot.Paused,this._masterVolume=0,this._metronomeVolume=0,this._countInVolume=0,this._playbackSpeed=0,this._tickPosition=0,this._timePosition=0,this._isLooping=!1,this._playbackRange=null,this._midiEventsPlayedFilter=[],this.ready=new Qi,this.readyForPlayback=new Qi,this.finished=new Qi,this.soundFontLoaded=new Qi,this.soundFontLoadFailed=new Zi,this.midiLoaded=new Zi,this.midiLoadFailed=new Zi,this.stateChanged=new Zi,this.positionChanged=new Zi,this.midiEventsPlayed=new Zi,this.playbackRangeChanged=new Zi,this._workerIsReadyForPlayback=!1,this._workerIsReady=!1,this._outputIsReady=!1,this._state=Ot.Paused,this._masterVolume=0,this._metronomeVolume=0,this._playbackSpeed=0,this._tickPosition=0,this._timePosition=0,this._isLooping=!1,this._playbackRange=null,this._output=e,this._output.ready.on(this.onOutputReady.bind(this)),this._output.samplesPlayed.on(this.onOutputSamplesPlayed.bind(this)),this._output.sampleRequest.on(this.onOutputSampleRequest.bind(this)),this._output.open(t.player.bufferTimeInMilliseconds);try{this._synth=rc.createWebWorker(t)}catch(e){q.error("AlphaSynth",`Failed to create WebWorker: ${e}`)}this._synth.addEventListener("message",this.handleWorkerMessage.bind(this),!1),this._synth.postMessage({cmd:"alphaSynth.initialize",sampleRate:this._output.sampleRate,logLevel:t.core.logLevel,bufferTimeInMilliseconds:t.player.bufferTimeInMilliseconds}),this.masterVolume=1,this.playbackSpeed=1,this.metronomeVolume=0}destroy(){this._synth.postMessage({cmd:"alphaSynth.destroy"})}play(){return this._output.activate(),this._synth.postMessage({cmd:"alphaSynth.play"}),!0}pause(){this._synth.postMessage({cmd:"alphaSynth.pause"})}playPause(){this._output.activate(),this._synth.postMessage({cmd:"alphaSynth.playPause"})}stop(){this._synth.postMessage({cmd:"alphaSynth.stop"})}playOneTimeMidiFile(e){this._synth.postMessage({cmd:"alphaSynth.playOneTimeMidiFile",midi:$a.midiFileToJsObject(e)})}loadSoundFont(e,t){this._synth.postMessage({cmd:"alphaSynth.loadSoundFontBytes",data:e,append:t})}loadSoundFontFromUrl(e,t,s){q.debug("AlphaSynth",`Start loading Soundfont from url ${e}`);const i=new XMLHttpRequest;i.open("GET",e,!0,null,null),i.responseType="arraybuffer",i.onload=e=>{const s=new Uint8Array(i.response);this.loadSoundFont(s,t)},i.onerror=e=>{q.error("AlphaSynth",`Loading failed: ${e.message}`),this.soundFontLoadFailed.trigger(new Mr(e.message,i))},i.onprogress=e=>{q.debug("AlphaSynth",`Soundfont downloading: ${e.loaded}/${e.total} bytes`),s(new zr(e.loaded,e.total))},i.send()}resetSoundFonts(){this._synth.postMessage({cmd:"alphaSynth.resetSoundFonts"})}loadMidiFile(e){this._synth.postMessage({cmd:"alphaSynth.loadMidi",midi:$a.midiFileToJsObject(e)})}applyTranspositionPitches(e){this._synth.postMessage({cmd:"alphaSynth.applyTranspositionPitches",transpositionPitches:JSON.stringify(Array.from(e.entries()))})}setChannelTranspositionPitch(e,t){this._synth.postMessage({cmd:"alphaSynth.setChannelTranspositionPitch",channel:e,semitones:t})}setChannelMute(e,t){this._synth.postMessage({cmd:"alphaSynth.setChannelMute",channel:e,mute:t})}resetChannelStates(){this._synth.postMessage({cmd:"alphaSynth.resetChannelStates"})}setChannelSolo(e,t){this._synth.postMessage({cmd:"alphaSynth.setChannelSolo",channel:e,solo:t})}setChannelVolume(e,t){t=Math.max(t,K.MinVolume),this._synth.postMessage({cmd:"alphaSynth.setChannelVolume",channel:e,volume:t})}handleWorkerMessage(e){const t=e.data;switch(t.cmd){case"alphaSynth.ready":this._workerIsReady=!0,this.checkReady();break;case"alphaSynth.destroyed":this._synth.terminate();break;case"alphaSynth.readyForPlayback":this._workerIsReadyForPlayback=!0,this.checkReadyForPlayback();break;case"alphaSynth.positionChanged":this._timePosition=t.currentTime,this._tickPosition=t.currentTick,this.positionChanged.trigger(new $s(t.currentTime,t.endTime,t.currentTick,t.endTick,t.isSeek));break;case"alphaSynth.midiEventsPlayed":this.midiEventsPlayed.trigger(new ea(t.events.map($a.jsObjectToMidiEvent)));break;case"alphaSynth.playerStateChanged":this._state=t.state,this.stateChanged.trigger(new Ys(t.state,t.stopped));break;case"alphaSynth.playbackRangeChanged":this._playbackRange=t.playbackRange,this.playbackRangeChanged.trigger(new ta(this._playbackRange));break;case"alphaSynth.finished":this.finished.trigger();break;case"alphaSynth.soundFontLoaded":this.soundFontLoaded.trigger();break;case"alphaSynth.soundFontLoadFailed":this.soundFontLoadFailed.trigger(t.error);break;case"alphaSynth.midiLoaded":this.checkReadyForPlayback(),this.midiLoaded.trigger(new $s(t.currentTime,t.endTime,t.currentTick,t.endTick,t.isSeek));break;case"alphaSynth.midiLoadFailed":this.checkReadyForPlayback(),this.midiLoadFailed.trigger(t.error);break;case"alphaSynth.output.addSamples":this._output.addSamples(t.samples);break;case"alphaSynth.output.play":this._output.play();break;case"alphaSynth.output.pause":this._output.pause();break;case"alphaSynth.output.destroy":this._output.destroy();break;case"alphaSynth.output.resetSamples":this._output.resetSamples()}}checkReady(){this.isReady&&this.ready.trigger()}checkReadyForPlayback(){this.isReadyForPlayback&&this.readyForPlayback.trigger()}onOutputSampleRequest(){this._synth.postMessage({cmd:"alphaSynth.output.sampleRequest"})}onOutputSamplesPlayed(e){this._synth.postMessage({cmd:"alphaSynth.output.samplesPlayed",samples:e})}onOutputReady(){this._outputIsReady=!0,this.checkReady()}}class Xr{constructor(e,t){this._width=0,this.boundsLookup=null,this.preRender=new Zi,this.partialRenderFinished=new Zi,this.partialLayoutFinished=new Zi,this.renderFinished=new Zi,this.postRenderFinished=new Qi,this.error=new Zi,this._api=e;try{this._worker=rc.createWebWorker(t)}catch(e){return void q.error("Rendering",`Failed to create WebWorker: ${e}`)}this._worker.postMessage({cmd:"alphaTab.initialize",settings:this.serializeSettingsForWorker(t)}),this._worker.addEventListener("message",this.handleWorkerMessage.bind(this))}destroy(){this._worker.terminate()}updateSettings(e){this._worker.postMessage({cmd:"alphaTab.updateSettings",settings:this.serializeSettingsForWorker(e)})}serializeSettingsForWorker(e){const t=$a.settingsToJsObject(e);return t.delete("player"),t}render(){this._worker.postMessage({cmd:"alphaTab.render"})}resizeRender(){this._worker.postMessage({cmd:"alphaTab.resizeRender"})}renderResult(e){this._worker.postMessage({cmd:"alphaTab.renderResult",resultId:e})}get width(){return this._width}set width(e){this._width=e,this._worker.postMessage({cmd:"alphaTab.setWidth",width:e})}handleWorkerMessage(e){const t=e.data;switch(t.cmd){case"alphaTab.preRender":this.preRender.trigger(t.resize);break;case"alphaTab.partialRenderFinished":this.partialRenderFinished.trigger(t.result);break;case"alphaTab.partialLayoutFinished":this.partialLayoutFinished.trigger(t.result);break;case"alphaTab.renderFinished":this.renderFinished.trigger(t.result);break;case"alphaTab.postRenderFinished":this.boundsLookup=rr.fromJson(t.boundsLookup,this._api.score),this.boundsLookup.finish(),this.postRenderFinished.trigger();break;case"alphaTab.error":this.error.trigger(t.error)}}renderScore(e,t){const s=null==e?null:$a.scoreToJsObject(e);this._worker.postMessage({cmd:"alphaTab.renderScore",score:s,trackIndexes:t,fontSizes:Qa.FontSizeLookupTables})}}class Jr{constructor(e,t,s,i){this.cursorWrapper=e,this.barCursor=t,this.beatCursor=s,this.selectionWrapper=i}}class Yr{static init(){var e;Yr._isRegistered||(Yr._isRegistered=!0,registerProcessor("alphatab",((e=class extends AudioWorkletProcessor{constructor(t){super(t),this._outputBuffer=new Float32Array(0),this._bufferCount=0,this._requestedBufferCount=0,this._isStopped=!1,q.debug("WebAudio","creating processor"),this._bufferCount=Math.floor(t.processorOptions.bufferTimeInMilliseconds*sampleRate/1e3/e.BufferSize),this._circularBuffer=new Hr(e.BufferSize*this._bufferCount),this.port.onmessage=this.handleMessage.bind(this)}handleMessage(e){const t=e.data;switch(t.cmd){case qa.CmdOutputAddSamples:const e=t.samples;this._circularBuffer.write(e,0,e.length),this._requestedBufferCount--;break;case qa.CmdOutputResetSamples:this._circularBuffer.clear();break;case qa.CmdOutputStop:this._isStopped=!0}}process(e,t,s){if(1!==t.length&&2!==t[0].length)return!1;const i=t[0][0],a=t[0][1];if(!i||!a)return!0;const r=i.length+a.length;let n=this._outputBuffer;n.length!==r&&(n=new Float32Array(r),this._outputBuffer=n);const o=this._circularBuffer.read(n,0,Math.min(n.length,this._circularBuffer.count));let h=0;const l=Math.min(i.length,o);for(let e=0;e<l;e++)i[e]=n[h++],a[e]=n[h++];if(o<i.length)for(let e=o;e<i.length;e++)i[e]=0,a[e]=0;return this.port.postMessage({cmd:qa.CmdOutputSamplesPlayed,samples:o/K.AudioChannels}),this.requestBuffers(),this._circularBuffer.count>0||!this._isStopped}requestBuffers(){const t=this._bufferCount/2|0,s=t*e.BufferSize;if(this._circularBuffer.count+this._requestedBufferCount*e.BufferSize<s){for(let e=0;e<t;e++)this.port.postMessage({cmd:qa.CmdOutputSampleRequest});this._requestedBufferCount+=t}}}).BufferSize=4096,e)))}}Yr._isRegistered=!1;class $r extends Vr{constructor(e){super(),this._worklet=null,this._bufferTimeInMilliseconds=0,this._settings=e}open(e){super.open(e),this._bufferTimeInMilliseconds=e,this.onReady()}play(){super.play();const e=this._context;rc.createAudioWorklet(e,this._settings).then((()=>{this._worklet=new AudioWorkletNode(e,"alphatab",{numberOfOutputs:1,outputChannelCount:[2],processorOptions:{bufferTimeInMilliseconds:this._bufferTimeInMilliseconds}}),this._worklet.port.onmessage=this.handleMessage.bind(this),this._source.connect(this._worklet),this._source.start(0),this._worklet.connect(e.destination)}),(e=>{q.error("WebAudio",`Audio Worklet creation failed: reason=${e}`)}))}handleMessage(e){const t=e.data;switch(t.cmd){case qa.CmdOutputSamplesPlayed:this.onSamplesPlayed(t.samples);break;case qa.CmdOutputSampleRequest:this.onSampleRequest()}}pause(){super.pause(),this._worklet&&(this._worklet.port.postMessage({cmd:qa.CmdOutputStop}),this._worklet.port.onmessage=null,this._worklet.disconnect()),this._worklet=null}addSamples(e){this._worklet?.port.postMessage({cmd:qa.CmdOutputAddSamples,samples:e})}resetSamples(){this._worklet?.port.postMessage({cmd:qa.CmdOutputResetSamples})}}class qr extends Rr{constructor(e,t,s){super(e),this._xscale=t,this._yscale=s}get width(){return this.element.offsetWidth/this._xscale}set width(e){this.element.style.width=e*this._xscale+"px"}get height(){return this.element.offsetHeight/this._yscale}set height(e){this.element.style.height=e>=0?e*this._yscale+"px":"100%"}setBounds(e,t,s,i){Number.isNaN(e)&&(e=this.lastBounds.x),Number.isNaN(t)&&(t=this.lastBounds.y),Number.isNaN(s)?s=this.lastBounds.w:s/=this._xscale,Number.isNaN(i)?i=this.lastBounds.h:i/=this._yscale,this.element.style.transform=`translate(${e}px, ${t}px) scale(${s}, ${i})`,this.element.style.transformOrigin="top left",this.lastBounds.x=e,this.lastBounds.y=t,this.lastBounds.w=s,this.lastBounds.h=i}}!function(e){e[e.LayoutDone=0]="LayoutDone",e[e.RenderRequested=1]="RenderRequested",e[e.RenderDone=2]="RenderDone",e[e.Detached=3]="Detached"}(es||(es={}));class jr{get resizeThrottle(){return 10}get canRender(){return this.areAllFontsLoaded()}areAllFontsLoaded(){if(rc.bravuraFontChecker.checkForFontAvailability(),!rc.bravuraFontChecker.isFontLoaded)return!1;let e=!1;for(const t of this._fontCheckers.values())t.isFontLoaded||(e=!0);return!e&&(q.debug("Font",`All fonts loaded: ${this._fontCheckers.size}`),!0)}onFontLoaded(e){Qa.generateFontLookup(e),this.areAllFontsLoaded()&&this.canRenderChanged.trigger()}constructor(e){if(this._fontCheckers=new Map,this._contents=null,this._file=null,this._totalResultCount=0,this._initialTrackIndexes=null,this._barToElementLookup=new Map,this._resultIdToElementLookup=new Map,this.rootContainerBecameVisible=new Qi,this.canRenderChanged=new Qi,this._highlightedElements=[],this._scrollContainer=null,rc.webPlatform!==Kt.Browser&&rc.webPlatform!==Kt.BrowserModule)throw new $e(Se.General,"Usage of AlphaTabApi is only possible in browser environments. For usage in node use the Low Level APIs");e.classList.add("alphaTab"),this.rootContainer=new Rr(e),this.areWorkersSupported="Worker"in window,rc.bravuraFontChecker.fontLoaded.on(this.onFontLoaded.bind(this)),this._intersectionObserver=new IntersectionObserver(this.onElementVisibilityChanged.bind(this),{threshold:[0,.01,1]}),this._intersectionObserver.observe(e)}onElementVisibilityChanged(e){for(const t of e){const e=t.target;if(e===this.rootContainer.element)t.isIntersecting&&(this.rootContainerBecameVisible.trigger(),this._intersectionObserver.unobserve(this.rootContainer.element));else if("layoutResultId"in e&&this._api.settings.core.enableLazyLoading){const s=e;t.isIntersecting?s.renderedResultId!==s.layoutResultId?this._resultIdToElementLookup.has(s.layoutResultId)?s.resultState!==es.RenderRequested&&(s.resultState=es.RenderRequested,this._api.renderer.renderResult(s.layoutResultId)):e.replaceChildren():s.resultState===es.Detached&&(e.replaceChildren(...s.renderedResult),s.resultState=es.RenderDone):s.resultState===es.RenderDone&&(s.resultState=es.Detached,s.replaceChildren())}}}createWorkerRenderer(){return new Xr(this._api,this._api.settings)}initialize(e,t){let s;this._api=e,s=t instanceof Ba?t:$a.jsObjectToSettings(t);const i=this.getDataAttributes();wa.fromJson(s,i),s.notation.notationMode===D.SongBook&&s.setSongBookModeSettings(),e.settings=s,this.setupFontCheckers(s),this._initialTrackIndexes=this.parseTracks(s.core.tracks),this._contents="";const a=e.container;s.core.tex&&(this._contents=a.element.innerHTML,a.element.innerHTML=""),this.createStyleElement(s),this._file=s.core.file}setupFontCheckers(e){this.registerFontChecker(e.display.resources.copyrightFont),this.registerFontChecker(e.display.resources.effectFont),this.registerFontChecker(e.display.resources.fingeringFont),this.registerFontChecker(e.display.resources.graceFont),this.registerFontChecker(e.display.resources.markerFont),this.registerFontChecker(e.display.resources.tablatureFont),this.registerFontChecker(e.display.resources.titleFont),this.registerFontChecker(e.display.resources.wordsFont),this.registerFontChecker(e.display.resources.barNumberFont),this.registerFontChecker(e.display.resources.fretboardNumberFont),this.registerFontChecker(e.display.resources.subTitleFont)}registerFontChecker(e){if(!this._fontCheckers.has(e.families.join(", "))){const t=new Or(e.families);this._fontCheckers.set(e.families.join(", "),t),t.fontLoaded.on(this.onFontLoaded.bind(this)),t.checkForFontAvailability()}}destroy(){this.rootContainer.element.innerHTML=""}createCanvasElement(){const e=document.createElement("div");return e.className="at-surface",e.style.fontSize="0",e.style.overflow="hidden",e.style.lineHeight="0",e.style.position="relative",new Rr(e)}triggerEvent(e,t,s=null,i){const a=e.element;t=`alphaTab.${t}`;const r=document.createEvent("CustomEvent"),n=i?i.mouseEvent:null;if(r.initCustomEvent(t,!1,!1,s),n&&(r.originalEvent=n),a.dispatchEvent(r),window&&"jQuery"in window){const e=window.jQuery,i=[];i.push(s),n&&i.push(n),e(a).trigger(t,i)}}load(e,t,s){if(e instanceof Je)return t(e),!0;if(e instanceof ArrayBuffer){const s=new Uint8Array(e);return t(Ir.loadScoreFromBytes(s,this._api.settings)),!0}return e instanceof Uint8Array?(t(Ir.loadScoreFromBytes(e,this._api.settings)),!0):"string"==typeof e&&(Ir.loadScoreAsync(e,t,s,this._api.settings),!0)}loadSoundFont(e,t){return!!this._api.player&&(e instanceof ArrayBuffer?(this._api.player.loadSoundFont(new Uint8Array(e),t),!0):e instanceof Uint8Array?(this._api.player.loadSoundFont(e,t),!0):"string"==typeof e&&(this._api.loadSoundFontFromUrl(e,t),!0))}initialRender(){this._api.renderer.preRender.on((e=>{this._totalResultCount=0,this._resultIdToElementLookup.clear(),this._barToElementLookup.clear()}));const e=()=>{this._api.renderer.width=0|this.rootContainer.width,this._api.renderer.updateSettings(this._api.settings),this._contents?(this._api.tex(this._contents,this._initialTrackIndexes??void 0),this._initialTrackIndexes=null):this._file&&Ir.loadScoreAsync(this._file,(e=>{this._api.renderScore(e,this._initialTrackIndexes??void 0),this._initialTrackIndexes=null}),(e=>{this._api.onError(e)}),this._api.settings)};this.rootContainer.isVisible?e():this.rootContainerBecameVisible.on(e)}createStyleElement(e){const t=this._api.container.element.ownerDocument;rc.createStyleElement(t,e.core.fontDirectory)}parseTracks(e){if(!e)return[];const t=[];if("string"==typeof e)try{if("all"===e)return[-1];e=JSON.parse(e)}catch(t){e=[0]}if("number"==typeof e)t.push(e);else if("length"in e){const s=e.length,i=e;for(let e=0;e<s;e++){const s=i[e];let a=0;a="number"==typeof s?s:"index"in s?s.index:Number.parseInt(s.toString()),(a>=0||-1===a)&&t.push(a)}}else"index"in e&&t.push(e.index);return t}getDataAttributes(){const e=new Map,t=this._api.container.element;if(t.dataset)for(const s of Object.keys(t.dataset)){let i=t.dataset[s];try{const e=i;i=JSON.parse(e)}catch(e){""===i&&(i=null)}e.set(s,i)}else for(let s=0;s<t.attributes.length;s++){const i=t.attributes.item(s),a=i.nodeName;if(a.startsWith("data-")){const t=a.substr(5).split("-");let s=t[0];for(let e=1;e<t.length;e++)s+=t[e].substr(0,1).toUpperCase()+t[e].substr(1);let r=i.nodeValue;try{r=JSON.parse(r)}catch(e){""===r&&(r=null)}e.set(s,r)}}return e}beginUpdateRenderResults(e){if(!this._resultIdToElementLookup.has(e.id))return;const t=this._resultIdToElementLookup.get(e.id),s=e.renderResult;"string"==typeof s?t.innerHTML=s:"nodeType"in s&&t.replaceChildren(s),t.resultState=es.RenderDone,t.renderedResultId=e.id,t.renderedResult=Array.from(t.children)}beginAppendRenderResults(e){const t=this._api.canvasElement.element;if(e){let s;this._totalResultCount<t.childElementCount?s=t.childNodes.item(this._totalResultCount):(s=document.createElement("div"),t.appendChild(s)),s.style.zIndex="1",s.style.position="absolute",s.style.left=`${e.x}px`,s.style.top=`${e.y}px`,s.style.width=`${e.width}px`,s.style.height=`${e.height}px`,s.style.display="inline-block",s.layoutResultId=e.id,s.resultState=es.LayoutDone,s.renderedResultId=void 0,s.renderedResult=void 0,this._resultIdToElementLookup.set(e.id,s);for(let t=e.firstMasterBarIndex;t<=e.lastMasterBarIndex;t++)t>=0&&this._barToElementLookup.set(t,s);this._api.settings.core.enableLazyLoading&&(this._intersectionObserver.unobserve(s),this._intersectionObserver.observe(s)),this._totalResultCount++}else for(;t.childElementCount>this._totalResultCount;)this._api.settings.core.enableLazyLoading&&this._intersectionObserver.unobserve(t.lastChild),t.removeChild(t.lastElementChild)}createWorkerPlayer(){let e=null;const t="ScriptProcessorNode"in window;return window.isSecureContext&&"AudioWorkletNode"in window&&this._api.settings.player.outputMode===jt.WebAudioAudioWorklets?(q.debug("Player","Will use webworkers for synthesizing and web audio api with worklets for playback"),e=new Ur(new $r(this._api.settings),this._api.settings)):t&&(q.debug("Player","Will use webworkers for synthesizing and web audio api with ScriptProcessor for playback"),e=new Ur(new Gr,this._api.settings)),e?e.ready.on((()=>{this._api.settings.player.soundFont&&this._api.loadSoundFontFromUrl(this._api.settings.player.soundFont,!1)})):q.error("Player","Player requires webworkers and web audio api, browser unsupported",null),e}beginInvoke(e){window.requestAnimationFrame((()=>{e()}))}highlightElements(e,t){const s=this._barToElementLookup.get(t);if(s){const t=s.getElementsByClassName(e);for(let e=0;e<t.length;e++)t.item(e).classList.add("at-highlight"),this._highlightedElements.push(t.item(e))}}removeHighlights(){const e=this._highlightedElements;if(e){for(const t of e)t.classList.remove("at-highlight");this._highlightedElements=[]}}destroyCursors(){const e=this._api.container.element,t=e.querySelector(".at-cursors");e.removeChild(t)}createCursors(){const e=this._api.container.element,t=document.createElement("div");t.classList.add("at-cursors");const s=document.createElement("div");s.classList.add("at-selection");const i=this.createScalingElement(),a=this.createScalingElement(),r=i.element;r.classList.add("at-cursor-bar");const n=a.element;return n.classList.add("at-cursor-beat"),e.style.position="relative",e.style.textAlign="left",t.style.position="absolute",t.style.zIndex="1000",t.style.display="inline",t.style.pointerEvents="none",s.style.position="absolute",r.style.position="absolute",r.style.left="0",r.style.top="0",r.style.willChange="transform",i.width=1,i.height=1,i.setBounds(0,0,1,1),n.style.position="absolute",n.style.transition="all 0s linear",n.style.left="0",n.style.top="0",n.style.willChange="transform",a.width=3,a.height=1,a.setBounds(0,0,1,1),e.insertBefore(t,e.firstChild),t.appendChild(s),t.appendChild(r),t.appendChild(n),new Jr(new Rr(t),i,a,new Rr(s))}getOffset(e,t){const s=t.element,i=s.getBoundingClientRect();let a=i.top+s.ownerDocument.defaultView.pageYOffset,r=i.left+s.ownerDocument.defaultView.pageXOffset;if(e){const t=e.element,s=t.nodeName.toLowerCase();if("html"!==s&&"body"!==s){const s=this.getOffset(null,e);a=a+t.scrollTop-s.y,r=r+t.scrollLeft-s.x}}const n=new mt;return n.x=r,n.y=a,n.w=i.width,n.h=i.height,n}getScrollContainer(){if(this._scrollContainer)return this._scrollContainer;let e="string"==typeof this._api.settings.player.scrollElement?document.querySelector(this._api.settings.player.scrollElement):this._api.settings.player.scrollElement;const t=e.nodeName.toLowerCase();if("html"===t||"body"===t)if("scrollingElement"in document)e=document.scrollingElement;else{e=-1!==navigator.userAgent.indexOf("WebKit")?document.body:document.documentElement}return this._scrollContainer=new Rr(e),this._scrollContainer}createSelectionElement(){return this.createScalingElement()}createScalingElement(){const e=document.createElement("div");e.style.position="absolute";const t=new qr(e,100,100);return t.width=1,t.height=1,t.setBounds(0,0,1,1),t}scrollToY(e,t,s){this.internalScrollToY(e.element,t,s)}scrollToX(e,t,s){this.internalScrollToX(e.element,t,s)}internalScrollToY(e,t,s){if(this._api.settings.player.nativeBrowserSmoothScroll)e.scrollTo({top:t,behavior:"smooth"});else{const i=e.scrollTop,a=t-i;let r=0;const n=t=>{0===r&&(r=t);const o=t-r,h=Math.min(o/s,1);e.scrollTop=i+a*h|0,o<s&&window.requestAnimationFrame(n)};window.requestAnimationFrame(n)}}internalScrollToX(e,t,s){if(this._api.settings.player.nativeBrowserSmoothScroll)e.scrollTo({left:t,behavior:"smooth"});else{const i=e.scrollLeft,a=t-i;let r=0;const n=t=>{0===r&&(r=t);const o=t-r,h=Math.min(o/s,1);e.scrollLeft=i+a*h|0,o<s&&window.requestAnimationFrame(n)};window.requestAnimationFrame(n)}}}class Kr extends Lr{constructor(e,t){super(new jr(e),t),this.soundFontLoad=new Zi}tex(e,t){const s=this.uiFacade;super.tex(e,s.parseTracks(t))}print(t,s=null){const i=window.open("","","width=0,height=0"),a=i.document.createElement("div");t?a.style.width=t:this.settings.display.layoutMode===e.Horizontal?a.style.width="297mm":a.style.width="210mm",i.document.write("\n <!DOCTYPE html>\n <html>\n <head>\n <style>\n .at-surface {\n width: auto !important;\n height: auto !important;\n }\n .at-surface > div {\n position: relative!important;\n left: auto !important;\n top: auto !important;\n break-inside: avoid;\n }\n </style>\n </head>\n <body></body>\n </html>\n ");const r=this.score;r&&(r.artist&&r.title?i.document.title=`${r.title} - ${r.artist}`:r.title&&(i.document.title=`${r.title}`)),i.document.body.appendChild(a);const n=void 0!==window.screenLeft?window.screenLeft:window.left,o=void 0!==window.screenTop?window.screenTop:window.top,h="innerWidth"in window?window.innerWidth:"clientWidth"in document.documentElement?document.documentElement.clientWidth:window.screen.width,l="innerHeight"in window?window.innerHeight:"clientHeight"in document.documentElement?document.documentElement.clientHeight:window.screen.height,c=a.offsetWidth+50,d=window.innerHeight,u=(h/2|0)-(c/2|0)+n,p=(l/2|0)-(d/2|0)+o;i.resizeTo(c,d),i.moveTo(u,p),i.focus();const g=$a.jsObjectToSettings($a.settingsToJsObject(this.settings));g.core.enableLazyLoading=!1,g.core.useWorkers=!0,g.core.file=null,g.core.tracks=null,g.player.enableCursor=!1,g.player.enablePlayer=!1,g.player.enableElementHighlighting=!1,g.player.enableUserInteraction=!1,g.player.soundFont=null,g.display.scale=.8,g.display.stretchForce=.8,wa.fromJson(g,s);const m=new Kr(a,g);i.onunload=()=>{m.destroy()},m.renderer.postRenderFinished.on((()=>{i.print()})),m.renderTracks(this.tracks)}downloadMidi(e=At.SingleTrackMultiChannel){if(!this.score)return;const t=new Ps;t.format=e;const s=new lr(t,!0);new wr(this.score,this.settings,s).generate();const i=t.toBinary(),a=this.score.title?`${this.score.title}.mid`:"File.mid",r=document.createElement("a");r.download=a;const n=new Blob([i],{type:"audio/midi"}),o=URL.createObjectURL(n);r.href=o,r.style.display="none",document.body.appendChild(r),r.click(),document.body.removeChild(r)}changeTrackMute(e,t){const s=this.trackIndexesToTracks(this.uiFacade.parseTracks(e));super.changeTrackMute(s,t)}changeTrackSolo(e,t){const s=this.trackIndexesToTracks(this.uiFacade.parseTracks(e));super.changeTrackSolo(s,t)}changeTrackVolume(e,t){const s=this.trackIndexesToTracks(this.uiFacade.parseTracks(e));super.changeTrackVolume(s,t)}trackIndexesToTracks(e){if(!this.score)return[];const t=[];if(1===e.length&&-1===e[0])for(const e of this.score.tracks)t.push(e);else for(const s of e)s>=0&&s<this.score.tracks.length&&t.push(this.score.tracks[s]);return t}loadSoundFontFromUrl(e,t){this.player&&this.player.loadSoundFontFromUrl(e,t,(e=>{this.soundFontLoad.trigger(e),this.uiFacade.triggerEvent(this.container,"soundFontLoad",e)}))}}class Qr{constructor(){this._initListeners=[]}exec(e,t,s){if("string"!=typeof t&&(s=[t],t="init"),95===t.charCodeAt(0)||"exec"===t)return null;const i=new jQuery(e),a=i.data("alphaTab");if("destroy"===t&&!a)return null;if("init"!==t&&!a)throw new Error("alphaTab not initialized");const r=this[t];if(r){const e=[i,a].concat(s);return r.apply(this,e)}return q.error("Api",`Method '${t}' does not exist on jQuery.alphaTab`),null}init(e,t,s){if(!t){t=new Kr(e[0],s),e.data("alphaTab",t);for(const i of this._initListeners)i(e,t,s)}}destroy(e,t){e.removeData("alphaTab"),t.destroy()}print(e,t,s,i){t.print(s,i)}load(e,t,s,i){return t.load(s,i)}render(e,t){t.render()}renderScore(e,t,s,i){t.renderScore(s,i)}renderTracks(e,t,s){t.renderTracks(s)}invalidate(e,t){t.render()}tex(e,t,s,i){t.tex(s,i)}muteTrack(e,t,s,i){t.changeTrackMute(s,i)}soloTrack(e,t,s,i){t.changeTrackSolo(s,i)}trackVolume(e,t,s,i){t.changeTrackVolume(s,i)}loadSoundFont(e,t,s,i){t.loadSoundFont(s,i)}resetSoundFonts(e,t){t.resetSoundFonts()}pause(e,t){t.pause()}play(e,t){return t.play()}playPause(e,t){t.playPause()}stop(e,t){t.stop()}api(e,t){return t}player(e,t){return t.player}isReadyForPlayback(e,t){return t.isReadyForPlayback}playerState(e,t){return t.playerState}masterVolume(e,t,s){return"number"==typeof s&&(t.masterVolume=s),t.masterVolume}metronomeVolume(e,t,s){return"number"==typeof s&&(t.metronomeVolume=s),t.metronomeVolume}countInVolume(e,t,s){return"number"==typeof s&&(t.countInVolume=s),t.countInVolume}midiEventsPlayedFilter(e,t,s){return Array.isArray(s)&&(t.midiEventsPlayedFilter=s),t.midiEventsPlayedFilter}playbackSpeed(e,t,s){return"number"==typeof s&&(t.playbackSpeed=s),t.playbackSpeed}tickPosition(e,t,s){return"number"==typeof s&&(t.tickPosition=s),t.tickPosition}timePosition(e,t,s){return"number"==typeof s&&(t.timePosition=s),t.timePosition}loop(e,t,s){return"boolean"==typeof s&&(t.isLooping=s),t.isLooping}renderer(e,t){return t.renderer}score(e,t){return t.score}settings(e,t){return t.settings}tracks(e,t){return t.tracks}_oninit(e){this._initListeners.push(e)}static restore(e){new jQuery(e).empty().removeData("alphaTab")}}class Zr{constructor(){this.buffer="",this._currentPath="",this._currentPathIsEmpty=!0,this.scale=1,this.color=new et(255,255,255,255),this.lineWidth=1,this.font=new na("Arial",10,Jt.Plain),this.textAlign=ne.Left,this.textBaseline=oe.Top}destroy(){}beginRender(e,t){this.scale=this.settings.display.scale,this.buffer=`<svg xmlns="http://www.w3.org/2000/svg" version="1.1" width="${0|e}px" height="${0|t}px" class="at-surface-svg">\n`,this._currentPath="",this._currentPathIsEmpty=!0,this.textBaseline=oe.Top}beginGroup(e){this.buffer+=`<g class="${e}">`}endGroup(){this.buffer+="</g>"}endRender(){return this.buffer+="</svg>",this.buffer}fillRect(e,t,s,i){s>0&&(this.buffer+=`<rect x="${e*this.scale|0}" y="${t*this.scale|0}" width="${s*this.scale}" height="${i*this.scale}" fill="${this.color.rgba}" />\n`)}strokeRect(e,t,s,i){const a=this.lineWidth*this.scale%2==0?0:.5;this.buffer+=`<rect x="${(e*this.scale|0)+a}" y="${(t*this.scale|0)+a}" width="${s*this.scale}" height="${i*this.scale}" stroke="${this.color.rgba}"`,1!==this.lineWidth&&(this.buffer+=` stroke-width="${this.lineWidth*this.scale}"`),this.buffer+=' fill="transparent" />\n'}beginPath(){}closePath(){this._currentPath+=" z"}moveTo(e,t){this._currentPath+=` M${e*this.scale},${t*this.scale}`}lineTo(e,t){this._currentPathIsEmpty=!1,this._currentPath+=` L${e*this.scale},${t*this.scale}`}quadraticCurveTo(e,t,s,i){this._currentPathIsEmpty=!1,this._currentPath+=` Q${e*this.scale},${t*this.scale},${s*this.scale},${i*this.scale}`}bezierCurveTo(e,t,s,i,a,r){this._currentPathIsEmpty=!1,this._currentPath+=` C${e*this.scale},${t*this.scale},${s*this.scale},${i*this.scale},${a*this.scale},${r*this.scale}`}fillCircle(e,t,s){this._currentPathIsEmpty=!1,e*=this.scale,t*=this.scale,s*=this.scale,this._currentPath+=` M${e-s},${t} A1,1 0 0,0 ${e+s},${t} A1,1 0 0,0 ${e-s},${t} z`,this.fill()}strokeCircle(e,t,s){this._currentPathIsEmpty=!1,e*=this.scale,t*=this.scale,s*=this.scale,this._currentPath+=` M${e-s},${t} A1,1 0 0,0 ${e+s},${t} A1,1 0 0,0 ${e-s},${t} z`,this.stroke()}fill(){this._currentPathIsEmpty||(this.buffer+=`<path d="${this._currentPath}"`,"#000000"!==this.color.rgba&&(this.buffer+=` fill="${this.color.rgba}"`),this.buffer+=' style="stroke: none"/>'),this._currentPath="",this._currentPathIsEmpty=!0}stroke(){if(!this._currentPathIsEmpty){let e=`<path d="${this._currentPath}" stroke="${this.color.rgba}"`;1===this.lineWidth&&1===this.scale||(e+=` stroke-width="${this.lineWidth*this.scale}"`),e+=' style="fill: none" />',this.buffer+=e}this._currentPath="",this._currentPathIsEmpty=!0}fillText(e,t,s){if(""===e)return;let i=`<text x="${t*this.scale|0}" y="${s*this.scale|0}" style='stroke: none; font:${this.font.toCssString(this.settings.display.scale)}; ${this.getSvgBaseLine()}'`;"#000000"!==this.color.rgba&&(i+=` fill="${this.color.rgba}"`),this.textAlign!==ne.Left&&(i+=` text-anchor="${this.getSvgTextAlignment(this.textAlign)}"`),i+=`>${Zr.escapeText(e)}</text>`,this.buffer+=i}static escapeText(e){return e.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/'/g,"&#39;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}getSvgTextAlignment(e){switch(e){case ne.Left:return"start";case ne.Center:return"middle";case ne.Right:return"end"}return""}getSvgBaseLine(){switch(this.textBaseline){case oe.Top:return"dominant-baseline: hanging";case oe.Bottom:return"dominant-baseline: ideographic";default:return""}}measureText(e){return e?Qa.measureString(e,this.font.families,this.font.size*this.scale,this.font.style,this.font.weight):new De(0,0)}onRenderFinished(){return null}beginRotate(e,t,s){this.buffer+=`<g transform="translate(${e*this.scale} ,${t*this.scale}) rotate( ${s})">`}endRotate(){this.buffer+="</g>"}}class en extends Zr{fillMusicFontSymbol(e,t,s,i,a){i!==re.None&&this.fillMusicFontSymbolText(e,t,s,`&#${i};`,a)}fillMusicFontSymbols(e,t,s,i,a){let r="";for(const e of i)e!==re.None&&(r+=`&#${e};`);this.fillMusicFontSymbolText(e,t,s,r,a)}fillMusicFontSymbolText(e,t,s,i,a){e*=this.scale,t*=this.scale,this.buffer+=`<g transform="translate(${e} ${t})" class="at" ><text`;const r=this.scale*s;this.buffer+=1!==r?` style="font-size: ${100*r}%; stroke:none"`:' style="stroke:none"',"#000000"!==this.color.rgba&&(this.buffer+=` fill="${this.color.rgba}"`),a&&(this.buffer+=` text-anchor="${this.getSvgTextAlignment(ne.Center)}"`),this.buffer+=`>${i}</text></g>`}}class tn{constructor(){this.isInsideBracket=!0,this.isRelevantForBoundsLookup=!0,this.hideOnMultiTrack=!1,this.hideOnPercussionTrack=!1}canCreate(e,t){return!this.hideOnPercussionTrack||!t.isPercussion}}!function(e){e[e.PreNotes=0]="PreNotes",e[e.OnNotes=1]="OnNotes",e[e.MiddleNotes=2]="MiddleNotes",e[e.Stem=3]="Stem",e[e.PostNotes=4]="PostNotes",e[e.EndBeat=5]="EndBeat"}(ts||(ts={}));class sn extends kr{constructor(){super(...arguments),this.glyphs=null}get isEmpty(){return!this.glyphs||0===this.glyphs.length}doLayout(){if(!this.glyphs||0===this.glyphs.length)return void(this.width=0);let e=0;for(let t=0,s=this.glyphs.length;t<s;t++){const s=this.glyphs[t];s.renderer=this.renderer,s.doLayout(),e=Math.max(e,s.width)}this.width=e}addGlyph(e){this.glyphs||(this.glyphs=[]),this.renderer&&(e.renderer=this.renderer),this.glyphs.push(e)}paint(e,t,s){const i=this.glyphs;if(i&&0!==i.length)for(const a of i)a.paint(e+this.x,t+this.y,s)}}class an extends sn{constructor(){super(0,0),this.glyphs=[]}doLayout(){}addGlyph(e){e.x=this.width,e.renderer=this.renderer,e.doLayout(),this.width=e.x+e.width,super.addGlyph(e)}}class rn{static score(e,t,s,i=!1){if(!s.style&&!i)return;const a=rn.scoreDefaultColor(e.settings.display.resources,t);return new nn(e,t,s.style,a)}static scoreColor(e,t,s){const i=rn.scoreDefaultColor(e,t);if(s.style&&s.style.colors.has(t))return s.style.colors.get(t)??i}static scoreDefaultColor(e,t){return e.mainGlyphColor}static bar(e,t,s,i=!1){if(!s.style&&!i)return;let a=e.settings.display.resources.mainGlyphColor;switch(t){case u.StandardNotationRepeats:case u.GuitarTabsRepeats:case u.SlashRepeats:case u.NumberedRepeats:case u.StandardNotationClef:case u.GuitarTabsClef:case u.StandardNotationKeySignature:case u.NumberedKeySignature:case u.StandardNotationTimeSignature:case u.GuitarTabsTimeSignature:case u.SlashTimeSignature:case u.NumberedTimeSignature:break;case u.StandardNotationBarLines:case u.GuitarTabsBarLines:case u.SlashBarLines:case u.NumberedBarLines:a=e.settings.display.resources.barSeparatorColor;break;case u.StandardNotationBarNumber:case u.SlashBarNumber:case u.NumberedBarNumber:case u.GuitarTabsBarNumber:a=e.settings.display.resources.barNumberColor;break;case u.StandardNotationStaffLine:case u.GuitarTabsStaffLine:case u.SlashStaffLine:case u.NumberedStaffLine:a=e.settings.display.resources.staffLineColor}return new nn(e,t,s.style,a)}static voice(e,t,s,i=!1){if(!s.style&&!i)return;const a=0===s.index?e.settings.display.resources.mainGlyphColor:e.settings.display.resources.secondaryGlyphColor;return new nn(e,t,s.style,a)}static trackColor(e,t,s){const i=rn.trackDefaultColor(e,t);if(s.style&&s.style.colors.has(t))return s.style.colors.get(t)??i}static trackDefaultColor(e,t){let s=e.mainGlyphColor;switch(t){case we.TrackName:case we.SystemSeparator:case we.StringTuning:break;case we.BracesAndBrackets:s=e.barSeparatorColor}return s}static track(e,t,s,i=!1){if(!s.style&&!i)return;const a=rn.trackDefaultColor(e.settings.display.resources,t);return new nn(e,t,s.style,a)}static beatColor(e,t,s){const i=rn.beatDefaultColor(e,t,s);if(s.style&&s.style.colors.has(t))return s.style.colors.get(t)??i}static beatDefaultColor(e,t,s){return 0===s.voice.index?e.mainGlyphColor:e.secondaryGlyphColor}static beat(e,t,s,i=!1){if(!s.style&&!i)return;const a=rn.beatDefaultColor(e.settings.display.resources,t,s);return new nn(e,t,s.style,a)}static noteColor(e,t,s){const i=rn.noteDefaultColor(e,t,s);if(s.style&&s.style.colors.has(t))return s.style.colors.get(t)??i}static noteDefaultColor(e,t,s){return 0===s.beat.voice.index?e.mainGlyphColor:e.secondaryGlyphColor}static note(e,t,s,i=!1){if(!s.style&&!i)return;const a=0===s.beat.voice.index?e.settings.display.resources.mainGlyphColor:e.settings.display.resources.secondaryGlyphColor;return new nn(e,t,s.style,a)}}class nn{constructor(e,t,s,i){this._canvas=e,s&&s.colors.has(t)?(this._previousColor=e.color,e.color=s.colors.get(t)??i):s||(this._previousColor=e.color,e.color=i)}[Symbol.dispose](){this._previousColor&&(this._canvas.color=this._previousColor)}}class on extends sn{constructor(e,t,s){super(e,t),this.voice=s,this.beatGlyphs=[],this.tupletGroups=[]}scaleToWidth(e){const t=this.renderer.layoutingInfo.spaceToForce(e);this.scaleToForce(t)}scaleToForce(e){this.width=this.renderer.layoutingInfo.calculateVoiceWidth(e);const t=this.renderer.layoutingInfo.buildOnTimePositions(e),s=this.beatGlyphs;for(let e=0,i=s.length;e<i;e++){const a=s[e];if(a.beat.graceType===w.None)a.x=t.get(a.beat.absoluteDisplayStart)-a.onTimeX;else{const i=a.beat.graceGroup.beats[0].absoluteDisplayStart,r=a.beat.graceGroup.id;if(a.beat.graceGroup.isComplete&&t.has(i)){a.x=t.get(i)-a.onTimeX;const e=this.renderer.layoutingInfo.allGraceRods.get(r),s=a.beat.graceGroup.beats[a.beat.graceGroup.beats.length-1].nextBeat,n=s?this.renderer.layoutingInfo.getPreBeatSize(s)+Fr.GraceBeatPadding:0;a.x-=n,a.x-=e[a.beat.graceIndex].postSpringWidth,a.x+=e[a.beat.graceIndex].graceBeatWidth;const o=e[a.beat.graceGroup.beats.length-1];a.x-=o.graceBeatWidth}else{const t=this.renderer.layoutingInfo.incompleteGraceRods.get(r),i=t[a.beat.graceIndex].postSpringWidth-t[a.beat.graceIndex].preSpringWidth;e>0?0===a.beat.graceIndex?a.x=s[e-1].x+s[e-1].width:a.x=s[e-1].x+t[a.beat.graceIndex-1].postSpringWidth-t[a.beat.graceIndex-1].preSpringWidth-i:a.x=-i}}if(e>0){const t=a.x-s[e-1].x;s[e-1].scaleToWidth(t)}if(e===i-1){const e=this.width-s[s.length-1].x;a.scaleToWidth(e)}}}registerLayoutingInfo(e){const t=this.beatGlyphs;for(const s of t)s.registerLayoutingInfo(e)}applyLayoutingInfo(e){const t=this.beatGlyphs;for(const s of t)s.applyLayoutingInfo(e);this.scaleToForce(Math.max(this.renderer.settings.display.stretchForce,e.minStretchForce))}addGlyph(e){const t=e;e.x=0===this.beatGlyphs.length?0:this.beatGlyphs[this.beatGlyphs.length-1].x+this.beatGlyphs[this.beatGlyphs.length-1].width,e.renderer=this.renderer,e.doLayout(),this.beatGlyphs.push(t),this.width=e.x+e.width,t.beat.hasTuplet&&t.beat.tupletGroup.beats[0].id===t.beat.id&&this.tupletGroups.push(t.beat.tupletGroup)}doLayout(){}paint(e,t,s){const i=rn.voice(s,I.Glyphs,this.voice,!0);try{for(let i=0,a=this.beatGlyphs.length;i<a;i++)this.beatGlyphs[i].paint(e+this.x,t+this.y,s)}finally{i?.[Symbol.dispose]?.()}}}on.KeySizeBeat="Beat";class hn{constructor(){this.staffId="",this.up=0,this.down=0}}class ln{constructor(){this.startBeat=null,this.startX=0,this.startY=0,this.endBeat=null,this.endX=0,this.endY=0}calcY(e){return this.startX===this.endX?this.startY:(this.endY-this.startY)/(this.endX-this.startX)*(e-this.startX)+this.startY}}class cn{get isRestBeamHelper(){return 1===this.beats.length&&this.beats[0].isRest}hasLine(e,t){return e&&this.beatHasLine(t)||!e&&1===this.beats.length&&this.beatHasLine(t)}beatHasLine(e){return e.duration>_.Whole}hasFlag(e,t){return e&&this.beatHasFlag(t)||!e&&1===this.beats.length&&this.beatHasFlag(this.beats[0])}beatHasFlag(e){return!e.deadSlapped&&!e.isRest&&(e.duration>_.Quarter||e.graceType!==w.None)}constructor(e,t){this._beatLineXPositions=new Map,this._firstNonRestBeat=null,this._lastNonRestBeat=null,this.voice=null,this.beats=[],this.shortestDuration=_.QuadrupleWhole,this.hasTuplet=!1,this.slashBeats=[],this._firstBeatLowestNoteCompareValue=-1,this._firstBeatHighestNoteCompareValue=-1,this._lastBeatLowestNoteCompareValue=-1,this._lastBeatHighestNoteCompareValue=-1,this.lowestNoteInHelper=null,this._lowestNoteCompareValueInHelper=-1,this.highestNoteInHelper=null,this._highestNoteCompareValueInHelper=-1,this.invertBeamDirection=!1,this.preferredBeamDirection=null,this.isGrace=!1,this.minRestLine=null,this.beatOfMinRestLine=null,this.maxRestLine=null,this.beatOfMaxRestLine=null,this.direction=Te.Up,this.drawingInfos=new Map,this._staff=e,this._renderer=t,this.beats=[]}getBeatLineX(e,t){return t=t??this.direction,this.hasBeatLineX(e)?t===Te.Up?this._beatLineXPositions.get(e.index).up:this._beatLineXPositions.get(e.index).down:0}hasBeatLineX(e){return this._beatLineXPositions.has(e.index)}registerBeatLineX(e,t,s,i){const a=this.getOrCreateBeatPositions(t);a.staffId=e,a.up=s,a.down=i;for(const e of this.drawingInfos.values())e.startBeat===t?e.startX=this.getBeatLineX(t):e.endBeat===t&&(e.endX=this.getBeatLineX(t))}getOrCreateBeatPositions(e){return this._beatLineXPositions.has(e.index)||this._beatLineXPositions.set(e.index,new hn),this._beatLineXPositions.get(e.index)}finish(){this.direction=this.calculateDirection()}calculateDirection(){let e=null;if(this.voice?null!==this.preferredBeamDirection?e=this.preferredBeamDirection:this.voice.index>0?e=this.invert(Te.Down):(this.voice.bar.isMultiVoice||this.beats[0].graceType!==w.None)&&(e=this.invert(Te.Up)):e=Te.Up,this.highestNoteInHelper&&this.lowestNoteInHelper){const t=this._renderer.getNoteY(this.highestNoteInHelper,is.Center),s=this._renderer.getNoteY(this.lowestNoteInHelper,is.Center);if(null===e){const i=(t+s)/2;e=this.invert(this._renderer.middleYPosition<i?Te.Up:Te.Down)}this._renderer.completeBeamingHelper(this)}else e=this.invert(Te.Up),this._renderer.completeBeamingHelper(this);return e}static computeLineHeightsForRest(e){switch(e){case _.QuadrupleWhole:case _.DoubleWhole:return[2,2];case _.Whole:return[0,1];case _.Half:return[1,0];case _.Quarter:return[3,3];case _.Eighth:return[2,2];case _.Sixteenth:return[2,4];case _.ThirtySecond:return[4,4];case _.SixtyFourth:return[4,6];case _.OneHundredTwentyEighth:return[6,6];case _.TwoHundredFiftySixth:return[6,8]}return[0,0]}applyRest(e,t){if(this._lastNonRestBeat&&e.index>=this._lastNonRestBeat.index||this._firstNonRestBeat&&e.index<=this._firstNonRestBeat.index)return;let s=t,i=t;const a=cn.computeLineHeightsForRest(e.duration);s-=a[0],i+=a[1];const r=this.minRestLine,n=this.maxRestLine;(null===r||r>s)&&(this.minRestLine=s,this.beatOfMinRestLine=e),(null===n||n<i)&&(this.maxRestLine=i,this.beatOfMaxRestLine=e)}invert(e){return this.invertBeamDirection?e===Te.Down?Te.Up:Te.Down:e}checkBeat(e){e.invertBeamDirection&&(this.invertBeamDirection=!0),this.voice||(this.voice=e.voice);let t=!1;if(0===this.beats.length)t=!0;else switch(this.beats[this.beats.length-1].beamingMode){case fe.Auto:case fe.ForceSplitOnSecondaryToNext:t=cn.canJoin(this.beats[this.beats.length-1],e);break;case fe.ForceSplitToNext:t=!1;break;case fe.ForceMergeWithNext:t=!0}return t&&(null==this.preferredBeamDirection&&null!==e.preferredBeamDirection&&(this.preferredBeamDirection=e.preferredBeamDirection),e.hasTuplet&&(this.hasTuplet=!0),e.graceType!==w.None&&(this.isGrace=!0),e.isRest?0===this.beats.length&&this.beats.push(e):(this.isRestBeamHelper&&(this.beats=[]),this.beats.push(e),this.checkNote(e.minNote),this.checkNote(e.maxNote),this.shortestDuration<e.duration&&(this.shortestDuration=e.duration),this._firstNonRestBeat||(this._firstNonRestBeat=e),this._lastNonRestBeat=e),e.slashed&&this.slashBeats.push(e)),t}checkNote(e){if(!e)return;let t,s;this.voice&&e.isPercussion?(t=-Bs.getPercussionLine(this.voice.bar,Bs.getNoteValue(e)),s=t):(t=Bs.getNoteValue(e),s=t,e.harmonicType!==T.None&&e.harmonicType!==T.Natural&&(s=e.realValue-this._staff.displayTranspositionPitch)),1===this.beats.length&&this.beats[0]===e.beat&&((-1===this._firstBeatLowestNoteCompareValue||t<this._firstBeatLowestNoteCompareValue)&&(this._firstBeatLowestNoteCompareValue=t),(-1===this._firstBeatHighestNoteCompareValue||s>this._firstBeatHighestNoteCompareValue)&&(this._firstBeatHighestNoteCompareValue=s)),(-1===this._lastBeatLowestNoteCompareValue||t<this._lastBeatLowestNoteCompareValue)&&(this._lastBeatLowestNoteCompareValue=t),(-1===this._lastBeatHighestNoteCompareValue||s>this._lastBeatHighestNoteCompareValue)&&(this._lastBeatHighestNoteCompareValue=s),(!this.lowestNoteInHelper||t<this._lowestNoteCompareValueInHelper)&&(this.lowestNoteInHelper=e,this._lowestNoteCompareValueInHelper=t),(!this.highestNoteInHelper||s>this._highestNoteCompareValueInHelper)&&(this.highestNoteInHelper=e,this._highestNoteCompareValueInHelper=s)}static canJoin(e,t){if(!e||!t||e.graceType!==t.graceType||e.graceType===w.BendGrace||t.graceType===w.BendGrace||e.deadSlapped||t.deadSlapped)return!1;if(e.graceType!==w.None&&t.graceType!==w.None)return!0;const s=e.voice.bar;if(s!==t.voice.bar)return!1;const i=e.playbackStart,a=t.playbackStart;if(!cn.canJoinDuration(e.duration)||!cn.canJoinDuration(t.duration))return i===a;if(e.tupletGroup!==t.tupletGroup)return!1;if(e.hasTuplet&&t.hasTuplet&&e.tupletGroup===t.tupletGroup&&e.tupletGroup.isFull)return!0;let r=z.QuarterTime;if(8===s.masterBar.timeSignatureDenominator)s.masterBar.timeSignatureNumerator%3==0&&(r+=z.QuarterTime/2|0);return((r+i)/r|0)===((r+a)/r|0)}static canJoinDuration(e){switch(e){case _.Whole:case _.Half:case _.Quarter:return!1;default:return!0}}static isFullBarJoin(e,t,s){return ie.getIndex(e.duration)-2-s>0&&ie.getIndex(t.duration)-2-s>0}get beatOfLowestNote(){return this.lowestNoteInHelper.beat}get beatOfHighestNote(){return this.highestNoteInHelper.beat}isPositionFrom(e,t){return!this._beatLineXPositions.has(t.index)||(this._beatLineXPositions.get(t.index).staffId===e||!this._beatLineXPositions.get(t.index).staffId)}}class dn{constructor(e,t){this.topY=0,this.bottomY=0,this.topY=e,this.bottomY=t}}class un{constructor(e){this.topY=-1e3,this.bottomY=-1e3,this.slots=[],this.beat=e}addSlot(e,t){if(this.slots.push(new dn(e,t)),-1e3===this.topY)this.topY=e,this.bottomY=t;else{const s=Math.min(e,t),i=Math.max(e,t);s<this.topY&&(this.topY=s),i>this.bottomY&&(this.bottomY=i)}}}class pn{constructor(){this.reservedLayoutAreasByDisplayTime=new Map,this.restDurationsByDisplayTime=new Map}getBeatMinMaxY(){let e=-1e3,t=-1e3;for(const s of this.reservedLayoutAreasByDisplayTime.values())-1e3===e?(e=s.topY,t=s.bottomY):(e>s.topY&&(e=s.topY),t<s.bottomY&&(t=s.bottomY));return-1e3===e?[0,0]:[e,t]}reserveBeatSlot(e,t,s){t!==s&&(this.reservedLayoutAreasByDisplayTime.has(e.displayStart)||this.reservedLayoutAreasByDisplayTime.set(e.displayStart,new un(e)),this.reservedLayoutAreasByDisplayTime.get(e.displayStart).addSlot(t,s),e.isRest&&this.registerRest(e))}registerRest(e){this.restDurationsByDisplayTime.has(e.displayStart)||this.restDurationsByDisplayTime.set(e.displayStart,new Map),this.restDurationsByDisplayTime.get(e.displayStart).has(e.playbackDuration)||this.restDurationsByDisplayTime.get(e.displayStart).set(e.playbackDuration,e.id)}applyRestCollisionOffset(e,t,s){if(e.voice.index>0&&this.reservedLayoutAreasByDisplayTime.has(e.playbackStart)){const i=cn.computeLineHeightsForRest(e.duration).map((e=>e*s)),a=t-i[0],r=t+i[1];let n=a;const o=this.reservedLayoutAreasByDisplayTime.get(e.playbackStart);let h=!1;for(const e of o.slots)if(a>=e.topY&&a<=e.bottomY||r>=e.topY&&r<=e.bottomY){h=!0;break}if(h){n=1===e.voice.index?o.topY-i[1]-i[0]:o.bottomY;const t=n+i[0]+i[1],r=2*s,h=Math.ceil(Math.abs(n-a)/r);return o.addSlot(n,t),n<a?h*-r:h*r}}return 0}}class gn{constructor(e){this.beamHelpers=[],this.beamHelperLookup=[],this.preferredBeamDirection=null,this._renderer=e,this.collisionHelper=new pn}initialize(){const e=this._renderer,t=this._renderer.bar;let s=null,i=null;for(let a=0,r=t.voices.length;a<r;a++){const r=t.voices[a];this.beamHelpers.push([]),this.beamHelperLookup.push(new Map);for(let a=0,n=r.beats.length;a<n;a++){const n=r.beats[a];let o;n.graceType!==w.None?o=i:(o=s,i=null),o&&o.checkBeat(n)||(o&&o.finish(),o=new cn(t.staff,e),o.preferredBeamDirection=this.preferredBeamDirection,o.checkBeat(n),n.graceType!==w.None?i=o:s=o,this.beamHelpers[r.index].push(o)),this.beamHelperLookup[r.index].set(n.index,o)}s&&s.finish(),i&&i.finish(),s=null,i=null}}getBeamingHelperForBeat(e){return this.beamHelperLookup[e.voice.index].get(e.index)}}class mn extends Tr{constructor(e,t,s){super(e,t),this._textRow=0,this._fretRow=0,this._firstFretSpacing=0,this._chord=s}doLayout(){super.doLayout();const e=this.renderer.resources;this._textRow=1.5*e.effectFont.size,this._fretRow=1.5*e.effectFont.size,this._chord.firstFret>1?this._firstFretSpacing=mn.FretSpacing:this._firstFretSpacing=0,this.height=this._textRow+this._fretRow+mn.Frets*mn.FretSpacing+2*mn.Padding[1],this.width=this._firstFretSpacing+(this._chord.strings.length-1)*mn.StringSpacing+2*mn.Padding[0]}paint(e,t,s){e+=this.x+mn.Padding[0]+this._firstFretSpacing,t+=this.y;const i=mn.StringSpacing,a=mn.FretSpacing,r=this.renderer.resources,n=mn.CircleRadius,o=this.width-2*mn.Padding[0]-this._firstFretSpacing,h=s.textAlign,l=s.textBaseline;s.font=r.effectFont,s.textAlign=ne.Center,s.textBaseline=oe.Top,this._chord.showName&&s.fillText(this._chord.name,e+o/2,t+r.effectFont.size/2),t+=this._textRow,s.font=r.fretboardNumberFont,s.textBaseline=oe.Middle;for(let a=0;a<this._chord.strings.length;a++){const r=e+a*i,n=t+this._fretRow/2;let o=this._chord.strings[this._chord.strings.length-a-1];o<0?s.fillMusicFontSymbol(r,n,1,re.FretboardX,!0):0===o?s.fillMusicFontSymbol(r,n,1,re.FretboardO,!0):(o-=this._chord.firstFret-1,s.fillText(o.toString(),r,n))}t+=this._fretRow;for(let r=0;r<this._chord.strings.length;r++){const n=e+r*i;s.fillRect(n,t,1,a*mn.Frets+1)}this._chord.firstFret>1&&(s.textAlign=ne.Left,s.fillText(this._chord.firstFret.toString(),e-this._firstFretSpacing,t+a/2)),s.fillRect(e,t-1,o,2);for(let i=0;i<=mn.Frets;i++){const r=t+i*a;s.fillRect(e,r,o,1)}const c=new Map;for(const e of this._chord.barreFrets){const t=[-1,-1];c.set(e-this._chord.firstFret,t)}for(let r=0;r<this._chord.strings.length;r++){let o=this._chord.strings[r];if(o>0){if(o-=this._chord.firstFret,c.has(o)){const e=c.get(o);(-1===e[0]||r<e[0])&&(e[0]=r),(-1===e[1]||r>e[1])&&(e[1]=r)}const h=t+o*a+a/2+.5,l=e+(this._chord.strings.length-r-1)*i;s.fillCircle(l,h,n)}}for(const[r,o]of c){const h=t+r*a+a/2+.5,l=e+(this._chord.strings.length-o[1]-1)*i,c=e+(this._chord.strings.length-o[0]-1)*i;s.fillRect(l,h-n,c-l,2*n)}s.textAlign=h,s.textBaseline=l}}mn.Padding=[5,2],mn.Frets=5,mn.CircleRadius=2.5,mn.StringSpacing=10,mn.FretSpacing=12;class fn extends sn{constructor(e,t,s=ne.Center){super(e,t),this._glyphWidth=0,this.glyphs=[],this._align=s}doLayout(){let e=0;switch(this._align){case ne.Left:e=0;break;case ne.Center:e=(this.width-this._glyphWidth)/2;break;case ne.Right:e=this.width-this._glyphWidth}for(const t of this.glyphs)t.x=e,e+=t.width}addGlyphToRow(e){this.glyphs.push(e),this._glyphWidth+=e.width,e.height>this.height&&(this.height=e.height)}}class yn extends sn{constructor(e,t,s=ne.Center){super(e,t),this._rows=[],this.height=0,this.glyphs=[],this._align=s}doLayout(){let e=0,t=0;const s=yn.Padding;this._rows=[];let i=new fn(e,t,this._align);i.width=this.width;for(const a of this.glyphs)e+a.width<this.width?(i.addGlyphToRow(a),e+=a.width):(i.isEmpty||(i.doLayout(),this._rows.push(i),t+=i.height+s),e=0,i=new fn(e,t,this._align),i.width=this.width,i.addGlyphToRow(a),e+=a.width);i.isEmpty||(i.doLayout(),this._rows.push(i),t+=i.height+s),this.height=t}paint(e,t,s){for(const i of this._rows)i.paint(e+this.x,t+this.y,s)}}yn.Padding=3;class bn extends yn{addChord(e){if(e.strings.length>0){const t=new mn(0,0,e);t.renderer=this.renderer,t.doLayout(),this.glyphs.push(t)}}paint(e,t,s){if(this.glyphs.length>0){const i=rn.score(s,be.ChordDiagramList,this.renderer.scoreRenderer.score);try{super.paint(e,t,s)}finally{i?.[Symbol.dispose]?.()}}}}class Sn extends Tr{constructor(e,t,s,i,a=ne.Left,r=null,n){super(e,t),this._lineHeights=null,this._lines=s.split("\n"),this.font=i,this.textAlign=a,this.textBaseline=r,this.colorOverride=n}doLayout(){super.doLayout(),this._lineHeights=[];const e=this.renderer.scoreRenderer.canvas;for(const t of this._lines){e.font=this.font;const s=e.measureText(t),i=s.height;this._lineHeights.push(i),this.height+=i,this.width=Math.max(this.width,s.width)}}paint(e,t,s){const i=s.color;s.color=this.colorOverride??i,s.font=this.font;const a=s.textAlign,r=s.textBaseline;s.textAlign=this.textAlign,null!==this.textBaseline&&(s.textBaseline=this.textBaseline);let n=t+this.y;for(let t=0;t<this._lines.length;t++)s.fillText(this._lines[t],e+this.x,n),n+=this._lineHeights[t];s.textAlign=a,s.textBaseline=r,s.color=i}}class _n{get staffId(){return this._factory.staffId}get contentTop(){return this.y+this.staveTop+this.topSpacing+this.topOverflow}get contentBottom(){return this.y+this.topSpacing+this.topOverflow+this.staveBottom}constructor(e,t,s){this._sharedLayoutData=new Map,this.barRenderers=[],this.x=0,this.y=0,this.height=0,this.index=0,this.staffIndex=0,this.isFirstInSystem=!1,this.trackIndex=0,this.staveTop=0,this.topSpacing=0,this.bottomSpacing=0,this.staveBottom=0,this._factory=s,this.trackIndex=e,this.modelStaff=t}getSharedLayoutData(e,t){return this._sharedLayoutData.has(e)?this._sharedLayoutData.get(e):t}setSharedLayoutData(e,t){this._sharedLayoutData.set(e,t)}get isInsideBracket(){return this._factory.isInsideBracket}get isRelevantForBoundsLookup(){return this._factory.isRelevantForBoundsLookup}registerStaffTop(e){this.staveTop=e}registerStaffBottom(e){this.staveBottom=e}addBarRenderer(e){e.staff=this,e.index=this.barRenderers.length,e.reLayout(),this.barRenderers.push(e),this.system.layout.registerBarRenderer(this.staffId,e)}addBar(e,t,s){const i=this._factory.create(this.system.layout.renderer,e);i.additionalMultiRestBars=s,i.staff=this,i.index=this.barRenderers.length,i.layoutingInfo=t,i.doLayout(),i.registerLayoutingInfo();const a=i.barDisplayWidth;a>0&&this.system.layout.systemsLayoutMode===ss.FromModelWithWidths&&(i.width=a),this.barRenderers.push(i),e&&this.system.layout.registerBarRenderer(this.staffId,i)}revertLastBar(){const e=this.barRenderers[this.barRenderers.length-1];this.barRenderers.splice(this.barRenderers.length-1,1),this.system.layout.unregisterBarRenderer(this.staffId,e);for(const e of this.barRenderers)e.applyLayoutingInfo();return e}scaleToWidth(e){this._sharedLayoutData=new Map;const t=this.topOverflow;let s=0;switch(this.system.layout.systemsLayoutMode){case ss.Automatic:const i=(e-this.system.computedWidth)/this.barRenderers.length;for(const e of this.barRenderers){e.x=s,e.y=this.topSpacing+t;const a=e.computedWidth+i;e.scaleToWidth(a),s+=e.width}break;case ss.FromModelWithScale:e-=this.system.accoladeWidth;const a=this.system.totalBarDisplayScale;for(const i of this.barRenderers){i.x=s,i.y=this.topSpacing+t;const r=i.barDisplayScale*e/a;i.scaleToWidth(r),s+=i.width}break;case ss.FromModelWithWidths:for(const e of this.barRenderers){e.x=s,e.y=this.topSpacing+t;const i=e.barDisplayWidth;i>0?e.scaleToWidth(i):e.scaleToWidth(e.computedWidth),s+=e.width}}}get topOverflow(){let e=0;for(let t=0,s=this.barRenderers.length;t<s;t++){const s=this.barRenderers[t];s.topOverflow>e&&(e=s.topOverflow)}return e}get bottomOverflow(){let e=0;for(let t=0,s=this.barRenderers.length;t<s;t++){const s=this.barRenderers[t];s.bottomOverflow>e&&(e=s.bottomOverflow)}return e}calculateHeightForAccolade(){this.topSpacing=this._factory.getStaffPaddingTop(this),this.bottomSpacing=this._factory.getStaffPaddingBottom(this),this.height=this.barRenderers.length>0?this.barRenderers[0].height:0,this.height>0&&(this.height+=this.topSpacing+this.topOverflow+this.bottomOverflow+this.bottomSpacing)}finalizeStaff(){this.topSpacing=this._factory.getStaffPaddingTop(this),this.bottomSpacing=this._factory.getStaffPaddingBottom(this),this.height=0;let e=!1,t=this.topOverflow;for(let s=0;s<this.barRenderers.length;s++)this.barRenderers[s].y=this.topSpacing+t,this.height=Math.max(this.height,this.barRenderers[s].height),this.barRenderers[s].finalizeRenderer()&&(e=!0);if(e){t=this.topOverflow;for(let e=0;e<this.barRenderers.length;e++)this.barRenderers[e].y=this.topSpacing+t;for(let e=0;e<this.barRenderers.length;e++)this.barRenderers[e].finalizeRenderer()}this.height>0&&(this.height+=this.topSpacing+t+this.bottomOverflow+this.bottomSpacing)}paint(e,t,s,i,a){if(0!==this.height&&0!==a)for(let r=i,n=Math.min(i+a,this.barRenderers.length);r<n;r++)this.barRenderers[r].paint(e+this.x,t+this.y,s)}}class wn{constructor(){this.timePosition=0,this.longestDuration=0,this.smallestDuration=0,this.force=0,this.springConstant=0,this.preBeatWidth=0,this.graceBeatWidth=0,this.postSpringWidth=0,this.allDurations=new Set}get springWidth(){return this.preSpringWidth+this.postSpringWidth}get preSpringWidth(){return this.preBeatWidth+this.graceBeatWidth}}class Bn{constructor(){this._timeSortedSprings=[],this._minTime=-1,this._onTimePositionsForce=0,this._onTimePositions=new Map,this._incompleteGraceRodsWidth=0,this._minDuration=Bn.MinDuration,this.version=0,this.preBeatSize=0,this.postBeatSize=0,this.minStretchForce=0,this.totalSpringConstant=0,this.incompleteGraceRods=new Map,this.allGraceRods=new Map,this.springs=new Map,this.height=0}updateMinStretchForce(e){this.minStretchForce<e&&(this.minStretchForce=e)}getPreBeatSize(e){if(e.graceType!==w.None){const t=e.graceGroup.id;return this.allGraceRods.get(t)[e.graceIndex].preBeatWidth}const t=e.absoluteDisplayStart;return this.springs.has(t)?this.springs.get(t).preBeatWidth:0}getPostBeatSize(e){if(e.graceType!==w.None){const t=e.graceGroup.id;return this.allGraceRods.get(t)[e.graceIndex].postSpringWidth}const t=e.absoluteDisplayStart;return this.springs.has(t)?this.springs.get(t).postSpringWidth:0}addSpring(e,t,s,i,a){let r;if(this.version++,this.springs.has(e))r=this.springs.get(e),r.postSpringWidth<a&&(r.postSpringWidth=a),r.graceBeatWidth<s&&(r.graceBeatWidth=s),r.preBeatWidth<i&&(r.preBeatWidth=i),t<r.smallestDuration&&(r.smallestDuration=t),t>r.longestDuration&&(r.longestDuration=t),r.allDurations.add(t);else{if(r=new wn,r.timePosition=e,r.allDurations.add(t),this._timeSortedSprings.length>0){const e=this._timeSortedSprings[this._timeSortedSprings.length-1];for(const t of e.allDurations)e.timePosition;t<this._minDuration&&(this._minDuration=t)}r.longestDuration=t,r.postSpringWidth=a,r.graceBeatWidth=s,r.preBeatWidth=i,this.springs.set(e,r);const n=this._timeSortedSprings;let o=n.length-1;for(;o>0&&n[o].timePosition>e;)o--;this._timeSortedSprings.splice(o+1,0,r)}return(-1===this._minTime||this._minTime>e)&&(this._minTime=e),r}addBeatSpring(e,t,s){const i=e.absoluteDisplayStart;if(e.graceType!==w.None){const a=e.graceGroup.id;this.allGraceRods.has(a)||this.allGraceRods.set(a,new Array(e.graceGroup.beats.length)),e.graceGroup.isComplete||this.incompleteGraceRods.has(a)||this.incompleteGraceRods.set(a,new Array(e.graceGroup.beats.length));const r=this.allGraceRods.get(a)[e.graceIndex];if(r)r.postSpringWidth<s&&(r.postSpringWidth=s),r.preBeatWidth<t&&(r.preBeatWidth=t);else{const r=new wn;r.timePosition=i,r.postSpringWidth=s,r.preBeatWidth=t,e.graceGroup.isComplete||(this.incompleteGraceRods.get(a)[e.graceIndex]=r),this.allGraceRods.get(a)[e.graceIndex]=r}}else{let a=0;if(e.graceGroup&&this.allGraceRods.has(e.graceGroup.id))for(const t of this.allGraceRods.get(e.graceGroup.id))a+=t.springWidth;this.addSpring(i,e.displayDuration,a,t,s)}}finish(){for(const[e,t]of this.allGraceRods){let e=0;for(const s of t)e+=s.preBeatWidth,s.graceBeatWidth=e,e+=s.postSpringWidth}this._incompleteGraceRodsWidth=0;for(const e of this.incompleteGraceRods.values())for(const t of e)this._incompleteGraceRodsWidth+=t.preBeatWidth+t.postSpringWidth;this.calculateSpringConstants(),this.version++}calculateSpringConstants(){let e=0;const t=this._timeSortedSprings;if(0===t.length)return this.totalSpringConstant=-1,void(this.minStretchForce=-1);for(let s=0;s<t.length;s++){const i=t[s];let a=0;if(s===t.length-1)a=i.longestDuration;else{const e=t[s+1];a=Math.abs(e.timePosition-i.timePosition)}i.springConstant=this.calculateSpringConstant(i,a),e+=1/i.springConstant}this.totalSpringConstant=1/e,this.minStretchForce=0;for(let e=0;e<t.length;e++){const s=t[e];let i=0;if(e===t.length-1)i=s.postSpringWidth;else{const a=t[e+1];i=s.postSpringWidth+a.preSpringWidth}0===e&&(i+=s.preSpringWidth);const a=i*s.springConstant;this.updateMinStretchForce(a)}}paint(e,t,s){}calculateSpringConstant(e,t){t<=0&&(t=z.toTicks(_.TwoHundredFiftySixth)),0===e.smallestDuration&&(e.smallestDuration=t);const s=e.smallestDuration,i=this._minDuration,a=Bn.MinDurationWidth;return s/t*(1/((1+.85*Math.log2(t/i))*a))}spaceToForce(e){return-1!==this.totalSpringConstant?(this._timeSortedSprings.length>0&&(e-=this._timeSortedSprings[0].preSpringWidth),e-=this._incompleteGraceRodsWidth,Math.max(e,0)*this.totalSpringConstant):-1}calculateVoiceWidth(e){let t=0;return-1!==this.totalSpringConstant&&(t=this.calculateWidth(e,this.totalSpringConstant)),this._timeSortedSprings.length>0&&(t+=this._timeSortedSprings[0].preSpringWidth),t+=this._incompleteGraceRodsWidth,t}calculateWidth(e,t){return e/t}buildOnTimePositions(e){if(-1===this.totalSpringConstant)return new Map;if(ie.isAlmostEqualTo(this._onTimePositionsForce,e)&&this._onTimePositions)return this._onTimePositions;this._onTimePositionsForce=e;const t=new Map;this._onTimePositions=t;const s=this._timeSortedSprings;if(0===s.length)return t;let i=s[0].preSpringWidth;for(let a=0;a<s.length;a++)t.set(s[a].timePosition,i),i+=this.calculateWidth(e,s[a].springConstant);return t}}Bn.MinDuration=30,Bn.MinDurationWidth=7;class kn{constructor(){this.width=0,this.isLinkedToPrevious=!1,this.canWrap=!0,this.additionalMultiBarRestIndexes=null,this.renderers=[]}get lastMasterBarIndex(){return this.additionalMultiBarRestIndexes?this.additionalMultiBarRestIndexes[this.additionalMultiBarRestIndexes.length-1]:this.masterBar.index}}class Tn{constructor(e,t){this.staves=[],this.stavesRelevantForBoundsLookup=[],this.firstStaffInBracket=null,this.lastStaffInBracket=null,this.bracket=null,this.staffSystem=e,this.track=t}addStaff(e){this.staves.push(e),e.isRelevantForBoundsLookup&&this.stavesRelevantForBoundsLookup.push(e)}}class Nn{constructor(){this.firstStaffInBracket=null,this.lastStaffInBracket=null,this.drawAsBrace=!1,this.braceScale=1,this.width=0,this.index=0}finalizeBracket(){if(this.firstStaffInBracket===this.lastStaffInBracket)return void(this.width=0);const e=Nr.Heights.get(re.Brace),t=Nr.Widths.get(re.Brace);if(this.width=t,!this.drawAsBrace||!this.firstStaffInBracket||!this.lastStaffInBracket)return;const s=this.firstStaffInBracket.contentTop,i=(this.lastStaffInBracket.contentBottom-s)/e;this.braceScale=i,this.width=t*this.braceScale}}class xn extends Nn{constructor(e){super(),this.track=e,this.drawAsBrace=xn.isTrackDrawAsBrace(e)}includesStaff(e){return e.modelStaff.track===this.track}static isTrackDrawAsBrace(e){return e.staves.filter((e=>e.showStandardNotation)).length>1}}class vn extends xn{includesStaff(e){return e.modelStaff.track===this.track||!this.drawAsBrace&&this.track.playbackInfo.program===e.modelStaff.track.playbackInfo.program}}class Pn{constructor(e){this._allStaves=[],this._firstStaffInBrackets=null,this._lastStaffInBrackets=null,this._accoladeSpacingCalculated=!1,this._brackets=[],this._hasSystemSeparator=!1,this.x=0,this.y=0,this.index=0,this.accoladeWidth=0,this.isFull=!1,this.width=0,this.computedWidth=0,this.totalBarDisplayScale=0,this.isLast=!1,this.masterBarsRenderers=[],this.staves=[],this.layout=e,this.topPadding=e.renderer.settings.display.systemPaddingTop,this.bottomPadding=e.renderer.settings.display.systemPaddingBottom}get firstBarIndex(){return this.masterBarsRenderers[0].masterBar.index}get lastBarIndex(){return this.masterBarsRenderers[this.masterBarsRenderers.length-1].masterBar.index}addMasterBarRenderers(e,t){if(0===e.length)return null;this.masterBarsRenderers.push(t),t.layoutingInfo.preBeatSize=0;let s=0;for(let e=0,i=this.staves.length;e<i;e++){const i=this.staves[e];for(let e=0,a=i.staves.length;e<a;e++){const a=i.staves[e],r=t.renderers[s++];a.addBarRenderer(r)}}return this.calculateAccoladeSpacing(e),this.updateWidthFromLastBar(),t}addBars(e,t,s){const i=new kn;i.additionalMultiBarRestIndexes=s,i.layoutingInfo=new Bn,i.masterBar=e[0].score.masterBars[t],this.masterBarsRenderers.push(i);const a=i.layoutingInfo;for(const e of this.staves)for(const r of e.staves){const n=e.track.staves[r.modelStaff.index].bars[t],o=null==s?null:s.map((t=>e.track.staves[r.modelStaff.index].bars[t]));r.addBar(n,a,o);const h=r.barRenderers[r.barRenderers.length-1];i.renderers.push(h),h.isLinkedToPrevious&&(i.isLinkedToPrevious=!0),h.canWrap||(i.canWrap=!1)}return this.calculateAccoladeSpacing(e),a.finish(),i.width=this.updateWidthFromLastBar(),i}revertLastBar(){if(this.masterBarsRenderers.length>1){const e=this.masterBarsRenderers[this.masterBarsRenderers.length-1];this.masterBarsRenderers.splice(this.masterBarsRenderers.length-1,1);let t=0,s=0;for(let e=0,i=this._allStaves.length;e<i;e++){const i=this._allStaves[e].revertLastBar(),a=i.computedWidth;a>t&&(t=a);const r=i.barDisplayScale;r>s&&(s=r)}return this.width-=t,this.computedWidth-=t,this.totalBarDisplayScale-=s,e}return null}updateWidthFromLastBar(){let e=0,t=0;for(let s=0,i=this._allStaves.length;s<i;s++){const i=this._allStaves[s],a=i.barRenderers[i.barRenderers.length-1];a.applyLayoutingInfo(),a.computedWidth>e&&(e=a.computedWidth);const r=a.barDisplayScale;r>t&&(t=r)}return this.width+=e,this.computedWidth+=e,this.totalBarDisplayScale+=t,e}calculateAccoladeSpacing(e){const t=this.layout.renderer.settings;if(!this._accoladeSpacingCalculated){this._accoladeSpacingCalculated=!0,this.accoladeWidth=0;const s=this.layout.renderer.score.stylesheet;if(this.layout.renderer.settings.notation.isNotationElementVisible(E.TrackNames)){const n=1===this.layout.renderer.tracks.length?s.singleTrackTrackNamePolicy:s.multiTrackTrackNamePolicy,o=0===this.index?s.firstSystemTrackNameMode:s.otherSystemsTrackNameMode,h=0===this.index?s.firstSystemTrackNameOrientation:s.otherSystemsTrackNameOrientation;let l=!1;switch(n){case i.Hidden:break;case i.FirstSystem:l=0===this.index;break;case i.AllSystems:l=!0}let c=!1;if(l){const s=this.layout.renderer.canvas,i=t.display.resources.effectFont;s.font=i;for(const t of e){let e="";switch(o){case a.FullName:e=t.name;break;case a.ShortName:e=t.shortName}if(e.length>0){c=!0;const t=s.measureText(e);switch(h){case r.Horizontal:this.accoladeWidth=Math.ceil(Math.max(this.accoladeWidth,t.width));break;case r.Vertical:this.accoladeWidth=Math.ceil(Math.max(this.accoladeWidth,t.height))}}}c&&(this.accoladeWidth+=t.display.systemLabelPaddingLeft,this.accoladeWidth+=t.display.systemLabelPaddingRight)}}let n=0;for(const e of this._allStaves)e.y=n,e.calculateHeightForAccolade(),n+=e.height;let o=0;for(const e of this._brackets)e.finalizeBracket(),o=Math.max(o,e.width);this.accoladeWidth+=o,this.width+=this.accoladeWidth,this.computedWidth+=this.accoladeWidth}}getStaffTrackGroup(e){for(let t=0,s=this.staves.length;t<s;t++){const s=this.staves[t];if(s.track===e)return s}return null}addStaff(e,t){let i=this.getStaffTrackGroup(e);if(i||(i=new Tn(this,e),this.staves.push(i)),t.staffTrackGroup=i,t.system=this,t.index=this._allStaves.length,this._allStaves.push(t),i.addStaff(t),t.isInsideBracket){this._firstStaffInBrackets||(this._firstStaffInBrackets=t,t.isFirstInSystem=!0),i.firstStaffInBracket||(i.firstStaffInBracket=t),this._lastStaffInBrackets=t,i.lastStaffInBracket=t;let a=this._brackets.find((e=>e.includesStaff(t)));if(!a)switch(e.score.stylesheet.bracketExtendMode){case s.NoBrackets:break;case s.GroupStaves:a=new xn(e),a.index=this._brackets.length,this._brackets.push(a);break;case s.GroupSimilarInstruments:a=new vn(e),a.index=this._brackets.length,this._brackets.push(a)}a&&(a.firstStaffInBracket||(a.firstStaffInBracket=t),a.lastStaffInBracket=t,i.bracket=a)}}get height(){return 0===this._allStaves.length?0:this._allStaves[this._allStaves.length-1].y+this._allStaves[this._allStaves.length-1].height+this.topPadding+this.bottomPadding}scaleToWidth(e){for(let t=0,s=this._allStaves.length;t<s;t++)this._allStaves[t].scaleToWidth(e);this.width=e}paint(e,t,s){if(t+=this.topPadding,this.paintPartial(e+this.x,t+this.y,s,0,this.masterBarsRenderers.length),this._hasSystemSeparator){const i=rn.track(s,we.SystemSeparator,this._allStaves[0].modelStaff.track);try{s.fillMusicFontSymbol(e+this.x,t+this.y+this.height-10,1,re.SystemDivider,!1),s.fillMusicFontSymbol(e+this.x+this.width-Pn.SystemSignSeparatorWidth,t+this.y+this.height-Pn.SystemSignSeparatorPadding,1,re.SystemDivider,!1)}finally{i?.[Symbol.dispose]?.()}}}paintPartial(e,t,s,n,o){for(let i=0,a=this._allStaves.length;i<a;i++)this._allStaves[i].paint(e,t,s,n,o);const h=this.layout.renderer.settings.display.resources;if(this.staves.length>0&&0===n){s.color=h.barSeparatorColor;const n=this.layout.renderer.settings,o=this.layout.renderer.settings.notation.isNotationElementVisible(E.TrackNames);if(s.font=h.effectFont,o){const o=this.layout.renderer.score.stylesheet,h=1===this.layout.renderer.tracks.length?o.singleTrackTrackNamePolicy:o.multiTrackTrackNamePolicy,l=0===this.index?o.firstSystemTrackNameMode:o.otherSystemsTrackNameMode,c=0===this.index?o.firstSystemTrackNameOrientation:o.otherSystemsTrackNameOrientation;let d=!1;switch(h){case i.Hidden:break;case i.FirstSystem:d=0===this.index;break;case i.AllSystems:d=!0}if(d){const i=s.textBaseline,o=s.textAlign;for(const i of this.staves)if(i.firstStaffInBracket&&i.lastStaffInBracket){const o=t+i.firstStaffInBracket.contentTop,h=t+i.lastStaffInBracket.contentBottom;let d="";switch(l){case a.FullName:d=i.track.name;break;case a.ShortName:d=i.track.shortName}const u=rn.track(s,we.TrackName,i.track);try{if(d.length>0){const t=e+i.firstStaffInBracket.x-n.display.accoladeBarPaddingRight-(i.bracket?.width??0)-n.display.systemLabelPaddingRight;switch(c){case r.Horizontal:s.textBaseline=oe.Middle,s.textAlign=ne.Right,s.fillText(d,t,(o+h)/2);break;case r.Vertical:s.textBaseline=oe.Bottom,s.textAlign=ne.Center;const e=.1;s.beginRotate(t,(o+h)/2,-90-e),s.fillText(d,0,0),s.endRotate()}}}finally{u?.[Symbol.dispose]?.()}}s.textBaseline=i,s.textAlign=o}}if(this._allStaves.length>0){let i=null;for(const a of this._allStaves)if(a.isInsideBracket){if(null!==i){const r=i.contentBottom,n=a.contentTop,o=e+i.x,h=i.barRenderers[0],l=rn.bar(s,h.staffLineBarSubElement,h.bar);try{const e=Math.ceil(n-r);s.fillRect(o,t+r,1,e)}finally{l?.[Symbol.dispose]?.()}}i=a}}for(const i of this._brackets)if(i.firstStaffInBracket&&i.lastStaffInBracket){const a=e+i.firstStaffInBracket.x,r=i.width,o=n.display.accoladeBarPaddingRight;let h=t+i.firstStaffInBracket.contentTop,l=t+i.lastStaffInBracket.contentBottom;if(i.drawAsBrace)s.fillMusicFontSymbol(a-o-r,l,i.braceScale,re.Brace);else if(i.firstStaffInBracket!==i.lastStaffInBracket){const e=r/2;h-=e,l+=2*e,s.fillRect(a-o-r,h,r,Math.ceil(l-h));const t=a-o-r-.5;s.fillMusicFontSymbol(t,h,1,re.BracketTop),s.fillMusicFontSymbol(t,Math.floor(l),1,re.BracketBottom)}}}}finalizeSystem(){const e=this.layout.renderer.settings;0===this.index&&(this.topPadding=e.display.firstSystemPaddingTop),this.isLast?this.bottomPadding=e.display.lastSystemPaddingBottom:this.layout.renderer.score.stylesheet.useSystemSignSeparator&&this.layout.renderer.tracks.length>1&&(this.bottomPadding+=Pn.SystemSignSeparatorHeight,this._hasSystemSeparator=!0);let t=0;for(const e of this._allStaves)e.x=this.accoladeWidth,e.y=t,e.finalizeStaff(),t+=e.height;for(const e of this._brackets)e.finalizeBracket()}buildBoundingsLookup(e,t){if(this.layout.renderer.boundsLookup.isFinished)return;const s=this._firstStaffInBrackets,i=this._lastStaffInBrackets;if(!s||!i)return;t+=this.topPadding;const a=this._allStaves[this._allStaves.length-1],r=t+this.y+s.y,n=t+this.y+i.y+i.height,o=t+this.y+this._allStaves[0].y,h=t+this.y+a.y+a.height,l=t+this.y+s.y+s.topSpacing+s.topOverflow+(s.barRenderers.length>0?s.barRenderers[0].topPadding:0),c=n-r,d=t+this.y+a.y+a.height-a.bottomSpacing-a.bottomOverflow-(a.barRenderers.length>0?a.barRenderers[0].bottomPadding:0)-l,u=h-o,p=this.x+s.x,g=new ar;g.visualBounds=new mt,g.visualBounds.x=e+this.x,g.visualBounds.y=t+this.y,g.visualBounds.w=this.width,g.visualBounds.h=this.height-this.topPadding-this.bottomPadding,g.realBounds=new mt,g.realBounds.x=e+this.x,g.realBounds.y=t+this.y,g.realBounds.w=this.width,g.realBounds.h=this.height,this.layout.renderer.boundsLookup.addStaffSystem(g);const m=new Map;for(let e=0;e<this.staves.length;e++)for(const s of this.staves[e].stavesRelevantForBoundsLookup)for(const e of s.barRenderers){let i;m.has(e.bar.masterBar.index)?i=m.get(e.bar.masterBar.index):(i=new sr,i.index=e.bar.masterBar.index,i.isFirstOfLine=e.isFirstOfLine,i.realBounds=new mt,i.realBounds.x=p+e.x,i.realBounds.y=o,i.realBounds.w=e.width,i.realBounds.h=u,i.visualBounds=new mt,i.visualBounds.x=p+e.x,i.visualBounds.y=r,i.visualBounds.w=e.width,i.visualBounds.h=c,i.lineAlignedBounds=new mt,i.lineAlignedBounds.x=p+e.x,i.lineAlignedBounds.y=l,i.lineAlignedBounds.w=e.width,i.lineAlignedBounds.h=d,this.layout.renderer.boundsLookup.addMasterBar(i),m.set(i.index,i)),e.buildBoundingsLookup(i,p,t+this.y+s.y)}}getBarX(e){if(!this._firstStaffInBrackets||0===this.layout.renderer.tracks.length)return 0;const t=this.layout.renderer.tracks[0].staves[0].bars[e];return this.layout.getRendererForBar(this._firstStaffInBrackets.staffId,t).x}}Pn.SystemSignSeparatorHeight=40,Pn.SystemSignSeparatorPadding=10,Pn.SystemSignSeparatorWidth=36;class Fn extends yn{constructor(e,t){super(e,t,ne.Left)}}class Cn extends sn{constructor(e,t,s,i){super(e,t),this._tuning=s,this._trackLabel=i,this.glyphs=[]}doLayout(){if(!(this.glyphs.length>0)){this.createGlyphs(this._tuning);for(const e of this.glyphs)e.renderer=this.renderer,e.doLayout()}}paint(e,t,s){s.textBaseline=oe.Middle;const i=s.color;this.colorOverride&&(s.color=this.colorOverride),super.paint(e,t,s),s.color=i}createGlyphs(e){const t=this.renderer.resources;this.height=0;if(this._trackLabel.length>0){this.height+=1;const e=new Sn(0,this.height,this._trackLabel,t.effectFont,ne.Left);e.renderer=this.renderer,e.doLayout(),this.height+=e.height+1,e.y+=e.height/2,this.addGlyph(e)}const s=new Sn(0,this.height,e.name,t.effectFont,ne.Left);s.renderer=this.renderer,s.doLayout(),this.height+=s.height,s.y+=s.height/2,this.addGlyph(s);if(this.renderer.scoreRenderer.canvas.font=t.effectFont,this.width=Math.max(this.renderer.scoreRenderer.canvas.measureText(this._trackLabel).width,Math.max(this.renderer.scoreRenderer.canvas.measureText(e.name).width,128)),!e.isStandard){this.height+=15;const s=Cn.CircleNumberScale,i=Nr.Heights.get(re.GuitarString0)*s,a=0|Math.ceil(e.tunings.length/2);let r=0,n=this.height;for(let o=0,h=e.tunings.length;o<h;o++){const h=re.GuitarString0+(o+1);this.addGlyph(new xr(r,n+i/2.5,s,h));const l=`= ${st.getTextForTuning(e.tunings[o],!1)}`;this.addGlyph(new Sn(r+i+1,n,l,t.effectFont,ne.Left)),n+=15,o===a-1&&(n=this.height,r+=64)}this.height+=15*a}this.width+=15}}Cn.CircleNumberScale=.7;class Dn{constructor(e,t){this.args=e,this.renderCallback=t}}!function(e){e[e.Automatic=0]="Automatic",e[e.FromModelWithScale=1]="FromModelWithScale",e[e.FromModelWithWidths=2]="FromModelWithWidths"}(ss||(ss={}));class En{get scaledWidth(){return Math.round(this.width/this.renderer.settings.display.scale)}constructor(e){this._barRendererLookup=new Map,this.pagePadding=null,this.width=0,this.height=0,this.multiBarRestInfo=null,this.headerGlyphs=new Map,this.footerGlyphs=new Map,this.chordDiagrams=null,this.tuningGlyph=null,this.systemsLayoutMode=ss.Automatic,this._lazyPartials=new Map,this.firstBarIndex=0,this.lastBarIndex=0,this.renderer=e}resize(){this._lazyPartials.clear(),this.doResize()}layoutAndRender(){this._lazyPartials.clear();const e=this.renderer.score;this.firstBarIndex=ie.computeFirstDisplayedBarIndex(e,this.renderer.settings),this.lastBarIndex=ie.computeLastDisplayedBarIndex(e,this.renderer.settings,this.firstBarIndex),this.multiBarRestInfo=ie.buildMultiBarRestInfo(this.renderer.tracks,this.firstBarIndex,this.lastBarIndex),this.pagePadding=this.renderer.settings.display.padding.map((e=>e/this.renderer.settings.display.scale)),this.pagePadding||(this.pagePadding=[0,0,0,0]),1===this.pagePadding.length?this.pagePadding=[this.pagePadding[0],this.pagePadding[0],this.pagePadding[0],this.pagePadding[0]]:2===this.pagePadding.length&&(this.pagePadding=[this.pagePadding[0],this.pagePadding[1],this.pagePadding[0],this.pagePadding[1]]),this.createScoreInfoGlyphs(),this.doLayoutAndRender()}registerPartial(e,t){if(0===e.height)return;const s=this.renderer.settings.display.scale;e.x*=s,e.y*=s,e.width*=s,e.height*=s,e.totalWidth*=s,e.totalHeight*=s,this.renderer.settings.core.enableLazyLoading?(this._lazyPartials.set(e.id,new Dn(e,t)),this.renderer.partialLayoutFinished.trigger(e)):(this.renderer.partialLayoutFinished.trigger(e),this.internalRenderLazyPartial(e,t))}internalRenderLazyPartial(e,t){const s=this.renderer.canvas;s.beginRender(e.width,e.height),t(s),e.renderResult=s.endRender(),this.renderer.partialRenderFinished.trigger(e)}renderLazyPartial(e){if(this._lazyPartials.has(e)){const t=this._lazyPartials.get(e);this.internalRenderLazyPartial(t.args,t.renderCallback)}}createHeaderFooterGlyph(e,t,s,i){switch(s){case be.WordsAndMusic:if(t.words!==t.music)return;break;case be.Words:case be.Music:if(t.words===t.music)return;break;case be.CopyrightSecondLine:if(!this.headerGlyphs.has(be.Copyright))return}const a=e.display.resources,r=e.notation,n=t.style&&t.style.headerAndFooter.has(s)?t.style.headerAndFooter.get(s):Xe.defaultHeaderAndFooter.get(s);let o=void 0===n.isVisible||n.isVisible;if(void 0!==i&&(o=r.isNotationElementVisible(i)),!o)return;const h=n.buildText(t);return h?new Sn(0,0,h,a.getFontForElement(s),n.textAlign,void 0,rn.scoreColor(a,s,t)):void 0}createScoreInfoGlyphs(){q.debug("ScoreLayout","Creating score info glyphs");const e=this.renderer.settings,t=this.renderer.score;this.headerGlyphs=new Map,this.footerGlyphs=new Map;const s=new On(this.renderer,this.renderer.tracks[0].staves[0].bars[0]);for(const[i,a]of En.HeaderElements.value){const r=this.createHeaderFooterGlyph(e,t,i,a);r&&(r.renderer=s,r.doLayout(),this.headerGlyphs.set(i,r))}for(const[i,a]of En.FooterElements.value){const r=this.createHeaderFooterGlyph(e,t,i,a);r&&(r.renderer=s,r.doLayout(),this.footerGlyphs.set(i,r))}const i=e.notation,a=e.display.resources;if(i.isNotationElementVisible(E.GuitarTuning)){const e=[];for(const s of this.renderer.tracks)for(const i of s.staves){let a=!i.isPercussion&&i.isStringed&&i.tuning.length>0&&i.showTablature;if(t.stylesheet.perTrackDisplayTuning&&t.stylesheet.perTrackDisplayTuning.has(s.index)&&!1===t.stylesheet.perTrackDisplayTuning.get(s.index)&&(a=!1),a){e.push(i);break}}if(e.length>0&&t.stylesheet.globalDisplayTuning){this.tuningGlyph=new Fn(0,0),this.tuningGlyph.renderer=s;for(const t of e)if(t.stringTuning.tunings.length>0){const i=e.length>1?t.track.name:"",r=new Cn(0,0,t.stringTuning,i);r.colorOverride=rn.trackColor(a,we.StringTuning,t.track),r.renderer=s,r.doLayout(),this.tuningGlyph.addGlyph(r)}}}if(i.isNotationElementVisible(E.ChordDiagrams)){this.chordDiagrams=new bn(0,0),this.chordDiagrams.renderer=s;const e=new Set;for(const s of this.renderer.tracks){if(t.stylesheet.globalDisplayChordDiagramsOnTop&&(null==t.stylesheet.perTrackChordDiagramsOnTop||!t.stylesheet.perTrackChordDiagramsOnTop.has(s.index)||t.stylesheet.perTrackChordDiagramsOnTop.get(s.index)))for(const t of s.staves){const s=t.chords;if(s)for(const[,t]of s)e.has(t.uniqueId)||t.showDiagram&&(e.add(t.uniqueId),this.chordDiagrams.addChord(t))}}}}createEmptyStaffSystem(){const e=new Pn(this);for(let t=0;t<this.renderer.tracks.length;t++){const s=this.renderer.tracks[t];for(let i=0;i<s.staves.length;i++){const a=s.staves[i],r=rc.staveProfiles.get(this.renderer.settings.display.staveProfile);for(const i of r)i.canCreate(s,a)&&e.addStaff(s,new _n(t,a,i))}}return e}registerBarRenderer(e,t){if(this._barRendererLookup.has(e)||this._barRendererLookup.set(e,new Map),this._barRendererLookup.get(e).set(t.bar.id,t),t.additionalMultiRestBars)for(const s of t.additionalMultiRestBars)this._barRendererLookup.get(e).set(s.id,t)}unregisterBarRenderer(e,t){if(this._barRendererLookup.has(e)){const s=this._barRendererLookup.get(e);if(s.delete(t.bar.id),t.additionalMultiRestBars)for(const e of t.additionalMultiRestBars)s.delete(e.id)}}getRendererForBar(e,t){const s=t.id;return this._barRendererLookup.has(e)&&this._barRendererLookup.get(e).has(s)?this._barRendererLookup.get(e).get(s):null}layoutAndRenderBottomScoreInfo(e){e=Math.round(e);const t=new Za;t.x=0,t.y=e;let s=0;const i=this.renderer.settings.display.resources,a=[];let r=0;for(const[e,t]of En.FooterElements.value)if(this.footerGlyphs.has(e)){const t=this.footerGlyphs.get(e);t.y=s,this.alignScoreInfoGlyph(t),s+=1.2*t.font.size,a.push(t),r=Math.max(r,Math.round(t.x+t.width))}return s=Math.round(s),a.length>0&&(t.width=r,t.height=s,t.totalWidth=this.scaledWidth,t.totalHeight=e+t.height,this.registerPartial(t,(e=>{e.color=i.scoreInfoColor,e.textAlign=ne.Left,e.textBaseline=oe.Top;for(const t of a)t.paint(0,0,e)}))),e+s}alignScoreInfoGlyph(e){if(rc.getLayoutEngineFactory(this.renderer.settings.display.layoutMode).vertical)switch(e.textAlign){case ne.Left:e.x=this.pagePadding[0];break;case ne.Center:e.x=this.scaledWidth/2;break;case ne.Right:e.x=this.scaledWidth-this.pagePadding[2]}else e.x=this.firstBarX,e.textAlign=ne.Left}layoutAndRenderAnnotation(e){const t=this.renderer.settings.display.resources,s=na.withFamilyList(t.copyrightFont.families,12,Jt.Plain,Yt.Bold),i=new On(this.renderer,this.renderer.tracks[0].staves[0].bars[0]),a=new Sn(0,0,"rendered by alphaTab",s,ne.Center,void 0,t.mainGlyphColor);a.renderer=i,a.doLayout(),this.alignScoreInfoGlyph(a);const r=new Za;return r.width=a.x+a.width,r.x=0,r.height=12,r.y=e,r.totalWidth=this.scaledWidth,r.totalHeight=e+12,r.firstMasterBarIndex=-1,r.lastMasterBarIndex=-1,this.registerPartial(r,(e=>{e.color=t.mainGlyphColor,e.font=s,e.textAlign=ne.Left,e.textBaseline=oe.Top,a.paint(0,0,e)})),e+12}}En.HeaderElements=new Y((()=>new Map([[be.Title,E.ScoreTitle],[be.SubTitle,E.ScoreSubTitle],[be.Artist,E.ScoreArtist],[be.Album,E.ScoreAlbum],[be.Words,E.ScoreWords],[be.Music,E.ScoreMusic],[be.WordsAndMusic,E.ScoreWordsAndMusic],[be.Transcriber,void 0]]))),En.FooterElements=new Y((()=>new Map([[be.Copyright,E.ScoreCopyright],[be.CopyrightSecondLine,void 0]])));class Ln extends sn{constructor(){super(0,0),this._effectGlyphs=[],this._normalGlyphs=[],this.computedWidth=0}doLayout(){let e=0;if(this.glyphs)for(let t=0,s=this.glyphs.length;t<s;t++){const s=this.glyphs[t];s.x=e,s.renderer=this.renderer,s.doLayout(),e+=s.width}this.width=e,this.computedWidth=e}noteLoop(e){for(let t=this.container.beat.notes.length-1;t>=0;t--)e(this.container.beat.notes[t])}addEffect(e){super.addGlyph(e),this._effectGlyphs.push(e)}addNormal(e){super.addGlyph(e),this._normalGlyphs.push(e)}get effectElement(){}paint(e,t,s){this.paintEffects(e,t,s),this.paintNormal(e,t,s)}paintNormal(e,t,s){for(const i of this._normalGlyphs)i.paint(e+this.x,t+this.y,s)}paintEffects(e,t,s){const i=this.effectElement?rn.beat(s,this.effectElement,this.container.beat):void 0;try{for(const i of this._effectGlyphs)i.paint(e+this.x,t+this.y,s)}finally{i?.[Symbol.dispose]?.()}}}class Mn extends Ln{constructor(){super(...arguments),this.centerX=0}updateBeamingHelper(){}buildBoundingsLookup(e,t,s){}getNoteX(e,t){return 0}getNoteY(e,t){return 0}}class In extends kr{constructor(e,t,s,i=1){super(e,t),this._scale=0,this._symbols=[],this._symbols=In.getSymbols(s),this._scale=i}static getSymbols(e){const t=[];for(;e>0;){const s=e%10;t.unshift(In.getSymbol(s)),e=e/10|0}return t}static getSymbol(e){switch(e){case 0:return re.TimeSig0;case 1:return re.TimeSig1;case 2:return re.TimeSig2;case 3:return re.TimeSig3;case 4:return re.TimeSig4;case 5:return re.TimeSig5;case 6:return re.TimeSig6;case 7:return re.TimeSig7;case 8:return re.TimeSig8;case 9:return re.TimeSig9;default:return re.None}}doLayout(){let e=0;for(const t of this._symbols)e+=Nr.Widths.get(t);this.width=e}paint(e,t,s){s.fillMusicFontSymbols(e+this.x,t+this.y,this._scale,this._symbols)}}In.numberHeight=18;class An extends kr{constructor(){super(0,0),this._numberGlyph=[]}doLayout(){this.width=70,this.renderer.registerOverflowTop(this.renderer.getLineHeight(1));const e=this.renderer.additionalMultiRestBars.length+1;this._numberGlyph=In.getSymbols(e)}paint(e,t,s){s.fillMusicFontSymbols(e+this.x,t+this.y+this.renderer.height/2,1,[re.RestHBarLeft,re.RestHBarMiddle,re.RestHBarMiddle,re.RestHBarMiddle,re.RestHBarRight]);const i=this.renderer.getLineY(-1.5);s.fillMusicFontSymbols(e+this.x+An.BarWidth/2,t+this.y+i|0,1,this._numberGlyph,!0)}}An.BarWidth=60;class Rn extends Fr{constructor(e){super(Rn.getOrCreatePlaceholderBeat(e),e),this.preNotes=new Ln,this.onNotes=new Mn}doLayout(){this.renderer.showMultiBarRest&&this.onNotes.addNormal(new An),super.doLayout()}static getOrCreatePlaceholderBeat(e){if(e.voice.beats.length>1)return e.voice.beats[0];const t=new ze;return t.voice=e.voice,t}}!function(e){e[e.TopWithStem=0]="TopWithStem",e[e.Top=1]="Top",e[e.Center=2]="Center",e[e.Bottom=3]="Bottom",e[e.BottomWithStem=4]="BottomWithStem"}(is||(is={})),function(e){e[e.Left=0]="Left",e[e.Center=1]="Center",e[e.Right=2]="Right"}(as||(as={}));class On{get nextRenderer(){return this.bar&&this.bar.nextBar?this.scoreRenderer.layout.getRendererForBar(this.staff.staffId,this.bar.nextBar):null}get previousRenderer(){return this.bar&&this.bar.previousBar?this.scoreRenderer.layout.getRendererForBar(this.staff.staffId,this.bar.previousBar):null}get lastBar(){return this.additionalMultiRestBars?this.additionalMultiRestBars[this.additionalMultiRestBars.length-1]:this.bar}get showMultiBarRest(){return!1}constructor(e,t){this._preBeatGlyphs=new an,this._voiceContainers=new Map,this._postBeatGlyphs=new an,this._ties=[],this.additionalMultiRestBars=null,this.x=0,this.y=0,this.width=0,this.computedWidth=0,this.height=0,this.index=0,this.topOverflow=0,this.bottomOverflow=0,this.isLinkedToPrevious=!1,this.canWrap=!0,this.wasFirstOfLine=!1,this._appliedLayoutingInfo=0,this.isFinalized=!1,this.topPadding=0,this.bottomPadding=0,this.scoreRenderer=e,this.bar=t,t&&(this.helpers=new gn(this))}registerTies(e){this._ties.push(...e)}get middleYPosition(){return 0}registerOverflowTop(e){return e>this.topOverflow&&(this.topOverflow=e,!0)}registerOverflowBottom(e){return e>this.bottomOverflow&&(this.bottomOverflow=e,!0)}scaleToWidth(e){const t=e-this._preBeatGlyphs.width-this._postBeatGlyphs.width;for(const e of this._voiceContainers.values())e.scaleToWidth(t);this._postBeatGlyphs.x=this._preBeatGlyphs.x+this._preBeatGlyphs.width+t,this.width=e}get resources(){return this.settings.display.resources}get settings(){return this.scoreRenderer.settings}get barDisplayScale(){return this.staff.system.staves.length>1?this.bar.masterBar.displayScale:this.bar.displayScale}get barDisplayWidth(){return this.staff.system.staves.length>1?this.bar.masterBar.displayWidth:this.bar.displayWidth}get isFirstOfLine(){return 0===this.index}get isLast(){return!this.bar||this.bar.index===this.scoreRenderer.layout.lastBarIndex}registerLayoutingInfo(){const e=this.layoutingInfo,t=this._preBeatGlyphs.width;e.preBeatSize<t&&(e.preBeatSize=t);for(const t of this._voiceContainers.values())t.registerLayoutingInfo(e),t.x,t.width;const s=this._postBeatGlyphs.width;e.postBeatSize<s&&(e.postBeatSize=s)}applyLayoutingInfo(){if(this._appliedLayoutingInfo>=this.layoutingInfo.version)return!1;this._appliedLayoutingInfo=this.layoutingInfo.version,this._preBeatGlyphs.width=this.layoutingInfo.preBeatSize;let e=this._preBeatGlyphs.x+this._preBeatGlyphs.width;for(const t of this._voiceContainers.values()){t.x=this._preBeatGlyphs.x+this._preBeatGlyphs.width,t.applyLayoutingInfo(this.layoutingInfo);const s=t.x+t.width;e<s&&(e=s)}this._postBeatGlyphs.x=Math.floor(e),this._postBeatGlyphs.width=this.layoutingInfo.postBeatSize,this.width=Math.ceil(this._postBeatGlyphs.x+this._postBeatGlyphs.width),this.computedWidth=this.width;const t=this.barDisplayWidth;return t>0&&this.scoreRenderer.layout.systemsLayoutMode===ss.FromModelWithWidths&&(this.width=t,this.computedWidth=t),!0}finalizeRenderer(){this.isFinalized=!0;let e=!1;const t=this.y-this.staff.topSpacing,s=this.y+this.height+this.staff.bottomSpacing;for(const i of this._ties)if(i.doLayout(),i.height>0){const a=i.y+i.height-s;a>0&&this.registerOverflowBottom(a)&&(e=!0);const r=i.y-t;r<0&&this.registerOverflowTop(-1*r)&&(e=!0)}return e}doLayout(){if(this.bar){this.helpers.initialize(),this._ties=[],this._preBeatGlyphs=new an,this._preBeatGlyphs.renderer=this,this._voiceContainers.clear(),this._postBeatGlyphs=new an,this._postBeatGlyphs.renderer=this;for(let e=0;e<this.bar.voices.length;e++){const t=this.bar.voices[e];if(this.hasVoiceContainer(t)){const s=new on(0,0,t);s.renderer=this,this._voiceContainers.set(this.bar.voices[e].index,s)}}if(this.bar.simileMark===h.SecondOfDouble&&(this.canWrap=!1),this.createPreBeatGlyphs(),this.additionalMultiRestBars){const e=new Rn(this.getVoiceContainer(this.bar.voices[0]));this.addBeatGlyph(e)}else this.createBeatGlyphs();this.createPostBeatGlyphs(),this.updateSizes();for(const e of this.helpers.beamHelpers)for(const t of e)t.finish();this.computedWidth=this.width}}hasVoiceContainer(e){return!(!this.additionalMultiRestBars&&0!==e.index)||!e.isEmpty}updateSizes(){this.staff.registerStaffTop(this.topPadding),this.staff.registerStaffBottom(this.height-this.bottomPadding);const e=this._voiceContainers,t=this.beatGlyphsStart;let s=t;for(const i of e.values()){i.x=t,i.doLayout();const e=i.x+i.width;s<e&&(s=e)}this._postBeatGlyphs.x=Math.floor(s),this.width=Math.ceil(this._postBeatGlyphs.x+this._postBeatGlyphs.width),this.height+=this.layoutingInfo.height}addPreBeatGlyph(e){e.renderer=this,this._preBeatGlyphs.addGlyph(e)}addBeatGlyph(e){e.renderer=this,e.preNotes.renderer=this,e.onNotes.renderer=this,e.onNotes.beamingHelper=this.helpers.beamHelperLookup[e.beat.voice.index].get(e.beat.index),this.getVoiceContainer(e.beat.voice).addGlyph(e)}getVoiceContainer(e){return this._voiceContainers.has(e.index)?this._voiceContainers.get(e.index):void 0}getBeatContainer(e){return this.getVoiceContainer(e.voice)?.beatGlyphs?.[e.index]}getPreNotesGlyphForBeat(e){return this.getBeatContainer(e)?.preNotes}getOnNotesGlyphForBeat(e){return this.getBeatContainer(e)?.onNotes}paint(e,t,s){this.paintBackground(e,t,s),s.color=this.resources.mainGlyphColor,this._preBeatGlyphs.paint(e+this.x,t+this.y,s);for(const i of this._voiceContainers.values())i.paint(e+this.x,t+this.y,s);s.color=this.resources.mainGlyphColor,this._postBeatGlyphs.paint(e+this.x,t+this.y,s)}paintBackground(e,t,s){this.layoutingInfo.paint(e+this.x+this._preBeatGlyphs.x+this._preBeatGlyphs.width,t+this.y+this.height,s)}buildBoundingsLookup(e,t,s){const i=new er;i.bar=this.bar,i.visualBounds=new mt,i.visualBounds.x=t+this.x,i.visualBounds.y=s+this.y+this.topPadding,i.visualBounds.w=this.width,i.visualBounds.h=this.height-this.topPadding-this.bottomPadding,i.realBounds=new mt,i.realBounds.x=t+this.x,i.realBounds.y=s+this.y,i.realBounds.w=this.width,i.realBounds.h=this.height,e.addBar(i);for(const[e,a]of this._voiceContainers){const r=this.bar.isEmpty&&0===e;if(!a.voice.isEmpty||r)for(let e=0,n=a.beatGlyphs.length;e<n;e++){a.beatGlyphs[e].buildBoundingsLookup(i,t+this.x+a.x,s+this.y+a.y,r)}}}addPostBeatGlyph(e){this._postBeatGlyphs.addGlyph(e)}createPreBeatGlyphs(){this.wasFirstOfLine=this.isFirstOfLine}createBeatGlyphs(){for(const e of this.bar.voices)this.hasVoiceContainer(e)&&this.createVoiceGlyphs(e)}createVoiceGlyphs(e){}createPostBeatGlyphs(){}get beatGlyphsStart(){return this._preBeatGlyphs.x+this._preBeatGlyphs.width}get postBeatGlyphsStart(){return this._postBeatGlyphs.x}getBeatX(e,t=ts.PreNotes){const s=this.getBeatContainer(e);if(s)switch(t){case ts.PreNotes:return s.voiceContainer.x+s.x;case ts.OnNotes:return s.voiceContainer.x+s.x+s.onNotes.x;case ts.MiddleNotes:return s.voiceContainer.x+s.x+s.onTimeX;case ts.Stem:const t=s.onNotes.beamingHelper?s.onNotes.beamingHelper.getBeatLineX(e):s.onNotes.x+s.onNotes.width/2;return s.voiceContainer.x+t;case ts.PostNotes:return s.voiceContainer.x+s.x+s.onNotes.x+s.onNotes.width;case ts.EndBeat:return s.voiceContainer.x+s.x+s.width}return 0}getRatioPositionX(e){const t=this.bar.isEmpty?this.beatGlyphsStart:this.getBeatX(this.bar.voices[0].beats[0],ts.OnNotes);return t+(this.postBeatGlyphsStart-t)*e}getNoteX(e,t){const s=this.getBeatContainer(e.beat);return s?s.voiceContainer.x+s.x+s.onNotes.x+s.onNotes.getNoteX(e,t):0}getNoteY(e,t){const s=this.getOnNotesGlyphForBeat(e.beat);return s?s.getNoteY(e,t):Number.NaN}reLayout(){(this.wasFirstOfLine&&!this.isFirstOfLine||!this.wasFirstOfLine&&this.isFirstOfLine)&&this.recreatePreBeatGlyphs(),this.updateSizes(),this.registerLayoutingInfo()}recreatePreBeatGlyphs(){this._preBeatGlyphs=new an,this._preBeatGlyphs.renderer=this,this.createPreBeatGlyphs()}paintSimileMark(e,t,s){const i=rn.voice(s,I.Glyphs,this.bar.voices[0],!0);try{switch(this.bar.simileMark){case h.Simple:s.beginGroup(Fr.getGroupId(this.bar.voices[0].beats[0])),s.fillMusicFontSymbol(e+this.x+(this.width-20)/2,t+this.y+this.height/2,1,re.Repeat1Bar,!1),s.endGroup();break;case h.SecondOfDouble:s.beginGroup(Fr.getGroupId(this.bar.voices[0].beats[0])),s.beginGroup(Fr.getGroupId(this.bar.previousBar.voices[0].beats[0])),s.fillMusicFontSymbol(e+this.x-14,t+this.y+this.height/2,1,re.Repeat2Bars,!1),s.endGroup(),s.endGroup()}}finally{i?.[Symbol.dispose]?.()}}completeBeamingHelper(e){}getBeatDirection(e){return this.helpers.getBeamingHelperForBeat(e).direction}}On.RawLineSpacing=8,On.StemWidth=.12*On.RawLineSpacing,On.StaffLineThickness=.13*On.RawLineSpacing,On.BeamThickness=.5*On.RawLineSpacing,On.BeamSpacing=.25*On.RawLineSpacing,function(e){e[e.SinglePreBeat=0]="SinglePreBeat",e[e.SingleOnBeat=1]="SingleOnBeat",e[e.SingleOnBeatToEnd=2]="SingleOnBeatToEnd",e[e.GroupedOnBeat=3]="GroupedOnBeat",e[e.GroupedOnBeatToEnd=4]="GroupedOnBeatToEnd",e[e.FullBar=5]="FullBar"}(rs||(rs={}));class Hn extends kr{constructor(e,t){super(0,0),this._uniqueEffectGlyphs=[],this._effectGlyphs=[],this.isEmpty=!0,this.previousBand=null,this.isLinkedToPrevious=!1,this.firstBeat=null,this.lastBeat=null,this.height=0,this.originalHeight=0,this.slot=null,this.voice=e,this.info=t}doLayout(){super.doLayout();for(let e=0;e<this.renderer.bar.voices.length;e++)this._effectGlyphs.push(new Map),this._uniqueEffectGlyphs.push([])}createGlyph(e){if(e.voice===this.voice&&this.info.shouldCreateGlyph(this.renderer.settings,e)&&(!this.info.hideOnMultiTrack||0===this.renderer.staff.trackIndex)){if(this.isEmpty=!1,this.firstBeat&&!e.isBefore(this.firstBeat)||(this.firstBeat=e),!this.lastBeat||e.isAfter(this.lastBeat))switch(this.lastBeat=e,this.info.sizingMode){case rs.SingleOnBeatToEnd:case rs.GroupedOnBeatToEnd:this.lastBeat.nextBeat&&(this.lastBeat=this.lastBeat.nextBeat)}const t=this.createOrResizeGlyph(this.info.sizingMode,e);t.height>this.height&&(this.height=t.height,this.originalHeight=t.height)}}resetHeight(){this.height=this.originalHeight}createOrResizeGlyph(e,t){let s;switch(e){case rs.FullBar:case rs.SinglePreBeat:case rs.SingleOnBeat:case rs.SingleOnBeatToEnd:return s=this.info.createNewGlyph(this.renderer,t),s.renderer=this.renderer,s.beat=t,s.doLayout(),this._effectGlyphs[t.voice.index].set(t.index,s),this._uniqueEffectGlyphs[t.voice.index].push(s),s;case rs.GroupedOnBeat:case rs.GroupedOnBeatToEnd:const i=e===rs.GroupedOnBeat?rs.SingleOnBeat:rs.SingleOnBeatToEnd;if(t.index>0||this.renderer.index>0){const e=t.previousBeat;if(this.info.shouldCreateGlyph(this.renderer.settings,e)){let s=null;if(t.index>0&&this._effectGlyphs[t.voice.index].has(e.index))s=this._effectGlyphs[t.voice.index].get(e.index);else if(this.renderer.index>0){const t=this.renderer.previousRenderer.getBand(e.voice,this.info.effectId);if(t){const i=t._effectGlyphs[e.voice.index];i.has(e.index)&&(s=i.get(e.index))}}const a=this.createOrResizeGlyph(i,t);return s&&this.info.canExpand(e,t)&&(s.nextGlyph=a,a.previousGlyph=s,this.isLinkedToPrevious=!0),a}return this.createOrResizeGlyph(i,t)}return this.createOrResizeGlyph(i,t);default:return this.createOrResizeGlyph(rs.SingleOnBeat,t)}}paint(e,t,s){super.paint(e,t,s);for(let i=0,a=this._uniqueEffectGlyphs.length;i<a;i++){const a=this._uniqueEffectGlyphs[i];for(let i=0,r=a.length;i<r;i++){const r=a[i],n=rn.beat(s,ye.Effects,r.beat,!1);try{r.paint(e+this.x,t+this.y,s)}finally{n?.[Symbol.dispose]?.()}}}}alignGlyphs(){for(let e=0;e<this._effectGlyphs.length;e++)for(const t of this._effectGlyphs[e].keys())this.alignGlyph(this.info.sizingMode,this.renderer.bar.voices[e].beats[t])}alignGlyph(e,t){const s=this._effectGlyphs[t.voice.index].get(t.index),i=this.renderer.getBeatContainer(t);switch(e){case rs.SinglePreBeat:const e=this.renderer.layoutingInfo.getPreBeatSize(t);s.x=this.renderer.beatGlyphsStart+i.x-e;break;case rs.SingleOnBeat:case rs.GroupedOnBeat:s.x=this.renderer.beatGlyphsStart+i.x;break;case rs.SingleOnBeatToEnd:case rs.GroupedOnBeatToEnd:if(s.x=this.renderer.beatGlyphsStart+i.x,i.beat.isLastOfVoice)s.width=this.renderer.width-s.x;else{const e=this.renderer.layoutingInfo.getPostBeatSize(t);s.width=e}break;case rs.FullBar:s.width=this.renderer.width}}}class Wn{constructor(){this.uniqueEffectId=null,this.y=0,this.height=0,this.firstBeat=null,this.lastBeat=null}}class Vn{constructor(){this.bands=[],this.shared=new Wn}update(e){e.info.canShareBand||(this.shared.uniqueEffectId=e.info.effectId),e.slot=this,this.bands.push(e),e.height>this.shared.height&&(this.shared.height=e.height),this.shared.firstBeat&&!e.firstBeat.isBefore(this.shared.firstBeat)||(this.shared.firstBeat=e.firstBeat),this.shared.lastBeat&&!e.lastBeat.isAfter(this.shared.lastBeat)||(this.shared.lastBeat=e.lastBeat)}canBeUsed(e){return(!this.shared.uniqueEffectId&&e.info.canShareBand||e.info.effectId===this.shared.uniqueEffectId)&&(!this.shared.firstBeat||this.shared.lastBeat.isBefore(e.firstBeat)||this.shared.lastBeat.isBefore(this.shared.firstBeat))}}class Gn{constructor(){this.slots=[],this._effectSlot=new Map}getOrCreateSlot(e){if(this._effectSlot.has(e.info.effectId)){const t=this._effectSlot.get(e.info.effectId);if(t.canBeUsed(e))return t}for(const t of this.slots)if(t.canBeUsed(e))return t;const t=new Vn;return this.slots.push(t),t}register(e){const t=this.getOrCreateSlot(e);t.update(e),this._effectSlot.set(e.info.effectId,t)}}class zn extends On{constructor(e,t,s){super(e,t),this._bands=[],this._bandLookup=new Map,this.sizingInfo=null,this._infos=s}updateSizes(){this.topOverflow=0,this.bottomOverflow=0,this.topPadding=0,this.bottomPadding=0,this.updateHeight(),super.updateSizes()}finalizeRenderer(){let e=super.finalizeRenderer();return this.updateHeight()&&(e=!0),e}updateHeight(){if(!this.sizingInfo)return!1;let e=0;for(const t of this.sizingInfo.slots){t.shared.y=e;for(const s of t.bands)s.y=e,s.height=t.shared.height;e+=t.shared.height}return e!==this.height&&(this.height=e,!0)}applyLayoutingInfo(){const e=!super.applyLayoutingInfo();if(this.index>0){const e=this.previousRenderer;this.sizingInfo=e.sizingInfo}else this.sizingInfo=new Gn;for(const e of this._bands)e.resetHeight(),e.alignGlyphs(),e.isEmpty||this.sizingInfo.register(e);return this.updateHeight(),e}scaleToWidth(e){super.scaleToWidth(e);for(const e of this._bands)e.alignGlyphs()}createBeatGlyphs(){this._bands=[],this._bandLookup=new Map;for(const e of this.bar.voices)if(this.hasVoiceContainer(e))for(const t of this._infos){const s=new Hn(e,t);s.renderer=this,s.doLayout(),this._bands.push(s),this._bandLookup.set(`${e.index}.${t.effectId}`,s)}super.createBeatGlyphs();for(const e of this._bands)e.isLinkedToPrevious&&(this.isLinkedToPrevious=!0)}createVoiceGlyphs(e){for(const t of e.beats){const s=new Fr(t,this.getVoiceContainer(e));s.preNotes=new Ln,s.onNotes=new Mn,this.addBeatGlyph(s);for(const e of this._bands)e.createGlyph(t)}}paint(e,t,s){this.paintBackground(e,t,s);for(const i of this._bands)s.color=0===i.voice.index?this.resources.mainGlyphColor:this.resources.secondaryGlyphColor,i.isEmpty||i.paint(e+this.x,t+this.y,s)}getBand(e,t){const s=`${e.index}.${t}`;return this._bandLookup.has(s)?this._bandLookup.get(s):null}}class Un extends tn{get staffId(){return this._staffId}getStaffPaddingTop(e){return e.system.layout.renderer.settings.display.effectStaffPaddingTop}getStaffPaddingBottom(e){return e.system.layout.renderer.settings.display.effectStaffPaddingBottom}constructor(e,t,s=null){super(),this.infos=t,this._staffId=e,this.isInsideBracket=!1,this.isRelevantForBoundsLookup=!1,this.shouldShow=s}canCreate(e,t){const s=this.shouldShow;return super.canCreate(e,t)&&(!s||s(e,t))}create(e,t){return new zn(e,t,this.infos.filter((t=>e.settings.notation.isNotationElementVisible(t.notationElement))))}}class Xn extends Tr{constructor(e,t,s,i,a){super(e,t),this._endingsString="",this._endings=ie.getAlternateEndingsList(s),this._openLine=i,this._closeLine=a}doLayout(){super.doLayout(),this.height=this.renderer.resources.wordsFont.size+(Xn.Padding+2);let e="";for(let t=0,s=this._endings.length;t<s;t++)e+=this._endings[t]+1,e+=". ";this._endingsString=e}paint(e,t,s){const i=this._closeLine?this.width-4:this.width;if(e=.5+(0|e),t=.5+(0|t),this._openLine?(s.moveTo(e+this.x,t+this.y+this.height),s.lineTo(e+this.x,t+this.y)):s.moveTo(e+this.x,t+this.y),s.lineTo(e+this.x+i,t+this.y),this._closeLine&&s.lineTo(e+this.x+i,t+this.y+this.height),s.stroke(),this._openLine){const i=s.textBaseline;s.textBaseline=oe.Top;const a=this.renderer.resources;s.font=a.wordsFont,s.fillText(this._endingsString,e+this.x+Xn.Padding,t+this.y),s.textBaseline=i}}}Xn.Padding=3;class Jn{get effectId(){return this.notationElement.toString()}}class Yn extends Jn{get notationElement(){return E.EffectAlternateEndings}get hideOnMultiTrack(){return!0}get canShareBand(){return!1}get sizingMode(){return rs.FullBar}shouldCreateGlyph(e,t){return 0===t.voice.index&&0===t.index&&0!==t.voice.bar.masterBar.alternateEndings}createNewGlyph(e,t){const s=t.voice.bar.masterBar,i=null===s.previousMasterBar||s.alternateEndings!==s.previousMasterBar.alternateEndings;let a=s.isRepeatEnd||null===s.nextMasterBar||s.alternateEndings!==s.nextMasterBar.alternateEndings;return s.repeatGroup.closings.some((e=>e.index>=s.index))||(a=!1),new Xn(0,0,s.alternateEndings,i,a)}canExpand(e,t){return!0}}class $n extends Jn{get notationElement(){return E.EffectCapo}get hideOnMultiTrack(){return!1}get canShareBand(){return!1}get sizingMode(){return rs.SingleOnBeat}shouldCreateGlyph(e,t){return 0===t.index&&0===t.voice.bar.index&&0!==t.voice.bar.staff.capo}createNewGlyph(e,t){return new Sn(0,0,`Capo. fret ${t.voice.bar.staff.capo}`,e.resources.effectFont,ne.Left)}canExpand(e,t){return!1}}class qn extends Jn{get notationElement(){return E.EffectChordNames}get hideOnMultiTrack(){return!1}get canShareBand(){return!0}get sizingMode(){return rs.SingleOnBeat}shouldCreateGlyph(e,t){return t.hasChord}createNewGlyph(e,t){return new Sn(0,0,t.chord.name,e.resources.effectFont,ne.Center)}canExpand(e,t){return!1}}class jn extends Tr{constructor(e){super(),this.forceGroupedRendering=!1,this.endOnBarLine=!1,this.endPosition=e}get isLinkedWithPrevious(){return!!this.previousGlyph&&this.previousGlyph.renderer.staff.system===this.renderer.staff.system}get isLinkedWithNext(){return!!this.nextGlyph&&this.nextGlyph.renderer.isFinalized&&this.nextGlyph.renderer.staff.system===this.renderer.staff.system}paint(e,t,s){if(this.isLinkedWithPrevious)return;if(!this.isLinkedWithNext&&!this.forceGroupedRendering)return void this.paintNonGrouped(e,t,s);let i;if(!this.isLinkedWithNext&&this.forceGroupedRendering)i=this;else for(i=this.nextGlyph;i.isLinkedWithNext;)i=i.nextGlyph;const a=i.renderer,r=i.beat,n=this.endPosition,o=e-this.renderer.x,h=this.calculateEndX(a,r,o,n);this.paintGrouped(e,t,h,s)}calculateEndX(e,t,s,i){return t?s+e.x+e.getBeatX(t,i):s+e.x+this.x+this.width}paintNonGrouped(e,t,s){const i=e-this.renderer.x,a=this.calculateEndX(this.renderer,this.beat,i,this.endPosition);this.paintGrouped(e,t,a,s)}}class Kn extends jn{constructor(e,t,s){super(ts.EndBeat),this._crescendo=S.None,this._crescendo=s,this.x=e,this.y=t}doLayout(){super.doLayout(),this.height=17}paintGrouped(e,t,s,i){const a=e+this.x,r=this.height,n=Nr.Widths.get(re.NoteheadBlack)/2;i.beginPath(),this._crescendo===S.Crescendo?(s-=n,i.moveTo(s,t+this.y),i.lineTo(a,t+this.y+r/2),i.lineTo(s,t+this.y+r)):(s-=n,i.moveTo(a,t+this.y),i.lineTo(s,t+this.y+r/2),i.lineTo(a,t+this.y+r)),i.stroke()}}class Qn extends Jn{get notationElement(){return E.EffectCrescendo}get hideOnMultiTrack(){return!1}get canShareBand(){return!0}get sizingMode(){return rs.GroupedOnBeatToEnd}shouldCreateGlyph(e,t){return t.crescendo!==S.None}createNewGlyph(e,t){return new Kn(0,0,t.crescendo)}canExpand(e,t){return e.crescendo===t.crescendo}}class Zn extends xr{constructor(e,t,s){super(e,t,.6,Zn.getSymbol(s)),this.center=!0}doLayout(){super.doLayout(),this.y+=this.height/2}static getSymbol(e){switch(e){case g.PPP:return re.DynamicPPP;case g.PP:return re.DynamicPP;case g.P:return re.DynamicPiano;case g.MP:return re.DynamicMP;case g.MF:return re.DynamicMF;case g.F:return re.DynamicForte;case g.FF:return re.DynamicFF;case g.FFF:return re.DynamicFFF;case g.PPPP:return re.DynamicPPPP;case g.PPPPP:case g.PPPPPP:return re.DynamicPPPPP;case g.FFFF:return re.DynamicFFFF;case g.FFFFF:return re.DynamicFFFFF;case g.FFFFFF:return re.DynamicFFFFFF;case g.SF:return re.DynamicSforzando1;case g.SFP:return re.DynamicSforzandoPiano;case g.SFPP:return re.DynamicSforzandoPianissimo;case g.FP:return re.DynamicFortePiano;case g.RF:return re.DynamicRinforzando1;case g.RFZ:return re.DynamicRinforzando2;case g.SFZ:return re.DynamicSforzato;case g.SFFZ:return re.DynamicSforzatoFF;case g.FZ:return re.DynamicForzando;case g.N:return re.DynamicNiente;case g.PF:return re.DynamicPF;case g.SFZP:return re.DynamicSforzatoPiano;default:return re.None}}}class eo extends Jn{get notationElement(){return E.EffectDynamics}get hideOnMultiTrack(){return!1}get canShareBand(){return!1}get sizingMode(){return rs.SingleOnBeat}shouldCreateGlyph(e,t){return this.internalShouldCreateGlyph(t)}internalShouldCreateGlyph(e){if(e.voice.bar.staff.track.score.stylesheet.hideDynamics||e.isEmpty||e.voice.isEmpty||e.isRest)return!1;const t=this.getPreviousDynamicsBeat(e);let s=0===e.voice.index&&!t||e.dynamics!==t?.dynamics;if(s&&e.voice.index>0)for(const t of e.voice.bar.voices)if(t.index<e.voice.index){const i=t.getBeatAtPlaybackStart(e.playbackStart);i&&e.dynamics===i.dynamics&&this.internalShouldCreateGlyph(i)&&(s=!1)}return s}getPreviousDynamicsBeat(e){let t=e.previousBeat;for(;null!=t;){if(!t.isRest)return t;t=t.previousBeat}return null}createNewGlyph(e,t){return new Zn(0,0,t.dynamics)}canExpand(e,t){return!0}}class to extends xr{constructor(e){super(0,0,1,to.getSymbol(e)),this.center=!0}static getSymbol(e){switch(e){case ue.FadeIn:return re.GuitarFadeIn;case ue.FadeOut:return re.GuitarFadeOut;case ue.VolumeSwell:return re.GuitarVolumeSwell}return re.None}paint(e,t,s){super.paint(e,t+this.height,s)}}class so extends Jn{get notationElement(){return E.EffectFadeIn}get hideOnMultiTrack(){return!1}get canShareBand(){return!0}get sizingMode(){return rs.SingleOnBeat}shouldCreateGlyph(e,t){return t.fade!==ue.None}createNewGlyph(e,t){return new to(t.fade)}canExpand(e,t){return!0}}class io extends xr{constructor(e,t,s){super(e,t,1,io.getSymbol(s))}static getSymbol(e){switch(e){case ke.Short:return re.FermataShortAbove;case ke.Medium:return re.FermataAbove;case ke.Long:return re.FermataLongAbove;default:return re.None}}paint(e,t,s){super.paint(e-this.width/2,t+this.height,s)}}class ao extends Jn{get notationElement(){return E.EffectFermata}get hideOnMultiTrack(){return!1}get canShareBand(){return!1}get sizingMode(){return rs.SingleOnBeat}shouldCreateGlyph(e,t){return 0===t.voice.index&&!!t.fermata}createNewGlyph(e,t){return new io(0,0,t.fermata.type)}canExpand(e,t){return!0}}class ro extends Jn{get notationElement(){return E.EffectFingering}get hideOnMultiTrack(){return!1}get canShareBand(){return!0}get sizingMode(){return rs.SingleOnBeat}shouldCreateGlyph(e,t){return!(0!==t.voice.index||t.isRest||e.notation.fingeringMode!==C.SingleNoteEffectBand&&e.notation.fingeringMode!==C.SingleNoteEffectBandForcePiano)&&(1===t.notes.length&&t.notes[0].isFingering)}createNewGlyph(e,t){let s=k.Unknown,i=!1;const a=t.notes[0];a.leftHandFinger!==k.Unknown?(s=a.leftHandFinger,i=!0):a.rightHandFinger!==k.Unknown&&(s=a.rightHandFinger);const r=ie.fingerToString(e.settings,t,s,i)??"";return new Sn(0,0,r,e.resources.fingeringFont,ne.Left)}canExpand(e,t){return!0}}class no extends Jn{constructor(){super(...arguments),this.lastCreateInfo=null}shouldCreateGlyph(e,t){this.lastCreateInfo=[];for(let e=0,s=t.notes.length;e<s;e++){const s=t.notes[e];this.shouldCreateGlyphForNote(s)&&this.lastCreateInfo.push(s)}return this.lastCreateInfo.length>0}get hideOnMultiTrack(){return!1}get canShareBand(){return!0}canExpand(e,t){return!0}}class oo extends jn{constructor(e,t=!0){super(ts.OnNotes),this._label=e,this._dashed=t}doLayout(){this.renderer.settings.notation.extendLineEffectsToBeatEnd&&(this.endPosition=ts.EndBeat,this.forceGroupedRendering=!0),super.doLayout(),this.height=this.renderer.resources.effectFont.size}paintNonGrouped(e,t,s){const i=this.renderer.resources;s.font=i.effectFont;const a=s.textAlign;s.textAlign=ne.Center,s.fillText(this._label,e+this.x,t+this.y),s.textAlign=a}paintGrouped(e,t,s,i){this.paintNonGrouped(e,t,i);const a=i.measureText(this._label).width,r=e+this.x+a/2+3,n=t+this.y+4;if(this._dashed){if(s>r){let e=r;for(;e<s;)i.beginPath(),i.moveTo(e,0|n),i.lineTo(Math.min(e+8,s),0|n),e+=11,i.stroke();i.beginPath(),i.moveTo(s,n-5|0),i.lineTo(s,n+5|0),i.stroke()}}else i.beginPath(),i.moveTo(r,0|n),i.lineTo(s,0|n),i.lineTo(s,n+5|0),i.stroke()}}oo.LineSpacing=3,oo.LineTopPadding=4,oo.LineTopOffset=5,oo.LineSize=8;class ho extends no{get effectId(){return this._effectId}get notationElement(){return E.EffectHarmonics}constructor(e){switch(super(),this._beat=null,this._harmonicType=e,e){case T.None:this._effectId="harmonics-none";break;case T.Natural:this._effectId="harmonics-natural";break;case T.Artificial:this._effectId="harmonics-artificial";break;case T.Pinch:this._effectId="harmonics-pinch";break;case T.Tap:this._effectId="harmonics-tap";break;case T.Semi:this._effectId="harmonics-semi";break;case T.Feedback:this._effectId="harmonics-feedback";break;default:this._effectId=""}}shouldCreateGlyphForNote(e){return!(!e.isHarmonic||e.harmonicType!==this._harmonicType)&&(e.beat!==this._beat&&(this._beat=e.beat),!0)}get sizingMode(){return rs.GroupedOnBeat}createNewGlyph(e,t){return new oo(ho.harmonicToString(this._harmonicType))}static harmonicToString(e){switch(e){case T.Natural:return"N.H.";case T.Artificial:return"A.H.";case T.Pinch:return"P.H.";case T.Tap:return"T.H.";case T.Semi:return"S.H.";case T.Feedback:return"Fdbk."}return""}}class lo extends Jn{get notationElement(){return E.EffectLetRing}get canShareBand(){return!1}get hideOnMultiTrack(){return!1}shouldCreateGlyph(e,t){return t.isLetRing}get sizingMode(){return rs.GroupedOnBeat}createNewGlyph(e,t){return new oo("LetRing")}canExpand(e,t){return!0}}class co extends Tr{constructor(e,t,s,i,a=ne.Center){super(e,t),this._lines=s,this.font=i,this.textAlign=a}doLayout(){super.doLayout(),this.height=this.font.size*this._lines.length}paint(e,t,s){s.font=this.font;const i=s.textAlign;s.textAlign=this.textAlign;for(let i=0;i<this._lines.length;i++)this._lines[i]&&s.fillText(this._lines[i],e+this.x,t+this.y+i*this.font.size);s.textAlign=i}}class uo extends Jn{get notationElement(){return E.EffectLyrics}get hideOnMultiTrack(){return!1}get canShareBand(){return!1}get sizingMode(){return rs.SingleOnBeat}shouldCreateGlyph(e,t){return!!t.lyrics}createNewGlyph(e,t){return new co(0,0,t.lyrics,e.resources.effectFont,ne.Center)}canExpand(e,t){return!0}}class po extends Jn{get notationElement(){return E.EffectMarker}get hideOnMultiTrack(){return!0}get canShareBand(){return!0}get sizingMode(){return rs.SinglePreBeat}shouldCreateGlyph(e,t){return 0===t.voice.bar.staff.index&&0===t.voice.index&&0===t.index&&t.voice.bar.masterBar.isSectionStart}createNewGlyph(e,t){return new Sn(0,0,t.voice.bar.masterBar.section.marker?`[${t.voice.bar.masterBar.section.marker}] ${t.voice.bar.masterBar.section.text}`:t.voice.bar.masterBar.section.text,e.resources.markerFont,ne.Left)}canExpand(e,t){return!0}}class go extends jn{constructor(e,t){super(ts.PostNotes),this._ottava=e,this._aboveStaff=t}doLayout(){super.doLayout(),this.height=Nr.Heights.get(re.QuindicesimaAlta)}paintNonGrouped(e,t,s){this.paintOttava(e,t,s)}paintOttava(e,t,s){let i=0;switch(this._ottava){case o._15ma:i=.8*Nr.Widths.get(re.QuindicesimaAlta),s.fillMusicFontSymbol(e+this.x-i/2,t+this.y+this.height,.8,re.QuindicesimaAlta,!1);break;case o._8va:i=.8*Nr.Widths.get(re.OttavaAlta),s.fillMusicFontSymbol(e+this.x-i/2,t+this.y+this.height,.8,re.OttavaAlta,!1);break;case o._8vb:i=.8*Nr.Widths.get(re.OttavaBassaVb),s.fillMusicFontSymbol(e+this.x-i/2,t+this.y+this.height,.8,re.OttavaBassaVb,!1);break;case o._15mb:i=.8*(Nr.Widths.get(re.Quindicesima)+Nr.Widths.get(re.OctaveBaselineM)+Nr.Widths.get(re.OctaveBaselineB)),s.fillMusicFontSymbols(e+this.x-i/2,t+this.y+this.height,.8,[re.Quindicesima,re.OctaveBaselineM,re.OctaveBaselineB],!1)}return i/2}paintGrouped(e,t,s,i){const a=this.paintOttava(e,t,i),r=e+this.x+a+3;let n=t+this.y;n+=this._aboveStaff?2:this.height-2;if(s>r){let e=r;for(;e<s;)i.beginPath(),i.moveTo(e,0|n),i.lineTo(Math.min(e+8,s),0|n),e+=11,i.stroke();i.beginPath(),this._aboveStaff?(i.moveTo(s,n),i.lineTo(s,t+this.y+this.height)):(i.moveTo(s,n),i.lineTo(s,t+this.y)),i.stroke()}}}class mo extends Jn{get effectId(){return"ottavia-"+(this._aboveStaff?"above":"below")}get notationElement(){return E.EffectOttavia}get hideOnMultiTrack(){return!1}get canShareBand(){return!0}get sizingMode(){return rs.GroupedOnBeat}constructor(e){super(),this._aboveStaff=e}shouldCreateGlyph(e,t){switch(t.ottava){case o._15ma:case o._8va:return this._aboveStaff;case o._8vb:case o._15mb:return!this._aboveStaff}return!1}createNewGlyph(e,t){return new go(t.ottava,this._aboveStaff)}canExpand(e,t){return e.ottava===t.ottava}}class fo extends no{get notationElement(){return E.EffectPalmMute}shouldCreateGlyphForNote(e){return e.isPalmMute}get sizingMode(){return rs.GroupedOnBeat}createNewGlyph(e,t){return new oo("P.M.")}}class yo extends no{get notationElement(){return E.EffectPickSlide}shouldCreateGlyphForNote(e){return e.slideOutType===v.PickSlideDown||e.slideOutType===v.PickSlideUp}get sizingMode(){return rs.GroupedOnBeat}createNewGlyph(e,t){return new oo("P.S.")}}class bo extends xr{constructor(e,t,s){super(e,t,vr.GraceScale,bo.getSymbol(s))}paint(e,t,s){super.paint(e,t+this.height,s)}static getSymbol(e){switch(e){case ae.Up:return re.StringsUpBow;case ae.Down:return re.StringsDownBow;default:return re.None}}}class So extends Jn{get notationElement(){return E.EffectPickStroke}get hideOnMultiTrack(){return!1}get canShareBand(){return!0}get sizingMode(){return rs.SingleOnBeat}shouldCreateGlyph(e,t){return t.pickStroke!==ae.None}createNewGlyph(e,t){return new bo(0,0,t.pickStroke)}canExpand(e,t){return!0}}class _o extends jn{constructor(e){super(ts.EndBeat),this._stepSize=0,this._type=e}doLayout(){switch(super.doLayout(),this._type){case P.Slight:this._stepSize=12;break;case P.Wide:this._stepSize=23}this.height=18}paintGrouped(e,t,s,i){let a=e+this.x;const r=s-a,n=Math.max(1,r/this._stepSize);i.beginPath(),i.moveTo(a,t+this.y);for(let e=0;e<n;e++)i.lineTo(a+this._stepSize/2,t+this.y+this.height),i.lineTo(a+this._stepSize,t+this.y),a+=this._stepSize;i.stroke()}}class wo extends Jn{get notationElement(){return E.EffectSlightBeatVibrato}get hideOnMultiTrack(){return!1}get canShareBand(){return!0}get sizingMode(){return rs.GroupedOnBeatToEnd}shouldCreateGlyph(e,t){return t.vibrato===P.Slight}createNewGlyph(e,t){return new _o(P.Slight)}canExpand(e,t){return!0}}class Bo extends jn{constructor(e,t,s,i=1.2,a=!1){super(ts.EndBeat),this._scale=0,this._symbol=re.None,this._symbolSize=0,this._type=s,this._scale=i,this.x=e,this.y=t,this._partialWaves=a}doLayout(){switch(super.doLayout(),this._type){case P.Slight:this._symbol=re.WiggleTrill;break;case P.Wide:this._symbol=re.WiggleVibratoMediumFast}this._symbolSize=Nr.Widths.get(this._symbol)*this._scale,this.height=Nr.Heights.get(this._symbol)*this._scale}paintGrouped(e,t,s,i){const a=s-(e+this.x),r=this._symbolSize;let n=a/r;this._partialWaves||(n=Math.floor(n)),n<1&&(n=1);let o=0;for(let s=0;s<n;s++)i.fillMusicFontSymbol(e+this.x+o,t+this.y+2*this.height,this._scale,this._symbol,!1),o+=r}}class ko extends no{get notationElement(){return E.EffectSlightNoteVibrato}shouldCreateGlyphForNote(e){let t=e.vibrato===P.Slight||e.isTieDestination&&e.tieOrigin.vibrato===P.Slight;return this._hideOnTiedBend&&t&&e.isTieDestination&&e.tieOrigin.hasBend&&(t=!1),t}get sizingMode(){return rs.GroupedOnBeatToEnd}createNewGlyph(e,t){return new Bo(0,0,P.Slight,1.2)}constructor(e){super(),this._hideOnTiedBend=e}}class To extends Jn{get notationElement(){return E.EffectTap}get hideOnMultiTrack(){return!1}get canShareBand(){return!0}get sizingMode(){return rs.SingleOnBeat}shouldCreateGlyph(e,t){return t.slap||t.pop||t.tap}createNewGlyph(e,t){const s=e.resources;return t.slap?new Sn(0,0,"S",s.effectFont,ne.Left):t.pop?new Sn(0,0,"P",s.effectFont,ne.Left):new Sn(0,0,"T",s.effectFont,ne.Left)}canExpand(e,t){return!0}}class No extends Tr{constructor(e){super(0,0),this.tempoAutomations=e}doLayout(){super.doLayout(),this.height=25}paint(e,t,s){for(const i of this.tempoAutomations){let a=e+this.renderer.getRatioPositionX(i.ratioPosition);const r=this.renderer.resources;if(s.font=r.markerFont,s.textBaseline=oe.Top,i.text){const e=s.measureText(i.text);s.fillText(i.text,a,t+this.y+s.font.size/2),a+=e.width+.7*s.font.size}s.fillMusicFontSymbol(a,t+this.y+.8*this.height,.5,re.NoteQuarterUp,!0),s.fillText(`= ${i.value.toString()}`,a+.5*Nr.Widths.get(re.NoteQuarterUp)+3,t+this.y+s.font.size/2)}}}class xo extends Jn{get notationElement(){return E.EffectTempo}get hideOnMultiTrack(){return!0}get canShareBand(){return!1}get sizingMode(){return rs.SinglePreBeat}shouldCreateGlyph(e,t){return 0===t.voice.bar.staff.index&&0===t.voice.index&&0===t.index&&t.voice.bar.masterBar.tempoAutomations.length>0}createNewGlyph(e,t){return new No(t.voice.bar.masterBar.tempoAutomations)}canExpand(e,t){return!0}}class vo extends Jn{get notationElement(){return E.EffectText}get hideOnMultiTrack(){return!1}get canShareBand(){return!1}get sizingMode(){return rs.SingleOnBeat}shouldCreateGlyph(e,t){return!!t.text}createNewGlyph(e,t){return new Sn(0,0,t.text,e.resources.effectFont,ne.Left)}canExpand(e,t){return!0}}class Po extends jn{constructor(e,t){super(ts.EndBeat),this.x=e,this.y=t}doLayout(){super.doLayout(),this.height=Nr.Heights.get(re.OrnamentTrill)/2}paintGrouped(e,t,s,i){let a=e+this.x;i.fillMusicFontSymbol(a,t+this.y+this.height,1,re.OrnamentTrill,!0),a+=Nr.Widths.get(re.OrnamentTrill)/2;const r=1.2*Nr.Widths.get(re.WiggleTrill),n=Math.floor((s-a)/r),o=t+this.y+1.37*this.height;let h=a;for(let e=0;e<n;e++)i.fillMusicFontSymbol(h,o,1.2,re.WiggleTrill,!1),h+=r}}class Fo extends no{get notationElement(){return E.EffectTrill}shouldCreateGlyphForNote(e){return e.isTrill}get sizingMode(){return rs.GroupedOnBeatToEnd}createNewGlyph(e,t){return new Po(0,0)}}!function(e){e[e.Full=0]="Full",e[e.PartialLeft=1]="PartialLeft",e[e.PartialRight=2]="PartialRight"}(ns||(ns={}));class Co extends Tr{constructor(e){super(0,0),this._tripletFeel=e}doLayout(){super.doLayout(),this.height=25}paint(e,t,s){e+=this.x;const i=(t+=this.y)+this.height*vr.GraceScale,a=i+8;s.font=this.renderer.resources.effectFont,s.fillText("(",e,t+.3*this.height);const r=e+10,n=e+40;let o=[],h=[],l=[],c=[];switch(this._tripletFeel){case M.NoTripletFeel:o=[re.TextBlackNoteLongStem,re.TextCont8thBeamLongStem,re.TextBlackNoteFrac8thLongStem],l=[re.TextBlackNoteLongStem,re.TextCont8thBeamLongStem,re.TextBlackNoteFrac8thLongStem];break;case M.Triplet8th:o=[re.TextBlackNoteLongStem,re.TextCont8thBeamLongStem,re.TextBlackNoteFrac8thLongStem],l=[re.TextBlackNoteLongStem,re.Space,re.NoteEighthUp],c=[re.TextTupletBracketStartLongStem,re.TextTuplet3LongStem,re.TextTupletBracketEndLongStem];break;case M.Triplet16th:o=[re.TextBlackNoteLongStem,re.TextCont8thBeamLongStem,re.TextBlackNoteFrac8thLongStem],l=[re.TextBlackNoteLongStem,re.TextCont8thBeamLongStem,re.TextBlackNoteFrac16thLongStem],c=[re.TextTupletBracketStartLongStem,re.TextTuplet3LongStem,re.TextTupletBracketEndLongStem];break;case M.Dotted8th:o=[re.TextBlackNoteLongStem,re.TextCont8thBeamLongStem,re.TextBlackNoteFrac8thLongStem],h=[re.TextAugmentationDot],l=[re.TextBlackNoteLongStem,re.TextCont8thBeamLongStem,re.TextBlackNoteFrac16thLongStem];break;case M.Dotted16th:o=[re.TextBlackNoteLongStem,re.TextCont16thBeamLongStem,re.TextBlackNoteFrac16thLongStem],h=[re.TextAugmentationDot],l=[re.TextBlackNoteLongStem,re.TextCont16thBeamLongStem,re.TextBlackNoteFrac32ndLongStem],s.fillCircle(n+9,i,1);break;case M.Scottish8th:o=[re.TextBlackNoteLongStem,re.TextCont8thBeamLongStem,re.TextBlackNoteFrac8thLongStem],l=[re.TextBlackNoteLongStem,re.TextCont16thBeamLongStem,re.TextBlackNoteFrac8thLongStem,re.TextAugmentationDot];break;case M.Scottish16th:o=[re.TextBlackNoteLongStem,re.TextCont16thBeamLongStem,re.TextBlackNoteFrac16thLongStem],l=[re.TextBlackNoteLongStem,re.TextCont32ndBeamLongStem,re.TextBlackNoteFrac16thLongStem,re.TextAugmentationDot]}s.fillMusicFontSymbols(r,i,Co.NoteScale,o,!1),s.fillText("=",e+32,t+5),s.fillMusicFontSymbols(n,i,Co.NoteScale,l,!1),h.length>0&&s.fillMusicFontSymbols(n+7,i,Co.NoteScale,h,!1),c.length>0&&s.fillMusicFontSymbols(n,a,Co.TupletScale,c,!1),s.fillText(")",e+65,t+.3*this.height)}}Co.NoteScale=.5,Co.TupletScale=.7;class Do extends Jn{get notationElement(){return E.EffectTripletFeel}get hideOnMultiTrack(){return!0}get canShareBand(){return!1}get sizingMode(){return rs.SinglePreBeat}shouldCreateGlyph(e,t){return 0===t.index&&(0===t.voice.bar.masterBar.index&&t.voice.bar.masterBar.tripletFeel!==M.NoTripletFeel||t.voice.bar.masterBar.index>0&&t.voice.bar.masterBar.tripletFeel!==t.voice.bar.masterBar.previousMasterBar.tripletFeel)}createNewGlyph(e,t){return new Co(t.voice.bar.masterBar.tripletFeel)}canExpand(e,t){return!0}}class Eo extends Jn{get notationElement(){return E.EffectWhammyBar}get hideOnMultiTrack(){return!1}get canShareBand(){return!1}get sizingMode(){return rs.GroupedOnBeat}shouldCreateGlyph(e,t){return t.hasWhammyBar}createNewGlyph(e,t){return new oo("w/bar")}canExpand(e,t){return!0}}class Lo extends Jn{get notationElement(){return E.EffectWideBeatVibrato}get hideOnMultiTrack(){return!1}get canShareBand(){return!0}get sizingMode(){return rs.GroupedOnBeatToEnd}shouldCreateGlyph(e,t){return t.vibrato===P.Wide}createNewGlyph(e,t){return new _o(P.Wide)}canExpand(e,t){return!0}}class Mo extends no{get notationElement(){return E.EffectWideNoteVibrato}shouldCreateGlyphForNote(e){return e.vibrato===P.Wide||e.isTieDestination&&e.tieOrigin.vibrato===P.Wide}get sizingMode(){return rs.GroupedOnBeatToEnd}createNewGlyph(e,t){return new Bo(0,0,P.Wide,1.2)}}class Io{constructor(){this.x=0,this.width=0,this.masterBars=[]}}class Ao extends En{constructor(){super(...arguments),this._system=null}get name(){return"HorizontalScreen"}get supportsResize(){return!1}get firstBarX(){let e=this.pagePadding[0];return this._system&&(e+=this._system.accoladeWidth),e}doResize(){}doLayoutAndRender(){switch(this.renderer.settings.display.systemsLayoutMode){case $t.Automatic:this.systemsLayoutMode=ss.Automatic;break;case $t.UseModelLayout:this.systemsLayoutMode=ss.FromModelWithWidths}const e=this.renderer.score;let t=this.renderer.settings.display.startBar;t--,t=Math.min(e.masterBars.length-1,Math.max(0,t));let s=t,i=this.renderer.settings.display.barCount;i<=0&&(i=e.masterBars.length),i=t+i-1,i=Math.min(e.masterBars.length-1,Math.max(0,i)),this._system=this.createEmptyStaffSystem(),this._system.isLast=!0,this._system.x=this.pagePadding[0],this._system.y=this.pagePadding[1];const a=this.renderer.settings.display.barCountPerPartial,r=[];let n=new Io,o=0;for(;s<=i;){const t=this.multiBarRestInfo,i=null!==t&&t.has(s)?t.get(s):null,h=this._system.addBars(this.renderer.tracks,s,i);if(0===n.masterBars.length&&h.isLinkedToPrevious&&r.length>0){const t=r[r.length-1];t.masterBars.push(e.masterBars[s]),t.width+=h.width,o+=h.width,n.x+=o}else n.masterBars.push(e.masterBars[s]),n.width+=h.width,n.masterBars.length>=a&&(0===r.length&&(n.width+=this._system.accoladeWidth+this.pagePadding[0]),o+=n.width,r.push(n),q.debug(this.name,`Finished partial from bar ${n.masterBars[0].index} to ${n.masterBars[n.masterBars.length-1].index}`,null),n=new Io,n.x=o);s++}n.masterBars.length>0&&(0===r.length&&(n.width+=this._system.accoladeWidth+this.pagePadding[0]),r.push(n),q.debug(this.name,`Finished partial from bar ${n.masterBars[0].index} to ${n.masterBars[n.masterBars.length-1].index}`,null)),this.finalizeStaffSystem();const h=this.renderer.settings.display.scale;this.height=Math.floor(this._system.y+this._system.height)*h,this.width=(this._system.x+this._system.width+this.pagePadding[2])*h,s=0;let l=0;for(let e=0;e<r.length;e++){const t=r[e],i=new Za;i.x=l,i.y=0,i.totalWidth=this.width/h,i.totalHeight=this.height/h,i.width=t.width,i.height=this.height/h,i.firstMasterBarIndex=t.masterBars[0].index,i.lastMasterBarIndex=t.masterBars[t.masterBars.length-1].index,l+=t.width;const a=s,n=e;this._system.buildBoundingsLookup(0,0),this.registerPartial(i,(e=>{let s=this._system.getBarX(t.masterBars[0].index)+this._system.accoladeWidth;0===n&&(s-=this._system.x+this._system.accoladeWidth),e.color=this.renderer.settings.display.resources.mainGlyphColor,e.textAlign=ne.Left,q.debug(this.name,`Rendering partial from bar ${t.masterBars[0].index} to ${t.masterBars[t.masterBars.length-1].index}`,null),this._system.paintPartial(-s,this._system.y,e,a,t.masterBars.length)})),s+=t.masterBars.length}this.height=this.layoutAndRenderBottomScoreInfo(this.height),this.height=this.layoutAndRenderAnnotation(this.height),this.height+=this.pagePadding[3]}finalizeStaffSystem(){this._system.scaleToWidth(this._system.width),this._system.finalizeSystem()}}class Ro extends En{constructor(){super(...arguments),this._systems=[],this._allMasterBarRenderers=[],this._barsFromPreviousSystem=[]}get name(){return"PageView"}doLayoutAndRender(){switch(this.renderer.settings.display.systemsLayoutMode){case $t.Automatic:this.systemsLayoutMode=ss.Automatic;break;case $t.UseModelLayout:this.systemsLayoutMode=ss.FromModelWithScale}let e=this.pagePadding[1];this.width=this.renderer.width,this._allMasterBarRenderers=[],e=this.layoutAndRenderScoreInfo(e,-1),e=this.layoutAndRenderTunings(e,-1),e=this.layoutAndRenderChordDiagrams(e,-1),e=this.layoutAndRenderScore(e),e=this.layoutAndRenderBottomScoreInfo(e),e=this.layoutAndRenderAnnotation(e),this.height=(e+this.pagePadding[3])*this.renderer.settings.display.scale}get supportsResize(){return!0}get firstBarX(){let e=this.pagePadding[0];return this._systems.length>0&&(e+=this._systems[0].accoladeWidth),e}doResize(){let e=this.pagePadding[1];this.width=this.renderer.width;const t=this.height;e=this.layoutAndRenderScoreInfo(e,t),e=this.layoutAndRenderTunings(e,t),e=this.layoutAndRenderChordDiagrams(e,t),e=this.resizeAndRenderScore(e,t),e=this.layoutAndRenderBottomScoreInfo(e),e=this.layoutAndRenderAnnotation(e),this.height=(e+this.pagePadding[3])*this.renderer.settings.display.scale}layoutAndRenderTunings(e,t=-1){if(!this.tuningGlyph)return e;const s=this.renderer.settings.display.resources;this.tuningGlyph.x=this.pagePadding[0],this.tuningGlyph.width=this.scaledWidth,this.tuningGlyph.doLayout();const i=Math.round(this.tuningGlyph.height),a=new Za;return a.x=0,a.y=e,a.width=this.scaledWidth,a.height=i,a.totalWidth=this.scaledWidth,a.totalHeight=t<0?e+a.height:t,this.registerPartial(a,(e=>{e.color=s.scoreInfoColor,e.textAlign=ne.Center,this.tuningGlyph.paint(0,0,e)})),e+i}layoutAndRenderChordDiagrams(e,t=-1){if(!this.chordDiagrams)return e;const s=this.renderer.settings.display.resources;this.chordDiagrams.width=this.scaledWidth,this.chordDiagrams.doLayout();const i=Math.round(this.chordDiagrams.height),a=new Za;return a.x=0,a.y=e,a.width=this.scaledWidth,a.height=i,a.totalWidth=this.scaledWidth,a.totalHeight=t<0?e+i:t,this.registerPartial(a,(e=>{e.color=s.scoreInfoColor,e.textAlign=ne.Center,this.chordDiagrams.paint(0,0,e)})),e+i}layoutAndRenderScoreInfo(e,t=-1){q.debug(this.name,"Layouting score info");const s=new Za;s.x=0,s.y=e;let i=0;const a=this.renderer.settings.display.resources,r=[];for(const[e,t]of En.HeaderElements.value)if(this.headerGlyphs.has(e)){const t=this.headerGlyphs.get(e);t.y=i,this.alignScoreInfoGlyph(t);let s=t.font.size;if(e===be.Words&&this.headerGlyphs.has(be.Music)){this.headerGlyphs.get(be.Music).textAlign!==t.textAlign&&(s=0)}i+=s,r.push(t)}return r.length>0&&(i=Math.floor(i+17),s.width=this.scaledWidth,s.height=i,s.totalWidth=this.scaledWidth,s.totalHeight=t<0?e+s.height:t,this.registerPartial(s,(e=>{e.color=a.scoreInfoColor,e.textAlign=ne.Center;for(const t of r)t.paint(0,0,e)}))),e+i}resizeAndRenderScore(e,t){if(this.renderer.settings.display.barsPerRow>0||this.systemsLayoutMode===ss.FromModelWithScale)for(let s=0;s<this._systems.length;s++){const i=this._systems[s];this.fitSystem(i),e+=this.paintSystem(i,t)}else{this._systems=[];let s=0;const i=this.maxWidth;let a=this.createEmptyStaffSystem();for(a.index=this._systems.length,a.x=this.pagePadding[0],a.y=e;s<this._allMasterBarRenderers.length;){let r=this._allMasterBarRenderers[s];if(a.width+r.width<=i||0===a.masterBarsRenderers.length)a.addMasterBarRenderers(this.renderer.tracks,r),s++;else{for(;r&&!r.canWrap&&a.masterBarsRenderers.length>1;)r=a.revertLastBar(),s--;a.isFull=!0,a.isLast=this.lastBarIndex===a.lastBarIndex,this._systems.push(a),this.fitSystem(a),e+=this.paintSystem(a,t),a=this.createEmptyStaffSystem(),a.index=this._systems.length,a.x=this.pagePadding[0],a.y=e}}a.isLast=this.lastBarIndex===a.lastBarIndex,this.fitSystem(a),e+=this.paintSystem(a,t)}return e}layoutAndRenderScore(e){let t=this.firstBarIndex;const s=this.lastBarIndex;for(this._systems=[];t<=s;){const i=this.createStaffSystem(t,s);this._systems.push(i),i.x=this.pagePadding[0],i.y=e,t=i.lastBarIndex+1,this.fitSystem(i),q.debug(this.name,`Rendering partial from bar ${i.firstBarIndex} to ${i.lastBarIndex}`,null),e+=this.paintSystem(i,e)}return e}paintSystem(e,t){const s=Math.floor(e.height),i=new Za;return i.x=0,i.y=e.y,i.totalWidth=this.scaledWidth,i.totalHeight=t,i.width=this.scaledWidth,i.height=s,i.firstMasterBarIndex=e.firstBarIndex,i.lastMasterBarIndex=e.lastBarIndex,e.buildBoundingsLookup(0,0),this.registerPartial(i,(t=>{this.renderer.canvas.color=this.renderer.settings.display.resources.mainGlyphColor,this.renderer.canvas.textAlign=ne.Left,e.paint(0,-i.y/this.renderer.settings.display.scale,t)})),s}fitSystem(e){e.isFull||e.width>this.maxWidth||this.renderer.settings.display.justifyLastSystem?e.scaleToWidth(this.maxWidth):e.scaleToWidth(e.width),e.finalizeSystem()}getBarsPerSystem(e){let t=this.renderer.settings.display.barsPerRow;if(this.systemsLayoutMode===ss.FromModelWithScale){let s,i;this.renderer.tracks.length>1?(s=this.renderer.score.defaultSystemsLayout,i=this.renderer.score.systemsLayout):(s=this.renderer.tracks[0].defaultSystemsLayout,i=this.renderer.tracks[0].systemsLayout),t=e<i.length?i[e]:s}return t}createStaffSystem(e,t){const s=this.createEmptyStaffSystem();s.index=this._systems.length;const i=this.getBarsPerSystem(s.index),a=this.maxWidth,r=t+1;let n=e;for(;n<r;){if(this._barsFromPreviousSystem.length>0)for(const e of this._barsFromPreviousSystem)s.addMasterBarRenderers(this.renderer.tracks,e),n=e.lastMasterBarIndex;else{const e=this.multiBarRestInfo,t=null!==e&&e.has(n)?e.get(n):null,i=s.addBars(this.renderer.tracks,n,t);this._allMasterBarRenderers.push(i),n=i.lastMasterBarIndex}this._barsFromPreviousSystem=[];let e=!1;if((-1===i&&s.width>=a&&0!==s.masterBarsRenderers.length||s.masterBarsRenderers.length===i+1)&&(e=!0),e){let e=s.revertLastBar();if(e)for(this._barsFromPreviousSystem.push(e);e&&!e.canWrap&&s.masterBarsRenderers.length>1;)e=s.revertLastBar(),e&&this._barsFromPreviousSystem.push(e);return s.isFull=!0,s.isLast=!1,this._barsFromPreviousSystem.reverse(),s}let t=!1,r=!0;for(const e of this.renderer.tracks)e.lineBreaks&&e.lineBreaks.has(n+1)?t=!0:r=!1;if(t&&r)return s.isFull=!0,s.isLast=!1,s;s.x=0,n++}return s.isLast=t===s.lastBarIndex,s}get maxWidth(){return this.scaledWidth-this.pagePadding[0]-this.pagePadding[2]}}class Oo extends xr{constructor(e,t,s,i){super(e,t,i,Oo.getMusicSymbol(s))}static getMusicSymbol(e){switch(e){case It.Natural:return re.AccidentalNatural;case It.Sharp:return re.AccidentalSharp;case It.Flat:return re.AccidentalFlat;case It.NaturalQuarterNoteUp:return re.AccidentalQuarterToneNaturalArrowUp;case It.SharpQuarterNoteUp:return re.AccidentalQuarterToneSharpArrowUp;case It.FlatQuarterNoteUp:return re.AccidentalQuarterToneFlatArrowUp;case It.DoubleSharp:return re.AccidentalDoubleSharp;case It.DoubleFlat:return re.AccidentalDoubleFlat}return re.None}}class Ho extends xr{constructor(e,t,s,i){super(e,t,1,Ho.getSymbol(s)),this._clef=s,this._clefOttava=i}static getSymbol(e){switch(e){case n.Neutral:return re.UnpitchedPercussionClef1;case n.C3:case n.C4:return re.CClef;case n.F4:return re.FClef;case n.G2:return re.GClef;default:return re.None}}paint(e,t,s){const i=rn.bar(s,u.StandardNotationClef,this.renderer.bar);try{let i;super.paint(e,t,s);let a=!1;switch(this._clefOttava){case o._15ma:i=new xr(-4,0,.5,re.Quindicesima),a=!0;break;case o._8va:i=new xr(-2,0,.5,re.Ottava),a=!0;break;case o._8vb:i=new xr(-6,0,.5,re.Ottava);break;case o._15mb:i=new xr(-8,0,.5,re.Quindicesima);break;default:return}let r=0,h=0;switch(this._clef){case n.Neutral:r=a?-12:15,h=0;break;case n.C3:case n.C4:r=a?-19:27,h=0;break;case n.F4:r=a?-9:27,h=-4;break;case n.G2:r=a?-37:30,h=0;break;default:return}i.renderer=this.renderer,i.doLayout();const l=this.width/2;i.paint(e+this.x+l+h,t+this.y+r,s)}finally{i?.[Symbol.dispose]?.()}}}class Wo extends Tr{constructor(e,t,s){super(e,t),this._note=s}static getSymbol(e,t){switch(e){case B.None:return re.None;case B.Normal:return t?re.ArticAccentAbove:re.ArticAccentBelow;case B.Heavy:return t?re.ArticMarcatoAbove:re.ArticMarcatoBelow;case B.Tenuto:return t?re.ArticTenutoAbove:re.ArticTenutoBelow;default:return re.None}}doLayout(){this.width=Nr.Widths.get(re.ArticAccentAbove),this.height=Nr.Heights.get(re.ArticAccentAbove)}paint(e,t,s){const i=this.renderer.getBeatDirection(this._note.beat),a=Wo.getSymbol(this._note.accentuated,i===Te.Down),r=i===Te.Up?t+this.y:t+this.y+this.height-2;s.fillMusicFontSymbol(e+this.x-2,r,1,a,!1)}}class Vo extends kr{constructor(e,t,s){super(e,t),this._size=0,this._size=s}doLayout(){this.width=this._size+3}paint(e,t,s){const i=s.color;this.colorOverride&&(s.color=this.colorOverride),s.fillCircle(e+this.x,t+this.y,this._size),s.color=i}}class Go extends xr{constructor(e,t,s){super(e,t,s?vr.GraceScale:1,re.NoteheadXOrnate)}}class zo extends xr{constructor(e,t,s,i){super(e,t,i?vr.GraceScale:1,zo.getSymbol(s))}static getSymbol(e){switch(e){case _.QuadrupleWhole:case _.DoubleWhole:case _.Whole:case _.Half:return re.NoteheadDiamondWhiteWide;default:return re.NoteheadDiamondBlackWide}}}class Uo extends kr{constructor(e,t,s){super(0,0),this.yOffset=0,this.startNoteRenderer=null,this.endNoteRenderer=null,this.tieDirection=Te.Up,this._startX=0,this._startY=0,this._endX=0,this._endY=0,this._tieHeight=0,this._shouldDraw=!1,this.startBeat=e,this.endBeat=t,this.forEnd=s}doLayout(){if(this.width=0,!this.endBeat)return void(this._shouldDraw=!1);const e=this.renderer.scoreRenderer.layout.getRendererForBar(this.renderer.staff.staffId,this.startBeat.voice.bar);this.startNoteRenderer=e;const t=this.renderer.scoreRenderer.layout.getRendererForBar(this.renderer.staff.staffId,this.endBeat.voice.bar);if(this.endNoteRenderer=t,this._startX=0,this._endX=0,this._startY=0,this._endY=0,this.height=0,this._shouldDraw=!1,this.tieDirection=e?this.getBeamDirection(this.startBeat,e):this.getBeamDirection(this.endBeat,t),!this.forEnd&&e?(e!==t?(this._startX=e.x+this.getStartX(),this._startY=e.y+this.getStartY()+this.yOffset,t&&e.staff===t.staff?(this._endX=t.x+this.getEndX(),this._endY=t.y+this.getEndY()+this.yOffset):(this._endX=e.x+e.width,this._endY=this._startY)):(this._startX=e.x+this.getStartX(),this._endX=t.x+this.getEndX(),this._startY=e.y+this.getStartY()+this.yOffset,this._endY=t.y+this.getEndY()+this.yOffset),this._shouldDraw=!0):e&&e.staff===t.staff||(this._startX=t.x,this._endX=t.x+this.getEndX(),this._startY=t.y+this.getEndY()+this.yOffset,this._endY=this._startY,this._shouldDraw=!0),this._shouldDraw)if(this.y=Math.min(this._startY,this._endY),this.shouldDrawBendSlur())this._tieHeight=0;else{this._tieHeight=this.getTieHeight(this._startX,this._startY,this._endX,this._endY);const e=Uo.calculateActualTieHeight(1,this._startX,this._startY,this._endX,this._endY,this.tieDirection===Te.Down,this._tieHeight,4);if(this.height=e.h,this.tieDirection===Te.Up){const t=this.y-e.y;t>0&&(this.y-=t)}}}paint(e,t,s){this._shouldDraw&&(this.shouldDrawBendSlur()?Uo.drawBendSlur(s,e+this._startX,t+this._startY,e+this._endX,t+this._endY,this.tieDirection===Te.Down,1):Uo.paintTie(s,1,e+this._startX,t+this._startY,e+this._endX,t+this._endY,this.tieDirection===Te.Down,this._tieHeight,4))}shouldDrawBendSlur(){return!1}getTieHeight(e,t,s,i){return 22}getBeamDirection(e,t){return Te.Down}getStartY(){return 0}getEndY(){return 0}getStartX(){return 0}getEndX(){return 0}static calculateActualTieHeight(e,t,s,i,a,r,n,o){const h=Uo.computeBezierControlPoints(e,t,s,i,a,r,n,o);t=h[0],s=h[1];const l=h[2],c=h[3];i=h[6],a=h[7];const d=(t-l)/(t-2*l+i),u=Uo.calculateExtrema(t,s,l,c,i,a,d),p=u.length>0?Math.min(t,i,u[0]):Math.min(t,i),g=u.length>0?Math.max(t,i,u[0]):Math.max(t,i),m=(s-c)/(s-2*c+a),f=Uo.calculateExtrema(t,s,l,c,i,a,m),y=f.length>0?Math.min(s,a,f[1]):Math.min(s,a),b=f.length>0?Math.max(s,a,f[1]):Math.max(s,a),S=new mt;return S.x=p,S.y=y,S.w=g-p,S.h=b-y,S}static calculateExtrema(e,t,s,i,a,r,n){if(n<=0||1<=n)return[];const o=e+(s-e)*n,h=t+(i-t)*n;return[o+(s+(a-s)*n-o)*n,h+(i+(r-i)*n-h)*n]}static computeBezierControlPoints(e,t,s,i,a,r,n,o){if(t===i&&s===a)return[];if(i<t){let e=t;t=i,i=e,e=s,s=a,a=e}n*=e,o*=e;let h=a-s,l=i-t;const c=Math.sqrt(h*h+l*l);r?h*=-1:l*=-1,h/=c,l/=c;const d=(i+t)/2,u=(a+s)/2;return[t,s,d+n*h,u+n*l,d+(n-o)*h,u+(n-o)*l,i,a]}static paintTie(e,t,s,i,a,r,n=!1,o=22,h=4){const l=Uo.computeBezierControlPoints(t,s,i,a,r,n,o,h);e.beginPath(),e.moveTo(l[0],l[1]),e.quadraticCurveTo(l[2],l[3],l[6],l[7]),e.quadraticCurveTo(l[4],l[5],l[0],l[1]),e.closePath(),e.fill()}static drawBendSlur(e,t,s,i,a,r,n,o){let h=a-s,l=i-t;const c=Math.sqrt(h*h+l*l);r?h*=-1:l*=-1,h/=c,l/=c;const d=(i+t)/2,u=(a+s)/2;let p=Uo.BendSlurHeight*n;i-t<20&&(p/=2);const g=d+p*h,m=u+p*l;if(e.beginPath(),e.moveTo(t,s),e.lineTo(g,m),e.lineTo(i,a),e.stroke(),o){const t=e.measureText(o).width,s=r?0:-e.font.size;e.fillText(o,g-t/2,m+s)}}}Uo.BendSlurHeight=11;class Xo extends kr{constructor(e){super(0,0),this._isOpen=e}doLayout(){super.doLayout(),this.width=Xo.Size}paint(e,t,s){const i=s.color;this.colorOverride&&(s.color=this.colorOverride),this._isOpen?Uo.paintTie(s,1,e+this.x+this.width,t+this.y+this.height,e+this.x+this.width,t+this.y,!1,6,3):Uo.paintTie(s,1,e+this.x,t+this.y,e+this.x,t+this.y+this.height,!1,6,3),s.color=i}}Xo.Size=6;class Jo{constructor(e,t,s){this.line=0,this.line=e,this.isGhost=t,this.color=s}}class Yo extends kr{constructor(e){super(0,0),this._infos=[],this._glyphs=[],this.isEmpty=!0,this._isOpen=e}addParenthesis(e){const t=this.renderer,s=t.getNoteLine(e),i=e.isGhost||this.isTiedBend(e)&&t.settings.notation.isNotationElementVisible(E.ParenthesisOnTiedBends),a=rn.noteColor(t.resources,le.Effects,e);this.add(new Jo(s,i,a))}addParenthesisOnLine(e,t){const s=new Jo(e,t,void 0);this.add(s)}add(e){this._infos.push(e),e.isGhost&&(this.isEmpty=!1)}isTiedBend(e){return!!e.isTieDestination&&(!!e.tieOrigin.hasBend||this.isTiedBend(e.tieOrigin))}doLayout(){const e=this.renderer;this._infos.sort(((e,t)=>e.line-t.line));let t=null;const s=e.getScoreHeight(1);for(let i=0,a=this._infos.length;i<a;i++){let a;if(this._infos[i].isGhost)if(t){const a=e.getScoreY(this._infos[i].line)+s;t.height=a-t.y}else a=new Xo(this._isOpen),a.colorOverride=this._infos[i].color,a.renderer=this.renderer,a.y=e.getScoreY(this._infos[i].line)-s,a.height=2*s,a.doLayout(),this._glyphs.push(a),t=a;else t=null}this.width=this._glyphs.length>0?this._glyphs[0].width:0}paint(e,t,s){super.paint(e,t,s);for(const i of this._glyphs)i.paint(e+this.x,t+this.y,s)}}class $o{constructor(e,t){this.steps=0,this.glyph=e,this.steps=t}}class qo extends kr{constructor(){super(0,0),this._infos=[],this._noteHeadPadding=0,this.minNote=null,this.maxNote=null,this.spacingChanged=new Qi,this.upLineX=0,this.downLineX=0,this.displacedX=0,this.noteStartX=0}add(e,t){const s=new $o(e,t);this._infos.push(s),(!this.minNote||this.minNote.steps>s.steps)&&(this.minNote=s),(!this.maxNote||this.maxNote.steps<s.steps)&&(this.maxNote=s)}doLayout(){this._infos.sort(((e,t)=>t.steps-e.steps));let e=0,t=!1,s=0,i=!1;const a=this.direction;let r=0;for(let n=0,o=this._infos.length;n<o;n++){const o=this._infos[n].glyph;o.renderer=this.renderer,o.doLayout();let h=!1;0===n?e=o.width:Math.abs(s-this._infos[n].steps)<=1?t?t=!1:(h=!0,o.x=e,i=!0,t=!0):t=!1,a===Te.Down?o.x=h?0:e:o.x=h?e:0,o.x+=this.noteStartX,s=this._infos[n].steps,r=Math.max(r,o.x+o.width),o instanceof vr&&o.centerOnStem&&(o.x=e)}i?(this._noteHeadPadding=0,this.upLineX=e,this.downLineX=e):(this._noteHeadPadding=a===Te.Down?-e:0,r+=this._noteHeadPadding,this.upLineX=r,this.downLineX=0),this.displacedX=e,this.width=r}paint(e,t,s){e+=this.x,t+=this.y,this.paintLedgerLines(e,t,s);const i=this._infos,a=e+this._noteHeadPadding;for(const e of i)e.glyph.renderer=this.renderer,e.glyph.paint(a,t,s)}paintLedgerLines(e,t,s){if(!this.minNote)return;const i=this.renderer,a=rn.bar(s,u.StandardNotationStaffLine,i.bar,!0);try{const a=3,r=this.width-this.noteStartX+2*a,n=i.getLineHeight(1),o=i.getLineY(-1),h=i.getLineY(i.drawnLineCount),l=i.getLineY(this.minNote.steps/2),c=i.getLineY(this.maxNote.steps/2);let d=o;for(;d>=l;)s.fillRect(e-a+this.noteStartX,t+d|0,r,On.StaffLineThickness),d-=n;for(d=h;d<=c;)s.fillRect(e-a+this.noteStartX,t+d|0,r,On.StaffLineThickness),d+=n}finally{a?.[Symbol.dispose]?.()}}}class jo extends xr{constructor(e,t,s){super(e,t,1,jo.getSymbol(s))}static getSymbol(e){switch(e){case _.ThirtySecond:return re.Tremolo3;case _.Sixteenth:return re.Tremolo2;case _.Eighth:return re.Tremolo1;default:return re.None}}}class Ko extends kr{constructor(){super(0,0)}doLayout(){this.width=26}paint(e,t,s){const i=this.renderer,a=i.getLineHeight(i.heightLineCount-1),r=i.getLineY(0)+i.getLineHeight(i.drawnLineCount-1)/2-a/2,n=s.lineWidth;s.lineWidth=2,s.moveTo(e+this.x,t+r),s.lineTo(e+this.x+this.width,t+r+a),s.moveTo(e+this.x,t+r+a),s.lineTo(e+this.x+this.width,t+r),s.stroke(),s.lineWidth=n}}class Qo extends qo{constructor(){super(...arguments),this._noteGlyphLookup=new Map,this._notes=[],this._deadSlapped=null,this._tremoloPicking=null,this.aboveBeatEffects=new Map,this.belowBeatEffects=new Map}get direction(){return this.beamingHelper.direction}getNoteX(e,t){if(this._noteGlyphLookup.has(e.id)){const s=this._noteGlyphLookup.get(e.id);let i=this.x+s.x+this._noteHeadPadding;switch(t){case as.Left:break;case as.Center:i+=s.width/2;break;case as.Right:i+=s.width}return i}return 0}getNoteY(e,t){if(this._noteGlyphLookup.has(e.id)){const s=this._noteGlyphLookup.get(e.id);let i=this.y+s.y;switch(t){case is.TopWithStem:i-=this.renderer.getStemSize(this.beamingHelper);break;case is.Top:i-=s.height/2;break;case is.Center:break;case is.Bottom:i+=s.height/2;break;case is.BottomWithStem:i+=this.renderer.getStemSize(this.beamingHelper)}return i}return 0}addNoteGlyph(e,t,s){super.add(e,s),this._noteGlyphLookup.set(t.id,e),this._notes.push(t)}updateBeamingHelper(e){this.beamingHelper&&this.beamingHelper.registerBeatLineX("score",this.beat,e+this.x+this.upLineX,e+this.x+this.downLineX)}doLayout(){super.doLayout();const e=this.renderer;this.beat.deadSlapped&&(this._deadSlapped=new Ko,this._deadSlapped.renderer=this.renderer,this._deadSlapped.doLayout(),this.width=this._deadSlapped.width);const t=this.direction;let s=0,i=0,a=1,r=-a,n=!1,o=!1;this.beat.deadSlapped?(i=e.getScoreY(0),s=e.getScoreY(e.heightLineCount)):this.direction===Te.Up?(n=!1,o=!0,i=e.getScoreY(this.maxNote.steps+2),s=e.getScoreY(this.minNote.steps)-e.getStemSize(this.beamingHelper,!0)):(n=!0,o=!1,i=e.getScoreY(this.minNote.steps-1),a*=-1,r*=-1,s=e.getScoreY(this.maxNote.steps)+e.getStemSize(this.beamingHelper,!0));let h=null,l=null;for(const e of this.aboveBeatEffects.values())e.renderer=this.renderer,e.doLayout(),o&&(s+=r*e.height),e.y=s,(null===h||h>s)&&(h=s),(null===l||l<s)&&(l=s),o||(s+=r*e.height);for(const e of this.belowBeatEffects.values())e.renderer=this.renderer,e.doLayout(),n&&(i+=a*e.height),e.y=i,(null===h||h>i)&&(h=i),(null===l||l<i)&&(l=i),n||(i+=a*e.height);if(null!==h&&e.registerBeatEffectOverflows(h,l??0),this.beat.isTremolo&&!this.beat.deadSlapped){let e=0;const s=t===Te.Up?this.minNote:this.maxNote;let i=t===Te.Up?this.upLineX:this.downLineX;const a=this.beat.tremoloSpeed;switch(a){case _.ThirtySecond:e=t===Te.Up?-15:15;break;case _.Sixteenth:e=t===Te.Up?-12:15;break;case _.Eighth:e=t===Te.Up?-10:10;break;default:e=t===Te.Up?-10:15}this.beat.duration<_.Half&&(i=this.width/2),this._tremoloPicking=new jo(i,s.glyph.y+e,a),this._tremoloPicking.renderer=this.renderer,this._tremoloPicking.doLayout()}}buildBoundingsLookup(e,t,s){for(const i of this._notes)if(this._noteGlyphLookup.has(i.id)){const a=this._noteGlyphLookup.get(i.id),r=new ir;r.note=i,r.noteHeadBounds=new mt,r.noteHeadBounds.x=t+this.x+this._noteHeadPadding+a.x,r.noteHeadBounds.y=s+this.y+a.y-a.height/2,r.noteHeadBounds.w=a.width,r.noteHeadBounds.h=a.height,e.addNote(r)}}paint(e,t,s){this.paintEffects(e,t,s),super.paint(e,t,s)}paintEffects(e,t,s){const i=rn.beat(s,ye.StandardNotationEffects,this.beat);try{for(const i of this.aboveBeatEffects.values())i.paint(e+this.x+2,t+this.y,s);for(const i of this.belowBeatEffects.values())i.paint(e+this.x+2,t+this.y,s);this._tremoloPicking&&this._tremoloPicking.paint(e,t,s),this._deadSlapped&&this._deadSlapped.paint(e,t,s)}finally{i?.[Symbol.dispose]?.()}}}class Zo extends xr{constructor(e,t,s){super(e,t,1,Zo.getSymbol(s))}static getSymbol(e){switch(e){case _.QuadrupleWhole:return re.RestLonga;case _.DoubleWhole:return re.RestDoubleWhole;case _.Whole:return re.RestWhole;case _.Half:return re.RestHalf;case _.Quarter:return re.RestQuarter;case _.Eighth:return re.RestEighth;case _.Sixteenth:return re.RestSixteenth;case _.ThirtySecond:return re.RestThirtySecond;case _.SixtyFourth:return re.RestSixtyFourth;case _.OneHundredTwentyEighth:return re.RestOneHundredTwentyEighth;case _.TwoHundredFiftySixth:return re.RestTwoHundredFiftySixth;default:return re.None}}updateBeamingHelper(e){this.beamingHelper&&this.beamingHelper.registerBeatLineX("score",this.beat,e+this.x+this.width/2,e+this.x+this.width/2)}paint(e,t,s){this.internalPaint(e,t,s,ye.StandardNotationRests)}internalPaint(e,t,s,i){const a=rn.beat(s,i,this.beat);try{super.paint(e,t,s)}finally{a?.[Symbol.dispose]?.()}}}class eh{constructor(){this.x=0,this.y=-3e3,this.width=0}}class th extends sn{constructor(){super(0,0)}doLayout(){if(!this.glyphs||0===this.glyphs.length)return void(this.width=0);this.glyphs.sort(((e,t)=>e.y<t.y?-1:e.y>t.y?1:0));const e=[];e.push(new eh);for(let t=0,s=this.glyphs.length;t<s;t++){const s=this.glyphs[t];s.renderer=this.renderer,s.doLayout();let i=0;for(;e[i].y>s.y;)i++,i===e.length&&e.push(new eh);s.x=i,e[i].y=s.y+21,e[i].width<s.width&&(e[i].width=s.width)}this.width=0;for(const t of e)this.width+=t.width,t.x=this.width;for(let t=0,s=this.glyphs.length;t<s;t++){const s=this.glyphs[t],i=e[s.x];s.x=this.width-i.x}}}class sh extends qo{get direction(){return Te.Up}constructor(e,t=!1){super(),this._showParenthesis=!1,this._noteValueLookup=new Map,this._accidentals=new th,this._preNoteParenthesis=null,this._postNoteParenthesis=null,this.isEmpty=!0,this.noteHeadOffset=0,this._beat=e,this._showParenthesis=t,t&&(this._preNoteParenthesis=new Yo(!0),this._postNoteParenthesis=new Yo(!1))}containsNoteValue(e){return this._noteValueLookup.has(e)}getNoteValueY(e){return this._noteValueLookup.has(e)?this.y+this._noteValueLookup.get(e).y:0}addGlyph(e,t,s){const i=this.renderer,a=new vr(0,0,_.Quarter,!0),r=i.accidentalHelper.applyAccidentalForValue(this._beat,e,t,!0),n=i.accidentalHelper.getNoteLineForValue(e,!1);if(a.y=i.getScoreY(n),this._showParenthesis&&(this._preNoteParenthesis.renderer=this.renderer,this._postNoteParenthesis.renderer=this.renderer,this._preNoteParenthesis.addParenthesisOnLine(n,!0),this._postNoteParenthesis.addParenthesisOnLine(n,!0)),r!==It.None){const e=new Oo(0,a.y,r,vr.GraceScale);e.renderer=this.renderer,this._accidentals.renderer=this.renderer,this._accidentals.addGlyph(e)}this._noteValueLookup.set(e,a),this.add(a,n),this.isEmpty=!1}doLayout(){let e=0;this._showParenthesis&&(this._preNoteParenthesis.x=e,this._preNoteParenthesis.renderer=this.renderer,this._preNoteParenthesis.doLayout(),e+=this._preNoteParenthesis.width+sh.ElementPadding),this._accidentals.isEmpty||(e+=this._accidentals.width+sh.ElementPadding,this._accidentals.x=e,this._accidentals.renderer=this.renderer,this._accidentals.doLayout(),e+=this._accidentals.width+sh.ElementPadding),this.noteStartX=e,super.doLayout(),this.noteHeadOffset=this.noteStartX+(this.width-this.noteStartX)/2,this._showParenthesis&&(this._postNoteParenthesis.x=this.width+sh.ElementPadding,this._postNoteParenthesis.renderer=this.renderer,this._postNoteParenthesis.doLayout(),this.width+=this._postNoteParenthesis.width+sh.ElementPadding)}paint(e,t,s){this._accidentals.isEmpty||this._accidentals.paint(e+this.x,t+this.y,s),this._showParenthesis&&(this._preNoteParenthesis.paint(e+this.x,t+this.y,s),this._postNoteParenthesis.paint(e+this.x,t+this.y,s)),super.paint(e,t,s)}}sh.ElementPadding=2;class ih extends kr{constructor(){super(...arguments),this.BendNoteHeads=[]}drawBendSlur(e,t,s,i,a,r,n,o){Uo.drawBendSlur(e,t,s,i,a,r,n,o)}doLayout(){super.doLayout(),this.width=0;for(const e of this.BendNoteHeads)e.doLayout(),this.width+=e.width+10}getTieDirection(e,t){return t.getBeatDirection(e)===Te.Up?Te.Down:Te.Up}}ih.EndPadding=8;class ah extends X{constructor(e=0,t=0){super(e,t),this.lineValue=0,this.lineValue=t}}class rh extends kr{constructor(){super(0,0),this._notes=[],this._renderPoints=new Map,this._preBendMinValue=-1,this._bendMiddleMinValue=-1,this._bendEndMinValue=-1,this._bendEndContinuedMinValue=-1,this._releaseMinValue=-1,this._releaseContinuedMinValue=-1,this._maxBendValue=-1}addBends(e){this._notes.push(e);const t=this.createRenderingPoints(e);this._renderPoints.set(e.id,t),(-1===this._maxBendValue||this._maxBendValue<e.maxBendPoint.value)&&(this._maxBendValue=e.maxBendPoint.value);let s=0;switch(e.bendType){case y.Bend:s=t[1].value,e.isTieOrigin?(-1===this._bendEndContinuedMinValue||s<this._bendEndContinuedMinValue)&&(this._bendEndContinuedMinValue=s):(-1===this._bendEndMinValue||s<this._bendEndMinValue)&&(this._bendEndMinValue=s);break;case y.Release:s=t[1].value,e.isTieOrigin?(-1===this._releaseContinuedMinValue||s<this._releaseContinuedMinValue)&&(this._releaseContinuedMinValue=s):s>0&&(-1===this._releaseMinValue||s<this._releaseMinValue)&&(this._releaseMinValue=s);break;case y.BendRelease:s=t[1].value,(-1===this._bendMiddleMinValue||s<this._bendMiddleMinValue)&&(this._bendMiddleMinValue=s),s=t[2].value,e.isTieOrigin?(-1===this._releaseContinuedMinValue||s<this._releaseContinuedMinValue)&&(this._releaseContinuedMinValue=s):s>0&&(-1===this._releaseMinValue||s<this._releaseMinValue)&&(this._releaseMinValue=s);break;case y.Prebend:s=t[0].value,(-1===this._preBendMinValue||s<this._preBendMinValue)&&(this._preBendMinValue=s);break;case y.PrebendBend:s=t[0].value,(-1===this._preBendMinValue||s<this._preBendMinValue)&&(this._preBendMinValue=s),s=t[1].value,e.isTieOrigin?(-1===this._bendEndContinuedMinValue||s<this._bendEndContinuedMinValue)&&(this._bendEndContinuedMinValue=s):(-1===this._bendEndMinValue||s<this._bendEndMinValue)&&(this._bendEndMinValue=s);break;case y.PrebendRelease:s=t[0].value,(-1===this._preBendMinValue||s<this._preBendMinValue)&&(this._preBendMinValue=s),s=t[1].value,e.isTieOrigin?(-1===this._releaseContinuedMinValue||s<this._releaseContinuedMinValue)&&(this._releaseContinuedMinValue=s):s>0&&(-1===this._releaseMinValue||s<this._releaseMinValue)&&(this._releaseMinValue=s)}}doLayout(){super.doLayout();const e=this._maxBendValue*rh.BendValueHeight;this.renderer.registerOverflowTop(e);let t=0;for(const e of this._notes){const s=this._renderPoints.get(e.id);switch(e.bendType){case y.Bend:s[1].lineValue=e.isTieOrigin?this._bendEndContinuedMinValue:this._bendEndMinValue;break;case y.Release:t=e.isTieOrigin?this._releaseContinuedMinValue:this._releaseMinValue,t>=0&&(s[1].lineValue=t);break;case y.BendRelease:s[1].lineValue=this._bendMiddleMinValue,t=e.isTieOrigin?this._releaseContinuedMinValue:this._releaseMinValue,t>=0&&(s[2].lineValue=t);break;case y.Prebend:s[0].lineValue=this._preBendMinValue;break;case y.PrebendBend:s[0].lineValue=this._preBendMinValue,s[1].lineValue=e.isTieOrigin?this._bendEndContinuedMinValue:this._bendEndMinValue;break;case y.PrebendRelease:s[0].lineValue=this._preBendMinValue,t=e.isTieOrigin?this._releaseContinuedMinValue:this._releaseMinValue,t>=0&&(s[1].lineValue=t)}}this.width=0,this._notes.sort(((e,t)=>e.isStringed?e.string-t.string:e.realValue-t.realValue))}createRenderingPoints(e){const t=[];switch(e.bendType){case y.Custom:for(const s of e.bendPoints)t.push(new ah(s.offset,s.value));break;case y.BendRelease:t.push(new ah(0,e.bendPoints[0].value)),t.push(new ah(X.MaxPosition/2|0,e.bendPoints[1].value)),t.push(new ah(X.MaxPosition,e.bendPoints[3].value));break;case y.Bend:case y.Hold:case y.Prebend:case y.PrebendBend:case y.PrebendRelease:case y.Release:t.push(new ah(0,e.bendPoints[0].value)),t.push(new ah(X.MaxPosition,e.bendPoints[1].value))}return t}paint(e,t,s){const i=s.color;this._notes.length>1&&(s.color=this.renderer.resources.secondaryGlyphColor);for(const a of this._notes){const r=this._renderPoints.get(a.id),n=this.renderer;let o=a,h=!1,l=null,c=!1;const d=a.bendStyle===f.Gradual?"grad.":"";let u=null;for(;o.isTieOrigin;){const e=o.tieDestination;if(l=this.renderer.scoreRenderer.layout.getRendererForBar(this.renderer.staff.staffId,e.beat.voice.bar),!l||n.staff!==l.staff)break;if(o=e,h=!0,o.hasBend||!this.renderer.settings.notation.extendBendArrowsOnTiedNotes||o.vibrato!==P.None){c=!0;break}}u=o.beat,l=this.renderer.scoreRenderer.layout.getRendererForBar(this.renderer.staff.staffId,u.voice.bar),u.isLastOfVoice&&!o.hasBend&&this.renderer.settings.notation.extendBendArrowsOnTiedNotes&&(u=null);let p=0,g=0;const m=t+n.y;p=e+n.x,r[0].value>0||a.isContinuedBend?p+=n.getBeatX(a.beat,ts.MiddleNotes):p+=n.getNoteX(a,as.Right),g=!u||u.isLastOfVoice&&!c?e+l.x+l.postBeatGlyphsStart:c||!u.nextBeat?e+l.x+l.getBeatX(u,ts.MiddleNotes):a.bendType===y.Hold?e+l.x+l.getBeatX(u.nextBeat,ts.OnNotes):e+l.x+l.getBeatX(u.nextBeat,ts.PreNotes),h||(g-=rh.ArrowSize);const b=(g-p)/X.MaxPosition;s.beginPath();for(let e=0,t=r.length-1;e<t;e++){const t=r[e];let i=r[e+1];0!==e||0===t.value||a.isTieDestination||this.paintBend(a,new ah(0,0),t,p,m,b,d,s),a.bendType!==y.Prebend?(0===e&&(p+=2),this.paintBend(a,t,i,p,m,b,d,s)):a.isTieOrigin&&a.tieDestination.hasBend&&(i=new ah(X.MaxPosition,t.value),i.lineValue=t.lineValue,this.paintBend(a,t,i,p,m,b,d,s))}if(o.vibrato!==P.None){const i=g-e+rh.ArrowSize-l.x,a=m-t-rh.BendValueHeight*r[r.length-1].lineValue,n=new Bo(i,a,o.vibrato,1.2);n.beat=o.beat,n.renderer=l,n.doLayout(),n.paint(e+l.x,t,s)}s.color=i}}paintBend(e,t,s,i,a,r,n,o){const h=this.renderer,l=this.renderer.resources,c=h.lineOffset/2,d=i+r*t.offset,u=rh.BendValueHeight;let p=a-u*t.lineValue;0===t.value?s.offset===t.offset?p+=h.getNoteY(e.beat.maxStringNote,is.Top):p+=h.getNoteY(e,is.Center):p+=c;const g=i+r*s.offset;let m=a-u*s.lineValue;0===s.lineValue?m+=h.getNoteY(e,is.Center):m+=c;let f=0;const y=rh.ArrowSize;if(s.value>t.value?(m+y>p&&(m=p-y),o.beginPath(),o.moveTo(g,m),o.lineTo(g-.5*y,m+y),o.lineTo(g+.5*y,m+y),o.closePath(),o.fill(),f=y):s.value!==t.value&&(m<p&&(m=p+y),o.beginPath(),o.moveTo(g,m),o.lineTo(g-.5*y,m-y),o.lineTo(g+.5*y,m-y),o.closePath(),o.fill(),f=-y),o.beginPath(),t.value===s.value){if(t.lineValue>0){let e=g;const t=rh.DashSize,s=d+t;if((e-d)/(2*t)<1)o.moveTo(e,p),o.lineTo(d,p);else for(;e>s;)o.moveTo(e,p),o.lineTo(e-t,p),e-=2*t;o.stroke()}}else g>d?(o.moveTo(d,p),o.bezierCurveTo((d+g)/2,p,g,p,g,m+f),o.stroke()):(o.moveTo(d,p),o.lineTo(g,m),o.stroke());if(n&&t.offset<s.offset){o.font=l.graceFont;const e=o.measureText(n).width;let t=0,s=0;if(p>m){const i=Math.abs(p-m);t=i>1.3*o.font.size?p-i/2:p,s=(d+g-e)/2}else t=p,s=g-e;o.fillText(n,s,t)}if(0!==s.value&&t.value!==s.value){let e=s.value;const i=s.value>t.value;e=Math.abs(e);let r="";if(4===e)r="full",e-=4;else if(e>=4||e<=-4){const t=e/4|0;r+=t,e-=4*t}if(e>0&&(r+=rh.getFractionSign(e)),""!==r){m=a-u*s.value;let e=m;i||(e=p+1*Math.abs(m-p)/3),o.font=l.tablatureFont;const t=o.measureText(r).width,n=e-.5*l.tablatureFont.size-2,h=g-t/2;o.fillText(r,h,n)}}}static getFractionSign(e){switch(e){case 1:return"¼";case 2:return"½";case 3:return"¾";default:return`${e}/ 4`}}}rh.ArrowSize=6,rh.DashSize=3,rh.BendValueHeight=6;class nh extends kr{constructor(e){super(0,0),this._isSimpleDip=!1,this._beat=e,this._renderPoints=this.createRenderingPoints(e)}createRenderingPoints(e){if(e.whammyBarType===ce.Custom)return e.whammyBarPoints;const t=[];switch(e.whammyBarType){case ce.Dive:case ce.Hold:case ce.PrediveDive:case ce.Predive:t.push(new X(0,e.whammyBarPoints[0].value)),t.push(new X(X.MaxPosition,e.whammyBarPoints[1].value));break;case ce.Dip:t.push(new X(0,e.whammyBarPoints[0].value)),t.push(new X(X.MaxPosition/2|0,e.whammyBarPoints[1].value)),t.push(new X(X.MaxPosition,e.whammyBarPoints[e.whammyBarPoints.length-1].value))}return t}doLayout(){super.doLayout(),this._isSimpleDip=this.renderer.settings.notation.notationMode===D.SongBook&&this._beat.whammyBarType===ce.Dip;let e=null,t=null,s=this._beat;for(;s&&s.hasWhammyBar;)(!e||e.value>s.minWhammyPoint.value)&&(e=s.minWhammyPoint),(!t||t.value<s.maxWhammyPoint.value)&&(t=s.maxWhammyPoint),s=s.nextBeat;let i=t.value>0?Math.abs(this.getOffset(t.value)):0;(i>0||0!==this._beat.whammyBarPoints[0].value||this.renderer.settings.notation.isNotationElementVisible(E.ZerosOnDiveWhammys))&&(i+=2*this.renderer.resources.tablatureFont.size);const a=e.value<0?Math.abs(this.getOffset(e.value)):0;this.renderer.registerOverflowTop(i+a);i>this.renderer.staff.getSharedLayoutData(nh.TopOffsetSharedDataKey,-1)&&this.renderer.staff.setSharedLayoutData(nh.TopOffsetSharedDataKey,i)}getOffset(e){if(0===e)return 0;let t=nh.PerHalfSize+Math.log2(Math.abs(e)/2)*nh.PerHalfSize;return e<0&&(t=-t),t}paint(e,t,s){const i=rn.beat(s,ye.StandardNotationEffects,this._beat);try{const i=this.renderer;let a=this._beat.nextBeat,r=null,n=ts.PreNotes;a&&(r=this.renderer.scoreRenderer.layout.getRendererForBar(this.renderer.staff.staffId,a.voice.bar),r&&r.staff===i.staff&&(r===i||a.hasWhammyBar)?n=!a.hasWhammyBar||i.settings.notation.notationMode===D.SongBook&&a.whammyBarType===ce.Dip?ts.PreNotes:ts.MiddleNotes:(a=null,r=null));let o=0,h=0;this._isSimpleDip?(o=e+i.x+i.getBeatX(this._beat,ts.OnNotes)-2,h=e+i.x+i.getBeatX(this._beat,ts.PostNotes)+2):(o=e+i.x+i.getBeatX(this._beat,ts.MiddleNotes),h=r?e+r.x+r.getBeatX(a,n):e+i.x+i.width-2);const l=s.textAlign;if(s.textAlign=ne.Center,this._renderPoints.length>=2){const e=(h-o)/X.MaxPosition;s.beginPath();const i=t+this.renderer.staff.getSharedLayoutData(nh.TopOffsetSharedDataKey,0);let a=this._beat.whammyStyle===f.Gradual?"grad.":"";for(let t=0,r=this._renderPoints.length-1;t<r;t++){const n=this._renderPoints[t],h=this._renderPoints[t+1],l=t<r-2?this._renderPoints[t+2]:null;let c=0===t;0!==t||0===n.value||this._beat.isContinuedWhammy||(this.paintWhammy(!1,new X(0,0),n,h,o,i,e,s),c=!1),this.paintWhammy(c,n,h,l,o,i,e,s,a),a=""}s.stroke()}s.textAlign=l}finally{i?.[Symbol.dispose]?.()}}paintWhammy(e,t,s,i,a,r,n,o,h){const l=a+n*t.offset,c=a+n*s.offset,d=r-this.getOffset(t.value),u=r-this.getOffset(s.value);if(t.offset===s.offset){const e=nh.DashSize;if(Math.abs(u-d)/(2*e)<1)o.moveTo(l,d),o.lineTo(c,u);else{const t=Math.max(d,u);let s=Math.min(d,u);for(;t>s;)o.moveTo(l,s),o.lineTo(l,s+e),s+=2*e}o.stroke()}else if(t.value===s.value){const e=nh.DashSize;if(Math.abs(c-l)/(2*e)<1)o.moveTo(l,d),o.lineTo(c,u);else{let t=Math.max(l,c);const s=Math.min(l,c);for(;t>s;)o.moveTo(t,d),o.lineTo(t-e,d),t-=2*e}o.stroke()}else o.moveTo(l,d),o.lineTo(c,u);const p=this.renderer.resources;if(e&&!this._beat.isContinuedWhammy&&!this._isSimpleDip){let e=d;e-=p.tablatureFont.size+2,this.renderer.settings.notation.isNotationElementVisible(E.ZerosOnDiveWhammys)&&o.fillText("0",l,e),h&&(e-=p.tablatureFont.size+2,o.fillText(h,l,e))}let g=Math.abs(s.value);if((0!==g||this.renderer.settings.notation.isNotationElementVisible(E.ZerosOnDiveWhammys)&&!this._isSimpleDip)&&t.value!==s.value){let e="";if(s.value<0&&(e+="-"),g>=4){const t=g/4|0;e+=t,g-=4*t}else 0===g&&(e+="0");g>0&&(e+=rh.getFractionSign(g));let a=0;this._isSimpleDip?a=Math.min(d,u)-p.tablatureFont.size-2:(a=t.offset===s.offset?Math.min(d,u):u,a-=p.tablatureFont.size+2,i&&i.value>s.value&&(a-=2));const r=c;o.fillText(e,r,a)}}}nh.TopOffsetSharedDataKey="tab.whammy.topoffset",nh.PerHalfSize=6,nh.DashSize=3;class oh extends ih{constructor(e){super(0,0),this._beat=e}doLayout(){const e=this.renderer.settings.notation.notationMode;switch(this._beat.whammyBarType){case ce.None:case ce.Custom:case ce.Hold:return;case ce.Dive:case ce.PrediveDive:{const e=new sh(this._beat,!1);e.renderer=this.renderer;const t=this._beat.whammyBarPoints[this._beat.whammyBarPoints.length-1];for(const s of this._beat.notes)s.isTieOrigin||e.addGlyph(this.getBendNoteValue(s,t),t.value%2!=0,void 0);e.doLayout(),this.BendNoteHeads.push(e)}break;case ce.Dip:if(e===D.SongBook){const e=this.renderer.resources;this.renderer.simpleWhammyOverflow=1.5*e.tablatureFont.size+oh.SimpleDipHeight+oh.SimpleDipPadding}else{const e=new sh(this._beat,!1);if(e.renderer=this.renderer,this.renderer.settings.notation.notationMode===D.GuitarPro){const t=this._beat.whammyBarPoints[1];for(const s of this._beat.notes)e.addGlyph(this.getBendNoteValue(s,this._beat.whammyBarPoints[1]),t.value%2!=0,void 0)}e.doLayout(),this.BendNoteHeads.push(e);const t=new sh(this._beat,!1);if(t.renderer=this.renderer,this.renderer.settings.notation.notationMode===D.GuitarPro){const e=this._beat.whammyBarPoints[this._beat.whammyBarPoints.length-1];for(const s of this._beat.notes)t.addGlyph(this.getBendNoteValue(s,e),e.value%2!=0,void 0)}t.doLayout(),this.BendNoteHeads.push(t)}case ce.Predive:}super.doLayout()}paint(e,t,s){const i=this._beat;switch(i.whammyBarType){case ce.None:case ce.Custom:return}const a=this.renderer.settings.notation.notationMode,r=this.renderer.scoreRenderer.layout.getRendererForBar(this.renderer.staff.staffId,i.voice.bar),n=rn.beat(s,ye.StandardNotationEffects,i);try{const n=e+r.x+r.getBeatX(i,ts.MiddleNotes),o=this.getTieDirection(i,r);let h=1===this._beat.notes.length?o:Te.Up;const l=s.textAlign,c=Nr.Heights.get(re.NoteheadBlack);for(let l=0;l<i.notes.length;l++){const d=i.notes[l],u=rn.note(s,le.StandardNotationEffects,d);try{let u=t+r.y;l>0&&l>=(this._beat.notes.length/2|0)&&(h=Te.Down),h===Te.Down?u+=r.getNoteY(d,is.Bottom):u+=r.getNoteY(d,is.Top);let p=e+r.x;i.isLastOfVoice?p+=r.width:p+=r.getBeatX(i,ts.EndBeat),p-=8;const g=i.whammyStyle===f.Gradual&&0===l?"grad.":"";let m=null;d.isTieOrigin&&(m=this.renderer.scoreRenderer.layout.getRendererForBar(this.renderer.staff.staffId,d.tieDestination.beat.voice.bar),m&&m.staff===r.staff?p=e+m.x+m.getBeatX(d.tieDestination.beat,ts.MiddleNotes):m=null);let y=c*vr.GraceScale*.5;h===Te.Up&&(y=-y);const b=i.whammyBarPoints.length>0?this.getBendNoteValue(d,i.whammyBarPoints[i.whammyBarPoints.length-1]):0;let S=0,_=!1;switch(this.BendNoteHeads.length>0&&this.BendNoteHeads[0].containsNoteValue(b)?(S=this.BendNoteHeads[0].getNoteValueY(b)+y,_=!0):m&&(d.isTieOrigin&&d.tieDestination.beat.hasWhammyBar||d.beat.isContinuedWhammy)?(S=t+m.y+m.getNoteY(d.tieDestination,is.Top),_=!0,h===Te.Down&&(S+=c)):d.isTieOrigin&&(S=m?t+m.y+m.getNoteY(d.tieDestination,is.Top):u,h===Te.Down&&(S+=c)),i.whammyBarType){case ce.Hold:d.isTieOrigin&&Uo.paintTie(s,1,n,u,p,S,o===Te.Down,22,4);break;case ce.Dive:if(0===l){this.BendNoteHeads[0].x=p-this.BendNoteHeads[0].noteHeadOffset;const e=this.BendNoteHeads[0].y;this.BendNoteHeads[0].y=t+r.y,this.BendNoteHeads[0].paint(0,0,s),this.BendNoteHeads[0].containsNoteValue(b)&&(S-=e,S+=this.BendNoteHeads[0].y)}_?this.drawBendSlur(s,n,u,p,S,h===Te.Down,1,g):d.isTieOrigin&&Uo.paintTie(s,1,n,u,p,S,o===Te.Down,22,4);break;case ce.Dip:if(a===D.SongBook){if(0===l){const i=e+r.x+r.getBeatX(this._beat,ts.OnNotes)-2,a=e+r.x+r.getBeatX(this._beat,ts.PostNotes)+2,n=(i+a)/2,o=((this._beat.whammyBarPoints[1].value-this._beat.whammyBarPoints[0].value)/4|0).toString();s.font=this.renderer.resources.tablatureFont,s.fillText(o,n,t+this.y);const h=t+this.y+s.font.size+2,l=h+oh.SimpleDipHeight;this._beat.whammyBarPoints[1].value>this._beat.whammyBarPoints[0].value?(s.moveTo(i,l),s.lineTo(n,h),s.lineTo(a,l)):(s.moveTo(i,h),s.lineTo(n,l),s.lineTo(a,h)),s.stroke()}d.isTieOrigin&&Uo.paintTie(s,1,n,u,p,S,o===Te.Down,22,4)}else{const e=(n+p)/2;this.BendNoteHeads[0].x=e-this.BendNoteHeads[0].noteHeadOffset,this.BendNoteHeads[0].y=t+r.y,this.BendNoteHeads[0].paint(0,0,s);const a=this.getBendNoteValue(d,i.whammyBarPoints[1]),o=this.BendNoteHeads[0].getNoteValueY(a)+y;this.drawBendSlur(s,n,u,e,o,h===Te.Down,1,g),this.BendNoteHeads[1].x=p-this.BendNoteHeads[1].noteHeadOffset,this.BendNoteHeads[1].y=t+r.y,this.BendNoteHeads[1].paint(0,0,s),S=this.BendNoteHeads[1].getNoteValueY(b)+y,this.drawBendSlur(s,e,o,p,S,h===Te.Down,1,g)}break;case ce.PrediveDive:case ce.Predive:let c=e+r.x+r.getBeatX(d.beat,ts.PreNotes);c+=r.getPreNotesGlyphForBeat(d.beat).prebendNoteHeadOffset;const m=t+r.y+r.getScoreY(r.accidentalHelper.getNoteLineForValue(d.displayValue-(d.beat.whammyBarPoints[0].value/2|0),!1))+y;this.drawBendSlur(s,c,m,n,u,h===Te.Down,1,g),this.BendNoteHeads.length>0&&(this.BendNoteHeads[0].x=p-this.BendNoteHeads[0].noteHeadOffset,this.BendNoteHeads[0].y=t+r.y,this.BendNoteHeads[0].paint(0,0,s),this.drawBendSlur(s,n,u,p,S,h===Te.Down,1,g))}}finally{u?.[Symbol.dispose]?.()}}s.textAlign=l}finally{n?.[Symbol.dispose]?.()}}getBendNoteValue(e,t){return e.displayValueWithoutBend+(t.value/2|0)}}oh.SimpleDipHeight=2*nh.PerHalfSize,oh.SimpleDipPadding=2;class hh extends kr{constructor(e,t,s){super(e,t),this.width=s}}class lh extends xr{constructor(e,t,s,i,a){super(e,t,a?vr.GraceScale:1,s.getSymbol(i)),this._isGrace=a,this._articulation=s}paint(e,t,s){const i=s.color;this.colorOverride&&(s.color=this.colorOverride);const a=this._isGrace?1:0;s.fillMusicFontSymbol(e+this.x,t+this.y+a,this.glyphScale,this.symbol,!1),this._articulation.techniqueSymbol!==re.None&&this._articulation.techniqueSymbolPlacement===oe.Middle&&s.fillMusicFontSymbol(e+this.x,t+this.y+a,this.glyphScale,this._articulation.techniqueSymbol,!1),s.color=i}doLayout(){super.doLayout(),0===this.width&&(this.height=Nr.Widths.get(re.NoteheadBlack)),0===this.height&&(this.height=Nr.Heights.get(re.NoteheadBlack))}}class ch extends xr{constructor(e,t){super(e,t,vr.GraceScale,re.ArticStaccatoAbove)}paint(e,t,s){super.paint(e+3,t+5,s)}}class dh extends xr{constructor(e,t){super(e,t,.5,re.PictEdgeOfCymbal)}paint(e,t,s){super.paint(e-3,t+this.height,s)}}class uh extends xr{constructor(e,t,s=!1){super(e,t,vr.GraceScale,re.GuitarGolpe),this.center=s}paint(e,t,s){super.paint(e,t+this.height,s)}}class ph extends Tr{constructor(){super(...arguments),this._strings=new Set}addString(e){this._strings.add(e)}doLayout(){const e=Nr.Widths.get(re.GuitarString0)*Cn.CircleNumberScale;this.height=(e+3)*this._strings.size,this.width=e}paint(e,t,s){const i=this.renderer.bar.staff.tuning.length;let a=0;const r=Nr.Widths.get(re.GuitarString0)*Cn.CircleNumberScale,n=Nr.Heights.get(re.NoteheadBlack);for(const o of this._strings){const h=i-o,l=re.GuitarString1+h;s.fillMusicFontSymbol(e+this.x+n/2,t+this.y+r+a,Cn.CircleNumberScale,l,!0),a+=r+3}}}class gh extends Tr{constructor(e,t,s,i,a){super(e,t),this.beatEffects=new Map,this.noteHeadElement=le.SlashNoteHead,this.effectElement=ye.SlashEffects,this._isGrace=i,this._symbol=gh.getSymbol(s),this.beat=a}paint(e,t,s){const i=0===this.beat.notes.length?void 0:rn.note(s,this.noteHeadElement,this.beat.notes[0]);try{const i=this._isGrace?1:0,a=this._isGrace?vr.GraceScale:1;s.fillMusicFontSymbol(e+this.x,t+this.y+i,a,this._symbol,!1),this.paintEffects(e,t,s)}finally{i?.[Symbol.dispose]?.()}}paintEffects(e,t,s){const i=rn.beat(s,this.effectElement,this.beat);try{for(const i of this.beatEffects.values())i.paint(e+this.x,t+this.y,s)}finally{i?.[Symbol.dispose]?.()}}doLayout(){const e=this._isGrace?vr.GraceScale:1;this.width=Nr.Widths.get(this._symbol)*e,this.height=Nr.Heights.get(this._symbol)*e;let t=Nr.Heights.get(this._symbol);for(const e of this.beatEffects.values())e.y+=t,e.x+=this.width/2,e.renderer=this.renderer,t+=7,e.doLayout()}static getSymbol(e){switch(e){case _.QuadrupleWhole:case _.DoubleWhole:case _.Whole:return re.NoteheadSlashWhiteWhole;case _.Half:return re.NoteheadSlashWhiteHalf;default:return re.NoteheadSlashVerticalEnds}}updateBeamingHelper(e){this.beamingHelper&&this.beamingHelper.registerBeatLineX("slash",this.beat,e+this.x+this.width,e+this.x)}}class mh extends Mn{constructor(){super(...arguments),this._collisionOffset=-1e3,this._skipPaint=!1,this.slash=null,this.noteHeads=null,this.restGlyph=null}get effectElement(){return ye.StandardNotationEffects}getNoteX(e,t){return this.noteHeads?this.noteHeads.getNoteX(e,t):0}buildBoundingsLookup(e,t,s){this.noteHeads&&this.noteHeads.buildBoundingsLookup(e,t+this.x,s+this.y)}getNoteY(e,t){return this.noteHeads?this.noteHeads.getNoteY(e,t):0}updateBeamingHelper(){if(this.noteHeads)this.noteHeads.updateBeamingHelper(this.container.x+this.x);else if(this.restGlyph){if(this.restGlyph.updateBeamingHelper(this.container.x+this.x),this.renderer.bar.isMultiVoice&&-1e3===this._collisionOffset){this._collisionOffset=this.renderer.helpers.collisionHelper.applyRestCollisionOffset(this.container.beat,this.restGlyph.y,this.renderer.getScoreHeight(1)),this.y+=this._collisionOffset;const e=this.renderer.helpers.collisionHelper.restDurationsByDisplayTime;e.has(this.container.beat.playbackStart)&&e.get(this.container.beat.playbackStart).has(this.container.beat.playbackDuration)&&e.get(this.container.beat.playbackStart).get(this.container.beat.playbackDuration)!==this.container.beat.id&&(this._skipPaint=!0)}}else this.slash&&this.slash.updateBeamingHelper(this.container.x+this.x)}paint(e,t,s){this._skipPaint||super.paint(e,t,s)}doLayout(){const e=this.renderer;if(!this.container.beat.isEmpty)if(this.container.beat.isRest){let t=2*Math.ceil((this.renderer.bar.staff.standardNotationLineCount-1)/2);this.container.beat.duration===_.Whole&&1!==this.renderer.bar.staff.standardNotationLineCount&&3!==this.renderer.bar.staff.standardNotationLineCount&&(t-=2);const s=new Zo(0,e.getScoreY(t),this.container.beat.duration);if(this.restGlyph=s,s.beat=this.container.beat,s.beamingHelper=this.beamingHelper,this.addNormal(s),this.renderer.bar.isMultiVoice)if(0===this.container.beat.voice.index){const t=cn.computeLineHeightsForRest(this.container.beat.duration),i=s.y-e.getScoreHeight(t[0]),a=s.y+e.getScoreHeight(t[1]);this.renderer.helpers.collisionHelper.reserveBeatSlot(this.container.beat,i,a)}else this.renderer.helpers.collisionHelper.registerRest(this.container.beat);if(this.beamingHelper&&this.beamingHelper.applyRest(this.container.beat,t),this.container.beat.dots>0){this.addNormal(new hh(0,0,5));for(let e=0;e<this.container.beat.dots;e++){const e=new sn(0,0);e.renderer=this.renderer,this.createBeatDot(t,e),this.addEffect(e)}}}else{if(this.container.beat.slashed){const t=this.container.beat.graceType!==w.None,s=(e.heightLineCount-1)/2,i=e.getLineY(s),a=new gh(0,i,this.container.beat.duration,t,this.container.beat);a.noteHeadElement=le.StandardNotationNoteHead,a.effectElement=ye.StandardNotationEffects,this.slash=a,a.beat=this.container.beat,a.beamingHelper=this.beamingHelper,this.addNormal(a)}else{const e=new Qo;this.noteHeads=e,e.beat=this.container.beat,e.beamingHelper=this.beamingHelper;const t=new Yo(!1);t.renderer=this.renderer;for(const e of this.container.beat.notes)e.isVisible&&(this.createNoteGlyph(e),t.addParenthesis(e));this.addNormal(e),t.isEmpty||(this.addNormal(new hh(0,0,4*(this.container.beat.graceType!==w.None?vr.GraceScale:1))),this.addEffect(t))}if(this.container.beat.hasWhammyBar){const e=new oh(this.container.beat);e.renderer=this.renderer,e.doLayout(),this.container.ties.push(e)}if(this.container.beat.dots>0){this.addNormal(new hh(0,0,5));for(let t=0;t<this.container.beat.dots;t++){const t=new sn(0,0);t.renderer=this.renderer;for(const s of this.container.beat.notes){this.createBeatDot(e.getNoteLine(s),t).colorOverride=rn.noteColor(e.resources,le.StandardNotationEffects,s)}this.addEffect(t)}}}super.doLayout(),this.container.beat.isEmpty?this.centerX=this.width/2:this.restGlyph?this.centerX=this.restGlyph.x+this.restGlyph.width/2:this.noteHeads?this.centerX=this.noteHeads.x+this.noteHeads.width/2:this.slash&&(this.centerX=this.slash.x+this.slash.width/2)}createBeatDot(e,t){const s=this.renderer,i=new Vo(0,s.getScoreY(e),1.5);return t.addGlyph(i),i}createNoteHeadGlyph(e){const t=this.container.beat.graceType!==w.None,s=e.style;if(void 0!==s?.noteHead){const i=new vr(0,0,e.beat.duration,t);return i.symbol=s.noteHead,s.noteHeadCenterOnStem&&(i.centerOnStem=!0),i}if(e.beat.voice.bar.staff.isPercussion){const s=Le.getArticulation(e);if(s)return new lh(0,0,s,e.beat.duration,t);q.warning("Rendering",`No articulation found for percussion instrument ${e.percussionArticulation}`)}return e.isDead?new Go(0,0,t):e.beat.graceType===w.BendGrace?new vr(0,0,_.Quarter,!0):e.harmonicType===T.Natural?new zo(0,0,e.beat.duration,t):new vr(0,0,e.beat.duration,t)}createNoteGlyph(e){if(e.beat.graceType===w.BendGrace&&!e.hasBend)return;const t=this.renderer,s=this.createNoteHeadGlyph(e);s.colorOverride=rn.noteColor(t.resources,le.StandardNotationNoteHead,e);let i=t.getNoteLine(e);if(s.y=t.getScoreY(i),this.noteHeads.addNoteGlyph(s,e,i),e.harmonicType!==T.None&&e.harmonicType!==T.Natural){const a=e.displayValue+e.harmonicPitch,r=new zo(0,0,e.beat.duration,this.container.beat.graceType!==w.None);r.colorOverride=s.colorOverride,i=t.accidentalHelper.getNoteLineForValue(a,!1),r.y=t.getScoreY(i),this.noteHeads.addNoteGlyph(r,e,i)}const a=this.noteHeads.belowBeatEffects,r=this.noteHeads.aboveBeatEffects;if(e.isStaccato&&!a.has("Staccato")&&a.set("Staccato",new ch(0,0)),e.accentuated!==B.Normal||a.has("Accent")||a.set("Accent",new Wo(0,0,e)),e.accentuated!==B.Heavy||a.has("HAccent")||a.set("HAccent",new Wo(0,0,e)),e.accentuated!==B.Tenuto||a.has("Tenuto")||a.set("Tenuto",new Wo(0,0,e)),e.showStringNumber&&e.isStringed){let t;r.has("StringNumber")?t=r.get("StringNumber"):(t=new ph(0,0),r.set("StringNumber",t)),t.addString(e.string)}if(e.isPercussion){const t=Le.getArticulation(e);if(t&&t.techniqueSymbolPlacement!==oe.Middle){const e=t.techniqueSymbolPlacement===oe.Top?this.noteHeads.aboveBeatEffects:this.noteHeads.belowBeatEffects;switch(t.techniqueSymbol){case re.PictEdgeOfCymbal:e.set("PictEdgeOfCymbal",new dh(0,0));break;case re.ArticStaccatoAbove:e.set("ArticStaccatoAbove",new ch(0,0));break;case re.StringsUpBow:e.set("StringsUpBow",new bo(0,0,ae.Up));break;case re.StringsDownBow:e.set("StringsDownBow",new bo(0,0,ae.Down));break;case re.GuitarGolpe:e.set("GuitarGolpe",new uh(0,0))}}}}}class fh extends kr{constructor(e){super(0,0),this._beat=e}doLayout(){this.width=this._beat.brushType===b.ArpeggioUp||this._beat.brushType===b.ArpeggioDown?10:0}paint(e,t,s){if(this._beat.brushType===b.ArpeggioUp||this._beat.brushType===b.ArpeggioDown){const i=this.renderer,a=i.lineOffset,r=t+this.y+(i.getNoteY(this._beat.maxNote,is.Bottom)-a),n=t+this.y+i.getNoteY(this._beat.minNote,is.Top)+a,o=e+this.x+this.width/2,h=8,l=new Bo(0,0,P.Slight,1.2,!0);l.renderer=this.renderer,l.doLayout();const c=-l.height/2;if(this._beat.brushType===b.ArpeggioUp){const t=r+h,i=n-h;l.width=Math.abs(i-t),s.beginRotate(e+this.x+5,i,-90),l.paint(0,c,s),s.endRotate(),s.beginPath(),s.moveTo(o,n),s.lineTo(o+h/2,n-h),s.lineTo(o-h/2,n-h),s.closePath(),s.fill()}else if(this._beat.brushType===b.ArpeggioDown){const t=r+h,i=n;l.width=Math.abs(i-t),s.beginRotate(e+this.x+5,t,90),l.paint(0,c,s),s.endRotate(),s.beginPath(),s.moveTo(o,r),s.lineTo(o+h/2,r+h),s.lineTo(o-h/2,r+h),s.closePath(),s.fill()}}}}class yh{constructor(e,t){this.line=0,this.line=e,this.text=t}}class bh extends sn{constructor(){super(0,0),this._infos=new Map}get isEmpty(){return 0===this._infos.size}addFingers(e){const t=this.renderer.settings;if(t.notation.fingeringMode!==C.ScoreDefault&&t.notation.fingeringMode!==C.ScoreForcePiano)return;const s=ie.fingerToString(this.renderer.settings,e.beat,e.leftHandFinger,!0);s&&this.addFinger(e,s);const i=ie.fingerToString(this.renderer.settings,e.beat,e.rightHandFinger,!1);i&&this.addFinger(e,i)}addFinger(e,t){const s=this.renderer,i=s.getNoteLine(e);if(this._infos.has(i)){this._infos.get(i).text+=t}else{const a=new yh(i,t);a.color=rn.noteColor(s.resources,le.StandardNotationEffects,e),this._infos.set(i,a)}}doLayout(){const e=this.renderer;for(const[t,s]of this._infos){const t=new Sn(0,0,s.text,e.resources.inlineFingeringFont,ne.Left,oe.Middle);t.colorOverride=s.color,t.renderer=e,t.y=e.getScoreY(s.line),t.doLayout(),this.addGlyph(t),this.width=Math.max(this.width,t.width)}}}class Sh extends Ln{constructor(){super(...arguments),this._prebends=null,this.accidentals=null}get prebendNoteHeadOffset(){return this._prebends?this._prebends.x+this._prebends.noteHeadOffset:0}get effectElement(){return ye.StandardNotationEffects}doLayout(){if(!this.container.beat.isRest){const e=new th;e.renderer=this.renderer;const t=new bh;t.renderer=this.renderer;const s=new Yo(!0);s.renderer=this.renderer;const i=new sh(this.container.beat,!0);this._prebends=i,i.renderer=this.renderer;for(const a of this.container.beat.notes){const r=rn.noteColor(this.renderer.resources,le.StandardNotationEffects,a);if(a.isVisible){if(a.hasBend)switch(a.bendType){case y.PrebendBend:case y.Prebend:case y.PrebendRelease:i.addGlyph(a.displayValue-(a.bendPoints[0].value/2|0),!1,r)}else if(a.beat.hasWhammyBar)switch(a.beat.whammyBarType){case ce.PrediveDive:case ce.Predive:this._prebends.addGlyph(a.displayValue-(a.beat.whammyBarPoints[0].value/2|0),!1,r)}this.createAccidentalGlyph(a,e),s.addParenthesis(a),t.addFingers(a)}}i.isEmpty||(this.addEffect(i),this.addNormal(new hh(0,0,4*(this.container.beat.graceType!==w.None?vr.GraceScale:1)))),this.container.beat.brushType!==b.None&&(this.addEffect(new fh(this.container.beat)),this.addNormal(new hh(0,0,4))),t.isEmpty||(this.isEmpty||this.addNormal(new hh(0,0,2*(this.container.beat.graceType!==w.None?vr.GraceScale:1))),this.addEffect(t),this.addNormal(new hh(0,0,2*(this.container.beat.graceType!==w.None?vr.GraceScale:1)))),s.isEmpty||(this.addEffect(s),this.addNormal(new hh(0,0,4*(this.container.beat.graceType!==w.None?vr.GraceScale:1)))),e.isEmpty||(this.accidentals=e,this.isEmpty||this.addNormal(new hh(0,0,2*(this.container.beat.graceType!==w.None?vr.GraceScale:1))),this.addNormal(e),this.addNormal(new hh(0,0,2*(this.container.beat.graceType!==w.None?vr.GraceScale:1))))}super.doLayout()}createAccidentalGlyph(e,t){const s=this.renderer;let i=s.accidentalHelper.applyAccidental(e),a=s.getNoteLine(e);const r=this.container.beat.graceType!==w.None,n=rn.noteColor(s.resources,le.StandardNotationAccidentals,e),o=r?vr.GraceScale:1;if(i!==It.None){const e=new Oo(0,s.getScoreY(a),i,o);e.colorOverride=n,e.renderer=this.renderer,t.addGlyph(e)}if(e.harmonicType!==T.None&&e.harmonicType!==T.Natural){const h=e.displayValue+e.harmonicPitch;i=s.accidentalHelper.applyAccidentalForValue(e.beat,h,r,!1),a=s.accidentalHelper.getNoteLineForValue(h,!1);const l=new Oo(0,s.getScoreY(a),i,o);l.colorOverride=n,l.renderer=this.renderer,t.addGlyph(l)}}}class _h extends sn{constructor(e,t,s,i,a,r){super(e,t),this._numerator=0,this._denominator=0,this.barSubElement=u.StandardNotationTimeSignature,this._numerator=s,this._denominator=i,this._isCommon=a,this._isFreeTime=r}paint(e,t,s){const i=rn.bar(s,this.barSubElement,this.renderer.bar);try{super.paint(e,t,s)}finally{i?.[Symbol.dispose]?.()}}doLayout(){let e=0;const t=In.numberHeight;if(this._isFreeTime){const s=new Xo(!0);s.renderer=this.renderer,s.y=-t,s.height=2*t,s.doLayout(),this.addGlyph(s),e+=s.width+10}if(this._isCommon&&2===this._numerator&&2===this._denominator){const t=new xr(e,0,this.commonScale,re.TimeSigCutCommon);this.addGlyph(t),super.doLayout()}else if(this._isCommon&&4===this._numerator&&4===this._denominator){const t=new xr(e,0,this.commonScale,re.TimeSigCommon);this.addGlyph(t),super.doLayout()}else{const s=new In(e,-t/2,this._numerator,this.numberScale),i=new In(e,t/2,this._denominator,this.numberScale);this.addGlyph(s),this.addGlyph(i),super.doLayout();const a=this.width-e;s.x=e+(a-s.width)/2,i.x=e+(a-i.width)/2}if(this._isFreeTime){const e=new Xo(!1);e.renderer=this.renderer,e.x=this.width+13,e.y=-t,e.height=2*t,e.doLayout(),this.addGlyph(e),this.width=e.x+e.width}}}class wh extends _h{get commonScale(){return 1}get numberScale(){return 1}}class Bh extends ih{constructor(e){super(0,0),this._notes=[],this._endNoteGlyph=null,this._middleNoteGlyph=null,this._beat=e}addBends(e){if(this._notes.push(e),e.isTieOrigin)return;const t=rn.noteColor(this.renderer.resources,le.StandardNotationEffects,e);switch(e.bendType){case y.Bend:case y.PrebendRelease:case y.PrebendBend:{let s=this._endNoteGlyph;s||(s=new sh(e.beat,!1),s.renderer=this.renderer,this._endNoteGlyph=s,this.BendNoteHeads.push(s));const i=e.bendPoints[e.bendPoints.length-1];s.addGlyph(this.getBendNoteValue(e,i),i.value%2!=0,t)}break;case y.Release:if(!e.isTieOrigin){let s=this._endNoteGlyph;s||(s=new sh(e.beat,!1),s.renderer=this.renderer,this._endNoteGlyph=s,this.BendNoteHeads.push(s));const i=e.bendPoints[e.bendPoints.length-1];s.addGlyph(this.getBendNoteValue(e,i),i.value%2!=0,t)}break;case y.BendRelease:{let s=this._middleNoteGlyph;s||(s=new sh(e.beat,!1),this._middleNoteGlyph=s,s.renderer=this.renderer,this.BendNoteHeads.push(s));const i=e.bendPoints[1];s.addGlyph(this.getBendNoteValue(e,e.bendPoints[1]),i.value%2!=0,t);let a=this._endNoteGlyph;a||(a=new sh(e.beat,!1),a.renderer=this.renderer,this._endNoteGlyph=a,this.BendNoteHeads.push(a));const r=e.bendPoints[e.bendPoints.length-1];a.addGlyph(this.getBendNoteValue(e,r),r.value%2!=0,t)}}}paint(e,t,s){const i=this.renderer.scoreRenderer.layout.getRendererForBar(this.renderer.staff.staffId,this._beat.voice.bar),a=e+i.x+i.getBeatX(this._beat,ts.MiddleNotes);let r=e+i.x;this._beat.isLastOfVoice?r+=i.postBeatGlyphsStart:r+=i.getBeatX(this._beat.nextBeat,ts.PreNotes),r-=8;const n=(a+r)/2;this._middleNoteGlyph&&(this._middleNoteGlyph.x=n-this._middleNoteGlyph.noteHeadOffset,this._middleNoteGlyph.y=t+i.y,this._middleNoteGlyph.paint(0,0,s)),this._endNoteGlyph&&(this._endNoteGlyph.x=r-this._endNoteGlyph.noteHeadOffset,this._endNoteGlyph.y=t+i.y,this._endNoteGlyph.paint(0,0,s)),this._notes.sort(((e,t)=>t.displayValue-e.displayValue));const o=this._beat.graceType===w.BendGrace?this._beat.nextBeat:this._beat;let h=1===this._notes.length?this.getTieDirection(o,i):Te.Up;const l=Nr.Heights.get(re.NoteheadBlack);for(let o=0;o<this._notes.length;o++){const c=this._notes[o],d=rn.note(s,le.StandardNotationEffects,c);try{o>0&&o>=(this._notes.length/2|0)&&(h=Te.Down);let d=t+i.y+i.getNoteY(c,is.Top),u=l*vr.GraceScale*.5;h===Te.Down&&(d+=l);const p=c.bendStyle===f.Gradual?"grad.":"";if(c.isTieOrigin){const r=c.tieDestination,n=r?this.renderer.scoreRenderer.layout.getRendererForBar(this.renderer.staff.staffId,r.beat.voice.bar):null;if(n&&n.staff===i.staff){const i=e+n.x+n.getBeatX(r.beat,ts.MiddleNotes);let o=t+n.y+n.getNoteY(r,is.Top);h===Te.Down&&(o+=l),c.bendType===y.Hold||c.bendType===y.Prebend?Uo.paintTie(s,1,a,d,i,o,h===Te.Down,22,4):this.drawBendSlur(s,a,d,i,o,h===Te.Down,1,p)}else{const r=e+i.x+i.width,n=c.tieDestination.realValue;i.accidentalHelper.applyAccidentalForValue(c.beat,n,!1,!0);const o=t+i.y+i.getScoreY(i.accidentalHelper.getNoteLineForValue(n,!1));c.bendType===y.Hold||c.bendType===y.Prebend?Uo.paintTie(s,1,a,d,r,o,h===Te.Down,22,4):this.drawBendSlur(s,a,d,r,o,h===Te.Down,1,p)}switch(c.bendType){case y.Prebend:case y.PrebendBend:case y.PrebendRelease:let r=e+i.x+i.getBeatX(c.beat,ts.PreNotes);r+=i.getPreNotesGlyphForBeat(c.beat).prebendNoteHeadOffset;const n=t+i.y+i.getScoreY(i.accidentalHelper.getNoteLineForValue(c.displayValue-(c.bendPoints[0].value/2|0),!1))+u;this.drawBendSlur(s,r,n,a,d,h===Te.Down,1)}}else{h===Te.Up&&(u=-u);let o=0,l=0;switch(c.bendType){case y.Bend:o=this.getBendNoteValue(c,c.bendPoints[c.bendPoints.length-1]),l=this._endNoteGlyph.getNoteValueY(o)+u,this.drawBendSlur(s,a,d,r,l,h===Te.Down,1,p);break;case y.BendRelease:const g=this.getBendNoteValue(c,c.bendPoints[1]),m=this._middleNoteGlyph.getNoteValueY(g)+u;this.drawBendSlur(s,a,d,n,m,h===Te.Down,1,p),o=this.getBendNoteValue(c,c.bendPoints[c.bendPoints.length-1]),l=this._endNoteGlyph.getNoteValueY(o)+u,this.drawBendSlur(s,n,m,r,l,h===Te.Down,1,p);break;case y.Release:this.BendNoteHeads.length>0&&(o=this.getBendNoteValue(c,c.bendPoints[c.bendPoints.length-1]),l=this.BendNoteHeads[0].getNoteValueY(o)+u,this.drawBendSlur(s,a,d,r,l,h===Te.Down,1,p));break;case y.Prebend:case y.PrebendBend:case y.PrebendRelease:let f=e+i.x+i.getBeatX(c.beat,ts.PreNotes);f+=i.getPreNotesGlyphForBeat(c.beat).prebendNoteHeadOffset;const b=t+i.y+i.getScoreY(i.accidentalHelper.getNoteLineForValue(c.displayValue-(c.bendPoints[0].value/2|0),!1))+u;this.drawBendSlur(s,f,b,a,d,h===Te.Down,1),this.BendNoteHeads.length>0&&(o=this.getBendNoteValue(c,c.bendPoints[c.bendPoints.length-1]),l=this.BendNoteHeads[0].getNoteValueY(o)+u,this.drawBendSlur(s,a,d,r,l,h===Te.Down,1,p))}}}finally{d?.[Symbol.dispose]?.()}}}getBendNoteValue(e,t){return e.displayValueWithoutBend+(t.value/2|0)}}class kh extends Uo{constructor(e,t,s=!1){super(e,t,s)}doLayout(){super.doLayout()}getBeamDirection(e,t){return e.isRest?Te.Up:t.getBeatDirection(e)===Te.Up?Te.Down:Te.Up}getStartY(){return this.startBeat.isRest?this.startNoteRenderer.getScoreY(9):this.tieDirection===Te.Up?this.startNoteRenderer.getNoteY(this.startBeat.maxNote,is.Top):this.startNoteRenderer.getNoteY(this.startBeat.minNote,is.Bottom)}getEndY(){const e=this.endNoteRenderer;if(this.endBeat.isRest)return this.tieDirection===Te.Up?e.getScoreY(9):e.getScoreY(0);const t=this.startNoteRenderer.getBeatDirection(this.startBeat),s=e.getBeatDirection(this.endBeat);return t!==s&&this.startBeat.graceType===w.None?s===this.tieDirection?this.tieDirection===Te.Up?e.getNoteY(this.endBeat.maxNote,is.TopWithStem):e.getNoteY(this.endBeat.minNote,is.BottomWithStem):this.tieDirection===Te.Up?e.getNoteY(this.endBeat.maxNote,is.BottomWithStem):e.getNoteY(this.endBeat.minNote,is.TopWithStem):this.tieDirection===Te.Up?e.getNoteY(this.endBeat.maxNote,is.Top):e.getNoteY(this.endBeat.minNote,is.Bottom)}getStartX(){return this.startNoteRenderer.getBeatX(this.startBeat,ts.MiddleNotes)}getEndX(){const e=this.endNoteRenderer.getBeatDirection(this.endBeat);return this.endNoteRenderer.getBeatX(this.endBeat,this.endBeat.duration>_.Whole&&e===this.tieDirection?ts.Stem:ts.MiddleNotes)}}class Th extends kr{constructor(e,t,s,i){super(0,0),this._outType=t,this._inType=e,this._startNote=s,this._parent=i}doLayout(){this.width=0}paint(e,t,s){this.paintSlideIn(e,t,s),this.drawSlideOut(e,t,s)}paintSlideIn(e,t,s){const i=this.renderer;let a=e+i.x+i.getNoteX(this._startNote,as.Left)-2;const r=t+i.y+i.getNoteY(this._startNote,is.Center);let n=a-12,o=t+i.y;switch(this._inType){case x.IntoFromBelow:o+=i.getNoteY(this._startNote,is.Bottom);break;case x.IntoFromAbove:o+=i.getNoteY(this._startNote,is.Top);break;default:return}const h=this.getAccidentalsWidth(i,this._startNote.beat);n-=h,a-=h,this.paintSlideLine(s,!1,n,a,o,r)}getAccidentalsWidth(e,t){const s=e.getPreNotesGlyphForBeat(t);return s&&s.accidentals?s.accidentals.width:0}drawSlideOut(e,t,s){const i=this.renderer;let a=0,r=0,n=0,o=0,h=!1;switch(this._outType){case v.Shift:case v.Legato:if(a=e+i.x+i.getBeatX(this._startNote.beat,ts.PostNotes)+2,r=t+i.y+i.getNoteY(this._startNote,is.Center),this._startNote.slideTarget){const s=this.renderer.scoreRenderer.layout.getRendererForBar(this.renderer.staff.staffId,this._startNote.slideTarget.beat.voice.bar);s&&s.staff===i.staff?(n=e+s.x+s.getBeatX(this._startNote.slideTarget.beat,ts.PreNotes)-2,o=t+s.y+s.getNoteY(this._startNote.slideTarget,is.Center)):(n=e+i.x+i.width,o=r),this._startNote.slideTarget.realValue>this._startNote.realValue?(r+=2,o-=2):(r-=2,o+=2)}else n=e+i.x+this._parent.x,o=r;break;case v.OutUp:a=e+i.x+i.getNoteX(this._startNote,as.Right)+2,r=t+i.y+i.getNoteY(this._startNote,is.Center),n=a+12,o=t+i.y+i.getNoteY(this._startNote,is.Top);break;case v.OutDown:a=e+i.x+i.getNoteX(this._startNote,as.Right)+2,r=t+i.y+i.getNoteY(this._startNote,is.Center),n=a+12,o=t+i.y+i.getNoteY(this._startNote,is.Bottom);break;case v.PickSlideUp:a=e+i.x+i.getNoteX(this._startNote,as.Right)+4,r=t+i.y+i.getNoteY(this._startNote,is.Center),o=t+i.y+i.getNoteY(this._startNote,is.Top),n=e+i.x+i.width,this._startNote.beat.nextBeat&&this._startNote.beat.nextBeat.voice===this._startNote.beat.voice&&(n=e+i.x+i.getBeatX(this._startNote.beat.nextBeat,ts.PreNotes)),h=!0;break;case v.PickSlideDown:a=e+i.x+i.getNoteX(this._startNote,as.Right)+4,r=t+i.y+i.getNoteY(this._startNote,is.Center),o=t+i.y+i.getNoteY(this._startNote,is.Bottom),n=e+i.x+i.width,this._startNote.beat.nextBeat&&this._startNote.beat.nextBeat.voice===this._startNote.beat.voice&&(n=e+i.x+i.getBeatX(this._startNote.beat.nextBeat,ts.PreNotes)),h=!0;break;default:return}this.paintSlideLine(s,h,a,n,r,o)}paintSlideLine(e,t,s,i,a,r){if(t){const t=new Bo(0,0,P.Slight,1.2);t.renderer=this.renderer,t.doLayout(),a-=t.height/2;const n=i-s,o=(r-=t.height/2)-a,h=Math.sqrt(Math.pow(o,2)+Math.pow(n,2));t.width=n;const l=Math.asin(o/h)*(180/Math.PI);e.beginRotate(s,a,l),t.paint(0,0,e),e.endRotate()}else e.beginPath(),e.moveTo(s,a),e.lineTo(i,r),e.stroke()}}class Nh extends kh{constructor(e,t,s=!1){super(e.beat,t.beat,s),this._startNote=e,this._endNote=t}getTieHeight(e,t,s,i){return Math.log2(s-e+1)*this.renderer.settings.notation.slurHeight}getStartY(){return this.isStartCentered()?this.tieDirection===Te.Up?this.startNoteRenderer.getNoteY(this._startNote,is.Top):this.startNoteRenderer.getNoteY(this._startNote,is.Bottom):this.startNoteRenderer.getNoteY(this._startNote,is.Center)}getEndY(){return this.isEndCentered()?this.isEndOnStem()?this.tieDirection===Te.Up?this.endNoteRenderer.getNoteY(this._endNote,is.TopWithStem):this.endNoteRenderer.getNoteY(this._endNote,is.BottomWithStem):this.tieDirection===Te.Up?this.endNoteRenderer.getNoteY(this._endNote,is.Top):this.endNoteRenderer.getNoteY(this._endNote,is.Bottom):this.endNoteRenderer.getNoteY(this._endNote,is.Center)}isStartCentered(){return this._startNote===this._startNote.beat.maxNote&&this.tieDirection===Te.Up||this._startNote===this._startNote.beat.minNote&&this.tieDirection===Te.Down}isEndCentered(){return this._startNote.beat.graceType===w.None&&(this._endNote===this._endNote.beat.maxNote&&this.tieDirection===Te.Up||this._endNote===this._endNote.beat.minNote&&this.tieDirection===Te.Down)}isEndOnStem(){const e=this.endNoteRenderer;return this.startNoteRenderer.getBeatDirection(this.startBeat)!==e.getBeatDirection(this.endBeat)&&this.startBeat.graceType===w.None}getStartX(){return this.isStartCentered()?this.startNoteRenderer.getBeatX(this._startNote.beat,ts.MiddleNotes):this.startNoteRenderer.getNoteX(this._startNote,as.Right)}getEndX(){return this.isEndCentered()?this.isEndOnStem()?this.endNoteRenderer.getBeatX(this._endNote.beat,ts.Stem):this.endNoteRenderer.getNoteX(this._endNote,as.Center):this.endNoteRenderer.getBeatX(this._endNote.beat,ts.PreNotes)}}class xh extends Uo{constructor(e,t,s=!1){super(e?e.beat:null,t?t.beat:null,s),this.startNote=e,this.endNote=t}shouldDrawBendSlur(){return this.renderer.settings.notation.extendBendArrowsOnTiedNotes&&!!this.startNote.bendOrigin&&this.startNote.isTieOrigin}doLayout(){super.doLayout()}getBeamDirection(e,t){return t.getBeatDirection(e)===Te.Up?Te.Down:Te.Up}getStartY(){return this.startBeat.isRest?this.startNoteRenderer.getScoreY(9):this.tieDirection===Te.Up?this.startNoteRenderer.getNoteY(this.startNote,is.Top):this.startNoteRenderer.getNoteY(this.startNote,is.Bottom)}getEndY(){const e=this.endNoteRenderer;return this.endBeat.isRest?this.tieDirection===Te.Up?e.getScoreY(9):e.getScoreY(0):this.tieDirection===Te.Up?e.getNoteY(this.endNote,is.Top):e.getNoteY(this.endNote,is.Bottom)}getStartX(){return this.startNoteRenderer.getBeatX(this.startNote.beat,ts.PostNotes)}getEndX(){return this.endNoteRenderer.getBeatX(this.endNote.beat,ts.PreNotes)}}class vh extends Fr{constructor(){super(...arguments),this._bend=null,this._effectSlur=null,this._effectEndSlur=null}doLayout(){this._effectSlur=null,this._effectEndSlur=null,super.doLayout(),this._bend&&(this._bend.renderer=this.renderer,this._bend.doLayout(),this.updateWidth())}createTies(e){if(e.isVisible){if(e.isTieOrigin&&!e.hasBend&&!e.beat.hasWhammyBar&&e.beat.graceType!==w.BendGrace&&e.tieDestination&&e.tieDestination.isVisible){const t=new xh(e,e.tieDestination,!1);this.addTie(t)}if(e.isTieDestination&&!e.tieOrigin.hasBend&&!e.beat.hasWhammyBar){const t=new xh(e.tieOrigin,e,!0);this.addTie(t)}if(e.slideInType!==x.None||e.slideOutType!==v.None){const t=new Th(e.slideInType,e.slideOutType,e,this);this.addTie(t)}if(e.isSlurOrigin&&e.slurDestination&&e.slurDestination.isVisible){const t=new Nh(e,e.slurDestination,!1);this.addTie(t)}if(e.isSlurDestination){const t=new Nh(e.slurOrigin,e,!0);this.addTie(t)}if(!this._effectSlur&&e.isEffectSlurOrigin&&e.effectSlurDestination){const t=new Nh(e,e.effectSlurDestination,!1);this._effectSlur=t,this.addTie(t)}if(!this._effectEndSlur&&e.beat.isEffectSlurDestination&&e.beat.effectSlurOrigin){const t=this.onNotes.beamingHelper.direction,s=t===Te.Up?e.beat.effectSlurOrigin.minNote:e.beat.effectSlurOrigin.maxNote,i=t===Te.Up?e.beat.minNote:e.beat.maxNote,a=new Nh(s,i,!0);this._effectEndSlur=a,this.addTie(a)}if(e.hasBend){if(!this._bend){const t=new Bh(e.beat);this._bend=t,t.renderer=this.renderer,this.addTie(t)}this._bend.addBends(e)}if(this.beat.isLegatoOrigin){if(!this.beat.previousBeat||!this.beat.previousBeat.isLegatoOrigin){let e=this.beat.nextBeat;for(;e.nextBeat&&e.nextBeat.isLegatoDestination;)e=e.nextBeat;this.addTie(new kh(this.beat,e,!1))}}else if(this.beat.isLegatoDestination&&!this.beat.isLegatoOrigin){let e=this.beat.previousBeat;for(;e.previousBeat&&e.previousBeat.isLegatoOrigin;)e=e.previousBeat;this.addTie(new kh(e,this.beat,!0))}}}}class Ph extends kr{doLayout(){this.width=1}paint(e,t,s){const i=e+this.x,a=t+this.y+this.renderer.topPadding,r=t+this.y+this.renderer.height-this.renderer.bottomPadding-a;this.paintInternal(i,a,r,s)}}class Fh extends Ph{paintInternal(e,t,s,i){i.fillRect(e,t,1,s)}}class Ch extends Ph{paintInternal(e,t,s,i){const a=e,r=this.renderer.getLineHeight(1);let n=t+.5*r+1;const o=t+s;for(;n<o;)i.fillCircle(a,n,1),n+=r}}class Dh extends Ph{paintInternal(e,t,s,i){const a=Dh.DashSize,r=e+.5,n=Math.ceil(s/2/a),o=t+s;if(i.beginPath(),n<1)i.moveTo(r,t),i.lineTo(r,o);else{let e=t;const h=(s-n*a)/(n-1);for(;e<o;)i.moveTo(r,e),i.lineTo(r,e+a),e+=a+h}i.stroke()}}Dh.DashSize=4;class Eh extends Ph{doLayout(){this.width=4}paintInternal(e,t,s,i){i.fillRect(e,t,this.width,s)}}class Lh extends Ph{paintInternal(e,t,s,i){const a=1.5,r=(t+(t+s))/2;i.fillCircle(e,r-4.5,a),i.fillCircle(e,r+4.5,a)}}class Mh extends Ph{paintInternal(e,t,s,i){const a=this.renderer,r=a.drawnLineCount-1;if(r<=2)return;const n=a.getLineHeight(1),o=2*n,h=r/2*n-o/2;i.fillRect(e,t+h,1,o)}}class Ih extends Ph{paintInternal(e,t,s,i){const a=this.renderer.getLineHeight(1),r=-a/2+1;i.fillRect(e,t+r,1,a)}}class Ah extends an{constructor(e){super(),this._isRight=e}doLayout(){const e=this.renderer.bar,t=e.masterBar,s=this._isRight?e.getActualBarLineRight():e.getActualBarLineLeft(0===this.renderer.index);let i=p.Automatic;if(!this._isRight){const e=this.renderer.previousRenderer;if(e&&e.staff===this.renderer.staff&&(i=e.bar.getActualBarLineRight(),s===i))return}switch(this._isRight&&t.isRepeatEnd&&(this.addGlyph(new Lh(0,0)),this.width+=3),s){case p.Dashed:this.addGlyph(new Dh(0,0));break;case p.Dotted:this.addGlyph(new Ch(0,0));break;case p.Heavy:i!==p.LightHeavy&&i!==p.HeavyHeavy&&this.addGlyph(new Eh(0,0));break;case p.HeavyHeavy:i!==p.LightHeavy&&i!==p.Heavy&&this.addGlyph(new Eh(0,0)),this.width+=3,this.addGlyph(new Eh(0,0));break;case p.HeavyLight:i!==p.LightHeavy&&i!==p.Heavy&&i!==p.HeavyHeavy&&this.addGlyph(new Eh(0,0)),this.width+=3,this.addGlyph(new Fh(0,0));break;case p.LightHeavy:i!==p.HeavyLight&&i!==p.Regular&&i!==p.LightLight&&this.addGlyph(new Fh(0,0)),this.width+=3,this.addGlyph(new Eh(0,0));break;case p.LightLight:i!==p.HeavyLight&&i!==p.Regular&&this.addGlyph(new Fh(0,0)),this.width+=3,this.addGlyph(new Fh(0,0));break;case p.None:break;case p.Regular:i!==p.HeavyLight&&i!==p.LightLight&&this.addGlyph(new Fh(0,0));break;case p.Short:this.addGlyph(new Mh(0,0));break;case p.Tick:this.addGlyph(new Ih(0,0))}this._isRight||t.isRepeatStart&&(this.width+=3,this.addGlyph(new Lh(0,0)))}paint(e,t,s){const i=this.renderer,a=rn.bar(s,i.barLineBarSubElement,this.renderer.bar,!0);try{super.paint(e,t,s)}finally{a?.[Symbol.dispose]?.()}}}class Rh extends kr{constructor(e,t,s){super(e,t),this._count=0,this._count=0,this._count=s}doLayout(){this.width=0}paint(e,t,s){const i=rn.bar(s,this.renderer.repeatsBarSubElement,this.renderer.bar);try{const i=this.renderer.resources,a=s.textAlign;s.font=i.barNumberFont,s.textAlign=ne.Right;const r=`x${this._count}`,n=s.measureText(r).width/1.5;s.fillText(r,e+this.x-n,t+this.y),s.textAlign=a}finally{i?.[Symbol.dispose]?.()}}}class Oh extends kr{constructor(e,t,s){super(e,t),this._number=0,this._number=s}doLayout(){this.renderer.scoreRenderer.canvas.font=this.renderer.resources.barNumberFont,this.width=this.renderer.scoreRenderer.canvas.measureText(this._number.toString()).width+5}paint(e,t,s){if(!this.renderer.staff.isFirstInSystem)return;const i=rn.bar(s,this.renderer.barNumberBarSubElement,this.renderer.bar,!0);try{const i=this.renderer.resources,a=s.textBaseline;s.textBaseline=oe.Top,s.font=i.barNumberFont,s.fillText(this._number.toString(),e+this.x,t+this.y),s.textBaseline=a}finally{i?.[Symbol.dispose]?.()}}}class Hh extends On{constructor(){super(...arguments),this.firstLineY=0,this._startSpacing=!1,this.tupletSize=0}get lineOffset(){return this.lineSpacing+1}get tupletOffset(){return 10}get topGlyphOverflow(){const e=this.resources;return e.tablatureFont.size/2+.2*e.tablatureFont.size}get bottomGlyphOverflow(){const e=this.resources;return e.tablatureFont.size/2+.2*e.tablatureFont.size}initLineBasedSizes(){this.topPadding=this.topGlyphOverflow,this.bottomPadding=this.bottomGlyphOverflow,this.height=this.lineOffset*(this.heightLineCount-1)+this.topPadding+this.bottomPadding}updateSizes(){this.initLineBasedSizes(),this.adjustSizes(),this.updateFirstLineY(),super.updateSizes()}adjustSizes(){}updateFirstLineY(){const e=this.lineOffset*(this.heightLineCount-1),t=(this.drawnLineCount-1)*this.lineOffset;this.firstLineY=this.topPadding+(e-t)/2}doLayout(){this.initLineBasedSizes(),this.updateFirstLineY(),this.tupletSize=15+.3*this.resources.effectFont.size,super.doLayout()}getLineY(e){return this.firstLineY+this.getLineHeight(e)}getLineHeight(e){return this.lineOffset*e}paintBackground(e,t,s){super.paintBackground(e,t,s),this.paintStaffLines(e,t,s),this.paintSimileMark(e,t,s)}paintStaffLines(e,t,s){const i=rn.bar(s,this.staffLineBarSubElement,this.bar,!0);try{const i=[];for(let e=0,t=this.drawnLineCount;e<t;e++)i.push([]);this.additionalMultiRestBars||this.collectSpaces(i);for(const e of i)e.sort(((e,t)=>e[0]>t[0]?1:e[0]<t[0]?-1:0));const a=Math.ceil(this.width);for(let r=0;r<this.drawnLineCount;r++){const n=this.getLineY(r);let o=0;for(const a of i[r])s.fillRect(e+this.x+o,t+this.y+n|0,a[0]-o,On.StaffLineThickness),o=a[0]+a[1];s.fillRect(e+this.x+o,t+this.y+n|0,a-o,On.StaffLineThickness)}}finally{i?.[Symbol.dispose]?.()}}collectSpaces(e){}createStartSpacing(){if(this._startSpacing)return;const e=0===this.index?this.settings.display.firstStaffPaddingLeft:this.settings.display.staffPaddingLeft;this.addPreBeatGlyph(new hh(0,0,e)),this._startSpacing=!0}paintTuplets(e,t,s,i,a=!1){for(const r of this.bar.voices)if(this.hasVoiceContainer(r)){const n=this.getVoiceContainer(r);for(const r of n.tupletGroups)this.paintTupletHelper(e+this.beatGlyphsStart,t,s,r,i,a)}}getTupletBeamDirection(e){return this.getBeamDirection(e)}paintTupletHelper(e,t,s,i,a,r){const n=this.resources,o=s.textAlign,h=s.textBaseline;let l;s.color=0===i.voice.index?this.resources.mainGlyphColor:this.resources.secondaryGlyphColor,s.textAlign=ne.Center,s.textBaseline=oe.Middle;const c=i.beats[0].tupletNumerator,d=i.beats[0].tupletDenominator;l=2===c&&3===d?"2":3===c&&2===d?"3":4===c&&6===d?"4":5===c&&4===d?"5":6===c&&4===d?"6":7===c&&4===d?"7":9===c&&8===d?"9":10===c&&8===d?"10":11===c&&8===d?"11":12===c&&8===d?"12":13===c&&8===d?"13":`${c}:${d}`;let u=this.tupletOffset,p=5;const g=rn.beat(s,a,i.beats[0]);try{if(1!==i.beats.length&&i.isFull){const a=i.beats[0],o=i.beats[i.beats.length-1];let h=null,c=null;for(let e=0;e<i.beats.length;e++)if(!i.beats[e].isRest){h=i.beats[e];break}for(let e=i.beats.length-1;e>=0;e--)if(!i.beats[e].isRest){c=i.beats[e];break}let d=!1;h||(h=a,d=!0),c||(c=o);const g=this.helpers.beamHelperLookup[i.voice.index].get(a.index),m=this.helpers.beamHelperLookup[i.voice.index].get(o.index),f=g.getBeatLineX(a),y=m.getBeatLineX(o),b=this.helpers.beamHelperLookup[i.voice.index].get(h.index),S=this.helpers.beamHelperLookup[i.voice.index].get(c.index),_=this.getTupletBeamDirection(g);let w=this.calculateBeamYWithDirection(b,f,_),B=this.calculateBeamYWithDirection(S,y,_);d&&(w=Math.max(w,B),B=w),s.font=n.effectFont;const k=s.measureText(l).width,T=3,N=(f+y)/2,x=N-k/2-T,v=N+k/2+T,P=(B-w)/(y-f),F=w-P*f,C=P*x+F,D=P*N+F,E=P*v+F;_===Te.Down&&(u*=-1,p*=-1),s.beginPath(),s.moveTo(e+this.x+f,t+this.y+w-u|0),r?s.quadraticCurveTo(e+this.x+(x+f)/2,t+this.y+C-u-p|0,e+this.x+x,t+this.y+C-u-p|0):(s.lineTo(e+this.x+f,t+this.y+w-u-p|0),s.lineTo(e+this.x+x,t+this.y+C-u-p|0)),s.stroke(),s.beginPath(),s.moveTo(e+this.x+v,t+this.y+E-u-p|0),r?s.quadraticCurveTo(e+this.x+(y+v)/2,t+this.y+E-u-p|0,e+this.x+y,t+this.y+B-u|0):(s.lineTo(e+this.x+y,t+this.y+B-u-p|0),s.lineTo(e+this.x+y,t+this.y+B-u|0)),s.stroke(),s.fillText(l,e+this.x+N,t+this.y+D-u-p)}else for(const a of i.beats){const r=this.helpers.beamHelperLookup[i.voice.index].get(a.index);if(!r)continue;const o=this.getTupletBeamDirection(r),h=r.getBeatLineX(a);let c=this.calculateBeamYWithDirection(r,h,o);o===Te.Down?c+=u+p:c-=u+p,s.font=n.effectFont,s.fillText(l,e+this.x+h,t+this.y+c)}s.textAlign=o,s.textBaseline=h}finally{g?.[Symbol.dispose]?.()}}paintBeams(e,t,s,i,a){for(const r of this.helpers.beamHelpers)for(const n of r)this.paintBeamHelper(e+this.beatGlyphsStart,t,s,n,i,a)}drawBeamHelperAsFlags(e){return 1===e.beats.length}paintBeamHelper(e,t,s,i,a,r){s.color=0===i.voice.index?this.resources.mainGlyphColor:this.resources.secondaryGlyphColor,i.isRestBeamHelper||(this.drawBeamHelperAsFlags(i)?this.paintFlag(e,t,s,i,a):this.paintBar(e,t,s,i,r))}shouldPaintFlag(e,t){return e.graceType!==w.BendGrace&&(!e.deadSlapped&&(!!t.hasBeatLineX(e)&&((e.graceType===w.None||this.settings.notation.notationMode!==D.SongBook)&&(e.duration!==_.Whole&&e.duration!==_.DoubleWhole&&e.duration!==_.QuadrupleWhole))))}paintFlag(e,t,s,i,a){for(const r of i.beats){if(!this.shouldPaintFlag(r,i))continue;const n=r.graceType!==w.None,o=n?vr.GraceScale:1,h=this.getFlagStemSize(i.shortestDuration),l=i.getBeatLineX(r),c=this.getBeamDirection(i);let d=this.getFlagTopY(r,c),u=this.getFlagBottomY(r,c),p=0;if(c===Te.Down?(u+=h*o,p=u):(d-=h*o,p=d),!i.hasLine(!0,r))continue;this.paintBeamingStem(r,t+this.y,e+this.x+l,t+this.y+d,t+this.y+u,s);const g=rn.beat(s,a,r);try{if(r.graceType===w.BeforeBeat){const i=15,a=12;s.beginPath(),c===Te.Down?(s.moveTo(e+this.x+l-a/2,t+this.y+u-i),s.lineTo(e+this.x+l+a/2,t+this.y+u)):(s.moveTo(e+this.x+l-a/2,t+this.y+d+i),s.lineTo(e+this.x+l+a/2,t+this.y+d)),s.stroke()}if(i.hasFlag(!0,r)){const i=new Pr(l-.5,p,r.duration,c,n);i.renderer=this,i.doLayout(),i.paint(e+this.x,t+this.y,s)}}finally{g?.[Symbol.dispose]?.()}}}getFlagStemSize(e,t=!1){let s=0;switch(e){case _.QuadrupleWhole:case _.Half:case _.Quarter:case _.Eighth:case _.Sixteenth:case _.ThirtySecond:case _.SixtyFourth:case _.OneHundredTwentyEighth:case _.TwoHundredFiftySixth:s=3;break;default:s=t?3:0}return this.getLineHeight(s)}recreatePreBeatGlyphs(){this._startSpacing=!1,super.recreatePreBeatGlyphs()}calculateBeamY(e,t){return this.calculateBeamYWithDirection(e,t,this.getBeamDirection(e))}createPreBeatGlyphs(){super.createPreBeatGlyphs(),this.addPreBeatGlyph(new Ah(!1)),this.createLinePreBeatGlyphs(),this.addPreBeatGlyph(new Oh(0,this.getLineHeight(-.25),this.bar.index+1))}createPostBeatGlyphs(){super.createPostBeatGlyphs();const e=this.lastBar;this.addPostBeatGlyph(new Ah(!0)),e.masterBar.isRepeatEnd&&e.masterBar.repeatCount>2&&this.addPostBeatGlyph(new Rh(0,this.getLineHeight(-.25),this.bar.masterBar.repeatCount))}paintBar(e,t,s,i,a){for(let r=0,n=i.beats.length;r<n;r++){const n=i.beats[r];if(!i.hasBeatLineX(n)||n.deadSlapped)continue;const o=n.graceType!==w.None?vr.GraceScale:1,h=i.getBeatLineX(n),l=this.getBeamDirection(i),c=t+this.y+this.getBarLineStart(n,l),d=t+this.y+this.calculateBeamY(i,h);this.paintBeamingStem(n,t+this.y,e+this.x+h,c,d,s);const u=rn.beat(s,a,n);try{let a=d;l===Te.Down?a+=2*s.font.size:0!==r&&(a-=1.5*s.font.size);const c=6*o;let u=(On.BeamSpacing+On.BeamThickness)*o,p=On.BeamThickness*o;const g=ie.getIndex(n.duration)-2,m=t+this.y;l===Te.Down&&(u=-u,p=-p);for(let t=0;t<g;t++){let a=0,o=0,l=0,d=0;const f=m+t*u;if(r<i.beats.length-1){const u=cn.isFullBarJoin(n,i.beats[r+1],t);if(t===g-1&&u&&n.beamingMode===fe.ForceSplitOnSecondaryToNext)a=h,o=a+c,l=f+this.calculateBeamY(i,a),d=f+this.calculateBeamY(i,o),Hh.paintSingleBar(s,e+this.x+a,l,e+this.x+o,d,p),o=i.getBeatLineX(i.beats[r+1]),a=o-c,l=f+this.calculateBeamY(i,a),d=f+this.calculateBeamY(i,o),Hh.paintSingleBar(s,e+this.x+a,l,e+this.x+o,d,p);else{if(u)a=h,o=i.getBeatLineX(i.beats[r+1]);else{if(0!==r&&cn.isFullBarJoin(i.beats[r-1],n,t))continue;a=h,o=a+c}l=f+this.calculateBeamY(i,a),d=f+this.calculateBeamY(i,o),Hh.paintSingleBar(s,e+this.x+a,l,e+this.x+o,d,p)}}else r>0&&!cn.isFullBarJoin(n,i.beats[r-1],t)&&(a=h-c,o=h,l=f+this.calculateBeamY(i,a),d=f+this.calculateBeamY(i,o),Hh.paintSingleBar(s,e+this.x+a,l,e+this.x+o,d,p))}}finally{u?.[Symbol.dispose]?.()}}}static paintSingleBar(e,t,s,i,a,r){e.beginPath(),e.moveTo(t,s),e.lineTo(i,a),e.lineTo(i,a+r),e.lineTo(t,s+r),e.closePath(),e.fill()}}class Wh extends an{paint(e,t,s){const i=rn.bar(s,u.StandardNotationKeySignature,this.renderer.bar);try{super.paint(e,t,s)}finally{i?.[Symbol.dispose]?.()}}}class Vh extends Hh{constructor(e,t){super(e,t),this.simpleWhammyOverflow=0,this.beatEffectsMinY=null,this.beatEffectsMaxY=null,this.accidentalHelper=new Bs(this)}get repeatsBarSubElement(){return u.StandardNotationRepeats}get barNumberBarSubElement(){return u.StandardNotationBarNumber}get barLineBarSubElement(){return u.StandardNotationBarLines}get staffLineBarSubElement(){return u.StandardNotationStaffLine}get showMultiBarRest(){return!0}get lineSpacing(){return On.RawLineSpacing}get heightLineCount(){return 5}get drawnLineCount(){return this.bar.staff.standardNotationLineCount}registerBeatEffectOverflows(e,t){const s=this.beatEffectsMinY;(null==s||e<s)&&(this.beatEffectsMinY=e);const i=this.beatEffectsMaxY;(null==i||t>i)&&(this.beatEffectsMaxY=t)}getScoreY(e){return super.getLineY(e/2)}getScoreHeight(e){return super.getLineHeight(e/2)}doLayout(){if(super.doLayout(),!this.bar.isEmpty&&this.accidentalHelper.maxLineBeat){const e=this.getScoreY(-2),t=this.getScoreY(10),s=this.simpleWhammyOverflow,i=this.beatEffectsMinY;if(null!==i){const t=e-i;t>0&&this.registerOverflowTop(t)}const a=this.beatEffectsMaxY;if(null!==a){const e=a-t;e>0&&this.registerOverflowBottom(e)}this.registerOverflowTop(s);let r=this.getScoreY(this.accidentalHelper.maxLine);const n=this.helpers.getBeamingHelperForBeat(this.accidentalHelper.maxLineBeat);n.direction===Te.Up&&(r-=this.getStemSize(n),n.hasTuplet&&(r-=this.tupletSize)),r<e&&this.registerOverflowTop(Math.abs(r)+s);let o=this.getScoreY(this.accidentalHelper.minLine);const h=this.helpers.getBeamingHelperForBeat(this.accidentalHelper.minLineBeat);h.direction===Te.Down&&(o+=this.getStemSize(h),h.hasTuplet&&(o+=this.tupletSize)),o>t&&this.registerOverflowBottom(Math.abs(o)-t)}}paint(e,t,s){super.paint(e,t,s),this.paintBeams(e,t,s,ye.StandardNotationFlags,ye.StandardNotationBeams),this.paintTuplets(e,t,s,ye.StandardNotationTuplet)}getSlashFlagY(e,t){let s=(this.heightLineCount-1)/2,i=0;switch(e){case _.QuadrupleWhole:case _.DoubleWhole:case _.Whole:i+=2;break;default:i+=1}t===Te.Down?s+=i:s-=i;return this.getLineY(s)}getFlagTopY(e,t){return e.slashed?this.getSlashFlagY(e.duration,t):this.getScoreY(this.accidentalHelper.getMinLine(e))}getFlagBottomY(e,t){return e.slashed?this.getSlashFlagY(e.duration,t):this.getScoreY(this.accidentalHelper.getMaxLine(e))}getBeamDirection(e){return e.direction}getStemSize(e,t=!1){let s=1===e.beats.length?this.getFlagStemSize(e.shortestDuration,t):this.getBarStemSize(e.shortestDuration);return e.isGrace&&(s*=vr.GraceScale),s}getBarStemSize(e){let t=0;switch(e){case _.QuadrupleWhole:case _.Half:case _.Quarter:case _.Eighth:case _.Sixteenth:t=6;break;case _.ThirtySecond:t=8;break;case _.SixtyFourth:case _.OneHundredTwentyEighth:t=9;break;case _.TwoHundredFiftySixth:t=10;break;default:t=0}return this.getScoreHeight(t)}get middleYPosition(){return this.getScoreY(this.bar.staff.standardNotationLineCount-1)}getNoteY(e,t){if(e.beat.slashed){const e=(this.heightLineCount-1)/2;return this.getLineY(e)}let s=super.getNoteY(e,t);if(Number.isNaN(s)){const t=Bs.computeLineWithoutAccidentals(this.bar,e);s=this.getScoreY(t)}return s}applyLayoutingInfo(){const e=super.applyLayoutingInfo();if(e&&this.bar.isMultiVoice){const e=this.getScoreY(-2),t=this.getScoreY(10),s=this.helpers.collisionHelper.getBeatMinMaxY();s[0]<e&&this.registerOverflowTop(Math.abs(s[0])),s[1]>t&&this.registerOverflowBottom(Math.abs(s[1])-t)}return e}calculateBeamYWithDirection(e,t,s){const i=this.getStemSize(e);if(!e.drawingInfos.has(s)){const t=new ln;e.drawingInfos.set(s,t);const a=e.beats[0],r=e.beats[e.beats.length-1],n=e.isRestBeamHelper;t.startBeat=a,t.startX=e.getBeatLineX(a),t.startY=n?s===Te.Up?this.getScoreY(e.minRestLine):this.getScoreY(e.maxRestLine):s===Te.Up?this.getFlagTopY(a,s)-i:this.getFlagBottomY(a,s)+i,t.endBeat=r,t.endX=e.getBeatLineX(r),t.endY=n?s===Te.Up?this.getScoreY(e.minRestLine):this.getScoreY(e.maxRestLine):s===Te.Up?this.getFlagTopY(r,s)-i:this.getFlagBottomY(r,s)+i;const o=10;if(s===Te.Down&&t.startY>t.endY&&t.startY-t.endY>o&&(t.endY=t.startY-o),s===Te.Down&&t.endY>t.startY&&t.endY-t.startY>o&&(t.startY=t.endY-o),s===Te.Up&&t.startY<t.endY&&t.endY-t.startY>o&&(t.endY=t.startY+o),s===Te.Up&&t.endY<t.startY&&t.startY-t.endY>o&&(t.startY=t.endY+o),e.beats.length>1){if(s===Te.Up){const s=this.getScoreY(this.accidentalHelper.getMinLine(e.beatOfHighestNote))-i,a=t.calcY(e.getBeatLineX(e.beatOfHighestNote))-s;a>0&&(t.startY-=a,t.endY-=a)}else{const s=this.getScoreY(this.accidentalHelper.getMaxLine(e.beatOfLowestNote))+i-t.calcY(e.getBeatLineX(e.beatOfLowestNote));s>0&&(t.startY+=s,t.endY+=s)}if(null!==e.minRestLine||null!==e.maxRestLine){const i=ie.getIndex(e.shortestDuration)-2,a=e.isGrace?vr.GraceScale:1;let r=i*(On.BeamSpacing+On.BeamThickness)*a;if(r+=On.BeamSpacing,s===Te.Up&&null!==e.minRestLine){const s=this.getScoreY(e.minRestLine)-r,i=t.calcY(e.getBeatLineX(e.beatOfMinRestLine))-s;i>0&&(t.startY-=i,t.endY-=i)}else if(s===Te.Down&&null!==e.maxRestLine){const s=this.getScoreY(e.maxRestLine)+r-t.calcY(e.getBeatLineX(e.beatOfMaxRestLine));s>0&&(t.startY+=s,t.endY+=s)}}if(e.slashBeats.length>0)for(const a of e.slashBeats){const r=t.calcY(e.getBeatLineX(a));let n=this.getSlashFlagY(a.duration,s);s===Te.Up?n-=i:s===Te.Down&&(n+=i);const o=n-r;o>0&&(t.startY+=o,t.endY+=o)}}}return e.drawingInfos.get(s).calcY(t)}getBarLineStart(e,t){return e.slashed?this.getSlashFlagY(e.duration,t):t===Te.Up?this.getScoreY(this.accidentalHelper.getMaxLine(e)):this.getScoreY(this.accidentalHelper.getMinLine(e))}createLinePreBeatGlyphs(){let e=!1;if(this.isFirstOfLine||this.bar.clef!==this.bar.previousBar.clef||this.bar.clefOttava!==this.bar.previousBar.clefOttava){let t=0;switch(this.bar.clef){case n.Neutral:t=this.bar.staff.standardNotationLineCount-1;break;case n.F4:t=2;break;case n.C3:t=4;break;case n.C4:t=2;break;case n.G2:t=6}this.createStartSpacing(),this.addPreBeatGlyph(new Ho(0,this.getScoreY(t)+.5*On.StaffLineThickness,this.bar.clef,this.bar.clefOttava)),e=!0}(e||0===this.index&&this.bar.keySignature!==l.C||this.bar.previousBar&&this.bar.keySignature!==this.bar.previousBar.keySignature)&&(this.createStartSpacing(),this.createKeySignatureGlyphs()),(!this.bar.previousBar||this.bar.previousBar&&this.bar.masterBar.timeSignatureNumerator!==this.bar.previousBar.masterBar.timeSignatureNumerator||this.bar.previousBar&&this.bar.masterBar.timeSignatureDenominator!==this.bar.previousBar.masterBar.timeSignatureDenominator||this.bar.previousBar&&this.bar.masterBar.isFreeTime&&this.bar.masterBar.isFreeTime!==this.bar.previousBar.masterBar.isFreeTime)&&(this.createStartSpacing(),this.createTimeSignatureGlyphs())}createKeySignatureGlyphs(){let e=0;const t=this.bar.keySignature,s=this.bar.previousBar?this.bar.previousBar.keySignature:0;switch(this.bar.clef){case n.Neutral:e=0;break;case n.G2:e=1;break;case n.F4:e=3;break;case n.C3:e=2;break;case n.C4:e=0}const i=new Wh;i.renderer=this;const a=new Map,r=[];if(ie.keySignatureIsSharp(t))for(let s=0;s<Math.abs(t);s++){const t=Vh.SharpKsSteps[s]+e;r.push(new Oo(0,this.getScoreY(t),It.Sharp,1)),a.set(t,!0)}else for(let s=0;s<Math.abs(t);s++){const t=Vh.FlatKsSteps[s]+e;r.push(new Oo(0,this.getScoreY(t),It.Flat,1)),a.set(t,!0)}if(this.bar.keySignature===l.C){const t=Math.abs(s),r=ie.keySignatureIsSharp(s)?Vh.SharpKsSteps:Vh.FlatKsSteps;for(let s=0;s<t;s++){const t=r[s]+e;a.has(t)||i.addGlyph(new Oo(0,this.getScoreY(r[s]+e),It.Natural,1))}}for(const e of r)i.addGlyph(e);this.addPreBeatGlyph(i)}createTimeSignatureGlyphs(){this.addPreBeatGlyph(new hh(0,0,5));const e=this.bar.staff.standardNotationLineCount-1;this.addPreBeatGlyph(new wh(0,this.getScoreY(e),this.bar.masterBar.timeSignatureNumerator,this.bar.masterBar.timeSignatureDenominator,this.bar.masterBar.timeSignatureCommon,this.bar.masterBar.isFreeTime))}createVoiceGlyphs(e){for(const t of e.beats){const s=new vh(t,this.getVoiceContainer(e));s.preNotes=new Sh,s.onNotes=new mh,this.addBeatGlyph(s)}}getNoteLine(e){return this.accidentalHelper.getNoteLine(e)}completeBeamingHelper(e){if(this.bar.isMultiVoice&&e.highestNoteInHelper&&e.lowestNoteInHelper){let t=this.getNoteY(e.highestNoteInHelper,is.Center),s=this.getNoteY(e.lowestNoteInHelper,is.Center),i=this.getStemSize(e);e.hasTuplet&&(i+=2*this.resources.effectFont.size),e.direction===Te.Up?t-=i:s+=i;for(const i of e.beats)this.helpers.collisionHelper.reserveBeatSlot(i,t,s)}}paintBeamingStem(e,t,s,i,a,r){const n=rn.beat(r,ye.StandardNotationStem,e);try{r.lineWidth=On.StemWidth,r.beginPath(),r.moveTo(s,i),r.lineTo(s,a),r.stroke(),r.lineWidth=1}finally{n?.[Symbol.dispose]?.()}}}Vh.StaffId="score",Vh.SharpKsSteps=[-1,2,-2,1,4,0,3],Vh.FlatKsSteps=[3,0,4,1,5,2,6];class Gh extends tn{get staffId(){return Vh.StaffId}getStaffPaddingTop(e){return e.system.layout.renderer.settings.display.notationStaffPaddingTop}getStaffPaddingBottom(e){return e.system.layout.renderer.settings.display.notationStaffPaddingBottom}create(e,t){return new Vh(e,t)}canCreate(e,t){return super.canCreate(e,t)&&t.showStandardNotation}}class zh extends kr{constructor(e,t,s,i){super(0,0),this._inType=e,this._outType=t,this._startNote=s,this._parent=i}doLayout(){this.width=0}paint(e,t,s){this.paintSlideIn(e,t,s),this.paintSlideOut(e,t,s)}paintSlideIn(e,t,s){const i=this.renderer;let a=0,r=0,n=0,o=0;switch(this._inType){case x.IntoFromBelow:n=e+i.x+i.getNoteX(this._startNote,as.Left)-2,o=t+i.y+i.getNoteY(this._startNote,is.Center),a=n-12,r=t+i.y+i.getNoteY(this._startNote,is.Center)+3;break;case x.IntoFromAbove:n=e+i.x+i.getNoteX(this._startNote,as.Left)-2,o=t+i.y+i.getNoteY(this._startNote,is.Center),a=n-12,r=t+i.y+i.getNoteY(this._startNote,is.Center)-3;break;default:return}this.paintSlideLine(s,!1,a,n,r,o)}paintSlideOut(e,t,s){const i=this.renderer;let a=0,r=0,n=0,o=0,h=!1;switch(this._outType){case v.Shift:case v.Legato:if(a=e+i.x+i.getBeatX(this._startNote.beat,ts.PostNotes)+2,r=t+i.y+i.getNoteY(this._startNote,is.Center),this._startNote.slideTarget){const s=this.renderer.scoreRenderer.layout.getRendererForBar(this.renderer.staff.staffId,this._startNote.slideTarget.beat.voice.bar);s&&s.staff===i.staff?(n=e+s.x+s.getBeatX(this._startNote.slideTarget.beat,ts.OnNotes)-2,o=t+s.y+s.getNoteY(this._startNote.slideTarget,is.Center)):(n=e+i.x+i.width,o=r),this._startNote.slideTarget.fret>this._startNote.fret?(r+=3,o-=3):(r-=3,o+=3)}else n=e+i.x+this._parent.x,o=r;break;case v.OutUp:a=e+i.x+i.getNoteX(this._startNote,as.Right)+2,r=t+i.y+i.getNoteY(this._startNote,is.Center),n=a+12,o=t+i.y+i.getNoteY(this._startNote,is.Center)-3;break;case v.OutDown:a=e+i.x+i.getNoteX(this._startNote,as.Right)+2,r=t+i.y+i.getNoteY(this._startNote,is.Center),n=a+12,o=t+i.y+i.getNoteY(this._startNote,is.Center)+3;break;case v.PickSlideDown:a=e+i.x+i.getNoteX(this._startNote,as.Right)+4,r=t+i.y+i.getNoteY(this._startNote,is.Center),n=e+i.x+i.width,o=r+9,this._startNote.beat.nextBeat&&this._startNote.beat.nextBeat.voice===this._startNote.beat.voice&&(n=e+i.x+i.getBeatX(this._startNote.beat.nextBeat,ts.PreNotes)),h=!0;break;case v.PickSlideUp:a=e+i.x+i.getNoteX(this._startNote,as.Right)+4,r=t+i.y+i.getNoteY(this._startNote,is.Center),n=e+i.x+i.width,o=r-9,this._startNote.beat.nextBeat&&this._startNote.beat.nextBeat.voice===this._startNote.beat.voice&&(n=e+i.x+i.getBeatX(this._startNote.beat.nextBeat,ts.PreNotes)),h=!0;break;default:return}this.paintSlideLine(s,h,a,n,r,o)}paintSlideLine(e,t,s,i,a,r){if(t){const t=new Bo(0,0,P.Slight,1.2);t.renderer=this.renderer,t.doLayout(),a-=t.height/2;const n=i-s,o=(r-=t.height/2)-a,h=Math.sqrt(Math.pow(o,2)+Math.pow(n,2));t.width=n;const l=Math.asin(o/h)*(180/Math.PI);e.beginRotate(s,a,l),t.paint(0,0,e),e.endRotate()}else e.beginPath(),e.moveTo(s,a),e.lineTo(i,r),e.stroke()}}class Uh extends Uo{constructor(e,t,s=!1){super(e.beat,t.beat,s),this.startNote=e,this.endNote=t}getTieHeight(e,t,s,i){return this.startNote===this.endNote?15:super.getTieHeight(e,t,s,i)}getBeamDirection(e,t){return this.startNote===this.endNote?Te.Up:Uh.getBeamDirectionForNote(this.startNote)}static getBeamDirectionForNote(e){return e.string>3?Te.Up:Te.Down}getStartY(){return this.startNote===this.endNote?this.startNoteRenderer.getNoteY(this.startNote,is.Center):this.tieDirection===Te.Up?this.startNoteRenderer.getNoteY(this.startNote,is.Top):this.startNoteRenderer.getNoteY(this.startNote,is.Bottom)}getEndY(){return this.getStartY()}getStartX(){return this.startNote===this.endNote?this.getEndX()-20:this.startNoteRenderer.getNoteX(this.startNote,as.Center)}getEndX(){return this.startNote===this.endNote?this.endNoteRenderer.getNoteX(this.endNote,as.Left):this.endNoteRenderer.getNoteX(this.endNote,as.Center)}}class Xh extends Uh{constructor(e,t,s,i=!1){super(e,t,i),this._direction=Uh.getBeamDirectionForNote(e),this._forSlide=s}getTieHeight(e,t,s,i){return Math.log(s-e+1)*this.renderer.settings.notation.slurHeight}tryExpand(e,t,s,i){if(this._forSlide!==s)return!1;if(this.forEnd!==i)return!1;if(this.startNote.beat.id!==e.beat.id)return!1;if(this.endNote.beat.id!==t.beat.id)return!1;if(this._direction!==Uh.getBeamDirectionForNote(e))return!1;switch(this._direction){case Te.Up:e.realValue>this.startNote.realValue&&(this.startNote=e,this.startBeat=e.beat),t.realValue>this.endNote.realValue&&(this.endNote=t,this.endBeat=t.beat);break;case Te.Down:e.realValue<this.startNote.realValue&&(this.startNote=e,this.startBeat=e.beat),t.realValue<this.endNote.realValue&&(this.endNote=t,this.endBeat=t.beat)}return!0}paint(e,t,s){const i=this.renderer.scoreRenderer.layout.getRendererForBar(this.renderer.staff.staffId,this.startBeat.voice.bar),a=this.getBeamDirection(this.startBeat,i),r=`tab.slur.${this.startNote.beat.id}.${this.endNote.beat.id}.${a}`,n=this.renderer;n.staff.getSharedLayoutData(r,!1)||(n.staff.setSharedLayoutData(r,!0),super.paint(e,t,s))}}class Jh extends Fr{constructor(){super(...arguments),this._bend=null,this._effectSlurs=[]}drawBeamHelperAsFlags(e){return e.hasFlag(this.renderer.drawBeamHelperAsFlags(e),this.beat)}doLayout(){this._effectSlurs=[],super.doLayout(),this._bend&&(this._bend.renderer=this.renderer,this._bend.doLayout(),this.updateWidth())}createTies(e){if(!e.isVisible)return;const t=this.renderer;if(e.isTieOrigin&&t.showTiedNotes&&e.tieDestination.isVisible){const t=new Uh(e,e.tieDestination,!1);this.addTie(t)}if(e.isTieDestination&&t.showTiedNotes){const t=new Uh(e.tieOrigin,e,!0);this.addTie(t)}if(e.isLeftHandTapped&&!e.isHammerPullDestination){const t=new Uh(e,e,!1);this.addTie(t)}if(e.isEffectSlurOrigin&&e.effectSlurDestination){let t=!1;for(const s of this._effectSlurs)if(s.tryExpand(e,e.effectSlurDestination,!1,!1)){t=!0;break}if(!t){const t=new Xh(e,e.effectSlurDestination,!1,!1);this._effectSlurs.push(t),this.addTie(t)}}if(e.isEffectSlurDestination&&e.effectSlurOrigin){let t=!1;for(const s of this._effectSlurs)if(s.tryExpand(e.effectSlurOrigin,e,!1,!0)){t=!0;break}if(!t){const t=new Xh(e.effectSlurOrigin,e,!1,!0);this._effectSlurs.push(t),this.addTie(t)}}if(e.slideInType!==x.None||e.slideOutType!==v.None){const t=new zh(e.slideInType,e.slideOutType,e,this);this.addTie(t)}if(e.hasBend){if(!this._bend){const e=new rh;this._bend=e,e.renderer=this.renderer,this.addTie(e)}this._bend.addBends(e)}}}class Yh extends kr{constructor(e,t,s){super(e,t),this._noteString=null,this._trillNoteString=null,this._trillNoteStringWidth=0,this.isEmpty=!1,this.noteStringWidth=0,this._note=s}doLayout(){const e=this._note;let t=e.fret-e.beat.voice.bar.staff.transpositionPitch;if(e.harmonicType===T.Natural&&0!==e.harmonicValue&&(t=e.harmonicValue-e.beat.voice.bar.staff.transpositionPitch),e.isTieDestination)0===e.beat.index&&this.renderer.settings.notation.notationMode===D.GuitarPro||(e.bendType===y.Bend||e.bendType===y.BendRelease)&&this.renderer.settings.notation.isNotationElementVisible(E.TabNotesOnTiedBends)?this._noteString=`(${(e.tieOrigin.fret-e.beat.voice.bar.staff.transpositionPitch).toString()})`:this._noteString="";else if(this._noteString=e.isDead?"x":t.toString(),e.isGhost)this._noteString=`(${this._noteString})`;else if(e.harmonicType===T.Natural){const e=this._noteString.indexOf(String.fromCharCode(46));e>=0&&(this._noteString=this._noteString.substr(0,e+2)),this._noteString=`<${this._noteString}>`}if(e.isTrill)this._trillNoteString=`(${(e.trillFret-e.beat.voice.bar.staff.transpositionPitch).toString()})`;else if(ie.isAlmostEqualTo(e.harmonicValue,0))this._trillNoteString="";else switch(e.harmonicType){case T.Artificial:case T.Pinch:case T.Tap:case T.Semi:case T.Feedback:let s=(t+e.harmonicValue).toString();const i=s.indexOf(String.fromCharCode(46));i>=0&&(s=s.substr(0,i+2)),this._trillNoteString=`<${s}>`;break;default:this._trillNoteString=""}if(this.isEmpty=!this._noteString,!this.isEmpty){this.renderer.scoreRenderer.canvas.font=this.renderer.resources.tablatureFont,this.noteStringWidth=this.renderer.scoreRenderer.canvas.measureText(this._noteString).width,this.width=this.noteStringWidth,this.height=this.renderer.scoreRenderer.canvas.font.size;!!this._trillNoteString&&(this.renderer.scoreRenderer.canvas.font=this.renderer.resources.graceFont,this._trillNoteStringWidth=3+this.renderer.scoreRenderer.canvas.measureText(this._trillNoteString).width,this.width+=this._trillNoteStringWidth)}}paint(e,t,s){if(this.isEmpty)return;const i=this.noteStringWidth+this._trillNoteStringWidth,a=e+this.x+(this.width-i)/2;this.paintTrill(a,t,s);const r=rn.note(s,le.GuitarTabFretNumber,this._note);try{s.fillText(this._noteString,a,t+this.y)}finally{r?.[Symbol.dispose]?.()}}paintTrill(e,t,s){const i=rn.note(s,le.GuitarTabFretNumber,this._note);try{const i=this.renderer.scoreRenderer.canvas.font;this.renderer.scoreRenderer.canvas.font=this.renderer.resources.graceFont,s.fillText(this._trillNoteString,e+this.noteStringWidth+3,t+this.y),this.renderer.scoreRenderer.canvas.font=i}finally{i?.[Symbol.dispose]?.()}}buildBoundingsLookup(e,t,s){const i=new ir;i.note=this._note,i.noteHeadBounds=new mt,i.noteHeadBounds.x=t+this.x,i.noteHeadBounds.y=s+this.y-this.height/2,i.noteHeadBounds.w=this.width,i.noteHeadBounds.h=this.height,e.addNote(i)}}class $h extends kr{constructor(e,t,s){super(e,t),this._notes=[],this._deadSlapped=null,this.minStringNote=null,this.beatEffects=new Map,this.notesPerString=new Map,this.noteStringWidth=0,this._isGrace=s}buildBoundingsLookup(e,t,s){for(const i of this._notes)i.buildBoundingsLookup(e,t+this.x,s+this.y)}getNoteX(e,t){if(this.notesPerString.has(e.string)){const s=this.notesPerString.get(e.string);let i=this.x+s.x;switch(t){case as.Left:break;case as.Center:i+=s.noteStringWidth/2;break;case as.Right:i+=s.width}return i}return 0}getNoteY(e,t){if(this.notesPerString.has(e.string)){const s=this.notesPerString.get(e.string);let i=this.y+s.y;switch(t){case is.Top:case is.TopWithStem:i-=s.height/2+2;break;case is.Center:break;case is.Bottom:case is.BottomWithStem:i+=s.height/2}return i}return 0}doLayout(){let e=0;if(this.beat.deadSlapped)this._deadSlapped=new Ko,this._deadSlapped.renderer=this.renderer,this._deadSlapped.doLayout(),e=this._deadSlapped.width,this.noteStringWidth=e;else{let t=0;for(let s=0,i=this._notes.length;s<i;s++){const i=this._notes[s];i.renderer=this.renderer,i.doLayout(),i.width>e&&(e=i.width),i.noteStringWidth>t&&(t=i.noteStringWidth)}this.noteStringWidth=t;const s=this.renderer.resources.tablatureFont.size;let i=this.getNoteY(this.minStringNote,is.Center)+s/2;const a=7;for(const e of this.beatEffects.values())e.y+=i,e.x+=this.width/2,e.renderer=this.renderer,i+=a,e.doLayout()}this.width=e}addNoteGlyph(e,t){this._notes.push(e),this.notesPerString.set(t.string,e),(!this.minStringNote||t.string<this.minStringNote.string)&&(this.minStringNote=t)}paint(e,t,s){if(e+=this.x,t+=this.y,this.beat.deadSlapped)this._deadSlapped?.paint(e,t,s);else{const i=this.renderer.resources,a=s.textBaseline;s.textBaseline=oe.Middle,s.font=this._isGrace?i.graceFont:i.tablatureFont;const r=this._notes,n=this.width;for(const i of r)i.renderer=this.renderer,i.width=n,i.paint(e,t,s);s.textBaseline=a;const o=rn.beat(s,ye.GuitarTabEffects,this.beat);try{for(const i of this.beatEffects.values())i.paint(e,t,s)}finally{o?.[Symbol.dispose]?.()}}}updateBeamingHelper(e){this.beamingHelper&&this.beamingHelper.isPositionFrom("tab",this.beat)&&this.beamingHelper.registerBeatLineX("tab",this.beat,e+this.x+this.width/2,e+this.x+this.width/2)}}class qh extends xr{constructor(e,t,s,i){super(e,t,1,Zo.getSymbol(i)),this._isVisibleRest=s}doLayout(){super.doLayout(),this._isVisibleRest||(this.width=10)}updateBeamingHelper(e){this.beamingHelper&&this.beamingHelper.isPositionFrom("tab",this.beat)&&this.beamingHelper.registerBeatLineX("tab",this.beat,e+this.x+this.width/2,e+this.x+this.width/2)}paint(e,t,s){if(this._isVisibleRest){const i=rn.beat(s,ye.GuitarTabRests,this.beat);try{super.paint(e,t,s)}finally{i?.[Symbol.dispose]?.()}}}}class jh extends Mn{constructor(){super(...arguments),this.slash=null,this.noteNumbers=null,this.restGlyph=null}get effectElement(){return ye.GuitarTabEffects}getNoteX(e,t){return this.noteNumbers?this.noteNumbers.getNoteX(e,t):0}getNoteY(e,t){return this.noteNumbers?this.noteNumbers.getNoteY(e,t):0}buildBoundingsLookup(e,t,s){this.noteNumbers&&this.noteNumbers.buildBoundingsLookup(e,t+this.x,s+this.y)}doLayout(){const e=this.renderer;if(this.container.beat.isRest){const t=Math.floor((this.renderer.bar.staff.tuning.length-1)/2),s=e.getTabY(t),i=new qh(0,s,e.showRests,this.container.beat.duration);if(this.restGlyph=i,i.beat=this.container.beat,i.beamingHelper=this.beamingHelper,this.addNormal(i),this.container.beat.dots>0&&e.showRests){this.addNormal(new hh(0,0,5));for(let e=0;e<this.container.beat.dots;e++)this.addEffect(new Vo(0,s,1.5))}}else{const t=this.renderer.settings.notation.smallGraceTabNotes&&this.container.beat.graceType!==w.None;let s;if(this.container.beat.slashed&&!this.container.beat.notes.some((e=>e.isTieDestination))){const i=Math.floor((this.renderer.bar.staff.tuning.length-1)/2),a=e.getLineY(i),r=new gh(0,a,this.container.beat.duration,t,this.container.beat);r.noteHeadElement=le.GuitarTabFretNumber,r.effectElement=ye.GuitarTabEffects,this.slash=r,r.beat=this.container.beat,r.beamingHelper=this.beamingHelper,this.addNormal(r),s=r.beatEffects}else{const e=new $h(0,0,t);this.noteNumbers=e,e.beat=this.container.beat,e.beamingHelper=this.beamingHelper;for(const e of this.container.beat.notes)e.isVisible&&this.createNoteGlyph(e);this.addNormal(e),s=e.beatEffects}if(this.container.beat.hasWhammyBar){const e=new nh(this.container.beat);e.renderer=this.renderer,e.doLayout(),this.container.ties.push(e)}if(this.container.beat.isTremolo&&!s.has("tremolo")){let e=0;const t=this.container.beat.tremoloSpeed;let i=5;switch(t){case _.ThirtySecond:e=10;break;case _.Sixteenth:e=5;break;case _.Eighth:e=0}this.container.beat.duration<_.Half&&(i=0),s.set("tremolo",new jo(i,e,t))}if(this.container.beat.dots>0&&e.rhythmMode!==F.Hidden){this.addNormal(new hh(0,0,5));for(let t=0;t<this.container.beat.dots;t++)this.addEffect(new Vo(0,e.lineOffset*e.bar.staff.tuning.length+e.settings.notation.rhythmHeight,1.5))}}if(this.isEmpty)return;let t=0;for(let e=0,s=this.glyphs.length;e<s;e++){const s=this.glyphs[e];s.x=t,s.renderer=this.renderer,s.doLayout(),t+=s.width}this.width=t,this.computedWidth=t,this.container.beat.isEmpty?this.centerX=this.width/2:this.restGlyph?this.centerX=this.restGlyph.x+this.restGlyph.width/2:this.noteNumbers?this.centerX=this.noteNumbers.x+this.noteNumbers.noteStringWidth/2:this.slash&&(this.centerX=this.slash.x+this.slash.width/2)}updateBeamingHelper(){this.noteNumbers?this.noteNumbers.updateBeamingHelper(this.container.x+this.x):this.restGlyph?this.restGlyph.updateBeamingHelper(this.container.x+this.x):this.slash&&this.slash.updateBeamingHelper(this.container.x+this.x)}createNoteGlyph(e){const t=this.renderer,s=new Yh(0,0,e),i=e.beat.voice.bar.staff.tuning.length-e.string;s.y=t.getTabY(i),s.renderer=this.renderer,s.doLayout(),this.noteNumbers.addNoteGlyph(s,e);const a=s.y-s.height/2,r=a+s.height;this.renderer.helpers.collisionHelper.reserveBeatSlot(this.container.beat,a,r)}}class Kh extends kr{constructor(e){super(0,0),this._beat=e}doLayout(){this.width=10}paint(e,t,s){const i=this.renderer,a=t+this.x+i.getNoteY(this._beat.maxStringNote,is.Top),r=t+this.y+i.getNoteY(this._beat.minStringNote,is.Bottom),n=e+this.x+this.width/2|0;if(this._beat.brushType!==b.None){if(this._beat.brushType===b.BrushUp||this._beat.brushType===b.BrushDown)s.beginPath(),s.moveTo(n,a),s.lineTo(n,r),s.stroke();else if(this._beat.brushType===b.ArpeggioUp){const t=new Bo(0,0,P.Slight,1.2,!0);t.renderer=this.renderer,t.doLayout();const i=a,n=r-8;t.width=Math.abs(n-i),s.beginRotate(e+this.x+4,n,-90),t.paint(0,-t.height/2,s),s.endRotate()}else if(this._beat.brushType===b.ArpeggioDown){const t=new Bo(0,0,P.Slight,1.2,!0);t.renderer=this.renderer,t.doLayout();const i=a+8,n=r;t.width=Math.abs(n-i),s.beginRotate(e+this.x+4,i,90),t.paint(0,-t.height/2,s),s.endRotate()}this._beat.brushType===b.BrushUp||this._beat.brushType===b.ArpeggioUp?(s.beginPath(),s.moveTo(n,r),s.lineTo(n+4,r-8),s.lineTo(n-4,r-8),s.closePath(),s.fill()):(s.beginPath(),s.moveTo(n,a),s.lineTo(n+4,a+8),s.lineTo(n-4,a+8),s.closePath(),s.fill())}}}class Qh extends Ln{doLayout(){this.container.beat.brushType===b.None||this.container.beat.isRest||(this.addEffect(new Kh(this.container.beat)),this.addNormal(new hh(0,0,4))),super.doLayout()}get effectElement(){return ye.GuitarTabEffects}}class Zh extends kr{doLayout(){this.width=Nr.Widths.get(re.SixStringTabClef)}paint(e,t,s){const i=rn.bar(s,u.GuitarTabsClef,this.renderer.bar);try{const i=this.renderer.bar.staff.tuning.length,a=i<=4?re.FourStringTabClef:re.SixStringTabClef,r=i<=4?i/4.5:i/6.5;s.fillMusicFontSymbol(e+this.x+5,t+this.y,r,a,!1)}finally{i?.[Symbol.dispose]?.()}}}class el extends _h{doLayout(){this.barSubElement=u.GuitarTabsTimeSignature,super.doLayout()}get commonScale(){return 1}get numberScale(){return this.renderer.bar.staff.tuning.length<=4?vr.GraceScale:1}}class tl extends Hh{get showMultiBarRest(){return this._showMultiBarRest}get repeatsBarSubElement(){return u.GuitarTabsRepeats}get barNumberBarSubElement(){return u.GuitarTabsBarNumber}get barLineBarSubElement(){return u.GuitarTabsBarLines}get staffLineBarSubElement(){return u.GuitarTabsStaffLine}constructor(e,t){super(e,t),this._hasTuplets=!1,this.showTimeSignature=!1,this.showRests=!1,this.showTiedNotes=!1,this._showMultiBarRest=!1,t.staff.showStandardNotation||(this.showTimeSignature=!0,this.showRests=!0,this.showTiedNotes=!0,this._showMultiBarRest=!0)}get lineSpacing(){return tl.TabLineSpacing}get heightLineCount(){return this.bar.staff.tuning.length}get drawnLineCount(){return this.bar.staff.tuning.length}get rhythmMode(){let e=this.settings.notation.rhythmMode;return e===F.Automatic&&(e=this.bar.staff.showStandardNotation?F.Hidden:F.ShowWithBars),e}getTabY(e){return super.getLineY(e)}getTabHeight(e){return super.getLineHeight(e)}collectSpaces(e){for(const t of this.bar.voices)if(this.hasVoiceContainer(t)){const s=this.getVoiceContainer(t);for(const t of s.beatGlyphs){const i=t.onNotes,a=i.noteNumbers;if(a)for(const[r,n]of a.notesPerString)n.isEmpty||e[this.bar.staff.tuning.length-r].push(new Float32Array([s.x+t.x+i.x+a.x,a.width+1]))}}}adjustSizes(){this.rhythmMode!==F.Hidden&&(this.height+=this.settings.notation.rhythmHeight,this.bottomPadding+=this.settings.notation.rhythmHeight)}doLayout(){if(super.doLayout(),this.rhythmMode!==F.Hidden){this._hasTuplets=!1;for(const e of this.bar.voices)if(this.hasVoiceContainer(e)){if(this.getVoiceContainer(e).tupletGroups.length>0){this._hasTuplets=!0;break}}this._hasTuplets&&this.registerOverflowBottom(this.tupletSize)}}createLinePreBeatGlyphs(){if(this.isFirstOfLine){const e=(this.bar.staff.tuning.length-1)/2;this.addPreBeatGlyph(new Zh(5,this.getTabY(e)))}this.showTimeSignature&&(!this.bar.previousBar||this.bar.previousBar&&this.bar.masterBar.timeSignatureNumerator!==this.bar.previousBar.masterBar.timeSignatureNumerator||this.bar.previousBar&&this.bar.masterBar.timeSignatureDenominator!==this.bar.previousBar.masterBar.timeSignatureDenominator||this.bar.previousBar&&this.bar.masterBar.isFreeTime&&this.bar.masterBar.isFreeTime!==this.bar.previousBar.masterBar.isFreeTime)&&(this.createStartSpacing(),this.createTimeSignatureGlyphs())}createTimeSignatureGlyphs(){this.addPreBeatGlyph(new hh(0,0,5));const e=(this.bar.staff.tuning.length+1)/2-1;this.addPreBeatGlyph(new el(0,this.getTabY(e),this.bar.masterBar.timeSignatureNumerator,this.bar.masterBar.timeSignatureDenominator,this.bar.masterBar.timeSignatureCommon,this.bar.masterBar.isFreeTime))}createVoiceGlyphs(e){if(this.additionalMultiRestBars){const t=new Rn(this.getVoiceContainer(e));this.addBeatGlyph(t)}else for(const t of e.beats){const s=new Jh(t,this.getVoiceContainer(e));s.preNotes=new Qh,s.onNotes=new jh,this.addBeatGlyph(s)}}paint(e,t,s){super.paint(e,t,s),this.rhythmMode!==F.Hidden&&(this.paintBeams(e,t,s,ye.GuitarTabFlags,ye.GuitarTabBeams),this.paintTuplets(e,t,s,ye.GuitarTabTuplet))}drawBeamHelperAsFlags(e){return super.drawBeamHelperAsFlags(e)||this.rhythmMode===F.ShowWithBeams}getFlagTopY(e,t){const s=this.getOnNotesGlyphForBeat(e);return s.noteNumbers&&e.duration!==_.Half?s.noteNumbers.getNoteY(s.noteNumbers.minStringNote,is.Bottom):this.height-this.settings.notation.rhythmHeight-this.tupletSize}getFlagBottomY(e,t){return this.getFlagAndBarPos()}getFlagStemSize(e,t=!1){return 0}getBarLineStart(e,t){const s=this.getOnNotesGlyphForBeat(e);return s.noteNumbers&&e.duration!==_.Half?s.noteNumbers.getNoteY(s.noteNumbers.minStringNote,is.Bottom)+this.lineOffset/2:this.height-this.settings.notation.rhythmHeight-this.tupletSize}getBeamDirection(e){return Te.Down}getFlagAndBarPos(){return this.height-(this._hasTuplets?this.tupletSize/2:0)}calculateBeamYWithDirection(e,t,s){return this.getFlagAndBarPos()}shouldPaintFlag(e,t){return!!super.shouldPaintFlag(e,t)&&(e.graceType===w.None&&this.drawBeamHelperAsFlags(t))}paintBeamingStem(e,t,s,i,a,r){if(a<i){const e=a;a=i,i=e}const n=rn.beat(r,ye.GuitarTabStem,e);try{r.lineWidth=On.StemWidth,r.beginPath();let n=[];this.helpers.collisionHelper.reservedLayoutAreasByDisplayTime.has(e.displayStart)&&(n=this.helpers.collisionHelper.reservedLayoutAreasByDisplayTime.get(e.displayStart).slots.slice(),n.sort(((e,t)=>e.topY-t.topY)));let o=a;for(;o>i;){r.moveTo(s,o);let e=i;if(!(n.length>0&&n[n.length-1].bottomY>e)){r.lineTo(s,e);break}{const i=n.pop();e=t+i.bottomY,r.lineTo(s,e),o=t+i.topY}}r.stroke(),r.lineWidth=1}finally{n?.[Symbol.dispose]?.()}}}tl.StaffId="tab",tl.TabLineSpacing=10;class sl extends tn{get staffId(){return tl.StaffId}getStaffPaddingTop(e){return e.system.layout.renderer.settings.display.notationStaffPaddingTop}getStaffPaddingBottom(e){return e.system.layout.renderer.settings.display.notationStaffPaddingBottom}constructor(){super(),this.showTimeSignature=null,this.showRests=null,this.showTiedNotes=null,this.hideOnPercussionTrack=!0}canCreate(e,t){return t.showTablature&&t.tuning.length>0&&super.canCreate(e,t)}create(e,t){const s=new tl(e,t);return null!==this.showRests&&(s.showRests=this.showRests),null!==this.showTimeSignature&&(s.showTimeSignature=this.showTimeSignature),null!==this.showTiedNotes&&(s.showTiedNotes=this.showTiedNotes),s}}class il extends Tr{constructor(){super(0,0)}doLayout(){super.doLayout();const e=this.renderer.resources.effectFont;this.height=e.size+il.Padding}paint(e,t,s){const i=this.renderer.resources;s.font=i.effectFont;const a=s.textAlign;s.textAlign=ne.Center,s.fillText("T",e+this.x,t+this.y+s.font.size/2),s.textAlign=a,s.strokeCircle(e+this.x,t+this.y+s.font.size/2+(il.Padding-1),s.font.size/1.6)}}il.Padding=4;class al extends no{get notationElement(){return E.EffectTap}get sizingMode(){return rs.SingleOnBeat}shouldCreateGlyphForNote(e){return e.isLeftHandTapped}createNewGlyph(e,t){return new il}}class rl{constructor(){this.noteRange=1,this.x=0,this.y=0}}!function(e){e[e.None=0]="None",e[e.Rectangle=1]="Rectangle",e[e.Ellipse=2]="Ellipse",e[e.Circle=3]="Circle"}(os||(os={}));class nl extends rl{constructor(){super(...arguments),this.align=ne.Left,this.frame=os.None,this.text="",this.fontFace="",this.weight=0,this.height=0}}class ol extends rl{constructor(){super(...arguments),this.chord=new je}}class hl extends rl{}class ll extends rl{}class cl extends rl{constructor(){super(...arguments),this.number=0}}class dl extends rl{constructor(){super(...arguments),this.decrescendo=!1}}class ul extends rl{constructor(){super(...arguments),this.allNumbers=!1,this.firstNumber=0,this.lastNumber=0}}class pl extends rl{constructor(){super(...arguments),this.octave=1}}class gl extends rl{}class ml{constructor(){this.defaultClef=n.G2,this.description="",this.percussion=!1,this.instrument=0,this.volume=0,this.transpose=0,this.index=0}}class fl{constructor(){this.from=0,this.to=0,this.curly=!1}}class yl{constructor(){this.currentBarIndex=-1,this.currentBarComplete=!0,this.currentBarDuration=0,this.currentPosition=0,this.voiceStemDir=null,this.repeatCount=0,this.repeatEnd=null}}class bl{constructor(){this._trackChannel=0,this._beamingMode=fe.Auto,this._isFirstSystem=!0,this._staffLookup=new Map,this._brackets=[],this._staffLayoutLookup=new Map,this._staffLayouts=[],this._timeSignature=new j,this._voiceStates=new Map}parseXml(e,t){this._galleryObjects=new Map,this._tieStarts=[],this._tieStartIds=new Map,this._voiceCounts=new Map,this._slurs=new Map,this._crescendo=new Map,this._isFirstSystem=!0;const s=new wt;try{s.parse(e)}catch(e){throw new qe("Could not parse XML",e)}this.parseDom(s),this.consolidate(),this.score.finish(t)}consolidate(){ie.consolidate(this.score),bl.applyEffectRange(this._slurs,((e,t)=>{t.isLegatoOrigin=!0})),bl.applyEffectRange(this._crescendo,((e,t)=>{t.crescendo=e.decrescendo?S.Decrescendo:S.Crescendo}))}static applyEffectRange(e,t){for(const[s,i]of e){const e=i.noteRange;let a=s;for(let s=0;s<e;s++)if(t(i,a),a.index+1<a.voice.beats.length)a=a.voice.beats[a.index+1];else{if(!(a.voice.bar.index+1<a.voice.bar.staff.bars.length))break;a=a.voice.bar.staff.bars[a.voice.bar.index+1].voices[a.voice.index].beats[0]}}}parseDom(e){const t=e.firstElement;if(!t)throw new qe("No valid XML");if("score"!==t.localName)throw new qe('Root node of XML was not "score"');this.score=new Je,this.score.tempo=120;for(const e of t.childElements())switch(e.localName){case"info":this.parseInfo(e);break;case"layout":this.parseLayout(e);break;case"gallery":this.parseGallery(e);break;case"pageObjects":this.parsePageObjects(e);break;case"systems":this.parseSystems(e)}}parseLayout(e){for(const t of e.childElements())switch(t.localName){case"staves":this.parseLayoutStaves(t);break;case"brackets":this.parseBrackets(t)}const t=this._brackets.filter((e=>!!e.curly));t.sort(((e,t)=>e.from-t.from));let s=0,i=null;for(let e=0;e<this._staffLayouts.length;e++){const a=this._staffLayouts[e];for(;s<t.length&&e>t[s].to;)s++;i&&s<t.length&&e>t[s].from&&e<=t[s].to?i.ensureStaveCount(i.staves.length+1):(i=new rt,i.ensureStaveCount(1),i.name=a.description,i.playbackInfo.volume=Math.floor(a.volume/128*16),i.playbackInfo.program=a.instrument,a.percussion?(i.playbackInfo.primaryChannel=9,i.playbackInfo.secondaryChannel=9):(i.playbackInfo.primaryChannel=this._trackChannel++,i.playbackInfo.secondaryChannel=this._trackChannel++),this.score.addTrack(i));const r=i.staves[i.staves.length-1];r.isPercussion=a.percussion,r.transpositionPitch=a.transpose,r.displayTranspositionPitch=0,r.showTablature=!1,this._staffLookup.set(a.index,r)}}parseBrackets(e){for(const t of e.childElements())if("bracket"===t.localName)this.parseBracket(t)}parseBracket(e){const t=new fl;t.from=Number.parseInt(e.getAttribute("from")),t.to=Number.parseInt(e.getAttribute("to")),e.attributes.has("curly")&&(t.curly="true"===e.attributes.get("curly")),this._brackets.push(t)}parseLayoutStaves(e){for(const t of e.childElements())if("staffLayout"===t.localName)this.parseStaffLayout(t)}parseStaffLayout(e){const t=new ml;t.description=e.getAttribute("description");for(const s of e.childElements())switch(s.localName){case"notation":s.attributes.has("defaultClef")&&(t.defaultClef=this.parseClef(s.attributes.get("defaultClef")));break;case"sound":s.attributes.has("percussion")&&(t.percussion="true"===s.attributes.get("percussion")),s.attributes.has("instr")&&(t.instrument=Number.parseInt(s.attributes.get("instr"))),s.attributes.has("volume")&&(t.volume=Number.parseInt(s.attributes.get("volume"))),s.attributes.has("transpose")&&(t.transpose=Number.parseInt(s.attributes.get("transpose")))}this._staffLayoutLookup.set(t.description,t),t.index=this._staffLayouts.length,this._staffLayouts.push(t)}parseClef(e){switch(e){case"treble":return n.G2;case"bass":return n.F4;case"alto":case"tenor":return n.C4}return n.G2}parseClefOttava(e){return e.endsWith("-")?o._8vb:e.endsWith("+")?o._8va:o.Regular}parseSystems(e){for(const t of e.childElements())if("system"===t.localName)this.parseSystem(t)}parseSystem(e){e.attributes.has("tempo")&&0===this.score.masterBars.length&&(this.score.tempo=Number.parseInt(e.attributes.get("tempo"))),"0"===e.getAttribute("beamGrouping")&&(this._beamingMode=fe.ForceSplitToNext);for(const t of e.childElements())if("staves"===t.localName)this.parseStaves(e,t);this._isFirstSystem=!1}parseStaves(e,t){const s=this.score.masterBars.length;for(const i of t.childElements())if("staff"===i.localName)this.parseStaff(e,s,i)}parseStaff(e,t,s){const i=s.getAttribute("layout");this._currentStaffLayout=this._staffLayoutLookup.get(i),this._timeSignature.timeSignatureNumerator=4,this._timeSignature.timeSignatureDenominator=4,this._timeSignature.timeSignatureCommon=!1,this.parseTime(s.getAttribute("defaultTime"));const a=this._staffLookup.get(this._currentStaffLayout.index);for(;a.bars.length<t;)this.addNewBar(a);for(const r of s.childElements())if("voices"===r.localName)this.parseVoices(i,a,e,t,r)}parseTime(e){switch(e){case"allaBreve":case"C":this._timeSignature.timeSignatureNumerator=2,this._timeSignature.timeSignatureDenominator=2,this._timeSignature.timeSignatureCommon=!0;break;case"longAllaBreve":this._timeSignature.timeSignatureNumerator=4,this._timeSignature.timeSignatureDenominator=4,this._timeSignature.timeSignatureCommon=!0;break;default:if(e.indexOf("/")>0){const t=e.split("/");this._timeSignature.timeSignatureNumerator=Number.parseInt(t[0]),this._timeSignature.timeSignatureDenominator=Number.parseInt(t[1]),this._timeSignature.timeSignatureCommon=!1}}}parseVoices(e,t,s,i,a){let r=0;for(const n of a.childElements())if("voice"===n.localName)this.parseVoice(e,t,s,r,i,n),r++}getOrCreateBar(e,t){return t<e.bars.length?e.bars[t]:this.addNewBar(e)}addNewBar(e){const t=new G;if(e.bars.length>0?(t.clef=e.bars[e.bars.length-1].clef,t.clefOttava=e.bars[e.bars.length-1].clefOttava,t.keySignature=e.bars[e.bars.length-1].keySignature,t.keySignatureType=e.bars[e.bars.length-1].keySignatureType):t.clef=this._currentStaffLayout.defaultClef,e.addBar(t),e.bars.length>this.score.masterBars.length){const e=new j;this.score.addMasterBar(e),e.index>0&&(e.tripletFeel=e.previousMasterBar.tripletFeel),e.timeSignatureDenominator=this._timeSignature.timeSignatureDenominator,e.timeSignatureNumerator=this._timeSignature.timeSignatureNumerator,e.timeSignatureCommon=this._timeSignature.timeSignatureCommon}return t}newBar(e,t){this._currentVoiceState.currentBarIndex++,this._currentBar=this.getOrCreateBar(e,this._currentVoiceState.currentBarIndex),this._currentVoiceState.currentBarDuration=this._currentBar.masterBar.calculateDuration(!1),this._currentVoiceState.currentBarComplete=!1,this._currentVoiceState.currentPosition=0,this.ensureVoice(e,t)}parseVoice(e,t,s,i,a,r){const n=`${e}_${i}`;if(this._currentVoiceState&&!this._currentVoiceState.currentBarComplete&&(this._currentBar.masterBar.isAnacrusis=!0),this._voiceStates.has(n)?(this._currentVoiceState=this._voiceStates.get(n),this._currentBar=this.getOrCreateBar(t,this._currentVoiceState.currentBarIndex),this.ensureVoice(t,i)):(this._currentVoiceState=new yl,this._currentVoiceState.currentBarIndex=a-1,this._voiceStates.set(n,this._currentVoiceState),this.newBar(t,i)),r.attributes.has("stemDir"))switch(r.attributes.get("stemDir")){case"up":this._currentVoiceState.voiceStemDir=Te.Up;break;case"down":this._currentVoiceState.voiceStemDir=Te.Down;break;default:this._currentVoiceState.voiceStemDir=null}else this._currentVoiceState.voiceStemDir=null;const o=r.findChildElement("noteObjects");if(s.attributes.has("tempo")){const e=new U;e.isLinear=!0,e.type=m.Tempo,e.value=Number.parseInt(s.attributes.get("tempo")),e.ratioPosition=this._currentVoiceState.currentPosition/this._currentVoiceState.currentBarDuration,this._currentBar.masterBar.tempoAutomations.push(e)}if(o)for(const e of o.childElements())switch(this._currentVoiceState.currentBarComplete&&"barline"!==e.localName&&this.newBar(t,i),e.localName){case"clefSign":this._currentBar.clef=this.parseClef(e.getAttribute("clef")),this._currentBar.clefOttava=this.parseClefOttava(e.getAttribute("clef"));break;case"keySign":this._currentBar.keySignature=Number.parseInt(e.getAttribute("fifths"));break;case"timeSign":this.parseTime(e.getAttribute("time")),this._currentBar.masterBar.timeSignatureDenominator=this._timeSignature.timeSignatureDenominator,this._currentBar.masterBar.timeSignatureNumerator=this._timeSignature.timeSignatureNumerator,this._currentBar.masterBar.timeSignatureCommon=this._timeSignature.timeSignatureCommon,this._currentVoiceState.currentPosition=0,this._currentVoiceState.currentBarDuration=this._currentBar.masterBar.calculateDuration(!1);break;case"barline":switch(e.getAttribute("type")){case"double":this._currentBar.barLineRight=p.LightLight,this._currentVoiceState.currentBarComplete||(this._currentBar.masterBar.isAnacrusis=!0),this._currentVoiceState.currentBarComplete=!0;break;case"end":this._currentVoiceState.currentBarComplete||(this._currentBar.masterBar.isAnacrusis=!0);break;case"repEnd":this._currentVoiceState.repeatEnd=this._currentBar.masterBar,this._currentBar.masterBar.repeatCount<this._currentVoiceState.repeatCount&&(this._currentBar.masterBar.repeatCount=this._currentVoiceState.repeatCount),this.parseBarDrawObject(e),this._currentVoiceState.currentBarComplete||(this._currentBar.masterBar.isAnacrusis=!0),this._currentVoiceState.currentBarComplete=!0;break;case"repBegin":this.newBar(t,i),this._currentBar.masterBar.isRepeatStart=!0,this._currentVoiceState.repeatEnd=null,this._currentVoiceState.repeatCount=0;break;case"repEndBegin":this._currentVoiceState.repeatEnd=this._currentBar.masterBar,this._currentBar.masterBar.repeatCount<this._currentVoiceState.repeatCount&&(this._currentBar.masterBar.repeatCount=this._currentVoiceState.repeatCount),this.parseBarDrawObject(e),this.newBar(t,i),this._currentBar.masterBar.isRepeatStart=!0;break;default:this._currentVoiceState.currentBarComplete||(this._currentBar.masterBar.isAnacrusis=!0),this._currentVoiceState.currentBarComplete=!0}break;case"chord":const s=new ze;this.initFromPreviousBeat(s,this._currentVoice),s.beamingMode=this._beamingMode,this._currentVoiceState.voiceStemDir&&(s.preferredBeamDirection=this._currentVoiceState.voiceStemDir),this.parseDuration(this._currentBar,s,e.findChildElement("duration")),s.updateDurations(),this._currentVoiceState.currentPosition+=s.playbackDuration,this._currentVoice.addBeat(s),this.parseChord(s,e),this._currentVoiceState.currentPosition>=this._currentVoiceState.currentBarDuration&&(this._currentVoiceState.currentBarComplete=!0);break;case"rest":const a=this.parseRestDurations(this._currentBar,e.findChildElement("duration"));a&&(this.initFromPreviousBeat(a,this._currentVoice),a.updateDurations(),this._currentVoiceState.currentPosition+=a.playbackDuration,this._currentVoice.addBeat(a),this._currentVoiceState.currentPosition>=this._currentVoiceState.currentBarDuration&&(this._currentVoiceState.currentBarComplete=!0))}}initFromPreviousBeat(e,t){const s=this.getLastBeat(t);s&&(e.dynamics=s.dynamics)}getLastBeat(e){if(e.beats.length>0)return e.beats[e.beats.length-1];if(e.bar.index>0){const t=e.bar.staff.bars[e.bar.index-1];if(e.index<t.voices.length){const s=t.voices[e.index];return this.getLastBeat(s)}}return null}ensureVoice(e,t){for(;this._currentBar.voices.length<t+1;)this._currentBar.addVoice(new ee);(!this._voiceCounts.has(e.track.index)||this._voiceCounts.get(e.track.index)<this._currentBar.voices.length)&&this._voiceCounts.set(e.track.index,this._currentBar.voices.length),this._currentVoice=this._currentBar.voices[t]}parseChord(e,t){const s=new Ae;for(const i of t.childElements())switch(i.localName){case"stem":switch(i.getAttribute("dir")){case"up":e.preferredBeamDirection=Te.Up;break;case"down":e.preferredBeamDirection=Te.Down}break;case"articulation":switch(i.getAttribute("type")){case"staccato":s.isStaccato=!0;break;case"normalAccent":s.accentuated=B.Normal;break;case"strongAccent":s.accentuated=B.Heavy}break;case"lyric":this.parseLyric(e,i);break;case"drawObjects":this.parseBeatDrawObject(e,i);break;case"heads":this.parseHeads(e,s,i);break;case"beam":switch(i.getAttribute("group")){case"force":e.beamingMode=fe.ForceMergeWithNext;break;case"divide":e.beamingMode=fe.ForceSplitToNext}}}parseHeads(e,t,s){for(const i of s.childElements())if("head"===i.localName)this.parseHead(e,t,i)}parseHead(e,t,s){const i=new Ae,a=ie.parseTuning(s.getAttribute("pitch"));i.octave=a.octave-1,i.tone=a.tone.noteValue,i.isStaccato=t.isStaccato,i.accentuated=t.accentuated,e.addNote(i);for(const e of s.childElements())switch(e.localName){case"alter":e.attributes.has("step")&&(i.tone+=Number.parseInt(e.attributes.get("step")));break;case"tie":e.attributes.has("begin")?this._tieStartIds.has(i.id)||(this._tieStartIds.set(i.id,!0),this._tieStarts.push(i)):e.attributes.has("end")&&this._tieStarts.length>0&&!i.isTieDestination&&(i.isTieDestination=!0,i.tieOrigin=this._tieStarts[0],this._tieStarts.splice(0,1),this._tieStartIds.delete(i.id))}}parseBeatDrawObject(e,t){for(const s of t.childElements())if("drawObj"===s.localName){const t=this.parseDrawObj(s);if(t)if(t instanceof nl)t.fontFace.startsWith("capella")?"u"===t.text?(e.fermata=new lt,e.fermata.type=ke.Medium):"f"===t.text?e.dynamics=g.F:"j"===t.text&&(e.dynamics=g.MF):this._isFirstSystem&&""===this.score.title&&t.align===ne.Center&&t.height>16&&t.weight>400?this.score.title=t.text:this._isFirstSystem&&""===this.score.artist&&t.align===ne.Center&&t.y<0?this.score.artist=t.text:this._isFirstSystem&&""===this.score.music&&t.align===ne.Right&&t.y<0?this.score.music=t.text:t.text.startsWith("by capella")||(e.text=t.text);else if(t instanceof ol);else if(t instanceof ll)e.vibrato=P.Slight;else if(t instanceof dl)e.crescendo=t.decrescendo?S.Decrescendo:S.Crescendo,t.noteRange++,this._crescendo.set(e,t);else if(t instanceof hl){const s=t;this._slurs.set(e,s)}else t instanceof ul&&this.applyVolta(t)}}parseBarDrawObject(e){for(const t of e.childElements())if("drawObj"===t.localName){const e=this.parseDrawObj(t);e&&e instanceof ul&&this.applyVolta(e)}}applyVolta(e){if(e.lastNumber>0?(this._currentVoiceState.repeatCount=e.lastNumber,this._currentVoiceState.repeatEnd&&this._currentVoiceState.repeatEnd.repeatCount<this._currentVoiceState.repeatCount&&(this._currentVoiceState.repeatEnd.repeatCount=this._currentVoiceState.repeatCount)):e.firstNumber>0&&(this._currentVoiceState.repeatCount=e.firstNumber,this._currentVoiceState.repeatEnd&&this._currentVoiceState.repeatEnd.repeatCount<this._currentVoiceState.repeatCount&&(this._currentVoiceState.repeatEnd.repeatCount=this._currentVoiceState.repeatCount)),e.lastNumber>0&&e.firstNumber>0){let t=0;for(let s=e.firstNumber;s<=e.lastNumber;s++)t|=1<<s-1;this._currentBar.masterBar.alternateEndings=t}else e.lastNumber>0?this._currentBar.masterBar.alternateEndings=1<<e.lastNumber-1:e.firstNumber>0&&(this._currentBar.masterBar.alternateEndings=1<<e.firstNumber-1)}parseLyric(e,t){for(const s of t.childElements())if("verse"===s.localName){e.lyrics||(e.lyrics=[]);let t=s.innerText;"true"===s.getAttribute("hyphen")&&(t+="-"),e.lyrics.push(t)}}parseRestDurations(e,t){const s=t.getAttribute("base");if(-1!==s.indexOf("/")){const s=new ze;return s.beamingMode=this._beamingMode,this.parseDuration(e,s,t),s}if(1===Number.parseInt(s)){const e=new ze;return e.beamingMode=this._beamingMode,e.duration=_.Whole,e}return q.warning("Importer","Multi-Bar rests are not supported"),null}parseDurationValue(e){switch(e){case"2/1":return _.DoubleWhole;case"1/1":return _.Whole;case"1/2":return _.Half;case"1/4":return _.Quarter;case"1/8":return _.Eighth;case"1/16":return _.Sixteenth;case"1/32":return _.ThirtySecond;case"1/64":return _.SixtyFourth;case"1/128":return _.OneHundredTwentyEighth;default:return q.warning("Importer","Unsupported duration"),_.Quarter}}parseDuration(e,t,s){const i=s.getAttribute("base");t.duration=this.parseDurationValue(i),s.attributes.has("dots")&&(t.dots=Number.parseInt(s.attributes.get("dots")));const a=s.findChildElement("tuplet");if(a){t.tupletNumerator=Number.parseInt(a.getAttribute("count"));const e="true"===a.getAttribute("tripartite")?3:1,s="true"===a.getAttribute("prolong")?0:1;let i=0;for(;e*Math.pow(2,i+s)<t.tupletNumerator;)i++;t.tupletDenominator=e*Math.pow(2,i)}}parsePageObjects(e){for(const t of e.childElements())if("drawObj"===t.localName){const e=this.parseDrawObj(t);if(e&&e instanceof nl)switch(e.align){case ne.Center:this.score.title?this.score.subTitle||(this.score.subTitle=t.innerText):this.score.title=t.innerText;break;case ne.Right:this.score.artist||(this.score.artist=t.innerText)}}}parseGallery(e){for(const t of e.childElements())if("drawObj"===t.localName){const e=this.parseDrawObj(t);e&&this._galleryObjects.set(t.getAttribute("name"),e)}}parseDrawObj(e){let t=null,s=1;for(const i of e.childElements())switch(i.localName){case"text":t=this.parseText(i);break;case"guitar":t=this.parseGuitar(i);break;case"slur":t=this.parseSlur(i);break;case"wavyLine":t=this.parseWavyLine(i);break;case"bracket":t=this.parseTupletBracket(i);break;case"wedge":t=this.parseWedge(i);break;case"volta":t=this.parseVolta(i);break;case"octaveClef":t=this.parseOctaveClef(i);break;case"trill":t=this.parseTrill(i);break;case"basic":i.attributes.has("noteRange")&&(s=Number.parseInt(i.attributes.get("noteRange")))}return t&&(t.noteRange=s),t}parseTrill(e){return new gl}parseOctaveClef(e){const t=new pl;return e.attributes.has("octave")&&(t.octave=Number.parseInt(e.attributes.get("octave"))),t}parseVolta(e){const t=new ul;return t.allNumbers="true"===e.attributes.get("allNumbers"),e.attributes.has("firstNumber")&&(t.firstNumber=Number.parseInt(e.attributes.get("firstNumber"))),e.attributes.has("lastNumber")&&(t.lastNumber=Number.parseInt(e.attributes.get("lastNumber"))),t}parseWedge(e){const t=new dl;return t.decrescendo="true"===e.attributes.get("decrescendo"),t}parseTupletBracket(e){const t=new cl;return e.attributes.has("number")&&(t.number=Number.parseInt(e.attributes.get("number"))),t}parseWavyLine(e){return new ll}parseSlur(e){return new hl}parseGuitar(e){const t=new ol,s=e.innerText.trim();for(let e=0;e<s.length;e++)"/"===s.charAt(e)?t.chord.strings.push(0):t.chord.strings.push(Number.parseInt(s.charAt(e)));return t}parseText(e){const t=new nl;switch(e.attributes.has("x")&&(t.x=Number.parseFloat(e.attributes.get("x"))),e.attributes.has("x")&&(t.y=Number.parseFloat(e.attributes.get("y"))),e.getAttribute("align")){case"left":t.align=ne.Left;break;case"center":t.align=ne.Center;break;case"right":t.align=ne.Right}switch(e.getAttribute("frame")){case"rectangle":t.frame=os.Rectangle;break;case"ellipse":t.frame=os.Ellipse;break;case"circle":t.frame=os.Circle;break;case"none":t.frame=os.None}if(e.firstElement)for(const s of e.childElements())switch(s.localName){case"font":t.fontFace=s.getAttribute("face"),s.attributes.has("weight")&&(t.weight=Number.parseInt(s.attributes.get("weight"))),s.attributes.has("height")&&(t.height=Number.parseInt(s.attributes.get("height")));break;case"content":t.text=s.innerText}else t.text=e.innerText;return t}parseInfo(e){for(const t of e.childElements())switch(t.localName){case"author":this.score.tab=t.firstChild.innerText;break;case"comment":this.score.notices=t.firstChild.innerText}}}class Sl extends Ye{get name(){return"Capella"}readScore(){q.debug(this.name,"Loading ZIP entries");let e,t=null;if(e=new ds(this.data).read(),q.debug(this.name,"Zip entries loaded"),e.length>0){for(const s of e)if("score.xml"===s.fileName)t=ot.toString(s.data,this.settings.importer.encoding)}else this.data.reset(),t=ot.toString(this.data.readAll(),this.settings.importer.encoding);if(!t)throw new qe("No valid capella file");q.debug(this.name,"Start Parsing score.xml");try{const e=new bl;e.parseXml(t,this.settings),q.debug(this.name,"score.xml parsed");return e.score}catch(e){throw new qe("Failed to parse CapXML",e)}}}class _l{constructor(e){this._targets=new Set,this._callback=e,window.addEventListener("resize",this.onWindowResize.bind(this),!1)}observe(e){this._targets.add(e)}unobserve(e){this._targets.delete(e)}disconnect(){this._targets.clear()}onWindowResize(){const e=[];for(const t of this._targets)e.push({target:t,contentRect:void 0,borderBoxSize:void 0,contentBoxSize:[],devicePixelContentBoxSize:[]});this._callback(e,this)}}class wl{constructor(e){this._elements=[];let t=null;const s=this.check.bind(this);this.check=()=>{t||(t=setTimeout((()=>{s(),t=null}),100))},this._callback=e,window.addEventListener("resize",this.check,!0),document.addEventListener("scroll",this.check,!0)}observe(e){this._elements.indexOf(e)>=0||(this._elements.push(e),this.check())}unobserve(e){this._elements=this._elements.filter((t=>t!==e))}check(){const e=[];for(const t of this._elements){const s=t.getBoundingClientRect();s.top+s.height>=0&&s.top<=window.innerHeight&&s.left+s.width>=0&&s.left<=window.innerWidth&&e.push({target:t,isIntersecting:!0})}e.length&&this._callback(e,this)}}var Bl="function"==typeof SuppressedError?SuppressedError:function(e,t,s){var i=new Error(s);return i.name="SuppressedError",i.error=e,i.suppressed=t,i};class kl{static enable(e,t){kl.alphaSkia=t,kl.initializeMusicFont(kl.alphaSkia.AlphaSkiaTypeface.register(e))}static initializeMusicFont(e){kl.musicTextStyle=new kl.alphaSkia.AlphaSkiaTextStyle([e.familyName],e.weight,e.isItalic)}static registerFont(e,t){const s=kl.alphaSkia.AlphaSkiaTypeface.register(e.buffer);return t||(t=na.withFamilyList([s.familyName],12,s.isItalic?Jt.Italic:Jt.Plain,s.weight>400?Yt.Bold:Yt.Regular)),t}get font(){return this._font}set font(e){if(this._font===e)return;this._font=e;const t=this.textStyleKey(e);if(this._textStyles.has(t))this._textStyle=this._textStyles.get(t);else{const s=new kl.alphaSkia.AlphaSkiaTextStyle(e.families,e.weight===Yt.Bold?700:400,e.isItalic);this._textStyles.set(t,s),this._textStyle=s}}textStyleKey(e){return[...e.families,e.weight.toString(),e.isItalic?"italic":"upright"].join("_")}constructor(){this._color=new et(0,0,0,0),this._lineWidth=0,this._textStyle=null,this._scale=1,this._textStyles=new Map,this._font=new na("Arial",10,Jt.Plain),this.textAlign=ne.Left,this.textBaseline=oe.Top,this._canvas=new kl.alphaSkia.AlphaSkiaCanvas,this.color=new et(0,0,0,255)}destroy(){this._canvas[Symbol.dispose]();for(const e of this._textStyles.values())e[Symbol.dispose]()}onRenderFinished(){return null}beginRender(e,t){this._scale=this.settings.display.scale,this._canvas.beginRender(e,t,rc.HighDpiFactor)}endRender(){return this._canvas.endRender()}get color(){return this._color}set color(e){this._color.rgba!==e.rgba&&(this._color=e,this._canvas.color=kl.alphaSkia.AlphaSkiaCanvas.rgbaToColor(e.r,e.g,e.b,e.a))}get lineWidth(){return this._lineWidth}set lineWidth(e){this._lineWidth=e,this._canvas.lineWidth=e}fillRect(e,t,s,i){s>0&&this._canvas.fillRect(e*this._scale|0,t*this._scale|0,s*this._scale,i*this._scale)}strokeRect(e,t,s,i){const a=this.lineWidth%2==0?0:.5;this._canvas.strokeRect((e*this._scale|0)+a,(t*this._scale|0)+a,s*this._scale,i*this._scale)}beginPath(){this._canvas.beginPath()}closePath(){this._canvas.closePath()}moveTo(e,t){this._canvas.moveTo(e*this._scale,t*this._scale)}lineTo(e,t){this._canvas.lineTo(e*this._scale,t*this._scale)}quadraticCurveTo(e,t,s,i){this._canvas.quadraticCurveTo(e*this._scale,t*this._scale,s*this._scale,i*this._scale)}bezierCurveTo(e,t,s,i,a,r){this._canvas.bezierCurveTo(e*this._scale,t*this._scale,s*this._scale,i*this._scale,a*this._scale,r*this._scale)}fillCircle(e,t,s){this._canvas.fillCircle(e*this._scale,t*this._scale,s*this._scale)}strokeCircle(e,t,s){this._canvas.strokeCircle(e*this._scale,t*this._scale,s*this._scale)}fill(){this._canvas.fill()}stroke(){this._canvas.stroke()}beginGroup(e){}endGroup(){}fillText(e,t,s){if(0===e.length)return;let i=kl.alphaSkia.AlphaSkiaTextAlign.Left;switch(this.textAlign){case ne.Left:i=kl.alphaSkia.AlphaSkiaTextAlign.Left;break;case ne.Center:i=kl.alphaSkia.AlphaSkiaTextAlign.Center;break;case ne.Right:i=kl.alphaSkia.AlphaSkiaTextAlign.Right}let a=kl.alphaSkia.AlphaSkiaTextBaseline.Top;switch(this.textBaseline){case oe.Top:a=kl.alphaSkia.AlphaSkiaTextBaseline.Top;break;case oe.Middle:a=kl.alphaSkia.AlphaSkiaTextBaseline.Middle;break;case oe.Bottom:a=kl.alphaSkia.AlphaSkiaTextBaseline.Bottom}this._canvas.fillText(e,this._textStyle,this._font.size*this._scale,t*this._scale|0,s*this._scale|0,i,a)}measureText(e){const t={stack:[],error:void 0,hasError:!1};try{const s=function(e,t,s){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var i,a;if(s){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");i=t[Symbol.asyncDispose]}if(void 0===i){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");i=t[Symbol.dispose],s&&(a=i)}if("function"!=typeof i)throw new TypeError("Object not disposable.");a&&(i=function(){try{a.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:i,async:s})}else s&&e.stack.push({async:!0});return t}(t,this._canvas.measureText(e,this._textStyle,this._font.size,kl.alphaSkia.AlphaSkiaTextAlign.Left,kl.alphaSkia.AlphaSkiaTextBaseline.Alphabetic),!1);return new De(s.width,s.actualBoundingBoxAscent+s.actualBoundingBoxDescent)}catch(e){t.error=e,t.hasError=!0}finally{!function(e){function t(t){e.error=e.hasError?new Bl(t,e.error,"An error was suppressed during disposal."):t,e.hasError=!0}var s,i=0;(function a(){for(;s=e.stack.pop();)try{if(!s.async&&1===i)return i=0,e.stack.push(s),Promise.resolve().then(a);if(s.dispose){var r=s.dispose.call(s.value);if(s.async)return i|=2,Promise.resolve(r).then(a,(function(e){return t(e),a()}))}else i|=1}catch(e){t(e)}if(1===i)return e.hasError?Promise.reject(e.error):Promise.resolve();if(e.hasError)throw e.error})()}(t)}}fillMusicFontSymbol(e,t,s,i,a){i!==re.None&&this.fillMusicFontSymbolText(e,t,s,String.fromCharCode(i),a)}fillMusicFontSymbols(e,t,s,i,a){let r="";for(const e of i)e!==re.None&&(r+=String.fromCharCode(e));this.fillMusicFontSymbolText(e,t,s,r,a)}fillMusicFontSymbolText(e,t,s,i,a){this._canvas.fillText(i,kl.musicTextStyle,rc.MusicFontSize*this._scale*s,e*this._scale,t*this._scale,a?kl.alphaSkia.AlphaSkiaTextAlign.Center:kl.alphaSkia.AlphaSkiaTextAlign.Left,kl.alphaSkia.AlphaSkiaTextBaseline.Alphabetic)}beginRotate(e,t,s){this._canvas.beginRotate(e*this._scale,t*this._scale,s)}endRotate(){this._canvas.endRotate()}}kl.musicTextStyle=null;class Tl extends Uo{constructor(e,t,s=!1){super(e.beat,t.beat,s),this.startNote=e,this.endNote=t}getTieHeight(e,t,s,i){return this.startNote===this.endNote?15:super.getTieHeight(e,t,s,i)}getBeamDirection(e,t){return Te.Down}static getBeamDirectionForNote(e){return Te.Down}getStartY(){return this.startNoteRenderer.getNoteY(this.startNote,is.Center)}getEndY(){return this.getStartY()}getStartX(){return this.startNote===this.endNote?this.getEndX()-20:this.startNoteRenderer.getNoteX(this.startNote,as.Right)}getEndX(){return this.endNoteRenderer.getNoteX(this.endNote,as.Left)}}class Nl extends Fr{constructor(){super(...arguments),this._tiedNoteTie=null}createTies(e){if(e.isVisible){if(!this._tiedNoteTie&&e.isTieOrigin&&e.tieDestination.isVisible){const t=new Tl(e,e.tieDestination,!1);this._tiedNoteTie=t,this.addTie(t)}if(!this._tiedNoteTie&&e.isTieDestination){const t=new Tl(e.tieOrigin,e,!0);this._tiedNoteTie=t,this.addTie(t)}}}}class xl extends Zo{updateBeamingHelper(e){this.beamingHelper&&this.beamingHelper.registerBeatLineX("slash",this.beat,e+this.x+this.width/2,e+this.x+this.width/2)}paint(e,t,s){super.internalPaint(e,t,s,ye.SlashRests)}}class vl extends Mn{constructor(){super(...arguments),this.noteHeads=null,this.deadSlapped=null,this.restGlyph=null}get effectElement(){return ye.SlashEffects}getNoteX(e,t){let s=null;if(this.noteHeads?s=this.noteHeads:this.deadSlapped&&(s=this.deadSlapped),s){let e=s.x;switch(t){case as.Left:break;case as.Center:e+=s.width/2;break;case as.Right:e+=s.width}return e}return 0}buildBoundingsLookup(e,t,s){if(this.noteHeads&&this.container.beat.notes.length>0){const i=new ir;i.note=this.container.beat.notes[0],i.noteHeadBounds=new mt,i.noteHeadBounds.x=t+this.x+this.noteHeads.x,i.noteHeadBounds.y=s+this.y+this.noteHeads.y-this.noteHeads.height/2,i.noteHeadBounds.w=this.width,i.noteHeadBounds.h=this.height,e.addNote(i)}}getNoteY(e,t){let s=null;if(this.noteHeads?s=this.noteHeads:this.deadSlapped&&(s=this.deadSlapped),s){let e=this.y+s.y;switch(t){case is.Top:case is.TopWithStem:e-=s.height/2+2;break;case is.Center:break;case is.Bottom:case is.BottomWithStem:e+=s.height/2}return e}return 0}updateBeamingHelper(){this.noteHeads?this.noteHeads.updateBeamingHelper(this.container.x+this.x):this.deadSlapped?this.beamingHelper&&this.beamingHelper.registerBeatLineX("slash",this.container.beat,this.container.x+this.x+this.deadSlapped.x+this.width,this.container.x+this.x+this.deadSlapped.x):this.restGlyph&&this.restGlyph.updateBeamingHelper(this.container.x+this.x)}doLayout(){const e=this.renderer,t=e.getNoteLine(),s=e.getLineY(t);if(this.container.beat.deadSlapped){const e=new Ko;e.renderer=this.renderer,e.doLayout(),this.deadSlapped=e,this.addEffect(e)}else if(!this.container.beat.isEmpty)if(this.container.beat.isRest){const e=new xl(0,s,this.container.beat.duration);this.restGlyph=e,e.beat=this.container.beat,e.beamingHelper=this.beamingHelper,this.addNormal(e),this.beamingHelper&&this.beamingHelper.applyRest(this.container.beat,0)}else{const e=this.container.beat.graceType!==w.None,t=new gh(0,s,this.container.beat.duration,e,this.container.beat);this.noteHeads=t,t.beat=this.container.beat,t.beamingHelper=this.beamingHelper,this.addNormal(t)}if(this.container.beat.dots>0){this.addNormal(new hh(0,0,5));for(let t=0;t<this.container.beat.dots;t++)this.addEffect(new Vo(0,e.getLineY(e.getNoteLine())-e.getLineHeight(.5),1.5))}super.doLayout(),this.container.beat.isEmpty?this.centerX=this.width/2:this.restGlyph?this.centerX=this.restGlyph.x+this.restGlyph.width/2:this.noteHeads?this.centerX=this.noteHeads.x+this.noteHeads.width/2:this.deadSlapped&&(this.centerX=this.deadSlapped.x+this.deadSlapped.width/2)}}class Pl extends Hh{constructor(e,t){super(e,t),this.simpleWhammyOverflow=0,this._isOnlySlash=!t.staff.showTablature&&!t.staff.showStandardNotation,this.helpers.preferredBeamDirection=Te.Up}get repeatsBarSubElement(){return u.SlashRepeats}get barNumberBarSubElement(){return u.SlashBarNumber}get barLineBarSubElement(){return u.SlashBarLines}get staffLineBarSubElement(){return u.SlashStaffLine}get lineSpacing(){return On.RawLineSpacing}get heightLineCount(){return 5}get drawnLineCount(){return 1}get bottomGlyphOverflow(){return 0}paint(e,t,s){super.paint(e,t,s),this.paintBeams(e,t,s,ye.SlashFlags,ye.SlashBeams),this.paintTuplets(e,t,s,ye.SlashTuplet)}doLayout(){super.doLayout();let e=!1;for(const t of this.bar.voices)if(this.hasVoiceContainer(t)){if(this.getVoiceContainer(t).tupletGroups.length>0){e=!0;break}}e&&this.registerOverflowTop(this.tupletSize)}getNoteLine(){return 0}getFlagTopY(e,t){const s=Nr.Heights.get(re.NoteheadSlashWhiteHalf);return this.getLineY(0)-s/2}getFlagBottomY(e,t){const s=Nr.Heights.get(re.NoteheadSlashWhiteHalf);return this.getLineY(0)-s/2}getBeamDirection(e){return Te.Up}getNoteY(e,t){let s=super.getNoteY(e,t);return Number.isNaN(s)&&(s=this.getLineY(0)),s}calculateBeamYWithDirection(e,t,s){return this.getLineY(0)-this.getFlagStemSize(e.shortestDuration)}getBarLineStart(e,t){const s=Nr.Heights.get(re.NoteheadSlashWhiteHalf);return this.getLineY(0)-s/2}createLinePreBeatGlyphs(){this._isOnlySlash&&(!this.bar.previousBar||this.bar.previousBar&&this.bar.masterBar.timeSignatureNumerator!==this.bar.previousBar.masterBar.timeSignatureNumerator||this.bar.previousBar&&this.bar.masterBar.timeSignatureDenominator!==this.bar.previousBar.masterBar.timeSignatureDenominator||this.bar.previousBar&&this.bar.masterBar.isFreeTime&&this.bar.masterBar.isFreeTime!==this.bar.previousBar.masterBar.isFreeTime)&&(this.createStartSpacing(),this.createTimeSignatureGlyphs())}createTimeSignatureGlyphs(){this.addPreBeatGlyph(new hh(0,0,5));const e=this.bar.masterBar,t=new wh(0,this.getLineY(0),e.timeSignatureNumerator,e.timeSignatureDenominator,e.timeSignatureCommon,e.isFreeTime&&(null==e.previousMasterBar||e.isFreeTime!==e.previousMasterBar.isFreeTime));t.barSubElement=u.SlashTimeSignature,this.addPreBeatGlyph(t)}createVoiceGlyphs(e){for(const t of e.beats){const s=new Nl(t,this.getVoiceContainer(e));s.preNotes=new Ln,s.onNotes=0===e.index?new vl:new Mn,this.addBeatGlyph(s)}}paintBeamingStem(e,t,s,i,a,r){const n=rn.beat(r,ye.SlashStem,e);try{r.lineWidth=On.StemWidth,r.beginPath(),r.moveTo(s,i),r.lineTo(s,a),r.stroke(),r.lineWidth=1}finally{n?.[Symbol.dispose]?.()}}}Pl.StaffId="slash";class Fl extends tn{get staffId(){return Pl.StaffId}getStaffPaddingTop(e){return e.system.layout.renderer.settings.display.notationStaffPaddingTop}getStaffPaddingBottom(e){return e.system.layout.renderer.settings.display.notationStaffPaddingBottom}create(e,t){return new Pl(e,t)}canCreate(e,t){return super.canCreate(e,t)&&t.showSlash}}class Cl extends Uo{constructor(e,t,s=!1){super(e?e.beat:null,t?t.beat:null,s),this.startNote=e,this.endNote=t}shouldDrawBendSlur(){return this.renderer.settings.notation.extendBendArrowsOnTiedNotes&&!!this.startNote.bendOrigin&&this.startNote.isTieOrigin}doLayout(){super.doLayout()}getBeamDirection(e,t){return Te.Up}getStartY(){return this.startNoteRenderer.getNoteY(this.startNote,is.Top)}getEndY(){return this.getStartY()}getStartX(){return this.startNote===this.endNote?this.getEndX()-20:this.startNoteRenderer.getNoteX(this.startNote,as.Center)}getEndX(){return this.startNote===this.endNote?this.endNoteRenderer.getNoteX(this.endNote,as.Left):this.endNoteRenderer.getNoteX(this.endNote,as.Center)}}class Dl extends Uh{constructor(e,t,s,i=!1){super(e,t,i),this._direction=Te.Up,this._forSlide=s}getTieHeight(e,t,s,i){return Math.log(s-e+1)*this.renderer.settings.notation.slurHeight}tryExpand(e,t,s,i){if(this._forSlide!==s)return!1;if(this.forEnd!==i)return!1;if(this.startNote.beat.id!==e.beat.id)return!1;if(this.endNote.beat.id!==t.beat.id)return!1;switch(this._direction){case Te.Up:e.realValue>this.startNote.realValue&&(this.startNote=e,this.startBeat=e.beat),t.realValue>this.endNote.realValue&&(this.endNote=t,this.endBeat=t.beat);break;case Te.Down:e.realValue<this.startNote.realValue&&(this.startNote=e,this.startBeat=e.beat),t.realValue<this.endNote.realValue&&(this.endNote=t,this.endBeat=t.beat)}return!0}paint(e,t,s){const i=this.renderer.scoreRenderer.layout.getRendererForBar(this.renderer.staff.staffId,this.startBeat.voice.bar),a=this.getBeamDirection(this.startBeat,i),r=`numbered.slur.${this.startNote.beat.id}.${this.endNote.beat.id}.${a}`,n=this.renderer;n.staff.getSharedLayoutData(r,!1)||(n.staff.setSharedLayoutData(r,!0),super.paint(e,t,s))}}class El extends Fr{constructor(){super(...arguments),this._effectSlurs=[]}createTies(e){if(e.isVisible){if(e.isTieOrigin&&e.tieDestination.isVisible){const t=new Cl(e,e.tieDestination,!1);this.addTie(t)}if(e.isTieDestination){const t=new Cl(e.tieOrigin,e,!0);this.addTie(t)}if(e.isLeftHandTapped&&!e.isHammerPullDestination){const t=new Cl(e,e,!1);this.addTie(t)}if(e.isEffectSlurOrigin&&e.effectSlurDestination){let t=!1;for(const s of this._effectSlurs)if(s.tryExpand(e,e.effectSlurDestination,!1,!1)){t=!0;break}if(!t){const t=new Dl(e,e.effectSlurDestination,!1,!1);this._effectSlurs.push(t),this.addTie(t)}}if(e.isEffectSlurDestination&&e.effectSlurOrigin){let t=!1;for(const s of this._effectSlurs)if(s.tryExpand(e.effectSlurOrigin,e,!1,!0)){t=!0;break}if(!t){const t=new Dl(e.effectSlurOrigin,e,!1,!0);this._effectSlurs.push(t),this.addTie(t)}}}}}class Ll extends kr{constructor(e,t,s,i,a){super(e,t),this._isGrace=i,this._number=s,this._beat=a}paint(e,t,s){const i=this._beat.isRest?rn.beat(s,ye.NumberedRests,this._beat):this._beat.notes.length>0?rn.note(s,le.NumberedNumber,this._beat.notes[0]):void 0;try{const i=this.renderer.resources;s.font=this._isGrace?i.numberedNotationGraceFont:i.numberedNotationFont,s.textBaseline=oe.Middle,s.textAlign=ne.Left,s.fillText(this._number.toString(),e+this.x,t+this.y)}finally{i?.[Symbol.dispose]?.()}}doLayout(){const e=this._isGrace?vr.GraceScale:1;this.width=Ll.NoteHeadWidth*e,this.height=Ll.NoteHeadHeight*e}}Ll.NoteHeadHeight=17,Ll.NoteHeadWidth=12;class Ml extends kr{constructor(e,t,s){super(e,t),this._beat=s}doLayout(){this.width=14+Ml.Padding,this.height=Ol.BarSize}paint(e,t,s){const i=rn.beat(s,ye.NumberedDuration,this._beat);try{const i=Ml.Padding;s.fillRect(e+this.x,t+this.y,this.width-i,this.height)}finally{i?.[Symbol.dispose]?.()}}}Ml.Padding=3;class Il extends Ln{constructor(){super(...arguments),this.isNaturalizeAccidental=!1,this.accidental=It.None}get effectElement(){return ye.NumberedEffects}doLayout(){if(!this.container.beat.isRest&&!this.container.beat.isEmpty){const e=new th;if(e.renderer=this.renderer,this.container.beat.notes.length>0){const t=this.container.beat.notes[0],s=t?t.accidentalMode:N.Default,i=Bs.getNoteValue(t);let a=Bs.computeAccidental(this.renderer.bar.keySignature,s,i,t.hasQuarterToneOffset);if(a===It.Natural){a=this.renderer.bar.keySignature+7<7?It.Sharp:It.Flat,this.isNaturalizeAccidental=!0}if(a!==It.None){this.accidental=a;const s=this.renderer,i=rn.noteColor(s.resources,le.NumberedAccidentals,t),r=new Oo(0,s.getLineY(0),a,t.beat.graceType!==w.None?vr.GraceScale*vr.GraceScale:vr.GraceScale);r.colorOverride=i,r.renderer=this.renderer,e.addGlyph(r),this.addNormal(e),this.addNormal(new hh(0,0,4))}}}super.doLayout()}}class Al extends Mn{constructor(){super(...arguments),this.noteHeads=null,this.deadSlapped=null,this.octaveDots=0}get effectElement(){return ye.NumberedEffects}getNoteX(e,t){let s=null;if(this.noteHeads?s=this.noteHeads:this.deadSlapped&&(s=this.deadSlapped),s){let e=s.x;switch(t){case as.Left:break;case as.Center:e+=s.width/2;break;case as.Right:e+=s.width}return e}return 0}buildBoundingsLookup(e,t,s){if(this.noteHeads&&this.container.beat.notes.length>0){const i=new ir;i.note=this.container.beat.notes[0],i.noteHeadBounds=new mt,i.noteHeadBounds.x=t+this.x+this.noteHeads.x,i.noteHeadBounds.y=s+this.y+this.noteHeads.y-this.noteHeads.height/2,i.noteHeadBounds.w=this.width,i.noteHeadBounds.h=this.height,e.addNote(i)}}getNoteY(e,t){let s=null;if(this.noteHeads?s=this.noteHeads:this.deadSlapped&&(s=this.deadSlapped),s){let e=this.y+s.y;switch(t){case is.Top:case is.TopWithStem:e-=s.height/2+2;break;case is.Center:break;case is.Bottom:case is.BottomWithStem:e+=s.height/2}return e}return 0}updateBeamingHelper(){if(this.beamingHelper){let e=null;this.noteHeads?e=this.noteHeads:this.deadSlapped&&(e=this.deadSlapped),e&&this.beamingHelper.registerBeatLineX("numbered",this.container.beat,this.container.x+this.x+e.x,this.container.x+this.x+e.x+e.width)}}doLayout(){const e=this.renderer;e.shortestDuration<this.container.beat.duration&&(e.shortestDuration=this.container.beat.duration);const t=e.getLineY(e.getNoteLine());if(!this.container.beat.isEmpty){let s="0";if(this.container.beat.notes.length>0){const t=this.renderer.bar.keySignatureType,i=this.renderer.bar.keySignature,a=i+7,r=(t===c.Minor?Al.MinorKeySignatureOneValues:Al.MajorKeySignatureOneValues)[a],n=this.container.beat.notes[0];if(n.isDead)s="X";else{const t=n.displayValue-r,o=t<0?(t%12+12)%12:t%12;let h=t<0?(Math.abs(t)+12)/12|0:t/12|0;t<0&&(h*=-1),this.octaveDots=h,e.registerOctave(h);let l=(ie.keySignatureIsSharp(i)||ie.keySignatureIsNatural(i)?Bs.FlatNoteSteps:Bs.SharpNoteSteps)[o]+1;Bs.AccidentalNotes[o]&&!this.container.preNotes.isNaturalizeAccidental&&(a<7?l++:l--),s=l.toString()}}if(this.container.beat.deadSlapped){const e=new Ko;e.renderer=this.renderer,e.doLayout(),this.deadSlapped=e,this.addEffect(e)}else{const e=this.container.beat.graceType!==w.None,i=new Ll(0,t,s,e,this.container.beat);this.noteHeads=i,this.addNormal(i)}if(this.container.beat.dots>0&&this.container.beat.duration>=_.Quarter){this.addNormal(new hh(0,0,5));for(let t=0;t<this.container.beat.dots;t++){const t=new Vo(0,e.getLineY(0),1.5);t.renderer=this.renderer,this.addEffect(t)}}let i=0;switch(this.container.beat.duration){case _.QuadrupleWhole:i=16;break;case _.DoubleWhole:i=8;break;case _.Whole:i=4;break;case _.Half:i=2}let a=i;for(let e=0;e<this.container.beat.dots;e++)a=a/2|0,i+=a;for(let t=0;t<i-1;t++){const t=new Ml(0,e.getLineY(0),this.container.beat);t.renderer=this.renderer,this.addNormal(t)}}super.doLayout(),this.container.beat.isEmpty?this.centerX=this.width/2:this.noteHeads?this.centerX=this.noteHeads.x+this.noteHeads.width/2:this.deadSlapped&&(this.centerX=this.deadSlapped.x+this.deadSlapped.width/2)}}Al.MajorKeySignatureOneValues=[59,66,61,68,63,58,65,60,67,62,69,64,71,66,61],Al.MinorKeySignatureOneValues=[71,66,73,68,63,70,65,72,67,74,69,64,71,66,73];class Rl extends kr{constructor(e,t,s,i){super(e,t),this._text="",this._accidental=It.None,this._accidentalOffset=0,this._keySignature=s,this._keySignatureType=i}doLayout(){super.doLayout();const e="1 = ";let t="",s=It.None;switch(this._keySignatureType){case c.Major:switch(this._keySignature){case l.Cb:t=" C",s=It.Flat;break;case l.Gb:t=" G",s=It.Flat;break;case l.Db:t=" D",s=It.Flat;break;case l.Ab:t=" A",s=It.Flat;break;case l.Eb:t=" E",s=It.Flat;break;case l.Bb:t=" B",s=It.Flat;break;case l.F:t="F";break;case l.C:t="C",s=It.None;break;case l.G:t="G",s=It.None;break;case l.D:t="D",s=It.None;break;case l.A:t="A",s=It.None;break;case l.E:t="E",s=It.None;break;case l.B:t="B",s=It.None;break;case l.FSharp:t=" F",s=It.Sharp;break;case l.CSharp:t=" C",s=It.Sharp}break;case c.Minor:switch(this._keySignature){case l.Cb:t=" a",s=It.Flat;break;case l.Gb:t=" e",s=It.Flat;break;case l.Db:t=" b",s=It.Flat;break;case l.Ab:t="f",s=It.None;break;case l.Eb:t="c",s=It.None;break;case l.Bb:t="g",s=It.None;break;case l.F:t="d";break;case l.C:t="a",s=It.None;break;case l.G:t="e",s=It.None;break;case l.D:t="b",s=It.None;break;case l.A:t=" f",s=It.Sharp;break;case l.E:t=" c",s=It.Sharp;break;case l.B:t=" g",s=It.Sharp;break;case l.FSharp:t=" d",s=It.Sharp;break;case l.CSharp:t=" a",s=It.Sharp}}this._text=e+t,this._accidental=s;const i=this.renderer.scoreRenderer.canvas,a=this.renderer.resources;i.font=a.numberedNotationFont,this._accidentalOffset=i.measureText(e).width,this.width=i.measureText(e+t).width}paint(e,t,s){const i=rn.bar(s,u.NumberedKeySignature,this.renderer.bar);try{const i=this.renderer.resources;s.font=i.numberedNotationFont,s.textBaseline=oe.Middle,s.fillText(this._text,e+this.x,t+this.y),this._accidental!==It.None&&s.fillMusicFontSymbol(e+this.x+this._accidentalOffset,t+this.y,.7,Oo.getMusicSymbol(this._accidental),!1)}finally{i?.[Symbol.dispose]?.()}}}class Ol extends Hh{registerOctave(e){null===this.lowestOctave?(this.lowestOctave=e,this.highestOctave=e):(e<this.lowestOctave&&(this.lowestOctave=e),e>this.highestOctave&&(this.highestOctave=e))}get repeatsBarSubElement(){return u.NumberedRepeats}get barNumberBarSubElement(){return u.NumberedBarNumber}get barLineBarSubElement(){return u.NumberedBarLines}get staffLineBarSubElement(){return u.NumberedStaffLine}constructor(e,t){super(e,t),this.simpleWhammyOverflow=0,this.shortestDuration=_.QuadrupleWhole,this.lowestOctave=null,this.highestOctave=null,this._isOnlyNumbered=!t.staff.showSlash&&!t.staff.showTablature&&!t.staff.showStandardNotation}get lineSpacing(){return On.RawLineSpacing}get heightLineCount(){return 5}get drawnLineCount(){return 0}get bottomGlyphOverflow(){return 0}paint(e,t,s){super.paint(e,t,s),this.paintBeams(e,t,s,ye.NumberedDuration,ye.NumberedDuration),this.paintTuplets(e,t,s,ye.NumberedTuplet,!0)}doLayout(){super.doLayout();let e=!1;for(const t of this.bar.voices)if(this.hasVoiceContainer(t)){if(this.getVoiceContainer(t).tupletGroups.length>0){e=!0;break}}if(e&&this.registerOverflowTop(this.tupletSize),!this.bar.isEmpty){const e=ie.getIndex(this.shortestDuration)-2;if(e>0){const t=(e-1)*Ol.BarSpacing+Ol.BarSize;let s=0;const i=this.lowestOctave;null!==i&&(s=Math.abs(i)*Ol.DotSpacing+Ol.DotSize),this.registerOverflowBottom(t+s)}const t=this.highestOctave;if(null!==t){const e=Math.abs(t)*Ol.DotSpacing+Ol.DotSize;this.registerOverflowTop(e)}}}paintFlag(e,t,s,i,a){this.paintBar(e,t,s,i,a)}paintBar(e,t,s,i,a){if(0===i.beats.length)return;const r=this.resources;for(let n=0,o=i.beats.length;n<o;n++){const o=i.beats[n],h=rn.beat(s,a,o);try{const a=Ol.BarSpacing,h=Ol.BarSize,l=ie.getIndex(o.duration)-2,c=t+this.y,d=this.getBeatX(o,ts.PreNotes)-this.beatGlyphsStart,u=this.calculateBeamY(i,d);for(let t=0;t<l;t++){let r=0,l=0,p=0;const g=c+t*a;n===i.beats.length-1?(r=d,l=this.getBeatX(o,ts.PostNotes)-this.beatGlyphsStart):(r=d,l=this.getBeatX(i.beats[n+1],ts.PreNotes)-this.beatGlyphsStart),p=g+u|0,Hh.paintSingleBar(s,e+this.x+r,p,e+this.x+l,p,h)}const p=this.getBeatContainer(o).onNotes;let g=p instanceof Al?p.octaveDots:0,m=0,f=0;g>0?(m=c+this.getLineY(0)-r.numberedNotationFont.size/1.5,f=-1*Ol.DotSpacing):g<0&&(m=c+u+l*a,f=Ol.DotSpacing);const y=this.getBeatX(o,ts.OnNotes)+4-this.beatGlyphsStart;g=Math.abs(g);for(let t=0;t<g;t++)s.fillCircle(e+this.x+y,m,Ol.DotSize),m+=f}finally{h?.[Symbol.dispose]?.()}}}getNoteLine(){return 0}get tupletOffset(){return super.tupletOffset+this.resources.numberedNotationFont.size}getFlagTopY(e,t){const s=Nr.Heights.get(re.NoteheadBlack);return this.getLineY(0)-s/2}getFlagBottomY(e,t){const s=Nr.Heights.get(re.NoteheadBlack);return this.getLineY(0)-s/2}getBeamDirection(e){return Te.Down}getTupletBeamDirection(e){return Te.Up}getNoteY(e,t){let s=super.getNoteY(e,t);return Number.isNaN(s)&&(s=this.getLineY(0)),s}calculateBeamYWithDirection(e,t,s){const i=this.resources.numberedNotationFont;return this.getLineY(0)+i.size}getBarLineStart(e,t){const s=Nr.Heights.get(re.NoteheadBlack);return this.getLineY(0)-s/2}createPreBeatGlyphs(){this.wasFirstOfLine=this.isFirstOfLine,(0===this.index||this.bar.masterBar.isRepeatStart&&this._isOnlyNumbered)&&this.addPreBeatGlyph(new Ah(!1)),this.createLinePreBeatGlyphs(),this.addPreBeatGlyph(new Oh(0,this.getLineHeight(-.25),this.bar.index+1))}createLinePreBeatGlyphs(){this.bar.previousBar&&this.bar.keySignature===this.bar.previousBar.keySignature||(this.createStartSpacing(),this.createKeySignatureGlyphs()),this._isOnlyNumbered&&(!this.bar.previousBar||this.bar.previousBar&&this.bar.masterBar.timeSignatureNumerator!==this.bar.previousBar.masterBar.timeSignatureNumerator||this.bar.previousBar&&this.bar.masterBar.timeSignatureDenominator!==this.bar.previousBar.masterBar.timeSignatureDenominator||this.bar.previousBar&&this.bar.masterBar.isFreeTime&&this.bar.masterBar.isFreeTime!==this.bar.previousBar.masterBar.isFreeTime)&&(this.createStartSpacing(),this.createTimeSignatureGlyphs())}createKeySignatureGlyphs(){this.addPreBeatGlyph(new Rl(0,this.getLineY(0),this.bar.keySignature,this.bar.keySignatureType))}createTimeSignatureGlyphs(){this.addPreBeatGlyph(new hh(0,0,5));const e=this.bar.masterBar,t=new wh(0,this.getLineY(0),e.timeSignatureNumerator,e.timeSignatureDenominator,e.timeSignatureCommon,e.isFreeTime&&(null==e.previousMasterBar||e.isFreeTime!==e.previousMasterBar.isFreeTime));t.barSubElement=u.NumberedTimeSignature,this.addPreBeatGlyph(t)}createPostBeatGlyphs(){this._isOnlyNumbered&&super.createPostBeatGlyphs()}createVoiceGlyphs(e){for(const t of e.beats){const s=new El(t,this.getVoiceContainer(e));s.preNotes=0===e.index?new Il:new Ln,s.onNotes=0===e.index?new Al:new Mn,this.addBeatGlyph(s)}}paintBeamingStem(e,t,s,i,a,r){}}Ol.StaffId="numbered",Ol.BarSpacing=On.BeamSpacing+On.BeamThickness,Ol.BarSize=2,Ol.DotSpacing=5,Ol.DotSize=2;class Hl extends tn{get staffId(){return Ol.StaffId}getStaffPaddingTop(e){return e.system.layout.renderer.settings.display.notationStaffPaddingTop}getStaffPaddingBottom(e){return e.system.layout.renderer.settings.display.notationStaffPaddingBottom}create(e,t){return new Ol(e,t)}canCreate(e,t){return super.canCreate(e,t)&&t.showNumbered}}class Wl extends Jn{get notationElement(){return E.EffectText}get hideOnMultiTrack(){return!1}get canShareBand(){return!0}get sizingMode(){return rs.SinglePreBeat}shouldCreateGlyph(e,t){const s=t.voice.bar.masterBar;return 0===t.voice.bar.staff.index&&0===t.voice.index&&0===t.index&&s.isFreeTime&&(0===s.index||s.isFreeTime!==s.previousMasterBar.isFreeTime)}createNewGlyph(e,t){return new Sn(0,0,"Free time",e.resources.effectFont,ne.Left)}canExpand(e,t){return!0}}class Vl extends Tr{constructor(){super(0,0)}doLayout(){super.doLayout(),this.height=Nr.Heights.get(re.KeyboardPedalPed)}paint(e,t,s){const i=this.renderer,a=t+this.y,r=this.height,n=i.bar.sustainPedals,o=Nr.Widths.get(re.KeyboardPedalPed),h=Nr.Widths.get(re.KeyboardPedalUp);let l=0;for(;l<n.length;){let t=n[l];for(;null!=t;){const i=e+this.renderer.getRatioPositionX(t.ratioPosition);let c=0;if(t.pedalType===d.Down?(s.fillMusicFontSymbol(i,a+r,1,re.KeyboardPedalPed,!0),c=o/2+Vl.TextLinePadding):t.pedalType===d.Up&&(s.fillMusicFontSymbol(i,a+r,1,re.KeyboardPedalUp,!0),c=h/2+Vl.StarLinePadding),t.nextPedalMarker)if(t.nextPedalMarker.bar===t.bar){let n=e+this.renderer.getRatioPositionX(t.nextPedalMarker.ratioPosition);switch(t.nextPedalMarker.pedalType){case d.Down:n-=o/2;break;case d.Hold:break;case d.Up:n-=h/2}const l=i+c;n>l&&s.fillRect(l,a+r-1,n-l,1)}else{const t=e+this.x+this.width,n=i+c;s.fillRect(n,a+r-1,t-n,1)}if(0===l&&t.previousPedalMarker){const t=e+this.x,n=i-c;s.fillRect(t,a+r-1,n-t,1)}l++,null!=t.nextPedalMarker&&t.nextPedalMarker.bar!==t.bar?(t=null,l=n.length):t=t.nextPedalMarker}}}}Vl.TextLinePadding=3,Vl.StarLinePadding=3;class Gl extends Jn{get notationElement(){return E.EffectSustainPedal}get hideOnMultiTrack(){return!1}get canShareBand(){return!1}get sizingMode(){return rs.FullBar}shouldCreateGlyph(e,t){return 0===t.voice.index&&0===t.index&&t.voice.bar.sustainPedals.length>0}createNewGlyph(e,t){return new Vl}canExpand(e,t){return!0}}class zl extends Jn{constructor(e,t){super(),this._type=e,this._shouldCreate=t}get notationElement(){return E.EffectGolpe}get hideOnMultiTrack(){return!1}get canShareBand(){return!0}get sizingMode(){return rs.SingleOnBeat}shouldCreateGlyph(e,t){const s=this._shouldCreate;return t.golpe===this._type&&(!s||s(e,t))}createNewGlyph(e,t){return new uh(0,0,!0)}canExpand(e,t){return!1}}class Ul extends xr{constructor(e){super(0,0,1,Ul.getSymbol(e)),this.center=!0}static getSymbol(e){switch(e){case pe.Open:return re.GuitarOpenPedal;case pe.Closed:return re.GuitarClosePedal}return re.None}paint(e,t,s){super.paint(e,t+this.height,s)}}class Xl extends Jn{get notationElement(){return E.EffectWahPedal}get hideOnMultiTrack(){return!1}get canShareBand(){return!0}get sizingMode(){return rs.SingleOnBeat}shouldCreateGlyph(e,t){return t.wahPedal!==pe.None}createNewGlyph(e,t){return new Ul(t.wahPedal)}canExpand(e,t){return!1}}class Jl extends Jn{get notationElement(){return E.EffectLetRing}get canShareBand(){return!1}get hideOnMultiTrack(){return!1}shouldCreateGlyph(e,t){return t.isBarre}get sizingMode(){return rs.GroupedOnBeat}createNewGlyph(e,t){let s="";switch(t.barreShape){case ge.None:case ge.Full:break;case ge.Half:s+="1/2"}return s+=`B ${Jl.toRoman(t.barreFret)}`,new oo(s,!1)}static toRoman(e){let t="";if(e>0)for(const[s,i]of Jl.RomanLetters){const a=Math.floor(e/i);e-=a*i,t+=s.repeat(a)}return t}canExpand(e,t){return e.barreFret===t.barreFret&&e.barreShape===t.barreShape}}Jl.RomanLetters=new Map([["L",50],["XL",40],["X",10],["IX",9],["V",5],["IV",4],["I",1]]);class Yl extends xr{constructor(e){super(0,0,1,Yl.getSymbol(e)),this.center=!0}static getSymbol(e){switch(e){case he.InvertedTurn:return re.OrnamentTurnInverted;case he.Turn:return re.OrnamentTurn;case he.UpperMordent:return re.OrnamentShortTrill;case he.LowerMordent:return re.OrnamentMordent}return re.None}paint(e,t,s){super.paint(e,t+this.height-4,s)}}class $l extends Jn{get notationElement(){return E.EffectNoteOrnament}get hideOnMultiTrack(){return!1}get canShareBand(){return!0}get sizingMode(){return rs.SingleOnBeat}shouldCreateGlyph(e,t){return t.notes.some((e=>e.ornament!==he.None))}createNewGlyph(e,t){return new Yl(t.notes.find((e=>e.ornament!==he.None)).ornament)}canExpand(e,t){return!1}}class ql extends Jn{get notationElement(){return E.EffectRasgueado}get canShareBand(){return!1}get hideOnMultiTrack(){return!1}shouldCreateGlyph(e,t){return t.hasRasgueado}get sizingMode(){return rs.GroupedOnBeat}createNewGlyph(e,t){return new oo("rasg.")}canExpand(e,t){return!0}}class jl extends kr{constructor(e){super(0,0),this._symbols=e}doLayout(){this.height=27}paint(e,t,s){s.fillMusicFontSymbols(e+this.x,t+this.y+this.height,.8,this._symbols,!0)}}class Kl extends kr{constructor(e){super(0,0),this._text=e}doLayout(){this.height=1.5*this.renderer.resources.directionsFont.size}paint(e,t,s){const i=s.font,a=s.textBaseline,r=s.textAlign;s.font=this.renderer.resources.directionsFont,s.textBaseline=oe.Middle,s.textAlign=ne.Right,s.fillText(this._text,e+this.x,t+this.y+this.height/2),s.font=i,s.textBaseline=a,s.textAlign=r}}class Ql extends Tr{constructor(e,t,s){super(e,t),this._barBeginGlyphs=[],this._barEndGlyphs=[],this._directions=s}doLayout(){const e=this._directions;e.has(Be.TargetSegnoSegno)&&this._barBeginGlyphs.push(new jl([re.Segno,re.Segno])),e.has(Be.TargetSegno)&&this._barBeginGlyphs.push(new jl([re.Segno])),e.has(Be.TargetDoubleCoda)&&this._barBeginGlyphs.push(new jl([re.Coda,re.Coda])),e.has(Be.TargetCoda)&&this._barBeginGlyphs.push(new jl([re.Coda])),e.has(Be.TargetFine)&&this._barEndGlyphs.push(new Kl("Fine")),e.has(Be.JumpDaDoubleCoda)&&this._barEndGlyphs.push(new Kl("To Double Coda")),e.has(Be.JumpDaCoda)&&this._barEndGlyphs.push(new Kl("To Coda")),e.has(Be.JumpDalSegnoSegno)&&this._barEndGlyphs.push(new Kl("D.S.S.")),e.has(Be.JumpDalSegnoSegnoAlCoda)&&this._barEndGlyphs.push(new Kl("D.S.S. al Coda")),e.has(Be.JumpDalSegnoSegnoAlDoubleCoda)&&this._barEndGlyphs.push(new Kl("D.S.S. al Double Coda")),e.has(Be.JumpDalSegnoSegnoAlFine)&&this._barEndGlyphs.push(new Kl("D.S.S. al Fine")),e.has(Be.JumpDalSegno)&&this._barEndGlyphs.push(new Kl("D.S.")),e.has(Be.JumpDalSegnoAlCoda)&&this._barEndGlyphs.push(new Kl("D.S. al Coda")),e.has(Be.JumpDalSegnoAlDoubleCoda)&&this._barEndGlyphs.push(new Kl("D.S. al Double Coda")),e.has(Be.JumpDalSegnoAlFine)&&this._barEndGlyphs.push(new Kl("D.S. al Fine")),e.has(Be.JumpDaCapo)&&this._barEndGlyphs.push(new Kl("D.C.")),e.has(Be.JumpDaCapoAlCoda)&&this._barEndGlyphs.push(new Kl("D.C. al Coda")),e.has(Be.JumpDaCapoAlDoubleCoda)&&this._barEndGlyphs.push(new Kl("D.C. al Double Coda")),e.has(Be.JumpDaCapoAlFine)&&this._barEndGlyphs.push(new Kl("D.C. al Fine"));const t=this.doSideLayout(this._barBeginGlyphs),s=this.doSideLayout(this._barEndGlyphs);this.height=Math.max(t,s)}doSideLayout(e){let t=0;for(const s of e)s.y=t,s.renderer=this.renderer,s.doLayout(),t+=s.height+3;return t}paint(e,t,s){for(const i of this._barBeginGlyphs)i.paint(e+this.x,t+this.y,s);for(const i of this._barEndGlyphs)i.paint(e+this.x+this.width,t+this.y,s)}}class Zl extends Jn{get notationElement(){return E.EffectDirections}get hideOnMultiTrack(){return!0}get canShareBand(){return!1}get sizingMode(){return rs.FullBar}shouldCreateGlyph(e,t){return 0===t.voice.index&&0===t.index&&null!==t.voice.bar.masterBar.directions&&t.voice.bar.masterBar.directions.size>0}createNewGlyph(e,t){return new Ql(0,0,t.voice.bar.masterBar.directions)}canExpand(e,t){return!0}}class ec extends Tr{constructor(e){super(0,0),this._text="",this._textWidth=0,this._textHeight=0,this._timer=e}doLayout(){const e=this._timer/6e4|0,t=(this._timer-6e4*e)/1e3|0;this._text=`${e}:${t.toString().padStart(2,"0")}`;const s=this.renderer.scoreRenderer.canvas;s.font=this.renderer.resources.timerFont;const i=s.measureText(this._text);this._textHeight=s.font.size+2*ec.PaddingY,this._textWidth=i.width+2*ec.PaddingX,this.height=this._textHeight+2*ec.MarginY}paint(e,t,s){const i=this._textWidth/2|0;s.strokeRect(e+this.x-i,t+this.y+ec.MarginY,this._textWidth,this._textHeight);const a=s.font,r=s.textBaseline,n=s.textAlign;s.font=this.renderer.resources.timerFont,s.textBaseline=oe.Middle,s.textAlign=ne.Center,s.fillText(this._text,e+this.x,t+this.y+this.height/2),s.font=a,s.textBaseline=r,s.textAlign=n}}ec.PaddingX=2,ec.PaddingY=2,ec.MarginY=2;class tc extends Jn{get notationElement(){return E.EffectBeatTimer}get hideOnMultiTrack(){return!0}get canShareBand(){return!0}get sizingMode(){return rs.SingleOnBeat}shouldCreateGlyph(e,t){return t.showTimer}createNewGlyph(e,t){return new ec(t.timer??0)}canExpand(e,t){return!0}}class sc{static print(e){e(`alphaTab ${sc.version}`),e(`commit: ${sc.commit}`),e(`build date: ${sc.date}`)}}sc.version="1.6.0-alpha.1399",sc.date="2025-05-06T02:05:53.707Z",sc.commit="b35f0f77c217a628a19f8346512c00d14c9ee778";class ic{constructor(e,t){this.vertical=e,this.createLayout=t}}class ac{constructor(e,t){this.supportsWorkers=e,this.createCanvas=t}}class rc{static createStyleElement(e,t){let s=e.getElementById("alphaTabStyle");if(!s){if(!t)return void q.error("AlphaTab","Font directory could not be detected, cannot create style element");s=e.createElement("style"),s.id="alphaTabStyle";const i=`\n @font-face {\n font-display: block;\n font-family: 'alphaTab';\n src: url('${t}Bravura.eot');\n src: url('${t}Bravura.eot?#iefix') format('embedded-opentype')\n , url('${t}Bravura.woff') format('woff')\n , url('${t}Bravura.otf') format('opentype')\n , url('${t}Bravura.svg#Bravura') format('svg');\n font-weight: normal;\n font-style: normal;\n }\n .at-surface * {\n cursor: default;\n vertical-align: top;\n overflow: visible;\n }\n .at-surface-svg text {\n dominant-baseline: central;\n white-space:pre;\n }\n .at {\n font-family: 'alphaTab';\n speak: none;\n font-style: normal;\n font-weight: normal;\n font-variant: normal;\n text-transform: none;\n line-height: 1;\n line-height: 1;\n -webkit-font-smoothing: antialiased;\n -moz-osx-font-smoothing: grayscale;\n font-size: ${rc.MusicFontSize}px;\n overflow: visible !important;\n }`;s.innerHTML=i,e.getElementsByTagName("head").item(0).appendChild(s),rc.bravuraFontChecker.checkForFontAvailability()}}static get globalThis(){if(void 0===rc._globalThis){try{rc._globalThis=globalThis}catch(e){}void 0===rc._globalThis&&(rc._globalThis=self),void 0===rc._globalThis&&(rc._globalThis=global),void 0===rc._globalThis&&(rc._globalThis=window),void 0===rc._globalThis&&(rc._globalThis=Function("return this")())}return rc._globalThis}static get isRunningInWorker(){return"WorkerGlobalScope"in rc.globalThis}static get isRunningInAudioWorklet(){return"AudioWorkletGlobalScope"in rc.globalThis}static throttle(e,t){let s=0;return()=>{rc.globalThis.clearTimeout(s),s=rc.globalThis.setTimeout(e,t)}}static detectScriptFile(){if(!rc.isRunningInWorker&&rc.globalThis.ALPHATAB_ROOT){let e=rc.globalThis.ALPHATAB_ROOT;return e=rc.ensureFullUrl(e),e=rc.appendScriptName(e),e}try{const e=import.meta.url;if(e&&-1===e.indexOf("file://"))return e}catch(e){}return"document"in rc.globalThis&&document.currentScript?document.currentScript.src:null}static ensureFullUrl(e){if(!e)return"";if(!e.startsWith("http")&&!e.startsWith("https")&&!e.startsWith("file")){let t="";const s=rc.globalThis.location;if(t+=s.protocol?.toString(),t+="//"?.toString(),s.hostname&&(t+=s.hostname?.toString()),s.port&&(t+=":"?.toString(),t+=s.port?.toString()),!e.startsWith("/")){const e=s.pathname.split("/").slice(0,-1).join("/");e.length>0&&(e.startsWith("/")||(t+="/"?.toString()),t+=e?.toString())}return e.startsWith("/")||(t+="/"?.toString()),t+=e?.toString(),t}return e}static appendScriptName(e){return e&&!e.endsWith(".js")&&(e.endsWith("/")||(e+="/"),e+="alphaTab.js"),e}static detectFontDirectory(){if(!rc.isRunningInWorker&&rc.globalThis.ALPHATAB_FONT)return rc.ensureFullUrl(rc.globalThis.ALPHATAB_FONT);const e=rc.scriptFile;if(e){const t=e.lastIndexOf(String.fromCharCode(47));if(t>=0)return`${e.substr(0,t)}/font/`}return null}static registerJQueryPlugin(){if(!rc.isRunningInWorker&&rc.globalThis&&"jQuery"in rc.globalThis){const e=rc.globalThis.jQuery,t=new Qr;e.fn.alphaTab=function(e){const s=Array.prototype.slice.call(arguments,1);return 1===this.length?t.exec(this[0],e,s):this.each(((i,a)=>{t.exec(a,e,s)}))},e.alphaTab={restore:Qr.restore},e.fn.alphaTab.fn=t}}static getRenderEngineFactory(e){return e&&rc.renderEngines.has(e)?rc.renderEngines.get(e):rc.renderEngines.get("default")}static getLayoutEngineFactory(t){return t&&rc.layoutEngines.has(t)?rc.layoutEngines.get(t):rc.layoutEngines.get(e.Page)}static buildImporters(){return[new ut,new _s,new ms,new xs,new Sl,new dt]}static createDefaultRenderEngines(){const e=new Map;return e.set("svg",new ac(!0,(()=>new en))),e.set("default",e.get("svg")),e.set("skia",new ac(!1,(()=>new kl))),rc.createPlatformSpecificRenderEngines(e),e}static enableAlphaSkia(e,t){kl.enable(e,t)}static registerAlphaSkiaCustomFont(e){return kl.registerFont(e)}static createPlatformSpecificRenderEngines(e){e.set("html5",new ac(!1,(()=>new hr)))}static createDefaultRenderers(){return[new Un(rc.StaffIdBeforeSlashAlways,[new xo,new Do,new po,new Zl,new Yn,new Wl,new vo,new tc,new qn]),new Fl,new Un(rc.StaffIdBeforeScoreAlways,[new ao,new Jl,new $l,new ql,new Xl]),new Un(rc.StaffIdBeforeScoreHideable,[new Eo,new Fo,new mo(!0),new Lo,new wo,new Mo,new ko(!1),new al,new zl(de.Finger)],((e,t)=>t.showStandardNotation)),new Gh,new Un(rc.StaffIdBeforeNumberedAlways,[new Qn,new mo(!1),new eo,new zl(de.Thumb,((e,t)=>t.voice.bar.staff.showStandardNotation)),new Gl]),new Hl,new Un(rc.StaffIdBeforeTabAlways,[new uo]),new Un(rc.StaffIdBeforeTabHideable,[new Fo,new Lo,new wo,new Mo,new ko(!0),new To,new so,new ho(T.Natural),new ho(T.Artificial),new ho(T.Pinch),new ho(T.Tap),new ho(T.Semi),new ho(T.Feedback),new lo,new $n,new ro,new fo,new So,new yo,new al,new zl(de.Finger,((e,t)=>!t.voice.bar.staff.showStandardNotation))],((e,t)=>t.showTablature)),new sl,new Un(rc.StaffIdBeforeEndAlways,[new zl(de.Thumb,((e,t)=>!t.voice.bar.staff.showStandardNotation))])]}static createDefaultStaveProfiles(){const e=new Map,s=rc.createDefaultRenderers();e.set(t.Default,s),e.set(t.ScoreTab,s);const i=new Set([rc.StaffIdBeforeSlashAlways,rc.StaffIdBeforeScoreAlways,rc.StaffIdBeforeNumberedAlways,rc.StaffIdBeforeTabAlways,Vh.StaffId,rc.StaffIdBeforeEndAlways]);e.set(t.Score,s.filter((e=>i.has(e.staffId))));const a=new Set([rc.StaffIdBeforeSlashAlways,rc.StaffIdBeforeScoreAlways,rc.StaffIdBeforeNumberedAlways,rc.StaffIdBeforeTabAlways,tl.StaffId,rc.StaffIdBeforeEndAlways]);return e.set(t.Tab,rc.createDefaultRenderers().filter((e=>{if(e instanceof sl){const t=e;t.showTimeSignature=!0,t.showRests=!0,t.showTiedNotes=!0}return a.has(e.staffId)}))),e.set(t.TabMixed,rc.createDefaultRenderers().filter((e=>{if(e instanceof sl){const t=e;t.showTimeSignature=!1,t.showRests=!1,t.showTiedNotes=!1}return a.has(e.staffId)}))),e}static createDefaultLayoutEngines(){const t=new Map;return t.set(e.Page,new ic(!0,(e=>new Ro(e)))),t.set(e.Horizontal,new ic(!1,(e=>new Ao(e)))),t}static initializeMain(e,t){rc.isRunningInWorker||rc.isRunningInAudioWorklet||(rc.webPlatform!==Kt.Browser&&rc.webPlatform!==Kt.BrowserModule||(rc.registerJQueryPlugin(),rc.HighDpiFactor=window.devicePixelRatio,"ResizeObserver"in rc.globalThis||(rc.globalThis.ResizeObserver=_l),"IntersectionObserver"in rc.globalThis||(rc.globalThis.IntersectionObserver=wl),"replaceChildren"in Element.prototype||(Element.prototype.replaceChildren=function(...e){this.innerHTML="",this.append(...e)},Document.prototype.replaceChildren=Element.prototype.replaceChildren,DocumentFragment.prototype.replaceChildren=Element.prototype.replaceChildren),"replaceAll"in String.prototype||(String.prototype.replaceAll=function(e,t){return this.replace(new RegExp(e,"g"),t)})),rc.createWebWorker=e,rc.createAudioWorklet=t)}static get alphaTabWorker(){return rc.globalThis.Worker}static get alphaTabUrl(){return rc.globalThis.URL}static initializeWorker(){if(!rc.isRunningInWorker)throw new $e(Se.General,"Not running in worker, cannot run worker initialization");or.init(),ja.init(),rc.createWebWorker=e=>{throw new $e(Se.General,"Nested workers are not supported")}}static initializeAudioWorklet(){if(!rc.isRunningInAudioWorklet)throw new $e(Se.General,"Not running in audio worklet, cannot run worklet initialization");Yr.init()}static detectWebPack(){try{if("function"==typeof __webpack_require__)return!0}catch(e){}return!1}static detectVite(){try{if("string"==typeof __BASE__)return!0}catch(e){}return!1}static detectWebPlatform(){try{if("[object process]"===Object.prototype.toString.call("undefined"!=typeof process?process:0))return Kt.NodeJs}catch(e){}try{const e=import.meta.url;if(e&&"string"==typeof e&&!e.startsWith("file://"))return Kt.BrowserModule}catch(e){}return Kt.Browser}static printEnvironmentInfo(e=!0){const t=e?e=>{q.log.debug("VersionInfo",e)}:e=>{q.debug("VersionInfo",e)};sc.print(t),t(`High DPI: ${rc.HighDpiFactor}`),rc.printPlatformInfo(t)}static printPlatformInfo(e){e(`Browser: ${navigator.userAgent}`),e(`Platform: ${Kt[rc.webPlatform]}`),e(`WebPack: ${rc.isWebPackBundled}`),e(`Vite: ${rc.isViteBundled}`),rc.webPlatform!==Kt.NodeJs&&(e(`Window Size: ${window.outerWidth}x${window.outerHeight}`),e(`Screen Size: ${window.screen.width}x${window.screen.height}`))}}rc.StaffIdBeforeSlashAlways="before-slash-always",rc.StaffIdBeforeScoreAlways="before-score-always",rc.StaffIdBeforeScoreHideable="before-score-hideable",rc.StaffIdBeforeNumberedAlways="before-numbered-always",rc.StaffIdBeforeTabAlways="before-tab-always",rc.StaffIdBeforeTabHideable="before-tab-hideable",rc.StaffIdBeforeEndAlways="before-end-always",rc.MusicFontSize=34,rc.HighDpiFactor=1,rc._globalThis=void 0,rc.webPlatform=rc.detectWebPlatform(),rc.isWebPackBundled=rc.detectWebPack(),rc.isViteBundled=rc.detectVite(),rc.scriptFile=rc.detectScriptFile(),rc.fontDirectory=rc.detectFontDirectory(),rc.bravuraFontChecker=new Or(["alphaTab"]),rc.renderEngines=rc.createDefaultRenderEngines(),rc.layoutEngines=rc.createDefaultLayoutEngines(),rc.staveProfiles=rc.createDefaultStaveProfiles();class nc{constructor(){this.scriptFile=null,this.fontDirectory=null,this.file=null,this.tex=!1,this.tracks=null,this.enableLazyLoading=!0,this.engine="default",this.logLevel=L.Info,this.useWorkers=!0,this.includeNoteBounds=!1,this.scriptFile=rc.scriptFile,this.fontDirectory=rc.fontDirectory}}const oc=Object.freeze(Object.defineProperty({__proto__:null,ScoreImporter:Ye,ScoreLoader:Ir,UnsupportedFormatError:qe},Symbol.toStringTag,{value:"Module"})),hc=Object.freeze(Object.defineProperty({__proto__:null,ByteBuffer:ht,IOHelper:ot},Symbol.toStringTag,{value:"Module"}));class lc{init(e,t){this.data=e,this.settings=t}export(e,t=null){const s=ht.withCapacity(1024);return this.init(s,t??new Ba),this.writeScore(e),s.toArray()}}var cc;!function(e){e[e.SteelGuitar=1]="SteelGuitar",e[e.AcousticGuitar=2]="AcousticGuitar",e[e.TwelveStringGuitar=3]="TwelveStringGuitar",e[e.ElectricGuitar=4]="ElectricGuitar",e[e.Bass=5]="Bass",e[e.ClassicalGuitar=23]="ClassicalGuitar",e[e.UprightBass=6]="UprightBass",e[e.Ukulele=7]="Ukulele",e[e.Banjo=8]="Banjo",e[e.Mandolin=9]="Mandolin",e[e.Piano=10]="Piano",e[e.Synth=12]="Synth",e[e.Strings=11]="Strings",e[e.Brass=13]="Brass",e[e.Reed=14]="Reed",e[e.Woodwind=15]="Woodwind",e[e.Vocal=16]="Vocal",e[e.PitchedIdiophone=17]="PitchedIdiophone",e[e.Fx=21]="Fx",e[e.PercussionKit=18]="PercussionKit",e[e.Idiophone=19]="Idiophone",e[e.Membraphone=20]="Membraphone"}(cc||(cc={}));class dc{constructor(e,t,s=null){if(this.icon=cc.Piano,this.icon=e,this.instrumentSetName=t,s)this.instrumentSetType=s;else{const e=t.split(" ");e[0]=e[0].substr(0,1).toLowerCase()+e[0].substr(1),this.instrumentSetType=e.join("")}}}class uc{constructor(){this._rhythmIdLookup=new Map}writeXml(e){const t=new wt;return this._rhythmIdLookup=new Map,this.writeDom(t,e),t.toFormattedString("",!0)}writeDom(e,t){const s=e.addElement("GPIF");s.addElement("GPVersion").innerText="7";const i=s.addElement("GPRevision");i.innerText="7",i.attributes.set("required","12021"),i.attributes.set("recommended","12023"),i.innerText="12025",s.addElement("Encoding").addElement("EncodingDescription").innerText="GP7",this.writeScoreNode(s,t),this.writeMasterTrackNode(s,t),this.writeAudioTracksNode(s,t),this.writeTracksNode(s,t),this.writeMasterBarsNode(s,t);const a=s.addElement("Bars"),r=s.addElement("Voices"),n=s.addElement("Beats"),o=s.addElement("Notes"),h=s.addElement("Rhythms");for(const e of t.tracks)for(const t of e.staves)for(const e of t.bars){this.writeBarNode(a,e);for(const t of e.voices){this.writeVoiceNode(r,t);for(const e of t.beats){this.writeBeatNode(n,e,h);for(const t of e.notes)this.writeNoteNode(o,t)}}}}writeNoteNode(e,t){const s=e.addElement("Note");s.attributes.set("id",t.id.toString()),this.writeNoteProperties(s,t),t.isGhost&&(s.addElement("AntiAccent").innerText="normal"),t.isLetRing&&s.addElement("LetRing"),t.isTrill&&(s.addElement("Trill").innerText=t.trillValue.toString());let i=0;switch(t.isStaccato&&(i|=1),t.accentuated){case B.Normal:i|=8;break;case B.Heavy:i|=4;break;case B.Tenuto:i|=16}if(i>0&&(s.addElement("Accent").innerText=i.toString()),t.isTieOrigin||t.isTieDestination){const e=s.addElement("Tie");e.attributes.set("origin",t.isTieOrigin?"true":"false"),e.attributes.set("destination",t.isTieDestination?"true":"false")}switch(t.vibrato){case P.Slight:s.addElement("Vibrato").innerText="Slight";break;case P.Wide:s.addElement("Vibrato").innerText="Wide"}if(t.isFingering){switch(t.leftHandFinger){case k.Thumb:s.addElement("LeftFingering").innerText="P";break;case k.IndexFinger:s.addElement("LeftFingering").innerText="I";break;case k.MiddleFinger:s.addElement("LeftFingering").innerText="M";break;case k.AnnularFinger:s.addElement("LeftFingering").innerText="A";break;case k.LittleFinger:s.addElement("LeftFingering").innerText="C"}switch(t.rightHandFinger){case k.Thumb:s.addElement("RightFingering").innerText="P";break;case k.IndexFinger:s.addElement("RightFingering").innerText="I";break;case k.MiddleFinger:s.addElement("RightFingering").innerText="M";break;case k.AnnularFinger:s.addElement("RightFingering").innerText="A";break;case k.LittleFinger:s.addElement("RightFingering").innerText="C"}}t.percussionArticulation>=0?s.addElement("InstrumentArticulation").innerText=t.percussionArticulation.toString():s.addElement("InstrumentArticulation").innerText="0",t.ornament!==he.None&&(s.addElement("Ornament").innerText=he[t.ornament])}writeNoteProperties(e,t){const s=e.addElement("Properties");if(this.writeConcertPitch(s,t),this.writeTransposedPitch(s,t),t.isStringed&&(this.writeSimplePropertyNode(s,"String","String",(t.string-1).toString()),this.writeSimplePropertyNode(s,"Fret","Fret",t.fret.toString()),this.writeSimplePropertyNode(s,"Midi","Number",t.realValue.toString()),t.showStringNumber&&this.writeSimplePropertyNode(s,"ShowStringNumber","Enable",null)),t.isPiano&&(this.writeSimplePropertyNode(s,"Octave","Number",t.octave.toString()),this.writeSimplePropertyNode(s,"Tone","Step",t.tone.toString()),this.writeSimplePropertyNode(s,"Midi","Number",t.realValue.toString())),t.beat.tap&&this.writeSimplePropertyNode(s,"Tapped","Enable",null),t.harmonicType!==T.None){switch(t.harmonicType){case T.Natural:this.writeSimplePropertyNode(s,"HarmonicType","HType","Natural");break;case T.Artificial:this.writeSimplePropertyNode(s,"HarmonicType","HType","Artificial");break;case T.Pinch:this.writeSimplePropertyNode(s,"HarmonicType","HType","Pinch");break;case T.Tap:this.writeSimplePropertyNode(s,"HarmonicType","HType","Tap");break;case T.Semi:this.writeSimplePropertyNode(s,"HarmonicType","HType","Semi");break;case T.Feedback:this.writeSimplePropertyNode(s,"HarmonicType","HType","Feedback")}0!==t.harmonicValue&&this.writeSimplePropertyNode(s,"HarmonicFret","HFret",t.harmonicValue.toString())}t.isDead&&this.writeSimplePropertyNode(s,"Muted","Enable",null),t.isPalmMute&&this.writeSimplePropertyNode(s,"PalmMuted","Enable",null),t.hasBend&&this.writeBend(s,t),t.isHammerPullOrigin&&this.writeSimplePropertyNode(s,"HopoOrigin","Enable",null),t.isHammerPullDestination&&this.writeSimplePropertyNode(s,"HopoDestination","Enable",null),t.isLeftHandTapped&&this.writeSimplePropertyNode(s,"LeftHandTapped","Enable",null);let i=0;switch(t.slideInType){case x.IntoFromAbove:i|=32;break;case x.IntoFromBelow:i|=16}switch(t.slideOutType){case v.Shift:i|=1;break;case v.Legato:i|=2;break;case v.OutDown:i|=4;break;case v.OutUp:i|=8;break;case v.PickSlideDown:i|=64;break;case v.PickSlideUp:i|=128}i>0&&this.writeSimplePropertyNode(s,"Slide","Flags",i.toString())}writeTransposedPitch(e,t){t.isPercussion?this.writePitch(e,"ConcertPitch","C","-1",""):this.writePitchForValue(e,"TransposedPitch",t.displayValueWithoutBend,t.accidentalMode)}writeConcertPitch(e,t){t.isPercussion?this.writePitch(e,"ConcertPitch","C","-1",""):this.writePitchForValue(e,"ConcertPitch",t.realValueWithoutHarmonic,t.accidentalMode)}writePitchForValue(e,t,s,i){let a=0,r=0,n="",o="";const h=()=>{a=s%12,r=s/12|0,n=st.defaultSteps[a],o=st.defaultAccidentals[a]};switch(h(),i){case N.Default:break;case N.ForceNone:case N.ForceNatural:o="";break;case N.ForceSharp:o="#";break;case N.ForceDoubleSharp:"#"===o&&(s-=2,h()),o="x";break;case N.ForceFlat:"#"===o&&(s+=1,h()),o="b";break;case N.ForceDoubleFlat:"#"===o&&(s+=2,h()),o="bb"}this.writePitch(e,t,n,r.toString(),o)}writePitch(e,t,s,i,a){const r=e.addElement("Property");r.attributes.set("name",t);const n=r.addElement("Pitch");n.addElement("Step").innerText=s,n.addElement("Accidental").innerText=a,n.addElement("Octave").innerText=i}writeBend(e,t){t.hasBend&&t.bendPoints.length<=4&&this.writeStandardBend(e,t.bendPoints)}writeStandardBend(e,t){this.writeSimplePropertyNode(e,"Bended","Enable",null);const s=t[0],i=t[t.length-1];let a,r;switch(t.length){case 4:a=t[1],r=t[2];break;case 3:a=t[1],r=t[1];break;default:a=new X((s.offset+i.offset)/2,(s.value+i.value)/2),r=a}this.writeSimplePropertyNode(e,"BendDestinationOffset","Float",this.toBendOffset(i.offset).toString()),this.writeSimplePropertyNode(e,"BendDestinationValue","Float",this.toBendValue(i.value).toString()),this.writeSimplePropertyNode(e,"BendMiddleOffset1","Float",this.toBendOffset(a.offset).toString()),this.writeSimplePropertyNode(e,"BendMiddleOffset2","Float",this.toBendOffset(r.offset).toString()),this.writeSimplePropertyNode(e,"BendMiddleValue","Float",this.toBendValue(a.value).toString()),this.writeSimplePropertyNode(e,"BendOriginOffset","Float",this.toBendOffset(s.offset).toString()),this.writeSimplePropertyNode(e,"BendOriginValue","Float",this.toBendValue(s.value).toString())}toBendValue(e){return 25*e}toBendOffset(e){return e/X.MaxPosition*100}writeBeatNode(e,t,s){const i=e.addElement("Beat");if(i.attributes.set("id",t.id.toString()),i.addElement("Dynamic").innerText=g[t.dynamics],t.fade!==ue.None&&(i.addElement("Fadding").innerText=ue[t.fade]),t.isTremolo)switch(t.tremoloSpeed){case _.Eighth:i.addElement("Tremolo").innerText="1/2";break;case _.Sixteenth:i.addElement("Tremolo").innerText="1/4";break;case _.ThirtySecond:i.addElement("Tremolo").innerText="1/8"}switch(t.hasChord&&i.addElement("Chord").setCData(t.chordId),t.crescendo!==S.None&&(i.addElement("Hairpin").innerText=S[t.crescendo]),t.brushType){case b.ArpeggioUp:i.addElement("Arpeggio").innerText="Up";break;case b.ArpeggioDown:i.addElement("Arpeggio").innerText="Down"}switch(t.text&&i.addElement("FreeText").setCData(t.text),t.graceType){case w.OnBeat:case w.BeforeBeat:i.addElement("GraceNotes").innerText=w[t.graceType]}if(t.ottava!==o.Regular&&(i.addElement("Ottavia").innerText=o[t.ottava].substr(1)),t.hasWhammyBar&&this.writeWhammyNode(i,t),t.isLegatoOrigin||t.isLegatoDestination){const e=i.addElement("Legato");e.attributes.set("origin",t.isLegatoOrigin?"true":"false"),e.attributes.set("destination",t.isLegatoDestination?"true":"false")}if(this.writeRhythm(i,t,s),null!==t.preferredBeamDirection)switch(t.preferredBeamDirection){case Te.Up:i.addElement("TransposedPitchStemOrientation").innerText="Upward",i.addElement("UserTransposedPitchStemOrientation").innerText="Upward";break;case Te.Down:i.addElement("TransposedPitchStemOrientation").innerText="Downward",i.addElement("UserTransposedPitchStemOrientation").innerText="Downward"}i.addElement("ConcertPitchStemOrientation").innerText="Undefined",t.slashed&&i.addElement("Slashed"),t.deadSlapped&&i.addElement("DeadSlapped"),t.notes.length>0&&(i.addElement("Notes").innerText=t.notes.map((e=>e.id)).join(" ")),t.golpe!==de.None&&(i.addElement("Golpe").innerText=de[t.golpe]),t.wahPedal!==pe.None&&(i.addElement("Wah").innerText=pe[t.wahPedal]),t.showTimer&&(i.addElement("Timer").innerText=(t.timer??0).toString()),this.writeBeatProperties(i,t),this.writeBeatXProperties(i,t),t.lyrics&&t.lyrics.length>0&&this.writeBeatLyrics(i,t.lyrics)}writeBeatLyrics(e,t){const s=e.addElement("Lyrics");for(const e of t){s.addElement("Line").setCData(e)}}writeBeatXProperties(e,t){const s=e.addElement("XProperties");switch(t.brushDuration>0&&this.writeSimpleXPropertyNode(s,"687935489","Int",t.brushDuration.toString()),t.beamingMode){case fe.ForceSplitToNext:this.writeSimpleXPropertyNode(s,"1124204546","Int","2");break;case fe.ForceMergeWithNext:this.writeSimpleXPropertyNode(s,"1124204546","Int","1");break;case fe.ForceSplitOnSecondaryToNext:this.writeSimpleXPropertyNode(s,"1124204552","Int","1")}}writeBeatProperties(e,t){const s=e.addElement("Properties");switch(t.brushType){case b.BrushUp:this.writeSimplePropertyNode(s,"Brush","Direction","Up");break;case b.BrushDown:this.writeSimplePropertyNode(s,"Brush","Direction","Down")}switch(t.pickStroke){case ae.Up:this.writeSimplePropertyNode(s,"PickStroke","Direction","Up");break;case ae.Down:this.writeSimplePropertyNode(s,"PickStroke","Direction","Down")}switch(t.slap&&this.writeSimplePropertyNode(s,"Slapped","Enable",null),t.pop&&this.writeSimplePropertyNode(s,"Popped","Enable",null),t.vibrato){case P.Wide:this.writeSimplePropertyNode(s,"VibratoWTremBar","Strength","Wide");break;case P.Slight:this.writeSimplePropertyNode(s,"VibratoWTremBar","Strength","Slight")}if(t.isBarre)switch(this.writeSimplePropertyNode(s,"BarreFret","Fret",t.barreFret.toString()),t.barreShape){case ge.Full:this.writeSimplePropertyNode(s,"BarreString","String","0");break;case ge.Half:this.writeSimplePropertyNode(s,"BarreString","String","1")}if(t.rasgueado!==me.None){let e="";switch(t.rasgueado){case me.Ii:e="ii_1";break;case me.Mi:e="mi_1";break;case me.MiiTriplet:e="mii_1";break;case me.MiiAnapaest:e="mii_2";break;case me.PmpTriplet:e="pmp_1";break;case me.PmpAnapaest:e="pmp_2";break;case me.PeiTriplet:e="pei_1";break;case me.PeiAnapaest:e="pei_2";break;case me.PaiTriplet:e="pai_1";break;case me.PaiAnapaest:e="pai_2";break;case me.AmiTriplet:e="ami_1";break;case me.AmiAnapaest:e="ami_2";break;case me.Ppp:e="ppp_1";break;case me.Amii:e="amii_1";break;case me.Amip:e="amip_1";break;case me.Eami:e="eami_1";break;case me.Eamii:e="eamii_1";break;case me.Peami:e="peami_1"}this.writeSimplePropertyNode(s,"Rasgueado","Rasgueado",e)}}writeRhythm(e,t,s){const i=`${t.duration}_${t.dots}_${t.tupletNumerator}_${t.tupletDenominator}';`;let a;if(this._rhythmIdLookup.has(i))a=this._rhythmIdLookup.get(i);else{a=this._rhythmIdLookup.size.toString(),this._rhythmIdLookup.set(i,a);const e=s.addElement("Rhythm");if(e.attributes.set("id",a),t.hasTuplet){const s=e.addElement("PrimaryTuplet");s.attributes.set("num",t.tupletNumerator.toString()),s.attributes.set("den",t.tupletDenominator.toString())}t.dots>0&&e.addElement("AugmentationDot").attributes.set("count",t.dots.toString());let r="Quarter";switch(t.duration){case _.QuadrupleWhole:r="Long";break;case _.DoubleWhole:r="DoubleWhole";break;case _.Whole:r="Whole";break;case _.Half:r="Half";break;case _.Quarter:r="Quarter";break;case _.Eighth:r="Eighth";break;case _.Sixteenth:r="16th";break;case _.ThirtySecond:r="32nd";break;case _.SixtyFourth:r="64th";break;case _.OneHundredTwentyEighth:r="128th";break;case _.TwoHundredFiftySixth:r="256th"}e.addElement("NoteValue").innerText=r}e.addElement("Rhythm").attributes.set("ref",a)}writeWhammyNode(e,t){t.hasWhammyBar&&t.whammyBarPoints.length<=4&&this.writeStandardWhammy(e,t.whammyBarPoints)}writeStandardWhammy(e,t){const s=e.addElement("Whammy"),i=t[0],a=t[t.length-1];let r,n;switch(t.length){case 4:r=t[1],n=t[2];break;case 3:r=t[1],n=t[1];break;default:r=new X((i.offset+a.offset)/2,(i.value+a.value)/2),n=r}s.attributes.set("destinationOffset",this.toBendOffset(a.offset).toString()),s.attributes.set("destinationValue",this.toBendValue(a.value).toString()),s.attributes.set("middleOffset1",this.toBendOffset(r.offset).toString()),s.attributes.set("middleOffset2",this.toBendOffset(n.offset).toString()),s.attributes.set("middleValue",this.toBendValue(r.value).toString()),s.attributes.set("originOffset",this.toBendOffset(i.offset).toString()),s.attributes.set("originValue",this.toBendValue(i.value).toString())}writeScoreNode(e,t){const s=e.addElement("Score");s.addElement("Title").setCData(t.title),s.addElement("SubTitle").setCData(t.subTitle),s.addElement("Artist").setCData(t.artist),s.addElement("Album").setCData(t.album),s.addElement("Words").setCData(t.words),s.addElement("Music").setCData(t.music),s.addElement("WordsAndMusic").setCData(t.words===t.music?t.words:""),s.addElement("Copyright").setCData(t.copyright),s.addElement("Tabber").setCData(t.tab),s.addElement("Instructions").setCData(t.instructions),s.addElement("Notices").setCData(t.notices),s.addElement("FirstPageHeader").setCData(""),s.addElement("FirstPageFooter").setCData(""),s.addElement("PageHeader").setCData(""),s.addElement("PageFooter").setCData(""),s.addElement("ScoreSystemsDefaultLayout").setCData(t.defaultSystemsLayout.toString()),s.addElement("ScoreSystemsLayout").setCData(t.systemsLayout.join(" ")),s.addElement("ScoreZoomPolicy").innerText="Value",s.addElement("ScoreZoom").innerText="1",s.addElement("MultiVoice").innerText="1>"}writeMasterTrackNode(e,t){const s=e.addElement("MasterTrack");s.addElement("Tracks").innerText=t.tracks.map((e=>e.index)).join(" ");const i=s.addElement("Automations");if(t.masterBars.length>0&&t.masterBars[0].isAnacrusis&&s.addElement("Anacrusis"),0===t.masterBars[0].tempoAutomations.length){const e=i.addElement("Automation");e.addElement("Type").innerText="Tempo",e.addElement("Linear").innerText="false",e.addElement("Bar").innerText="0",e.addElement("Position").innerText="0",e.addElement("Visible").innerText="true",e.addElement("Value").innerText=`${t.tempo} 2`,t.tempoLabel&&(e.addElement("Text").innerText=t.tempoLabel)}for(const e of t.masterBars)for(const t of e.tempoAutomations){const s=i.addElement("Automation");s.addElement("Type").innerText="Tempo",s.addElement("Linear").innerText=t.isLinear?"true":"false",s.addElement("Bar").innerText=e.index.toString(),s.addElement("Position").innerText=t.ratioPosition.toString(),s.addElement("Visible").innerText="true",s.addElement("Value").innerText=`${t.value} 2`,t.text&&(s.addElement("Text").innerText=t.text)}}writeAudioTracksNode(e,t){e.addElement("AudioTracks")}writeTracksNode(e,t){const s=e.addElement("Tracks");for(const e of t.tracks)this.writeTrackNode(s,e)}writeTrackNode(e,t){const s=e.addElement("Track");s.attributes.set("id",t.index.toString()),s.addElement("Name").setCData(t.name),s.addElement("ShortName").setCData(t.shortName),s.addElement("Color").innerText=`${t.color.r} ${t.color.g} ${t.color.b}`,s.addElement("SystemsDefautLayout").innerText=t.defaultSystemsLayout.toString(),s.addElement("SystemsLayout").innerText=t.systemsLayout.join(" "),s.addElement("AutoBrush"),s.addElement("PalmMute").innerText="0",s.addElement("PlayingStyle").innerText=A.isGuitar(t.playbackInfo.program)?"StringedPick":"Default",s.addElement("UseOneChannelPerString"),s.addElement("IconId").innerText=uc.getIconId(t.playbackInfo).toString(),this.writeInstrumentSetNode(s,t),this.writeTransposeNode(s,t),this.writeRseNode(s,t),s.addElement("ForcedSound").innerText="-1",this.writeMidiConnectionNode(s,t),t.playbackInfo.isSolo?s.addElement("PlaybackState").innerText="Solo":t.playbackInfo.isMute?s.addElement("PlaybackState").innerText="Mute":s.addElement("PlaybackState").innerText="Default",s.addElement("AudioEngineState").innerText="MIDI",this.writeLyricsNode(s,t),this.writeStavesNode(s,t),this.writeSoundsAndAutomations(s,t)}static getIconId(e){return 9===e.primaryChannel?uc.DrumKitProgramInfo.icon:uc.MidiProgramInfoLookup.has(e.program)?uc.MidiProgramInfoLookup.get(e.program).icon:cc.SteelGuitar}writeSoundAndAutomation(e,t,s,i,a,r,n,o=0){const h=e.addElement("Sound");h.addElement("Name").setCData(s),h.addElement("Label").setCData(s),h.addElement("Path").setCData(i),h.addElement("Role").setCData(a);const l=h.addElement("MIDI");l.addElement("LSB").innerText="0",l.addElement("MSB").innerText="0",l.addElement("Program").innerText=n.toString();const c=t.addElement("Automation");c.addElement("Type").innerText="Sound",c.addElement("Linear").innerText="false",c.addElement("Bar").innerText=r.toString(),c.addElement("Position").innerText=o.toString(),c.addElement("Visible").innerText="true",c.addElement("Value").setCData(`${i};${s};${a}`)}writeSoundsAndAutomations(e,t){const s=e.addElement("Sounds"),i=e.addElement("Automations");if(t.staves.length>0&&t.staves[0].bars.length>0){const e=`Track_${t.index}_Initial`,a=`Midi/${t.playbackInfo.program}`,r="Factory";let n=!1;for(const o of t.staves)for(const h of o.bars)for(const o of h.voices)for(const l of o.beats){const o=l.getAutomation(m.Instrument),c=0===h.index&&0===l.index;if(o){const d=c?e:`ProgramChange_${l.id}`,u=c?a:`Midi/${o.value}`,p=c?r:"User";c||n||(this.writeSoundAndAutomation(s,i,e,a,r,t.staves[0].bars[0].index,t.playbackInfo.program),n=!0),this.writeSoundAndAutomation(s,i,d,u,p,h.index,o.value,o.ratioPosition),c&&(n=!0)}}}for(const e of t.staves)for(const t of e.bars)for(const e of t.sustainPedals)if(e.pedalType!==d.Hold){const s=i.addElement("Automation");switch(s.addElement("Type").innerText="SustainPedal",s.addElement("Linear").innerText="false",s.addElement("Bar").innerText=t.index.toString(),s.addElement("Position").innerText=e.ratioPosition.toString(),s.addElement("Visible").innerText="true",e.pedalType){case d.Down:s.addElement("Value").innerText="0 1";break;case d.Up:s.addElement("Value").innerText="0 3"}}}writeMidiConnectionNode(e,t){const s=e.addElement("MidiConnection");s.addElement("Port").innerText=t.playbackInfo.port.toString(),s.addElement("PrimaryChannel").innerText=t.playbackInfo.primaryChannel.toString(),s.addElement("SecondaryChannel").innerText=t.playbackInfo.secondaryChannel.toString(),s.addElement("ForeOneChannelPerString").innerText="false"}writeRseNode(e,t){const s=e.addElement("RSE").addElement("ChannelStrip");s.attributes.set("version","E56");s.addElement("Parameters").innerText=`0.5 0.5 0.5 0.5 0.5 0.5 0.5 0.5 0.5 1 0.5 ${t.playbackInfo.balance/16} ${t.playbackInfo.volume/16} 0.5 0.5 0.5`}writeStavesNode(e,t){const s=e.addElement("Staves");for(const e of t.staves)this.writeStaffNode(s,e)}writeStaffNode(e,t){const s=e.addElement("Staff").addElement("Properties");if(this.writeSimplePropertyNode(s,"CapoFret","Fret",t.capo.toString()),this.writeSimplePropertyNode(s,"FretCount","Fret","24"),t.tuning.length>0){const e=s.addElement("Property");switch(e.attributes.set("name","Tuning"),e.addElement("Pitches").innerText=t.tuning.slice().reverse().join(" "),e.addElement("Label").setCData(t.tuningName),e.addElement("LabelVisible").innerText=t.tuningName?"true":"false",e.addElement("Flat"),t.tuning.length){case 3:e.addElement("Instrument").innerText="Shamisen";break;case 4:105===t.track.playbackInfo.program?e.addElement("Instrument").innerText="Banjo":42===t.track.playbackInfo.program?e.addElement("Instrument").innerText="Cello":43===t.track.playbackInfo.program?e.addElement("Instrument").innerText="Contrabass":40===t.track.playbackInfo.program?e.addElement("Instrument").innerText="Violin":41===t.track.playbackInfo.program?e.addElement("Instrument").innerText="Viola":e.addElement("Instrument").innerText="Bass";break;case 5:105===t.track.playbackInfo.program?e.addElement("Instrument").innerText="Banjo":e.addElement("Instrument").innerText="Bass";break;case 6:105===t.track.playbackInfo.program?e.addElement("Instrument").innerText="Banjo":t.track.playbackInfo.program<=39?e.addElement("Instrument").innerText="Bass":e.addElement("Instrument").innerText="Guitar";break;case 7:t.track.playbackInfo.program<=39?e.addElement("Instrument").innerText="Bass":e.addElement("Instrument").innerText="Guitar";break;default:e.addElement("Instrument").innerText="Guitar"}}this.writeSimplePropertyNode(s,"PartialCapoFret","Fret","0"),this.writeSimplePropertyNode(s,"PartialCapoStringFlags","Bitset",t.tuning.map((e=>"0")).join("")),this.writeSimplePropertyNode(s,"TuningFlat","Enable",null),this.writeDiagramCollection(s,t,"DiagramCollection"),this.writeDiagramCollection(s,t,"DiagramWorkingSet")}writeDiagramCollection(e,t,s){const i=e.addElement("Property");i.attributes.set("name",s);const a=i.addElement("Items"),r=t.chords;if(r)for(const[e,t]of r){const s=a.addElement("Item");s.attributes.set("id",e),s.attributes.set("name",t.name);const i=s.addElement("Diagram");i.attributes.set("stringCount",t.strings.length.toString()),i.attributes.set("fretCount","5"),i.attributes.set("baseFret",(t.firstFret-1).toString()),i.attributes.set("barStates",t.strings.map((e=>"1")).join(" "));const r=[],n=new Map;for(let e=0;e<t.strings.length;e++){const s=t.strings[e];if(-1!==s){const a=i.addElement("Fret"),o=t.strings.length-1-e;a.attributes.set("string",o.toString()),a.attributes.set("fret",(s-t.firstFret+1).toString()),n.has(s)||(n.set(s,[]),r.push(s)),n.get(s).push(o)}}r.sort();const o=i.addElement("Fingering");if(t.barreFrets.length>0){const e=[k.LittleFinger,k.AnnularFinger,k.MiddleFinger,k.IndexFinger];for(const s of r){const i=n.get(s);if(i.length>1&&t.barreFrets.indexOf(s)>=0){const a=e.length>0?e.pop():k.IndexFinger;for(const e of i){const i=o.addElement("Position");switch(a){case k.LittleFinger:i.attributes.set("finger","Pinky");break;case k.AnnularFinger:i.attributes.set("finger","Ring");break;case k.MiddleFinger:i.attributes.set("finger","Middle");break;case k.IndexFinger:i.attributes.set("finger","Index")}i.attributes.set("fret",(s-t.firstFret+1).toString()),i.attributes.set("string",e.toString())}}}}const h=i.addElement("Property");h.attributes.set("name","ShowName"),h.attributes.set("type","bool"),h.attributes.set("value",t.showName?"true":"false");const l=i.addElement("Property");l.attributes.set("name","ShowDiagram"),l.attributes.set("type","bool"),l.attributes.set("value",t.showDiagram?"true":"false");const c=i.addElement("Property");c.attributes.set("name","ShowFingering"),c.attributes.set("type","bool"),c.attributes.set("value",t.showFingering?"true":"false");const d=i.addElement("Chord"),u=d.addElement("KeyNote");u.attributes.set("step","C"),u.attributes.set("accidental","Natural");const p=d.addElement("BassNote");p.attributes.set("step","C"),p.attributes.set("accidental","Natural");const g=d.addElement("Degree");g.attributes.set("interval","Third"),g.attributes.set("alteration","Major"),g.attributes.set("omitted","false");const m=d.addElement("Degree");m.attributes.set("interval","Fifth"),m.attributes.set("alteration","Perfect"),m.attributes.set("omitted","false")}}writeSimplePropertyNode(e,t,s,i){const a=e.addElement("Property");a.attributes.set("name",t);const r=a.addElement(s);return null!==i&&(r.innerText=i),a}writeSimpleXPropertyNode(e,t,s,i){const a=e.addElement("XProperty");a.attributes.set("id",t);const r=a.addElement(s);return null!==i&&(r.innerText=i),a}writeLyricsNode(e,t){const s=e.addElement("Lyrics");s.attributes.set("dispatched","true");const i=[];for(const e of t.staves[0].bars)for(const t of e.voices)if(!t.isEmpty)for(const s of t.beats)if(s.lyrics)for(let t=0;t<s.lyrics.length;t++){for(;t>=i.length;){const t=new Ke;t.startBar=e.index,t.text="[Empty]",i.push(t)}const a=i[t];a.text="[Empty]"===a.text?s.lyrics[t]:`${a.text} ${s.lyrics[t].split(" ").join("+")}`}for(let e=0;e<i.length;e++){const t=s.addElement("Line");t.addElement("Text").setCData(i[e].text),t.addElement("Offset").innerText=i[e].startBar.toString()}}writeTransposeNode(e,t){const s=e.addElement("Transpose"),i=Math.floor(t.staves[0].displayTranspositionPitch/12),a=t.staves[0].displayTranspositionPitch-12*i;s.addElement("Chromatic").innerText=a.toString(),s.addElement("Octave").innerText=i.toString()}writeInstrumentSetNode(e,t){const s=e.addElement("InstrumentSet"),i=t.staves[0];if(s.addElement("LineCount").innerText=i.standardNotationLineCount.toString(),t.percussionArticulations.length>0||i.isPercussion){const e=t.percussionArticulations.length>0?t.percussionArticulations:Array.from(Le.instrumentArticulations.values());s.addElement("Name").innerText=uc.DrumKitProgramInfo.instrumentSetName,s.addElement("Type").innerText=uc.DrumKitProgramInfo.instrumentSetType;let i="",a=new yt;const r=new Map,n=s.addElement("Elements");for(const t of e){{const e=n.addElement("Element");let s=t.elementType;if(r.has(s)){const e=r.get(s);s+=` ${e}`,r.set(s,e+1)}else r.set(s,1);i=s,e.addElement("Name").innerText=s,e.addElement("Type").innerText=t.elementType,a=e.addElement("Articulations")}const e=a.addElement("Articulation");switch(e.addElement("Name").innerText=`${i} ${a.childNodes.length}`,e.addElement("StaffLine").innerText=t.staffLine.toString(),e.addElement("Noteheads").innerText=[this.mapMusicSymbol(t.noteHeadDefault),this.mapMusicSymbol(t.noteHeadHalf),this.mapMusicSymbol(t.noteHeadWhole)].join(" "),t.techniqueSymbolPlacement){case oe.Top:e.addElement("TechniquePlacement").innerText="below";break;case oe.Middle:e.addElement("TechniquePlacement").innerText="inside";break;case oe.Bottom:e.addElement("TechniquePlacement").innerText="above"}e.addElement("TechniqueSymbol").innerText=this.mapMusicSymbol(t.techniqueSymbol),e.addElement("InputMidiNumbers").innerText="",e.addElement("OutputMidiNumber").innerText=t.outputMidiNumber.toString()}}else{const e=uc.MidiProgramInfoLookup.has(t.playbackInfo.program)?uc.MidiProgramInfoLookup.get(t.playbackInfo.program):uc.MidiProgramInfoLookup.get(0);s.addElement("Name").innerText=e.instrumentSetName,s.addElement("Type").innerText=e.instrumentSetType;const i=s.addElement("Elements").addElement("Element");i.addElement("Pitched").innerText="Pitched",i.addElement("Type").innerText="pitched",i.addElement("SoundbankName").innerText="";const a=i.addElement("Articulations").addElement("Articulation");a.addElement("Name").innerText="",a.addElement("StaffLine").innerText="0",a.addElement("Noteheads").innerText="noteheadBlack noteheadHalf noteheadWhole",a.addElement("TechniquePlacement").innerText="outside",a.addElement("TechniqueSymbol").innerText="",a.addElement("InputMidiNumbers").innerText="",a.addElement("OutputRSESound").innerText="",a.addElement("OutputMidiNumber").innerText="0"}}mapMusicSymbol(e){if(e===re.None)return"";const t=re[e];return t.substring(0,1).toLowerCase()+t.substring(1)}writeMasterBarsNode(e,t){const s=e.addElement("MasterBars");for(const e of t.masterBars)this.writeMasterBarNode(s,e)}writeMasterBarNode(e,t){const s=e.addElement("MasterBar"),i=s.addElement("Key");i.addElement("AccidentalCount").innerText=t.keySignature.toString(),i.addElement("Mode").innerText=c[t.keySignatureType],i.addElement("Sharps").innerText="Sharps",s.addElement("Time").innerText=`${t.timeSignatureNumerator}/${t.timeSignatureDenominator}`,t.isFreeTime&&s.addElement("FreeTime");const a=[];for(const e of t.score.tracks)for(const s of e.staves)a.push(s.bars[t.index].id.toString());if(s.addElement("Bars").innerText=a.join(" "),t.isDoubleBar&&s.addElement("DoubleBar"),t.isSectionStart){const e=s.addElement("Section");e.addElement("Letter").setCData(t.section.marker),e.addElement("Text").setCData(t.section.text)}if(t.isRepeatStart||t.isRepeatEnd){const e=s.addElement("Repeat");e.attributes.set("start",t.isRepeatStart?"true":"false"),e.attributes.set("end",t.isRepeatEnd?"true":"false"),t.isRepeatEnd&&e.attributes.set("count",t.repeatCount.toString())}if(t.alternateEndings>0){let e=t.alternateEndings;const i=[];let a=0;for(;e>0;)1==(e>>a&1)&&(i.push(a+1),e&=~(1<<a)),a++;s.addElement("AlternateEndings").innerText=i.join(" ")}if(t.tripletFeel!==M.NoTripletFeel&&(s.addElement("TripletFeel").innerText=M[t.tripletFeel]),t.directions&&t.directions.size>0){const e=s.addElement("Directions");for(const s of t.directions)switch(s){case Be.TargetFine:e.addElement("Target").innerText="Fine";break;case Be.TargetSegno:e.addElement("Target").innerText="Segno";break;case Be.TargetSegnoSegno:e.addElement("Target").innerText="SegnoSegno";break;case Be.TargetCoda:e.addElement("Target").innerText="Coda";break;case Be.TargetDoubleCoda:e.addElement("Target").innerText="DoubleCoda";break;case Be.JumpDaCapo:e.addElement("Jump").innerText="DaCapo";break;case Be.JumpDaCapoAlCoda:e.addElement("Jump").innerText="DaCapoAlCoda";break;case Be.JumpDaCapoAlDoubleCoda:e.addElement("Jump").innerText="DaCapoAlDoubleCoda";break;case Be.JumpDaCapoAlFine:e.addElement("Jump").innerText="DaCapoAlFine";break;case Be.JumpDalSegno:e.addElement("Jump").innerText="DaSegno";break;case Be.JumpDalSegnoAlCoda:e.addElement("Jump").innerText="DaSegnoAlCoda";break;case Be.JumpDalSegnoAlDoubleCoda:e.addElement("Jump").innerText="DaSegnoAlDoubleCoda";break;case Be.JumpDalSegnoAlFine:e.addElement("Jump").innerText="DaSegnoAlFine";break;case Be.JumpDalSegnoSegno:e.addElement("Jump").innerText="DaSegnoSegno";break;case Be.JumpDalSegnoSegnoAlCoda:e.addElement("Jump").innerText="DaSegnoSegnoAlCoda";break;case Be.JumpDalSegnoSegnoAlDoubleCoda:e.addElement("Jump").innerText="DaSegnoSegnoAlDoubleCoda";break;case Be.JumpDalSegnoSegnoAlFine:e.addElement("Jump").innerText="DaSegnoSegnoAlFine";break;case Be.JumpDaCoda:e.addElement("Jump").innerText="DaCoda";break;case Be.JumpDaDoubleCoda:e.addElement("Jump").innerText="DaDoubleCoda"}}this.writeFermatas(s,t)}writeFermatas(e,t){const s=t.fermata?.size??0;if(0!==s&&s>0){const s=e.addElement("Fermatas");for(const[e,i]of t.fermata)this.writeFermata(s,e,i)}}writeFermata(e,t,s){let i=-1,a=1;if(t>0)for(;a<10&&(i=t/z.QuarterTime*a,i!==Math.floor(i));)i=-1,a++;else i=0,a=1;if(-1===i)return;const r=e.addElement("Fermata");r.addElement("Type").innerText=ke[s.type],r.addElement("Length").innerText=s.length.toString(),r.addElement("Offset").innerText=`${i}/${a}`}writeBarNode(e,t){const s=e.addElement("Bar");s.attributes.set("id",t.id.toString()),s.addElement("Voices").innerText=t.voices.map((e=>e.isEmpty?"-1":e.id.toString())).join(" "),s.addElement("Clef").innerText=n[t.clef],t.clefOttava!==o.Regular&&(s.addElement("Ottavia").innerText=o[t.clefOttava].substr(1)),t.simileMark!==h.None&&(s.addElement("SimileMark").innerText=h[t.simileMark])}writeVoiceNode(e,t){if(t.isEmpty)return;const s=e.addElement("Voice");s.attributes.set("id",t.id.toString()),s.addElement("Beats").innerText=t.beats.map((e=>e.id)).join(" ")}}uc.MidiProgramInfoLookup=new Map([[0,new dc(cc.Piano,"Acoustic Piano")],[1,new dc(cc.Piano,"Acoustic Piano")],[2,new dc(cc.Piano,"Electric Piano")],[3,new dc(cc.Piano,"Acoustic Piano")],[4,new dc(cc.Piano,"Electric Piano")],[5,new dc(cc.Piano,"Electric Piano")],[6,new dc(cc.Piano,"Harpsichord")],[7,new dc(cc.Piano,"Harpsichord")],[8,new dc(cc.PitchedIdiophone,"Celesta")],[9,new dc(cc.PitchedIdiophone,"Vibraphone")],[10,new dc(cc.PitchedIdiophone,"Vibraphone")],[11,new dc(cc.PitchedIdiophone,"Vibraphone")],[12,new dc(cc.PitchedIdiophone,"Xylophone")],[13,new dc(cc.PitchedIdiophone,"Xylophone")],[14,new dc(cc.PitchedIdiophone,"Vibraphone")],[15,new dc(cc.Banjo,"Banjo")],[16,new dc(cc.Piano,"Electric Organ")],[17,new dc(cc.Piano,"Electric Organ")],[18,new dc(cc.Piano,"Electric Organ")],[19,new dc(cc.Piano,"Electric Organ")],[20,new dc(cc.Piano,"Electric Organ")],[21,new dc(cc.Piano,"Electric Organ")],[22,new dc(cc.Woodwind,"Recorder")],[23,new dc(cc.Piano,"Electric Organ")],[24,new dc(cc.ClassicalGuitar,"Nylon Guitar")],[25,new dc(cc.SteelGuitar,"Steel Guitar")],[26,new dc(cc.SteelGuitar,"Electric Guitar")],[27,new dc(cc.ElectricGuitar,"Electric Guitar")],[28,new dc(cc.ElectricGuitar,"Electric Guitar")],[29,new dc(cc.ElectricGuitar,"Electric Guitar")],[30,new dc(cc.SteelGuitar,"Electric Guitar")],[31,new dc(cc.SteelGuitar,"Electric Guitar")],[32,new dc(cc.Bass,"Acoustic Bass")],[33,new dc(cc.Bass,"Electric Bass")],[34,new dc(cc.Bass,"Electric Bass")],[35,new dc(cc.Bass,"Acoustic Bass")],[36,new dc(cc.Bass,"Electric Bass")],[37,new dc(cc.Bass,"Electric Bass")],[38,new dc(cc.Synth,"Synth Bass")],[39,new dc(cc.Synth,"Synth Bass")],[40,new dc(cc.Strings,"Violin")],[41,new dc(cc.Strings,"Viola")],[42,new dc(cc.Strings,"Cello")],[43,new dc(cc.Strings,"Contrabass")],[44,new dc(cc.Strings,"Violin")],[45,new dc(cc.Strings,"Violin")],[46,new dc(cc.Piano,"Harp")],[47,new dc(cc.Membraphone,"Timpani")],[48,new dc(cc.Strings,"Violin")],[49,new dc(cc.Strings,"Violin")],[50,new dc(cc.Strings,"Violin")],[51,new dc(cc.Strings,"Violin")],[52,new dc(cc.Vocal,"Voice")],[53,new dc(cc.Vocal,"Voice")],[54,new dc(cc.Vocal,"Voice")],[55,new dc(cc.Synth,"Pad Synthesizer")],[56,new dc(cc.Brass,"Trumpet")],[57,new dc(cc.Brass,"Trombone")],[58,new dc(cc.Brass,"Tuba")],[59,new dc(cc.Brass,"Trumpet")],[60,new dc(cc.Brass,"French Horn")],[61,new dc(cc.Brass,"Trumpet")],[62,new dc(cc.Brass,"Trumpet")],[63,new dc(cc.Brass,"Trumpet")],[64,new dc(cc.Reed,"Saxophone")],[65,new dc(cc.Reed,"Saxophone")],[66,new dc(cc.Reed,"Saxophone")],[67,new dc(cc.Reed,"Saxophone")],[68,new dc(cc.Reed,"Oboe")],[69,new dc(cc.Reed,"English Horn")],[70,new dc(cc.Reed,"Bassoon")],[71,new dc(cc.Reed,"Clarinet")],[72,new dc(cc.Reed,"Piccolo")],[73,new dc(cc.Woodwind,"Flute")],[74,new dc(cc.Woodwind,"Recorder")],[75,new dc(cc.Woodwind,"Flute")],[76,new dc(cc.Woodwind,"Recorder")],[77,new dc(cc.Woodwind,"Flute")],[78,new dc(cc.Woodwind,"Recorder")],[79,new dc(cc.Woodwind,"Flute")],[80,new dc(cc.Synth,"Lead Synthesizer")],[81,new dc(cc.Synth,"Lead Synthesizer")],[82,new dc(cc.Synth,"Lead Synthesizer")],[83,new dc(cc.Synth,"Lead Synthesizer")],[84,new dc(cc.Synth,"Lead Synthesizer")],[85,new dc(cc.Synth,"Lead Synthesizer")],[86,new dc(cc.Synth,"Lead Synthesizer")],[87,new dc(cc.Synth,"Lead Synthesizer")],[88,new dc(cc.Synth,"Pad Synthesizer")],[89,new dc(cc.Synth,"Pad Synthesizer")],[90,new dc(cc.Synth,"Pad Synthesizer")],[91,new dc(cc.Synth,"Pad Synthesizer")],[92,new dc(cc.Synth,"Pad Synthesizer")],[93,new dc(cc.Synth,"Pad Synthesizer")],[94,new dc(cc.Synth,"Pad Synthesizer")],[95,new dc(cc.Synth,"Pad Synthesizer")],[96,new dc(cc.Fx,"Pad Synthesizer")],[97,new dc(cc.Fx,"Pad Synthesizer")],[98,new dc(cc.Fx,"Pad Synthesizer")],[99,new dc(cc.Fx,"Pad Synthesizer")],[100,new dc(cc.Fx,"Lead Synthesizer")],[101,new dc(cc.Fx,"Lead Synthesizer")],[102,new dc(cc.Fx,"Lead Synthesizer")],[103,new dc(cc.Fx,"Trumpet")],[104,new dc(cc.ElectricGuitar,"Banjo")],[105,new dc(cc.Banjo,"Banjo")],[106,new dc(cc.Ukulele,"Ukulele")],[107,new dc(cc.Banjo,"Banjo")],[108,new dc(cc.PitchedIdiophone,"Xylophone")],[109,new dc(cc.Reed,"Bassoon")],[110,new dc(cc.Strings,"Violin")],[111,new dc(cc.Woodwind,"Flute")],[112,new dc(cc.PitchedIdiophone,"Xylophone")],[113,new dc(cc.Idiophone,"Celesta")],[114,new dc(cc.PitchedIdiophone,"Vibraphone")],[115,new dc(cc.Idiophone,"Xylophone")],[116,new dc(cc.Membraphone,"Xylophone")],[117,new dc(cc.Membraphone,"Xylophone")],[118,new dc(cc.Membraphone,"Xylophone")],[119,new dc(cc.Idiophone,"Celesta")],[120,new dc(cc.Fx,"Steel Guitar")],[121,new dc(cc.Fx,"Recorder")],[122,new dc(cc.Fx,"Recorder")],[123,new dc(cc.Fx,"Recorder")],[124,new dc(cc.Fx,"Recorder")],[125,new dc(cc.Fx,"Recorder")],[126,new dc(cc.Fx,"Recorder")],[127,new dc(cc.Fx,"Timpani")]]),uc.DrumKitProgramInfo=new dc(cc.PercussionKit,"Drums","drumKit");class pc{static buildCrc32Lookup(){const e=new Uint32Array(256);for(let t=0;t<e.length;t++){let s=t;for(let e=0;e<8;e++)s=1&~s?s>>>1:s>>>1^3988292384;e[t]=s}return e}get value(){return~this._checkValue}constructor(){this._checkValue=pc.CrcInit,this.reset()}update(e,t,s){for(let i=0;i<s;i++)this._checkValue=pc.Crc32Lookup[255&(this._checkValue^e[t+i])]^this._checkValue>>>8}reset(){this._checkValue=pc.CrcInit}}pc.Crc32Lookup=pc.buildCrc32Lookup(),pc.CrcInit=4294967295;class gc{}gc.MAX_WBITS=15,gc.WSIZE=1<<gc.MAX_WBITS,gc.WMASK=gc.WSIZE-1,gc.MIN_MATCH=3,gc.MAX_MATCH=258,gc.DEFAULT_MEM_LEVEL=8,gc.PENDING_BUF_SIZE=1<<gc.DEFAULT_MEM_LEVEL+8,gc.HASH_BITS=gc.DEFAULT_MEM_LEVEL+7,gc.HASH_SIZE=1<<gc.HASH_BITS,gc.HASH_SHIFT=(gc.HASH_BITS+gc.MIN_MATCH-1)/gc.MIN_MATCH,gc.HASH_MASK=gc.HASH_SIZE-1,gc.MIN_LOOKAHEAD=gc.MAX_MATCH+gc.MIN_MATCH+1,gc.MAX_DIST=gc.WSIZE-gc.MIN_LOOKAHEAD;class mc{constructor(e,t,s,i){this.length=null,this.numCodes=0,this.codes=null,this.huffman=e,this.minNumCodes=s,this.maxLength=i,this.freqs=new Int16Array(t),this.bitLengthCounts=new Int32Array(i)}reset(){for(let e=0;e<this.freqs.length;e++)this.freqs[e]=0;this.codes=null,this.length=null}buildTree(){const e=this.freqs.length,t=new Int32Array(e);let s=0,i=0;for(let a=0;a<e;a++){const e=this.freqs[a];if(0!==e){let r=s++;for(;r>0;){const s=Math.floor((r-1)/2);if(!(this.freqs[t[s]]>e))break;t[r]=t[s],r=s}t[r]=a,i=a}}for(;s<2;){const e=i<2?++i:0;t[s++]=e}this.numCodes=Math.max(i+1,this.minNumCodes);const a=s,r=new Int32Array(4*s-2),n=new Int32Array(2*s-1);let o=a;for(let e=0;e<s;e++){const s=t[e];r[2*e]=s,r[2*e+1]=-1,n[e]=this.freqs[s]<<8,t[e]=e}do{const e=t[0];let i=t[--s],a=0,h=1;for(;h<s;)h+1<s&&n[t[h]]>n[t[h+1]]&&h++,t[a]=t[h],a=h,h=2*h+1;let l=n[i];for(;h=a,a>0&&(a=Math.floor((h-1)/2),n[t[a]]>l);)t[h]=t[a];t[h]=i;const c=t[0];i=o++,r[2*i]=e,r[2*i+1]=c;const d=Math.min(255&n[e],255&n[c]);for(l=n[e]+n[c]-d+1,n[i]=l,a=0,h=1;h<s;)h+1<s&&n[t[h]]>n[t[h+1]]&&h++,t[a]=t[h],a=h,h=2*a+1;for(;h=a,h>0&&(a=Math.floor((h-1)/2),n[t[a]]>l);)t[h]=t[a];t[h]=i}while(s>1);this.buildLength(r)}buildLength(e){this.length=new Uint8Array(this.freqs.length);const t=Math.floor(e.length/2),s=Math.floor((t+1)/2);let i=0;for(let e=0;e<this.maxLength;e++)this.bitLengthCounts[e]=0;const a=new Int32Array(t);a[t-1]=0;for(let s=t-1;s>=0;s--)if(-1!==e[2*s+1]){let t=a[s]+1;t>this.maxLength&&(t=this.maxLength,i++),a[e[2*s]]=t,a[e[2*s+1]]=t}else{const t=a[s];this.bitLengthCounts[t-1]++,this.length[e[2*s]]=a[s]}if(0===i)return;let r=this.maxLength-1;do{for(;0===this.bitLengthCounts[--r];);do{this.bitLengthCounts[r]--,this.bitLengthCounts[++r]++,i-=1<<this.maxLength-1-r}while(i>0&&r<this.maxLength-1)}while(i>0);this.bitLengthCounts[this.maxLength-1]+=i,this.bitLengthCounts[this.maxLength-2]-=i;let n=2*s;for(let t=this.maxLength;0!==t;t--){let s=this.bitLengthCounts[t-1];for(;s>0;){const i=2*e[n++];-1===e[i+1]&&(this.length[e[i]]=t,s--)}}}getEncodedLength(){let e=0;for(let t=0;t<this.freqs.length;t++)e+=this.freqs[t]*this.length[t];return e}calcBLFreq(e){let t,s,i,a=-1,r=0;for(;r<this.numCodes;){i=1;const n=this.length[r];for(0===n?(t=138,s=3):(t=6,s=3,a!==n&&(e.freqs[n]++,i=0)),a=n,r++;r<this.numCodes&&a===this.length[r]&&(r++,!(++i>=t)););i<s?e.freqs[a]+=i:0!==a?e.freqs[mc.Repeat3To6]++:i<=10?e.freqs[mc.Repeat3To10]++:e.freqs[mc.Repeat11To138]++}}setStaticCodes(e,t){this.codes=e,this.length=t}buildCodes(){const e=new Int32Array(this.maxLength);let t=0;this.codes=new Int16Array(this.freqs.length);for(let s=0;s<this.maxLength;s++)e[s]=t,t+=this.bitLengthCounts[s]<<15-s;for(let t=0;t<this.numCodes;t++){const s=this.length[t];s>0&&(this.codes[t]=fc.bitReverse(e[s-1]),e[s-1]+=1<<16-s)}}writeTree(e){let t,s,i,a=-1,r=0;for(;r<this.numCodes;){i=1;const n=this.length[r];for(0===n?(t=138,s=3):(t=6,s=3,a!==n&&(e.writeSymbol(n),i=0)),a=n,r++;r<this.numCodes&&a===this.length[r]&&(r++,!(++i>=t)););if(i<s)for(;i-- >0;)e.writeSymbol(a);else 0!==a?(e.writeSymbol(mc.Repeat3To6),this.huffman.pending.writeBits(i-3,2)):i<=10?(e.writeSymbol(mc.Repeat3To10),this.huffman.pending.writeBits(i-3,3)):(e.writeSymbol(mc.Repeat11To138),this.huffman.pending.writeBits(i-11,7))}}writeSymbol(e){this.huffman.pending.writeBits(65535&this.codes[e],this.length[e])}}mc.Repeat3To6=16,mc.Repeat3To10=17,mc.Repeat11To138=18;class fc{static staticInit(){let e=0;for(;e<144;)fc.staticLCodes[e]=fc.bitReverse(48+e<<8),fc.staticLLength[e++]=8;for(;e<256;)fc.staticLCodes[e]=fc.bitReverse(256+e<<7),fc.staticLLength[e++]=9;for(;e<280;)fc.staticLCodes[e]=fc.bitReverse(-256+e<<9),fc.staticLLength[e++]=7;for(;e<fc.LITERAL_NUM;)fc.staticLCodes[e]=fc.bitReverse(-88+e<<8),fc.staticLLength[e++]=8;for(e=0;e<fc.DIST_NUM;e++)fc.staticDCodes[e]=fc.bitReverse(e<<11),fc.staticDLength[e]=5}static bitReverse(e){return fc.bit4Reverse[15&e]<<12|fc.bit4Reverse[e>>4&15]<<8|fc.bit4Reverse[e>>8&15]<<4|fc.bit4Reverse[e>>12]}constructor(e){this.last_lit=0,this.extra_bits=0,this.pending=e,this.literalTree=new mc(this,fc.LITERAL_NUM,257,15),this.distTree=new mc(this,fc.DIST_NUM,1,15),this.blTree=new mc(this,fc.BITLEN_NUM,4,7),this.d_buf=new Int16Array(fc.BUFSIZE),this.l_buf=new Uint8Array(fc.BUFSIZE)}isFull(){return this.last_lit>=fc.BUFSIZE}reset(){this.last_lit=0,this.extra_bits=0,this.literalTree.reset(),this.distTree.reset(),this.blTree.reset()}flushStoredBlock(e,t,s,i){this.pending.writeBits((fc.STORED_BLOCK<<1)+(i?1:0),3),this.pending.alignToByte(),this.pending.writeShort(s),this.pending.writeShort(~s),this.pending.writeBlock(e,t,s),this.reset()}flushBlock(e,t,s,i){this.literalTree.freqs[fc.EOF_SYMBOL]++,this.literalTree.buildTree(),this.distTree.buildTree(),this.literalTree.calcBLFreq(this.blTree),this.distTree.calcBLFreq(this.blTree),this.blTree.buildTree();let a=4;for(let e=18;e>a;e--)this.blTree.length[fc.BL_ORDER[e]]>0&&(a=e+1);let r=14+3*a+this.blTree.getEncodedLength()+this.literalTree.getEncodedLength()+this.distTree.getEncodedLength()+this.extra_bits,n=this.extra_bits;for(let e=0;e<fc.LITERAL_NUM;e++)n+=this.literalTree.freqs[e]*fc.staticLLength[e];for(let e=0;e<fc.DIST_NUM;e++)n+=this.distTree.freqs[e]*fc.staticDLength[e];r>=n&&(r=n),t>=0&&s+4<r>>3?this.flushStoredBlock(e,t,s,i):r===n?(this.pending.writeBits((fc.STATIC_TREES<<1)+(i?1:0),3),this.literalTree.setStaticCodes(fc.staticLCodes,fc.staticLLength),this.distTree.setStaticCodes(fc.staticDCodes,fc.staticDLength),this.compressBlock(),this.reset()):(this.pending.writeBits((fc.DYN_TREES<<1)+(i?1:0),3),this.sendAllTrees(a),this.compressBlock(),this.reset())}sendAllTrees(e){this.blTree.buildCodes(),this.literalTree.buildCodes(),this.distTree.buildCodes(),this.pending.writeBits(this.literalTree.numCodes-257,5),this.pending.writeBits(this.distTree.numCodes-1,5),this.pending.writeBits(e-4,4);for(let t=0;t<e;t++)this.pending.writeBits(this.blTree.length[fc.BL_ORDER[t]],3);this.literalTree.writeTree(this.blTree),this.distTree.writeTree(this.blTree)}compressBlock(){for(let e=0;e<this.last_lit;e++){const t=255&this.l_buf[e];let s=this.d_buf[e];if(0!=s--){const e=fc.Lcode(t);this.literalTree.writeSymbol(e);let i=Math.floor((e-261)/4);i>0&&i<=5&&this.pending.writeBits(t&(1<<i)-1,i);const a=fc.Dcode(s);this.distTree.writeSymbol(a),i=Math.floor(a/2)-1,i>0&&this.pending.writeBits(s&(1<<i)-1,i)}else this.literalTree.writeSymbol(t)}this.literalTree.writeSymbol(fc.EOF_SYMBOL)}tallyDist(e,t){this.d_buf[this.last_lit]=e,this.l_buf[this.last_lit++]=t-3;const s=fc.Lcode(t-3);this.literalTree.freqs[s]++,s>=265&&s<285&&(this.extra_bits+=Math.floor((s-261)/4));const i=fc.Dcode(e-1);return this.distTree.freqs[i]++,i>=4&&(this.extra_bits+=Math.floor(i/2)-1),this.isFull()}tallyLit(e){return this.d_buf[this.last_lit]=0,this.l_buf[this.last_lit++]=e,this.literalTree.freqs[e]++,this.isFull()}static Lcode(e){if(255===e)return 285;let t=257;for(;e>=8;)t+=4,e>>=1;return t+e}static Dcode(e){let t=0;for(;e>=4;)t+=2,e>>=1;return t+e}}fc.BUFSIZE=1<<gc.DEFAULT_MEM_LEVEL+6,fc.LITERAL_NUM=286,fc.STORED_BLOCK=0,fc.STATIC_TREES=1,fc.DYN_TREES=2,fc.DIST_NUM=30,fc.staticLCodes=new Int16Array(fc.LITERAL_NUM),fc.staticLLength=new Uint8Array(fc.LITERAL_NUM),fc.staticDCodes=new Int16Array(fc.DIST_NUM),fc.staticDLength=new Uint8Array(fc.DIST_NUM),fc.BL_ORDER=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15],fc.bit4Reverse=new Uint8Array([0,8,4,12,2,10,6,14,1,9,5,13,3,11,7,15]),fc.BITLEN_NUM=19,fc.EOF_SYMBOL=256,fc.staticInit();class yc{constructor(e){this.maxChain=128,this.niceLength=128,this.goodLength=8,this.insertHashIndex=0,this.lookahead=0,this.inputBuf=null,this.inputOff=0,this.inputEnd=0,this.prevAvailable=!1,this.matchStart=0,this.matchLen=0,this.pending=e,this.huffman=new fc(e),this.inputCrc=new pc,this.window=new Uint8Array(2*gc.WSIZE),this.head=new Int16Array(gc.HASH_SIZE),this.prev=new Int16Array(gc.WSIZE),this.blockStart=1,this.strstart=1}reset(){this.huffman.reset(),this.inputCrc.reset(),this.blockStart=1,this.strstart=1,this.lookahead=0,this.prevAvailable=!1,this.matchLen=gc.MIN_MATCH-1;for(let e=0;e<gc.HASH_SIZE;e++)this.head[e]=0;for(let e=0;e<gc.WSIZE;e++)this.prev[e]=0}updateHash(){this.insertHashIndex=this.window[this.strstart]<<gc.HASH_SHIFT^this.window[this.strstart+1]}needsInput(){return this.inputEnd===this.inputOff}setInput(e,t,s){const i=t+s;this.inputBuf=e,this.inputOff=t,this.inputEnd=i}deflate(e,t){let s;do{this.fillWindow();const i=e&&this.inputOff===this.inputEnd;s=this.deflateSlow(i,t)}while(this.pending.isFlushed&&s);return s}deflateSlow(e,t){if(this.lookahead<gc.MIN_LOOKAHEAD&&!e)return!1;for(;this.lookahead>=gc.MIN_LOOKAHEAD||e;){if(0===this.lookahead)return this.prevAvailable&&this.huffman.tallyLit(255&this.window[this.strstart-1]),this.prevAvailable=!1,this.huffman.flushBlock(this.window,this.blockStart,this.strstart-this.blockStart,t),this.blockStart=this.strstart,!1;this.strstart>=2*gc.WSIZE-gc.MIN_LOOKAHEAD&&this.slideWindow();const e=this.matchStart;let s=this.matchLen;if(this.lookahead>=gc.MIN_MATCH){const e=this.insertString();0!==e&&this.strstart-e<=gc.MAX_DIST&&this.findLongestMatch(e)&&this.matchLen===gc.MIN_MATCH&&this.strstart-this.matchStart>yc.TooFar&&(this.matchLen=gc.MIN_MATCH-1)}if(s>=gc.MIN_MATCH&&this.matchLen<=s){this.huffman.tallyDist(this.strstart-1-e,s),s-=2;do{this.strstart++,this.lookahead--,this.lookahead>=gc.MIN_MATCH&&this.insertString()}while(--s>0);this.strstart++,this.lookahead--,this.prevAvailable=!1,this.matchLen=gc.MIN_MATCH-1}else this.prevAvailable&&this.huffman.tallyLit(255&this.window[this.strstart-1]),this.prevAvailable=!0,this.strstart++,this.lookahead--;if(this.huffman.isFull()){let e=this.strstart-this.blockStart;this.prevAvailable&&e--;const s=t&&0===this.lookahead&&!this.prevAvailable;return this.huffman.flushBlock(this.window,this.blockStart,e,s),this.blockStart+=e,!s}}return!0}findLongestMatch(e){let t,s=this.strstart;const i=s+Math.min(gc.MAX_MATCH,this.lookahead)-1,a=Math.max(s-gc.MAX_DIST,0),r=this.window,n=this.prev;let o=this.maxChain;const h=Math.min(this.niceLength,this.lookahead);if(this.matchLen=Math.max(this.matchLen,gc.MIN_MATCH-1),s+this.matchLen>i)return!1;let l=r[s+this.matchLen-1],c=r[s+this.matchLen];this.matchLen>=this.goodLength&&(o>>=2);do{if(t=e,s=this.strstart,r[t+this.matchLen]===c&&r[t+this.matchLen-1]===l&&r[t]===r[s]&&r[++t]===r[++s]){switch((i-s)%8){case 1:if(r[++s]===r[++t])break;break;case 2:if(r[++s]===r[++t]&&r[++s]===r[++t])break;break;case 3:if(r[++s]===r[++t]&&r[++s]===r[++t]&&r[++s]===r[++t])break;break;case 4:if(r[++s]===r[++t]&&r[++s]===r[++t]&&r[++s]===r[++t]&&r[++s]===r[++t])break;break;case 5:if(r[++s]===r[++t]&&r[++s]===r[++t]&&r[++s]===r[++t]&&r[++s]===r[++t]&&r[++s]===r[++t])break;break;case 6:if(r[++s]===r[++t]&&r[++s]===r[++t]&&r[++s]===r[++t]&&r[++s]===r[++t]&&r[++s]===r[++t]&&r[++s]===r[++t])break;break;case 7:if(r[++s]===r[++t]&&r[++s]===r[++t]&&r[++s]===r[++t]&&r[++s]===r[++t]&&r[++s]===r[++t]&&r[++s]===r[++t]&&r[++s]===r[++t])break}if(r[s]===r[t])do{if(s===i){++s,++t;break}}while(r[++s]===r[++t]&&r[++s]===r[++t]&&r[++s]===r[++t]&&r[++s]===r[++t]&&r[++s]===r[++t]&&r[++s]===r[++t]&&r[++s]===r[++t]&&r[++s]===r[++t]);if(s-this.strstart>this.matchLen){if(this.matchStart=e,this.matchLen=s-this.strstart,this.matchLen>=h)break;l=r[s-1],c=r[s]}e=65535&n[e&gc.WMASK]}}while(e>a&&0!=--o);return this.matchLen>=gc.MIN_MATCH}insertString(){const e=(this.insertHashIndex<<gc.HASH_SHIFT^this.window[this.strstart+(gc.MIN_MATCH-1)])&gc.HASH_MASK,t=this.head[e];return this.prev[this.strstart&gc.WMASK]=t,this.head[e]=this.strstart,this.insertHashIndex=e,65535&t}fillWindow(){if(this.strstart>=gc.WSIZE+gc.MAX_DIST&&this.slideWindow(),this.lookahead<gc.MIN_LOOKAHEAD&&this.inputOff<this.inputEnd){let e=2*gc.WSIZE-this.lookahead-this.strstart;e>this.inputEnd-this.inputOff&&(e=this.inputEnd-this.inputOff),this.window.set(this.inputBuf.subarray(this.inputOff,this.inputOff+e),this.strstart+this.lookahead),this.inputCrc.update(this.inputBuf,this.inputOff,e),this.inputOff+=e,this.lookahead+=e}this.lookahead>=gc.MIN_MATCH&&this.updateHash()}slideWindow(){this.window.set(this.window.subarray(gc.WSIZE,gc.WSIZE+gc.WSIZE),0),this.matchStart-=gc.WSIZE,this.strstart-=gc.WSIZE,this.blockStart-=gc.WSIZE;for(let e=0;e<gc.HASH_SIZE;++e){const t=65535&this.head[e];this.head[e]=t>=gc.WSIZE?t-gc.WSIZE:0}for(let e=0;e<gc.WSIZE;e++){const t=65535&this.prev[e];this.prev[e]=t>=gc.WSIZE?t-gc.WSIZE:0}}}yc.TooFar=4096;class bc{get isFlushed(){return 0===this._end}constructor(e){this._start=0,this._end=0,this._bits=0,this.bitCount=0,this._buffer=new Uint8Array(e)}reset(){this._start=0,this._end=0,this.bitCount=0}writeShortMSB(e){this._buffer[this._end++]=e>>8&255,this._buffer[this._end++]=255&e}writeShort(e){this._buffer[this._end++]=e,this._buffer[this._end++]=e>>8}writeBlock(e,t,s){this._buffer.set(e.subarray(t,t+s),this._end),this._end+=s}flush(e,t,s){return this.bitCount>=8&&(this._buffer[this._end++]=255&this._bits,this._bits>>=8,this.bitCount-=8),s>this._end-this._start?(s=this._end-this._start,e.set(this._buffer.subarray(this._start,this._start+s),t),this._start=0,this._end=0):(e.set(this._buffer.subarray(this._start,this._start+s),t),this._start+=s),s}writeBits(e,t){this._bits|=e<<this.bitCount,this.bitCount+=t,this.bitCount>=16&&(this._buffer[this._end++]=255&this._bits,this._buffer[this._end++]=this._bits>>8&255,this._bits>>=16,this.bitCount-=16)}alignToByte(){this.bitCount>0&&(this._buffer[this._end++]=255&this._bits,this.bitCount>8&&(this._buffer[this._end++]=this._bits>>8&255)),this._bits=0,this.bitCount=0}}class Sc{get inputCrc(){return this._engine.inputCrc.value}constructor(){this._state=0,this._pending=new bc(gc.PENDING_BUF_SIZE),this._engine=new yc(this._pending),this.reset()}get isNeedingInput(){return this._engine.needsInput()}get isFinished(){return this._state===Sc.FinishedState&&this._pending.isFlushed}reset(){this._state=Sc.BusyState,this._pending.reset(),this._engine.reset()}setInput(e,t,s){this._engine.setInput(e,t,s)}deflate(e,t,s){const i=s;for(;;){const a=this._pending.flush(e,t,s);if(t+=a,0===(s-=a)||this._state===Sc.FinishedState)break;if(!this._engine.deflate(!!(this._state&Sc.IsFlushing),!!(this._state&Sc.IsFinishing)))switch(this._state){case Sc.BusyState:return i-s;case Sc.FlushingState:let e=8+(7&-this._pending.bitCount);for(;e>0;)this._pending.writeBits(2,10),e-=10;this._state=Sc.BusyState;break;case Sc.FinishingState:this._pending.alignToByte(),this._state=Sc.FinishedState}}return i-s}finish(){this._state|=Sc.IsFlushing|Sc.IsFinishing}}Sc.IsFlushing=4,Sc.IsFinishing=8,Sc.BusyState=16,Sc.FlushingState=20,Sc.FinishingState=28,Sc.FinishedState=30;class _c{constructor(e,t,s,i,a){this.entry=e,this.crc32=t,this.localHeaderOffset=s,this.compressionMode=i,this.compressedSize=a}}class wc{constructor(e){this._centralDirectoryHeaders=[],this._deflater=new Sc,this._data=e}writeEntry(e){const t=cs.CompressionMethodDeflate,s=ht.empty(),i=this.compress(s,e.data,t),a=s.toArray(),r=new _c(e,i,this._data.bytesWritten,t,s.length);this._centralDirectoryHeaders.push(r),ot.writeInt32LE(this._data,cs.LocalFileHeaderSignature),ot.writeUInt16LE(this._data,10),ot.writeUInt16LE(this._data,2048),ot.writeUInt16LE(this._data,t),ot.writeInt16LE(this._data,0),ot.writeInt16LE(this._data,0),ot.writeInt32LE(this._data,i),ot.writeInt32LE(this._data,a.length),ot.writeInt32LE(this._data,e.data.length),ot.writeInt16LE(this._data,e.fullName.length),ot.writeInt16LE(this._data,0);const n=ot.stringToBytes(e.fullName);this._data.write(n,0,n.length),this._data.write(a,0,a.length)}compress(e,t,s){if(s!==cs.CompressionMethodDeflate){const s=new pc;return s.update(t,0,t.length),e.write(t,0,t.length),s.value}const i=new Uint8Array(512);for(this._deflater.reset(),this._deflater.setInput(t,0,t.length);!this._deflater.isNeedingInput;){const t=this._deflater.deflate(i,0,i.length);if(t<=0)break;e.write(i,0,t)}for(this._deflater.finish();!this._deflater.isFinished;){const t=this._deflater.deflate(i,0,i.length);if(t<=0)break;e.write(i,0,t)}return this._deflater.inputCrc}end(){const e=this._data.bytesWritten;for(const e of this._centralDirectoryHeaders)this.writeCentralDirectoryHeader(e);const t=this._data.bytesWritten;this.writeEndOfCentralDirectoryRecord(e,t)}writeEndOfCentralDirectoryRecord(e,t){ot.writeInt32LE(this._data,cs.EndOfCentralDirSignature),ot.writeInt16LE(this._data,0),ot.writeInt16LE(this._data,0),ot.writeInt16LE(this._data,this._centralDirectoryHeaders.length),ot.writeInt16LE(this._data,this._centralDirectoryHeaders.length),ot.writeInt32LE(this._data,t-e),ot.writeInt32LE(this._data,e),ot.writeInt16LE(this._data,0)}writeCentralDirectoryHeader(e){ot.writeInt32LE(this._data,cs.CentralFileHeaderSignature),ot.writeUInt16LE(this._data,10),ot.writeUInt16LE(this._data,10),ot.writeUInt16LE(this._data,2048),ot.writeUInt16LE(this._data,e.compressionMode),ot.writeInt16LE(this._data,0),ot.writeInt16LE(this._data,0),ot.writeInt32LE(this._data,e.crc32),ot.writeInt32LE(this._data,e.compressedSize),ot.writeInt32LE(this._data,e.entry.data.length),ot.writeInt16LE(this._data,e.entry.fullName.length),ot.writeInt16LE(this._data,0),ot.writeInt16LE(this._data,0),ot.writeInt16LE(this._data,0),ot.writeInt16LE(this._data,0),ot.writeInt32LE(this._data,0),ot.writeInt32LE(this._data,e.localHeaderOffset);const t=ot.stringToBytes(e.entry.fullName);this._data.write(t,0,t.length)}}const Bc=Object.freeze(Object.defineProperty({__proto__:null,Gp7Exporter:class extends lc{get name(){return"Guitar Pro 7"}writeScore(e){q.debug(this.name,"Writing data entries");const t=(new uc).writeXml(e),s=ft.writeForScore(e),i=vt.writeForScore(e),a=gs.writeForScore(e);q.debug(this.name,"Writing ZIP entries");const r=new wc(this.data);r.writeEntry(new cs("VERSION",ot.stringToBytes("7.0"))),r.writeEntry(new cs("Content/",new Uint8Array(0))),r.writeEntry(new cs("Content/BinaryStylesheet",s)),r.writeEntry(new cs("Content/PartConfiguration",i)),r.writeEntry(new cs("Content/LayoutConfiguration",a)),r.writeEntry(new cs("Content/score.gpif",ot.stringToBytes(t))),r.end()}},ScoreExporter:lc},Symbol.toStringTag,{value:"Module"}));class kc extends Fs{constructor(){super(0,0,Rt.EndOfTrack)}writeTo(e){throw new $e(Se.General,"Deprecated event, serialization not supported")}}var Tc,Nc,xc;!function(e){e[e.SequenceNumber=0]="SequenceNumber",e[e.TextEvent=1]="TextEvent",e[e.CopyrightNotice=2]="CopyrightNotice",e[e.SequenceOrTrackName=3]="SequenceOrTrackName",e[e.InstrumentName=4]="InstrumentName",e[e.LyricText=5]="LyricText",e[e.MarkerText=6]="MarkerText",e[e.CuePoint=7]="CuePoint",e[e.PatchName=8]="PatchName",e[e.PortName=9]="PortName",e[e.MidiChannel=32]="MidiChannel",e[e.MidiPort=33]="MidiPort",e[e.EndOfTrack=47]="EndOfTrack",e[e.Tempo=81]="Tempo",e[e.SmpteOffset=84]="SmpteOffset",e[e.TimeSignature=88]="TimeSignature",e[e.KeySignature=89]="KeySignature",e[e.SequencerSpecific=127]="SequencerSpecific"}(Tc||(Tc={}));class vc extends kc{get metaStatus(){return Tc.EndOfTrack}}!function(e){e[e.SystemExclusive=240]="SystemExclusive",e[e.MtcQuarterFrame=241]="MtcQuarterFrame",e[e.SongPosition=242]="SongPosition",e[e.SongSelect=243]="SongSelect",e[e.TuneRequest=246]="TuneRequest",e[e.SystemExclusive2=247]="SystemExclusive2"}(Nc||(Nc={}));class Pc extends kc{}!function(e){e[e.MetronomeTick=0]="MetronomeTick",e[e.Rest=1]="Rest"}(xc||(xc={}));class Fc extends Pc{constructor(){super(...arguments),this.data=new Uint8Array}get isMetronome(){return!1}get metronomeNumerator(){return-1}get metronomeDurationInTicks(){return-1}get metronomeDurationInMilliseconds(){return-1}get isRest(){return!1}get manufacturerId(){return 0}}Fc.AlphaTabManufacturerId=125;const Cc=Object.freeze(Object.defineProperty({__proto__:null,AlphaSynthMidiFileHandler:lr,AlphaTabMetronomeEvent:Es,AlphaTabRestEvent:Ls,AlphaTabSysExEvent:Ds,get AlphaTabSystemExclusiveEvents(){return xc},BeatTickLookup:pr,BeatTickLookupItem:ur,ControlChangeEvent:Rs,get ControllerType(){return Xt},DeprecatedMidiEvent:kc,EndOfTrackEvent:Gs,MasterBarTickLookup:mr,MasterBarTickLookupTempoChange:gr,MetaDataEvent:class extends vc{constructor(){super(...arguments),this.data=new Uint8Array}},MetaEvent:vc,get MetaEventType(){return Tc},MetaNumberEvent:class extends vc{constructor(){super(...arguments),this.value=0}},Midi20PerNotePitchBendEvent:class extends kc{constructor(){super(...arguments),this.noteKey=0,this.pitch=0}},MidiEvent:Fs,get MidiEventType(){return Rt},MidiFile:Ps,get MidiFileFormat(){return At},MidiFileGenerator:wr,MidiTickLookup:yr,MidiTickLookupFindBeatResult:fr,get MidiTickLookupFindBeatResultCursorMode(){return Zt},MidiTrack:vs,NoteBendEvent:Vs,NoteEvent:Ms,NoteOffEvent:As,NoteOnEvent:Is,PitchBendEvent:Ws,ProgramChangeEvent:Os,SystemCommonEvent:Pc,get SystemCommonType(){return Nc},SystemExclusiveEvent:Fc,TempoChangeEvent:Hs,TimeSignatureEvent:Cs},Symbol.toStringTag,{value:"Module"})),Dc=Object.freeze(Object.defineProperty({__proto__:null,get AccentuationType(){return B},get AccidentalType(){return It},Automation:U,get AutomationType(){return m},Bar:G,get BarLineStyle(){return p},BarStyle:V,get BarSubElement(){return u},get BarreShape(){return ge},Beat:ze,get BeatBeamingMode(){return fe},BeatStyle:Ge,get BeatSubElement(){return ye},BendPoint:X,get BendStyle(){return f},get BendType(){return y},get BracketExtendMode(){return s},get BrushType(){return b},Chord:je,get Clef(){return n},Color:et,get CrescendoType(){return S},get Direction(){return Be},get Duration(){return _},get DynamicValue(){return g},ElementStyle:H,get FadeType(){return ue},Fermata:lt,get FermataType(){return ke},get Fingers(){return k},Font:na,get FontStyle(){return Jt},get FontWeight(){return Yt},get GolpeType(){return de},GraceGroup:Q,get GraceType(){return w},get HarmonicType(){return T},HeaderFooterStyle:Ue,InstrumentArticulation:Ee,JsonConverter:$a,get KeySignature(){return l},get KeySignatureType(){return c},Lyrics:Ke,MasterBar:j,get MusicFontSymbol(){return re},Note:Ae,get NoteAccidentalMode(){return N},get NoteOrnament(){return he},NoteStyle:Ie,get NoteSubElement(){return le},get Ottavia(){return o},get PickStroke(){return ae},PlaybackInformation:tt,get Rasgueado(){return me},RenderStylesheet:R,RepeatGroup:O,Score:Je,ScoreStyle:Xe,get ScoreSubElement(){return be},Section:Qe,get SimileMark(){return h},get SlideInType(){return x},get SlideOutType(){return v},Staff:it,SustainPedalMarker:W,get SustainPedalMarkerType(){return d},Track:rt,get TrackNameMode(){return a},get TrackNameOrientation(){return r},get TrackNamePolicy(){return i},TrackStyle:at,get TrackSubElement(){return we},get TripletFeel(){return M},Tuning:st,TupletGroup:Re,get VibratoType(){return P},Voice:ee,VoiceStyle:Z,get VoiceSubElement(){return I},get WahPedal(){return pe},get WhammyType(){return ce}},Symbol.toStringTag,{value:"Module"})),Ec=Object.freeze(Object.defineProperty({__proto__:null,BarBounds:er,get BeamDirection(){return Te},BeatBounds:tr,Bounds:mt,BoundsLookup:rr,MasterBarBounds:sr,NoteBounds:ir,RenderFinishedEventArgs:Za,ScoreRenderer:nr,StaffSystemBounds:ar},Symbol.toStringTag,{value:"Module"})),Lc=Object.freeze(Object.defineProperty({__proto__:null,CssFontSvgCanvas:en,Cursors:Jr,FontSizeDefinition:Ka,FontSizes:Qa,MeasuredText:De,SvgCanvas:Zr,get TextAlign(){return ne},get TextBaseline(){return oe}},Symbol.toStringTag,{value:"Module"})),Mc=Object.freeze(Object.defineProperty({__proto__:null,ActiveBeatsChangedEventArgs:Dr,AlphaSynth:sa,AlphaSynthAudioWorkletOutput:$r,AlphaSynthScriptProcessorOutput:Gr,AlphaSynthWebAudioOutputBase:Vr,AlphaSynthWebWorkerApi:Ur,CircularSampleBuffer:Hr,MidiEventsPlayedEventArgs:ea,PlaybackRange:Br,PlaybackRangeChangedEventArgs:ta,get PlayerState(){return Ot},PlayerStateChangedEventArgs:Ys,PositionChangedEventArgs:$s},Symbol.toStringTag,{value:"Module"})),Ic=Object.freeze(Object.defineProperty({__proto__:null},Symbol.toStringTag,{value:"Module"}));export{Kr as AlphaTabApi,Lr as AlphaTabApiBase,$e as AlphaTabError,Se as AlphaTabErrorType,$ as ConsoleLogger,nc as CoreSettings,ha as DisplaySettings,rc as Environment,Mr as FileLoadError,C as FingeringMode,Ze as FormatError,la as ImporterSettings,e as LayoutMode,L as LogLevel,q as Logger,E as NotationElement,D as NotationMode,J as NotationSettings,jt as PlayerOutputMode,ua as PlayerSettings,zr as ProgressEventArgs,ac as RenderEngineFactory,oa as RenderingResources,Cr as ResizeEventArgs,qt as ScrollMode,Ba as Settings,da as SlidePlaybackSettings,t as StaveProfile,$t as SystemsLayoutMode,F as TabRhythmMode,ca as VibratoPlaybackSettings,Kt as WebPlatform,Bc as exporter,oc as importer,hc as io,Ic as json,sc as meta,Cc as midi,Dc as model,Lc as platform,Ec as rendering,Mc as synth};